|
|
const assetVersion = new URL(import.meta.url).searchParams.get('v');
|
|
|
|
|
|
function versionedModuleUrl(path) {
|
|
|
const url = new URL(path, import.meta.url);
|
|
|
url.search = '';
|
|
|
if (assetVersion) url.searchParams.set('v', assetVersion);
|
|
|
return url.href;
|
|
|
}
|
|
|
|
|
|
const [taskObserver, runtime, firewallInput] = await Promise.all([
|
|
|
import(versionedModuleUrl('./task-observer.js')),
|
|
|
import(versionedModuleUrl('/cloud/runtime.js')),
|
|
|
import(versionedModuleUrl('./firewall-input.js')),
|
|
|
]);
|
|
|
const {
|
|
|
announceTaskAccepted, normalizeTask, observeTask,
|
|
|
resolvedTaskFailureNotice,
|
|
|
taskSucceededWithoutRecovery,
|
|
|
} = taskObserver;
|
|
|
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,
|
|
|
} = runtime;
|
|
|
const { firewallPresetRules, validFirewallCidr } = firewallInput;
|
|
|
const requestUserConfirmation = options => window.VenixDialog?.confirm?.(options) ?? Promise.resolve(false);
|
|
|
const i18n = globalThis.VenixUserCopy;
|
|
|
const t = (key, parameters = {}) => i18n.text(key, parameters);
|
|
|
|
|
|
const VM_METADATA_FIELDS = Object.freeze([
|
|
|
'region', 'location', 'created_at', 'os_source', 'os_name',
|
|
|
'install_iso', 'guest_hostname', 'public_network_valid', 'public_network',
|
|
|
'public_ipv4', 'public_ipv4_cidr', 'public_ipv6', 'public_ipv6_cidr',
|
|
|
'public_ip_cidr', 'public_ip', 'login_name', 'vcpu',
|
|
|
'cpu_cores', 'memory_mib', 'ram_mib', 'disks', 'disk_gib',
|
|
|
'agent_metadata_version',
|
|
|
]);
|
|
|
|
|
|
let metadataRequest = null;
|
|
|
let operationLogsRequest = null;
|
|
|
let operationLogsLoadedVmId = null;
|
|
|
let operationLogsPage = 1;
|
|
|
let operationLogsPageCount = 1;
|
|
|
let displayNameSaving = false;
|
|
|
let displayNameStatusTimer = null;
|
|
|
const taskObservers = new Set();
|
|
|
const DISPLAY_NAME_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_.-]{0,62}$/;
|
|
|
|
|
|
function taskFailureMessage(task, fallback = t('instance_detail.task.error.execution_failed')) {
|
|
|
const message = fallback;
|
|
|
const resolvedNotice = resolvedTaskFailureNotice(task);
|
|
|
if (resolvedNotice) return resolvedNotice;
|
|
|
if (task?.recovery?.pending === true || task?.effect_may_have_applied) {
|
|
|
return t('instance_detail.task.effect_unknown', { message });
|
|
|
}
|
|
|
return task?.safe_to_resubmit === false
|
|
|
? t('instance_detail.task.locked', { message }) : message;
|
|
|
}
|
|
|
|
|
|
function watchTask(receipt, title, handlers = {}, accepted = true) {
|
|
|
if (accepted) announceTaskAccepted(receipt, { title });
|
|
|
const handle = observeTask(receipt, handlers);
|
|
|
if (!handle.url) return null;
|
|
|
taskObservers.add(handle);
|
|
|
void handle.done.finally(() => taskObservers.delete(handle));
|
|
|
return handle;
|
|
|
}
|
|
|
|
|
|
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(t('instance_detail.snapshot.validation.name_format'), 'error');
|
|
|
input.focus();
|
|
|
return;
|
|
|
}
|
|
|
const vm = selectedVm();
|
|
|
if (!vm) {
|
|
|
setDisplayNameStatus(t('instance_detail.error.stale_instance_refresh'), '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 = t('instance_detail.form.status.saving');
|
|
|
setDisplayNameStatus(t('instance_detail.snapshot.status.saving_name'));
|
|
|
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(t('instance_detail.static_info.error.invalid_instance_name'));
|
|
|
}
|
|
|
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(t('instance_detail.snapshot.notice.name_saved'), 'success');
|
|
|
trigger.focus();
|
|
|
void loadVmStatus(vmId, { force: true });
|
|
|
displayNameStatusTimer = window.setTimeout(() => setDisplayNameStatus(), 2600);
|
|
|
} catch (error) {
|
|
|
setDisplayNameStatus(t('instance_detail.snapshot.error.rename_failed'), 'error');
|
|
|
window.requestAnimationFrame(() => input.focus());
|
|
|
} finally {
|
|
|
displayNameSaving = false;
|
|
|
save.disabled = false;
|
|
|
cancel.disabled = false;
|
|
|
input.disabled = false;
|
|
|
save.textContent = t('instance_detail.form.action.save');
|
|
|
}
|
|
|
});
|
|
|
}
|
|
|
|
|
|
const OPERATION_STATUS_LABELS = Object.freeze({
|
|
|
queued: [t('instance_detail.task.status.queued'), 'queued'], running: [t('instance_detail.task.status.running'), 'running'],
|
|
|
succeeded: [t('instance_detail.task.status.completed'), 'succeeded'], failed: [t('instance_detail.status.failed'), 'failed'],
|
|
|
});
|
|
|
|
|
|
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 || t('instance_detail.operation_log.category.instance');
|
|
|
}
|
|
|
|
|
|
function operationStatusInfo(value) {
|
|
|
const key = String(value || '').toLowerCase();
|
|
|
return OPERATION_STATUS_LABELS[key] || [t('instance_detail.status.unknown'), 'unknown'];
|
|
|
}
|
|
|
|
|
|
function operationTime(value) {
|
|
|
const timestamp = Number(value);
|
|
|
if (!Number.isFinite(timestamp) || timestamp <= 0) return t('instance_detail.value.time_not_recorded');
|
|
|
return i18n.date(timestamp);
|
|
|
}
|
|
|
|
|
|
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 = t('instance_detail.pagination.empty_page');
|
|
|
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');
|
|
|
const normalizedTask = normalizeTask(entry);
|
|
|
const resolvedNotice = resolvedTaskFailureNotice(normalizedTask);
|
|
|
if (resolvedNotice || normalizedTask.recovery?.pending === true || entry.error) {
|
|
|
result.title = resolvedNotice || taskFailureMessage(normalizedTask);
|
|
|
}
|
|
|
item.append(operation, submitted, result);
|
|
|
list.append(item);
|
|
|
}
|
|
|
if (footer) footer.hidden = false;
|
|
|
if (summary) summary.textContent = t('instance_detail.logs.total', { 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 = t('instance_detail.operation_log.status.loading');
|
|
|
}
|
|
|
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 = t('instance_detail.operation_log.error.load_failed');
|
|
|
}
|
|
|
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?.agent_metadata_version) >= 1) return false;
|
|
|
const source = hasMetadataText(vm?.os_source) ? String(vm.os_source).trim() : '';
|
|
|
if (!source) return true;
|
|
|
if (source === 'cloud_template') {
|
|
|
// The Agent may refresh guest metadata, never the frozen public network
|
|
|
// identity. Keep invalid snapshots failed closed without a probe loop.
|
|
|
return !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(t('instance_detail.static_info.error.invalid_format'));
|
|
|
}
|
|
|
const currentUuid = String(current.uuid || '').toLowerCase();
|
|
|
const updateUuid = String(update.uuid || '').toLowerCase();
|
|
|
if (!updateUuid || updateUuid !== currentUuid) {
|
|
|
throw new Error(t('instance_detail.static_info.error.identity_mismatch'));
|
|
|
}
|
|
|
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(t('instance_detail.metadata.refresh_failed', { message: t('instance_detail.static_info.error.refresh_failed') }), 'error');
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function detailBootstrap() {
|
|
|
const source = byId('vm-detail-bootstrap');
|
|
|
if (!source) throw new Error(t('instance_detail.bootstrap.error.missing'));
|
|
|
try {
|
|
|
return JSON.parse(source.textContent || '{}');
|
|
|
} catch {
|
|
|
throw new Error(t('instance_detail.bootstrap.error.invalid_json'));
|
|
|
}
|
|
|
}
|
|
|
|
|
|
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: t('instance_detail.settings.field.hostname'), password: t('instance_detail.credentials.root_password'), ssh_key: t('instance_detail.settings.field.ssh_key'),
|
|
|
ip_change: t('instance_detail.network.public_ipv4'), upgrade: t('instance_detail.upgrade.section.title'), automatic_backup: t('instance_detail.backup.section.title'), firewall: t('instance_detail.firewall.section.title'),
|
|
|
snapshots: t('instance_detail.snapshot.section.title'), rescue: t('instance_detail.rescue.section.emergency_title'),
|
|
|
});
|
|
|
const INSTANCE_SETTING_TABS = Object.freeze([
|
|
|
'hostname', 'password', 'ssh_key', 'ip_change', 'upgrade', 'automatic_backup', 'firewall', 'snapshots', 'rescue',
|
|
|
]);
|
|
|
const UPGRADE_OFFER_FIELDS = Object.freeze([
|
|
|
'offer_id', 'name', 'cpu_cores', 'memory_mib', 'disk_gib',
|
|
|
'bandwidth_mbps', 'traffic_quota_bytes', 'validity_days',
|
|
|
'amount', 'renewal_price', 'currency',
|
|
|
]);
|
|
|
const FIREWALL_RULE_LIMIT = 50;
|
|
|
const FIREWALL_PENDING_STATES = new Set(['pending', 'queued', 'applying', 'running']);
|
|
|
const FIREWALL_FAILURE_STATES = new Set(['failed', 'error']);
|
|
|
const SNAPSHOT_LIMIT = 2;
|
|
|
const SNAPSHOT_STATE_LABELS = Object.freeze({
|
|
|
ready: [t('instance_detail.backup.status.restorable'), 'ready'], available: [t('instance_detail.backup.status.restorable'), 'ready'],
|
|
|
queued: [t('instance_detail.task.status.queued'), 'pending'], pending: [t('instance_detail.task.status.queued'), 'pending'], starting: [t('instance_detail.task.status.starting'), 'pending'],
|
|
|
creating: [t('instance_detail.snapshot.status.creating'), 'pending'], running: [t('instance_detail.task.status.processing'), 'pending'],
|
|
|
restoring: [t('instance_detail.backup_restore.status.restoring'), 'pending'], deleting: [t('instance_detail.snapshot.status.deleting'), 'pending'],
|
|
|
failed: [t('instance_detail.status.failed'), 'failed'], cancelled: [t('instance_detail.status.cancelled'), 'failed'],
|
|
|
});
|
|
|
const SNAPSHOT_ACTIVE_STATES = new Set([
|
|
|
'queued', 'pending', 'starting', 'creating', 'running', 'restoring', 'deleting',
|
|
|
]);
|
|
|
let snapshotRequest = null;
|
|
|
let snapshotLoadedVmId = null;
|
|
|
let snapshotPayload = null;
|
|
|
let snapshotMutation = null;
|
|
|
let snapshotEffectLocked = false;
|
|
|
let automaticBackupRequest = null;
|
|
|
let automaticBackupLoadedVmId = null;
|
|
|
let automaticBackupPayload = null;
|
|
|
let automaticBackupSaving = false;
|
|
|
let automaticBackupRestoring = false;
|
|
|
let firewallRequest = null;
|
|
|
let firewallLoadedVmId = null;
|
|
|
let firewallPayload = null;
|
|
|
let firewallSaving = false;
|
|
|
let firewallDirty = false;
|
|
|
let firewallPolling = false;
|
|
|
let ipChangeRequest = null;
|
|
|
let ipChangeLoadedVmId = null;
|
|
|
let ipChangePayload = null;
|
|
|
let ipChangeSubmitting = false;
|
|
|
let upgradeRequest = null;
|
|
|
let upgradeLoadedVmId = null;
|
|
|
let upgradePayload = null;
|
|
|
let upgradeSelectedOfferId = '';
|
|
|
let upgradeSubmitting = false;
|
|
|
let upgradePendingFingerprint = '';
|
|
|
let rescueRequest = null;
|
|
|
let rescueLoadedVmId = null;
|
|
|
let rescueSubmitting = false;
|
|
|
let rescueStatusReachable = false;
|
|
|
|
|
|
function instanceOperationBusy(vm = selectedVm()) {
|
|
|
return vm?.state_transitioning === true
|
|
|
|| String(vm?.operation_transition || '').trim() !== '';
|
|
|
}
|
|
|
|
|
|
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 === 'upgrade') {
|
|
|
settingStatus();
|
|
|
void loadUpgradeOptions(vmId).catch(() => null);
|
|
|
} else if (tab === 'automatic_backup') {
|
|
|
settingStatus();
|
|
|
void loadAutomaticBackup(vmId).catch(() => null);
|
|
|
} else if (tab === 'firewall') {
|
|
|
settingStatus();
|
|
|
void loadVmFirewall(vmId);
|
|
|
} else if (tab === 'snapshots') {
|
|
|
settingStatus();
|
|
|
void loadVmSnapshots(vmId, true);
|
|
|
} else if (tab === 'ip_change') {
|
|
|
settingStatus();
|
|
|
void loadIpChangeQuote(vmId);
|
|
|
} else if (tab === 'rescue') {
|
|
|
settingStatus();
|
|
|
void loadRescue(vmId).catch(() => null);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function bindInstanceSettingTabs(vmId, requestedTab = '') {
|
|
|
const buttons = Array.from(document.querySelectorAll('[data-instance-setting-tab]'));
|
|
|
if (!buttons.length) return;
|
|
|
const availableTabs = buttons.map(button => button.dataset.instanceSettingTab)
|
|
|
.filter(tab => INSTANCE_SETTING_TABS.includes(tab));
|
|
|
const initialTab = availableTabs.includes(requestedTab) ? requestedTab : availableTabs[0];
|
|
|
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', () => {
|
|
|
const tab = button.dataset.instanceSettingTab;
|
|
|
activateInstanceSettingTab(vmId, tab);
|
|
|
const url = new URL(location.href);
|
|
|
url.searchParams.set('tab', 'settings');
|
|
|
url.searchParams.set('setting', tab);
|
|
|
history.replaceState(null, '', url);
|
|
|
});
|
|
|
button.addEventListener('keydown', event => {
|
|
|
const current = availableTabs.indexOf(button.dataset.instanceSettingTab);
|
|
|
let next = current;
|
|
|
if ((compactLayout.matches && event.key === 'ArrowRight') || (!compactLayout.matches && event.key === 'ArrowDown')) next = (current + 1) % availableTabs.length;
|
|
|
else if ((compactLayout.matches && event.key === 'ArrowLeft') || (!compactLayout.matches && event.key === 'ArrowUp')) next = (current - 1 + availableTabs.length) % availableTabs.length;
|
|
|
else if (event.key === 'Home') next = 0;
|
|
|
else if (event.key === 'End') next = availableTabs.length - 1;
|
|
|
else return;
|
|
|
event.preventDefault();
|
|
|
activateInstanceSettingTab(vmId, availableTabs[next], true);
|
|
|
});
|
|
|
});
|
|
|
activateInstanceSettingTab(vmId, initialTab);
|
|
|
}
|
|
|
|
|
|
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 || ''),
|
|
|
effect_may_have_applied: source.effect_may_have_applied === true,
|
|
|
safe_to_resubmit: source.safe_to_resubmit === true,
|
|
|
rules,
|
|
|
};
|
|
|
}
|
|
|
|
|
|
function firewallStateInfo(policy) {
|
|
|
const state = String(policy?.sync_state || '').toLowerCase();
|
|
|
if (FIREWALL_FAILURE_STATES.has(state)) return [t('instance_detail.operation.status.apply_failed'), 'failed'];
|
|
|
if (['pending', 'queued'].includes(state)) return [t('instance_detail.firewall.status.pending_apply'), 'pending'];
|
|
|
if (['applying', 'running'].includes(state)) return [t('instance_detail.task.status.applying'), 'pending'];
|
|
|
if (['failed', 'error'].includes(state)) return [t('instance_detail.operation.status.apply_failed'), 'failed'];
|
|
|
if (!policy?.enabled || state === 'disabled') return [t('instance_detail.status.not_enabled'), 'disabled'];
|
|
|
if (['active', 'applied', 'succeeded'].includes(state)) return [t('instance_detail.firewall.status.applied'), 'active'];
|
|
|
return [t('instance_detail.status.effect_unknown'), 'unknown'];
|
|
|
}
|
|
|
|
|
|
function firewallTime(value) {
|
|
|
if (value === null || value === undefined || value === '') return t('instance_detail.value.not_recorded');
|
|
|
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 t('instance_detail.value.not_recorded');
|
|
|
return i18n.date(date.getTime());
|
|
|
}
|
|
|
|
|
|
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', t('instance_detail.firewall.field.protocol'));
|
|
|
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 = 43;
|
|
|
source.autocomplete = 'off';
|
|
|
source.spellcheck = false;
|
|
|
source.placeholder = t('instance_detail.firewall.placeholder.source_cidr');
|
|
|
source.value = String(rule.source_cidr || rule.source || '');
|
|
|
source.setAttribute('aria-label', t('instance_detail.firewall.field.source'));
|
|
|
|
|
|
const port = document.createElement('input');
|
|
|
port.name = 'ports';
|
|
|
port.type = 'text';
|
|
|
port.maxLength = 11;
|
|
|
port.autocomplete = 'off';
|
|
|
port.placeholder = t('instance_detail.firewall.placeholder.port_range');
|
|
|
port.value = protocol.value === 'ICMP' ? '' : firewallPortText(rule);
|
|
|
port.setAttribute('aria-label', t('instance_detail.firewall.field.port_range'));
|
|
|
|
|
|
const description = document.createElement('input');
|
|
|
description.name = 'description';
|
|
|
description.type = 'text';
|
|
|
description.maxLength = 100;
|
|
|
description.autocomplete = 'off';
|
|
|
description.placeholder = t('instance_detail.firewall.field.optional_description');
|
|
|
description.value = String(rule.description || '');
|
|
|
description.setAttribute('aria-label', t('instance_detail.firewall.field.description'));
|
|
|
|
|
|
const remove = firewallElement('button', 'button button-outline small danger', t('instance_detail.form.action.delete'));
|
|
|
remove.type = 'button';
|
|
|
remove.setAttribute('aria-label', t('instance_detail.firewall.action.delete_rule'));
|
|
|
const action = firewallElement('div', 'vm-firewall-cell action');
|
|
|
action.setAttribute('role', 'cell');
|
|
|
action.append(firewallElement('span', 'vm-firewall-cell-label', t('instance_detail.table.column.action')), remove);
|
|
|
|
|
|
const syncProtocol = () => {
|
|
|
const icmp = protocol.value === 'ICMP';
|
|
|
port.disabled = controlsDisabled || icmp;
|
|
|
port.placeholder = icmp ? t('instance_detail.firewall.notice.icmp_no_port') : t('instance_detail.firewall.placeholder.port_range');
|
|
|
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(t('instance_detail.firewall.field.protocol'), protocol, 'protocol'),
|
|
|
firewallRuleCell(t('instance_detail.firewall.placeholder.source_address'), source, 'source'),
|
|
|
firewallRuleCell(t('instance_detail.firewall.field.port'), port, 'ports'),
|
|
|
firewallRuleCell(t('instance_detail.firewall.field.description_short'), description, 'description'),
|
|
|
action,
|
|
|
);
|
|
|
return row;
|
|
|
}
|
|
|
|
|
|
function firewallControlsBlocked(policy = firewallPayload) {
|
|
|
const state = String(policy?.sync_state || '').toLowerCase();
|
|
|
return instanceOperationBusy() || firewallSaving || !policy || policy.can_mutate === false
|
|
|
|| FIREWALL_PENDING_STATES.has(state) || (FIREWALL_FAILURE_STATES.has(state) && policy?.effect_may_have_applied === true);
|
|
|
}
|
|
|
|
|
|
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 = t('instance_detail.settings.firewall.count', { current: total, limit: 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 - 2;
|
|
|
});
|
|
|
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 = t('instance_detail.form.status.submitting');
|
|
|
else if (FIREWALL_FAILURE_STATES.has(String(firewallPayload?.sync_state || '')) && firewallPayload?.effect_may_have_applied === true) save.textContent = t('instance_detail.operation.status.failed');
|
|
|
else if (FIREWALL_PENDING_STATES.has(String(firewallPayload?.sync_state || ''))) save.textContent = t('instance_detail.task.status.applying');
|
|
|
else save.textContent = t('instance_detail.firewall.action.apply_all');
|
|
|
}
|
|
|
|
|
|
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_FAILURE_STATES.has(syncState) && policy.effect_may_have_applied === true) {
|
|
|
setFirewallStatus(t('instance_detail.firewall.error.uncertain_locked'), 'error');
|
|
|
} else if (FIREWALL_PENDING_STATES.has(syncState)) {
|
|
|
setFirewallStatus(t('instance_detail.firewall.error.operation_pending'));
|
|
|
} else if (['failed', 'error'].includes(syncState)) {
|
|
|
const suffix = policy.last_error_code ? `(${policy.last_error_code})` : '';
|
|
|
setFirewallStatus(t('instance_detail.firewall.apply_failed', { detail: suffix }), 'error');
|
|
|
} else if (policy.can_mutate === false) {
|
|
|
setFirewallStatus(t('instance_detail.firewall.error.edit_not_allowed'), 'warning');
|
|
|
} else if (policy.enabled) {
|
|
|
setFirewallStatus(t('instance_detail.firewall.notice.enabled_default_deny'), 'success');
|
|
|
} else {
|
|
|
setFirewallStatus(t('instance_detail.firewall.notice.disabled_antispoof_active'));
|
|
|
}
|
|
|
return policy;
|
|
|
}
|
|
|
|
|
|
async function loadVmFirewall(vmId, force = false, replaceDraft = false) {
|
|
|
if (!byId('vm-settings-section-firewall')) return null;
|
|
|
if (firewallDirty && !replaceDraft) {
|
|
|
setFirewallStatus(t('instance_detail.firewall.notice.unsaved_changes'), 'warning');
|
|
|
return firewallPayload;
|
|
|
}
|
|
|
if (!force && firewallLoadedVmId === String(vmId) && firewallPayload) return firewallPayload;
|
|
|
if (firewallRequest) return firewallRequest;
|
|
|
setFirewallStatus(t('instance_detail.firewall.status.loading_policy'));
|
|
|
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) {
|
|
|
setFirewallStatus(t('instance_detail.firewall.notice.task_running'));
|
|
|
}
|
|
|
return policy;
|
|
|
} catch (error) {
|
|
|
firewallLoadedVmId = null;
|
|
|
setFirewallStatus(t('instance_detail.firewall.error.policy_load_failed'), 'error');
|
|
|
return null;
|
|
|
} finally {
|
|
|
firewallRequest = null;
|
|
|
}
|
|
|
})();
|
|
|
return firewallRequest;
|
|
|
}
|
|
|
|
|
|
function pollVmFirewall(vmId, receipt) {
|
|
|
if (firewallPolling || !receipt) return;
|
|
|
firewallPolling = true;
|
|
|
const handle = watchTask(receipt, t('instance_detail.firewall.action.apply'), {
|
|
|
onUpdate: () => setFirewallStatus(t('instance_detail.firewall.notice.task_running')),
|
|
|
onTerminal: task => {
|
|
|
firewallPolling = false;
|
|
|
void (async () => {
|
|
|
await loadVmFirewall(vmId, true, true);
|
|
|
if (taskSucceededWithoutRecovery(task)) {
|
|
|
setFirewallStatus(t('instance_detail.firewall.notice.policy_applied'), 'success');
|
|
|
} else {
|
|
|
setFirewallStatus(taskFailureMessage(task, t('instance_detail.firewall.error.task_failed')), 'error');
|
|
|
}
|
|
|
})();
|
|
|
},
|
|
|
onStop: reason => {
|
|
|
firewallPolling = false;
|
|
|
if (reason === 'pagehide') return;
|
|
|
void (async () => {
|
|
|
await loadVmFirewall(vmId, true, true);
|
|
|
setFirewallStatus(t('instance_detail.task.error.observer_stopped_refresh_edit'), 'warning');
|
|
|
})();
|
|
|
},
|
|
|
});
|
|
|
if (!handle) firewallPolling = false;
|
|
|
}
|
|
|
|
|
|
function addFirewallRules(rules) {
|
|
|
const list = byId('vm-firewall-rules');
|
|
|
if (!list || firewallControlsBlocked()) return;
|
|
|
const values = Array.isArray(rules) ? rules : [];
|
|
|
const current = list.querySelectorAll('.vm-firewall-rule-item').length;
|
|
|
if (values.length < 1 || current + values.length > FIREWALL_RULE_LIMIT) {
|
|
|
setFirewallFormError(t('instance_detail.firewall.rule_limit', { limit: FIREWALL_RULE_LIMIT }));
|
|
|
return;
|
|
|
}
|
|
|
const rows = values.map(rule => renderFirewallRule(rule, false));
|
|
|
list.append(...rows);
|
|
|
markFirewallDirty();
|
|
|
rows[0].querySelector('[name="source_cidr"]')?.focus();
|
|
|
}
|
|
|
|
|
|
function addFirewallRule(rule = {}) {
|
|
|
addFirewallRules([rule]);
|
|
|
}
|
|
|
|
|
|
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(t('instance_detail.firewall.rule_limit', { limit: 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, t('instance_detail.firewall.rule_protocol_invalid', { index: index + 1 }));
|
|
|
}
|
|
|
if (!validFirewallCidr(sourceCidr)) {
|
|
|
return invalidFirewallControl(sourceControl, t('instance_detail.firewall.rule_source_invalid', { index: index + 1 }));
|
|
|
}
|
|
|
let portFrom = null;
|
|
|
let portTo = null;
|
|
|
if (protocol !== 'ICMP') {
|
|
|
const range = firewallPortRange(portControl?.value || '');
|
|
|
if (!range) {
|
|
|
return invalidFirewallControl(portControl, t('instance_detail.firewall.rule_port_invalid', { index: index + 1 }));
|
|
|
}
|
|
|
[portFrom, portTo] = range;
|
|
|
}
|
|
|
const key = `${protocol}|${sourceCidr}|${portFrom || ''}|${portTo || ''}`;
|
|
|
if (unique.has(key)) {
|
|
|
return invalidFirewallControl(sourceControl, t('instance_detail.firewall.rule_duplicate', { index: 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 error?.mutationMayHaveApplied === true
|
|
|
|| (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(t('instance_detail.firewall.status.submitting_policy'));
|
|
|
updateFirewallEditorState();
|
|
|
try {
|
|
|
const result = await api(`/api/v1/vms/${encodeURIComponent(vmId)}/firewall`, {
|
|
|
method: 'PUT',
|
|
|
expectedStatus: 202,
|
|
|
requireTaskReceipt: true,
|
|
|
body: {
|
|
|
expected_revision: Number(firewallPayload?.desired_revision) || 0,
|
|
|
idempotency_key: firewallIdempotencyKey(),
|
|
|
enabled,
|
|
|
rules,
|
|
|
},
|
|
|
});
|
|
|
firewallPayload = {
|
|
|
...firewallPayload,
|
|
|
enabled,
|
|
|
rules,
|
|
|
sync_state: 'pending',
|
|
|
can_mutate: false,
|
|
|
};
|
|
|
firewallDirty = false;
|
|
|
renderVmFirewall(firewallPayload);
|
|
|
setFirewallStatus(t('instance_detail.task.notice.accepted_background_view_center'));
|
|
|
toast(t('instance_detail.task.notice.accepted'), 'success', t('instance_detail.firewall.action.apply'));
|
|
|
pollVmFirewall(vmId, result);
|
|
|
} catch (error) {
|
|
|
if (firewallTransportUncertain(error)) {
|
|
|
firewallDirty = false;
|
|
|
await loadVmFirewall(vmId, true, true);
|
|
|
setFirewallStatus(t('instance_detail.task.error.uncertain_refresh_edit_lock'), 'error');
|
|
|
} else {
|
|
|
firewallDirty = true;
|
|
|
setFirewallFormError(t('instance_detail.firewall.error.policy_submit_failed'));
|
|
|
setFirewallStatus(t('instance_detail.firewall.error.not_submitted_unchanged'), '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 current = document.querySelectorAll(
|
|
|
'#vm-firewall-rules .vm-firewall-rule-item',
|
|
|
).length;
|
|
|
const rules = firewallPresetRules(
|
|
|
button.dataset.firewallPreset,
|
|
|
current,
|
|
|
FIREWALL_RULE_LIMIT,
|
|
|
);
|
|
|
if (rules.length !== 2) {
|
|
|
setFirewallFormError(t('instance_detail.firewall.error.quick_fill_requires_two_slots'));
|
|
|
return;
|
|
|
}
|
|
|
addFirewallRules(rules);
|
|
|
});
|
|
|
});
|
|
|
form.addEventListener('submit', event => {
|
|
|
event.preventDefault();
|
|
|
void saveVmFirewall(vmId);
|
|
|
});
|
|
|
window.addEventListener('pagehide', () => { firewallPolling = false; });
|
|
|
updateFirewallEditorState();
|
|
|
}
|
|
|
|
|
|
function snapshotState(snapshot) {
|
|
|
const jobStatus = String(snapshot?.job_status || '').toLowerCase();
|
|
|
if (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] || [t('instance_detail.status.effect_unknown'), '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 t('instance_detail.value.time_not_recorded');
|
|
|
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 t('instance_detail.value.time_not_recorded');
|
|
|
return i18n.date(date.getTime());
|
|
|
}
|
|
|
|
|
|
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 t('instance_detail.snapshot.consistency.filesystem');
|
|
|
if (normalized === 'crash') return t('instance_detail.snapshot.consistency.crash');
|
|
|
return t('instance_detail.snapshot.consistency.unknown');
|
|
|
}
|
|
|
|
|
|
function snapshotFriendlyError(error, fallback = t('instance_detail.snapshot.error.operation_failed')) {
|
|
|
const message = String(error?.message || fallback);
|
|
|
if (/qemu[ -]?guest[ -]?agent|\bqga\b|guest agent|访客代理/i.test(message)) { // user-copy: allow technical-regex backend-error-classification
|
|
|
return t('instance_detail.snapshot.error.qga_freeze_no_fallback');
|
|
|
}
|
|
|
if (/snapshot.*limit|limit.*snapshot|最多.*快照|快照.*上限/i.test(message)) { // user-copy: allow technical-regex backend-error-classification
|
|
|
return t('instance_detail.snapshot.notice.retention_limit');
|
|
|
}
|
|
|
return fallback;
|
|
|
}
|
|
|
|
|
|
function snapshotTransportUncertain(error) {
|
|
|
const status = Number(error?.status);
|
|
|
return error?.mutationMayHaveApplied === true
|
|
|
|| (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: t('instance_detail.snapshot.action.create'), restore: t('instance_detail.snapshot.action.restore'), delete: t('instance_detail.snapshot.action.delete') }[action] || t('instance_detail.operation_log.category.snapshot');
|
|
|
}
|
|
|
|
|
|
function snapshotName(snapshot) {
|
|
|
return String(snapshot?.name || t('instance_detail.snapshot.section.title'));
|
|
|
}
|
|
|
|
|
|
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 snapshotHasUnsafeFailure(items) {
|
|
|
return items.some(snapshot => snapshotState(snapshot) === 'failed'
|
|
|
&& (snapshot?.effect_may_have_applied === true || snapshot?.safe_to_resubmit === false));
|
|
|
}
|
|
|
|
|
|
function snapshotPendingItem(items) {
|
|
|
return items.find(snapshot => SNAPSHOT_ACTIVE_STATES.has(snapshotState(snapshot)) && snapshot?.task_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', t('instance_detail.backup_restore.action.restore'));
|
|
|
restore.type = 'button';
|
|
|
const remove = snapshotElement('button', 'button button-outline small danger', t('instance_detail.form.action.delete'));
|
|
|
remove.type = 'button';
|
|
|
const key = snapshotKey(snapshot);
|
|
|
const ready = ['ready', 'available'].includes(snapshotState(snapshot));
|
|
|
const disabled = !key || !ready || controlsDisabled || snapshotEffectLocked;
|
|
|
restore.disabled = disabled;
|
|
|
remove.disabled = disabled;
|
|
|
if (!key) {
|
|
|
restore.title = t('instance_detail.snapshot.error.invalid_id');
|
|
|
remove.title = restore.title;
|
|
|
} else if (!ready) {
|
|
|
restore.title = t('instance_detail.snapshot.error.restore_requires_ready');
|
|
|
remove.title = t('instance_detail.snapshot.error.delete_requires_terminal');
|
|
|
}
|
|
|
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 busy = instanceOperationBusy() || Boolean(snapshotMutation)
|
|
|
|| activeJobPresent
|
|
|
|| items.some(item => SNAPSHOT_ACTIVE_STATES.has(snapshotState(item)));
|
|
|
const operationsUnavailable = payload?.can_mutate === false
|
|
|
&& !busy && !snapshotEffectLocked;
|
|
|
const canCreate = payload?.can_create !== false && used < SNAPSHOT_LIMIT
|
|
|
&& !busy && !snapshotEffectLocked;
|
|
|
|
|
|
summary.textContent = t('instance_detail.snapshots.usage', { used, limit: 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 (snapshotEffectLocked) create.textContent = t('instance_detail.operation.status.failed');
|
|
|
else if (snapshotMutation) create.textContent = t('instance_detail.snapshots.action_progress', { action: snapshotActionLabel(snapshotMutation.action) });
|
|
|
else if (busy) create.textContent = t('instance_detail.task.status.instance_busy');
|
|
|
else if (used >= SNAPSHOT_LIMIT) create.textContent = t('instance_detail.snapshot.status.limit_reached');
|
|
|
else if (operationsUnavailable) create.textContent = t('instance_detail.operation.status.unavailable');
|
|
|
else create.textContent = t('instance_detail.snapshot.dialog.create_title');
|
|
|
|
|
|
if (snapshotEffectLocked) {
|
|
|
setSnapshotStatus(t('instance_detail.snapshot.error.uncertain_locked'), 'error');
|
|
|
} else if (snapshotMutation) {
|
|
|
setSnapshotStatus(t('instance_detail.snapshots.task_running', { action: snapshotActionLabel(snapshotMutation.action) }));
|
|
|
} else if (busy) {
|
|
|
setSnapshotStatus(t('instance_detail.snapshots.other_task_running', { task: payload?.active_job?.kind_label || t('instance_detail.operation_log.category.other') }), 'warning');
|
|
|
} else if (operationsUnavailable) {
|
|
|
setSnapshotStatus(t('instance_detail.snapshot.error.operation_not_allowed'), 'warning');
|
|
|
}
|
|
|
}
|
|
|
|
|
|
async function loadVmSnapshots(vmId, force = false, observeActive = true) {
|
|
|
if (!byId('vm-settings-section-snapshots')) return;
|
|
|
if (!force && snapshotLoadedVmId === String(vmId) && snapshotPayload) return;
|
|
|
if (snapshotRequest) return snapshotRequest;
|
|
|
setSnapshotStatus(t('instance_detail.snapshot.status.loading'));
|
|
|
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();
|
|
|
snapshotEffectLocked = snapshotHasUnsafeFailure(items)
|
|
|
|| (activeJobStatus === 'failed' && snapshotPayload?.active_job?.effect_may_have_applied === true);
|
|
|
renderVmSnapshots(vmId, snapshotPayload);
|
|
|
const pending = snapshotPendingItem(items);
|
|
|
if (observeActive && !snapshotEffectLocked && !snapshotMutation && pending) {
|
|
|
const pendingState = snapshotState(pending);
|
|
|
const action = pendingState === 'restoring' ? 'restore' : pendingState === 'deleting' ? 'delete' : 'create';
|
|
|
snapshotMutation = { action, taskId: String(pending.task_id) };
|
|
|
renderVmSnapshots(vmId, snapshotPayload);
|
|
|
pollSnapshotJob(vmId, {
|
|
|
task_id: pending.task_id,
|
|
|
status_url: `/api/v1/tasks/${encodeURIComponent(String(pending.task_id))}`,
|
|
|
}, action, false);
|
|
|
} else if (!snapshotEffectLocked && !snapshotMutation) {
|
|
|
setSnapshotStatus();
|
|
|
}
|
|
|
} catch (error) {
|
|
|
snapshotLoadedVmId = null;
|
|
|
setSnapshotStatus(snapshotFriendlyError(error, t('instance_detail.snapshot.error.list_failed')), 'error');
|
|
|
} finally {
|
|
|
snapshotRequest = null;
|
|
|
}
|
|
|
})();
|
|
|
return snapshotRequest;
|
|
|
}
|
|
|
|
|
|
function pollSnapshotJob(vmId, receipt, action, accepted = true) {
|
|
|
const label = snapshotActionLabel(action);
|
|
|
const handle = watchTask(receipt, t('instance_detail.snapshots.task_title', { action: label }), {
|
|
|
onUpdate: () => setSnapshotStatus(t('instance_detail.task.running', { action: label })),
|
|
|
onTerminal: task => {
|
|
|
void (async () => {
|
|
|
snapshotMutation = null;
|
|
|
const succeeded = taskSucceededWithoutRecovery(task);
|
|
|
if (!succeeded) {
|
|
|
// Fail closed until the authoritative snapshot projection reloads;
|
|
|
// loadVmSnapshots replaces this transient receipt-derived guard.
|
|
|
snapshotEffectLocked = task.recovery?.pending === true
|
|
|
|| task.effect_may_have_applied || task.safe_to_resubmit === false;
|
|
|
}
|
|
|
await loadVmSnapshots(vmId, true, false);
|
|
|
if (succeeded) {
|
|
|
const actualConsistency = String(task?.result?.consistency || '').toLowerCase();
|
|
|
const completedMessage = action === 'create'
|
|
|
&& ['filesystem', 'crash'].includes(actualConsistency)
|
|
|
? t('instance_detail.snapshots.created_mode', { mode: snapshotConsistency(actualConsistency) })
|
|
|
: t('instance_detail.task.completed', { action: label });
|
|
|
if (action === 'create' && byId('vm-snapshot-name')) byId('vm-snapshot-name').value = '';
|
|
|
setSnapshotStatus(completedMessage, 'success');
|
|
|
toast(completedMessage, 'success');
|
|
|
return;
|
|
|
}
|
|
|
const message = taskFailureMessage(task, t('instance_detail.task.failed', { action: label }));
|
|
|
renderVmSnapshots(vmId, snapshotPayload);
|
|
|
setSnapshotStatus(message, 'error');
|
|
|
})();
|
|
|
},
|
|
|
onStop: reason => {
|
|
|
if (reason === 'pagehide') return;
|
|
|
snapshotMutation = null;
|
|
|
void (async () => {
|
|
|
await loadVmSnapshots(vmId, true, false);
|
|
|
renderVmSnapshots(vmId, snapshotPayload);
|
|
|
setSnapshotStatus(t('instance_detail.task.error.observer_stopped_refresh_actions'), 'warning');
|
|
|
})();
|
|
|
},
|
|
|
}, accepted);
|
|
|
if (!handle) {
|
|
|
snapshotMutation = null;
|
|
|
void (async () => {
|
|
|
await loadVmSnapshots(vmId, true, false);
|
|
|
renderVmSnapshots(vmId, snapshotPayload);
|
|
|
setSnapshotStatus(t('instance_detail.task.invalid_receipt', { action: label }), 'error');
|
|
|
})();
|
|
|
}
|
|
|
}
|
|
|
|
|
|
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 (instanceOperationBusy() || snapshotMutation || snapshotEffectLocked) return;
|
|
|
snapshotMutation = { action };
|
|
|
renderVmSnapshots(vmId, snapshotPayload);
|
|
|
try {
|
|
|
const result = await api(path, {
|
|
|
method: action === 'delete' ? 'DELETE' : 'POST', body,
|
|
|
expectedStatus: 202, requireTaskReceipt: true,
|
|
|
});
|
|
|
const taskId = result?.task_id;
|
|
|
snapshotMutation = { action, taskId: String(taskId || '') };
|
|
|
renderVmSnapshots(vmId, snapshotPayload);
|
|
|
toast(t('instance_detail.task.notice.accepted'), 'success', t('instance_detail.snapshots.task_title', { action: snapshotActionLabel(action) }));
|
|
|
pollSnapshotJob(vmId, result, action, true);
|
|
|
} catch (error) {
|
|
|
snapshotMutation = null;
|
|
|
const transportUncertain = snapshotTransportUncertain(error);
|
|
|
const message = transportUncertain
|
|
|
? t('instance_detail.task.error.uncertain_refresh_actions_lock')
|
|
|
: snapshotFriendlyError(error);
|
|
|
await loadVmSnapshots(vmId, true, false);
|
|
|
renderVmSnapshots(vmId, snapshotPayload);
|
|
|
setSnapshotStatus(message, 'error');
|
|
|
}
|
|
|
}
|
|
|
|
|
|
async function restoreVmSnapshot(vmId, snapshot) {
|
|
|
const key = snapshotKey(snapshot);
|
|
|
if (!key || instanceOperationBusy() || snapshotMutation || snapshotEffectLocked) return;
|
|
|
const name = snapshotName(snapshot);
|
|
|
const confirmed = await requestUserConfirmation({
|
|
|
title: t('instance_detail.snapshot.dialog.restore_system_disk_title'),
|
|
|
message: t('instance_detail.snapshots.restore_confirm', { name }),
|
|
|
confirmText: t('instance_detail.snapshot.action.restore'),
|
|
|
tone: 'danger',
|
|
|
});
|
|
|
if (!confirmed) 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 || instanceOperationBusy() || snapshotMutation || snapshotEffectLocked) return;
|
|
|
const name = snapshotName(snapshot);
|
|
|
const confirmed = await requestUserConfirmation({
|
|
|
title: t('instance_detail.snapshot.dialog.permanent_delete_title'),
|
|
|
message: t('instance_detail.snapshots.delete_confirm', { name }),
|
|
|
confirmText: t('instance_detail.snapshot.action.delete'),
|
|
|
tone: 'danger',
|
|
|
});
|
|
|
if (!confirmed) 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 (instanceOperationBusy() || snapshotMutation || snapshotEffectLocked) 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' }
|
|
|
);
|
|
|
});
|
|
|
}
|
|
|
|
|
|
function automaticBackupStatus(message = '', type = '') {
|
|
|
const target = byId('vm-automatic-backup-status');
|
|
|
if (!target) return;
|
|
|
target.textContent = message;
|
|
|
target.className = `vm-settings-status ${type}`.trim();
|
|
|
target.hidden = !message;
|
|
|
}
|
|
|
|
|
|
function automaticBackupError(message = '') {
|
|
|
const target = byId('vm-automatic-backup-error');
|
|
|
if (!target) return;
|
|
|
target.textContent = message;
|
|
|
target.hidden = !message;
|
|
|
}
|
|
|
|
|
|
function automaticBackupSubscription(payload = automaticBackupPayload) {
|
|
|
return payload?.subscription && typeof payload.subscription === 'object'
|
|
|
? payload.subscription : payload || {};
|
|
|
}
|
|
|
|
|
|
function automaticBackupBilling(payload = automaticBackupPayload) {
|
|
|
return payload?.billing && typeof payload.billing === 'object'
|
|
|
? payload.billing : payload || {};
|
|
|
}
|
|
|
|
|
|
function automaticBackupEnabled(payload = automaticBackupPayload) {
|
|
|
const billing = automaticBackupBilling(payload);
|
|
|
const subscription = automaticBackupSubscription(payload);
|
|
|
return billing?.subscription_enabled === true || subscription?.enabled === true;
|
|
|
}
|
|
|
|
|
|
function automaticBackupAmount(value) {
|
|
|
const amount = typeof value === 'string' ? value.trim() : String(value ?? '').trim();
|
|
|
return /^(?:0|[1-9][0-9]{0,9})\.[0-9]{2}$/.test(amount) ? amount : '';
|
|
|
}
|
|
|
|
|
|
function automaticBackupMoney(value, currency = 'USD') {
|
|
|
const amount = automaticBackupAmount(value);
|
|
|
if (!amount) return '—';
|
|
|
const code = /^[A-Z]{3}$/.test(String(currency || '').toUpperCase())
|
|
|
? String(currency).toUpperCase() : 'USD';
|
|
|
return `${code === 'USD' ? '$' : ''}${amount} ${code}`;
|
|
|
}
|
|
|
|
|
|
function automaticBackupEnableStorageKey(vmId) {
|
|
|
return `virt-cloud:pending-automatic-backup-enable:${state.userId || 'unknown'}:${vmId}`;
|
|
|
}
|
|
|
|
|
|
function pendingAutomaticBackupEnableKey(vmId, fingerprint) {
|
|
|
let saved = null;
|
|
|
try {
|
|
|
saved = JSON.parse(sessionStorage.getItem(automaticBackupEnableStorageKey(vmId)) || 'null');
|
|
|
} catch {}
|
|
|
const key = saved?.fingerprint === fingerprint
|
|
|
&& /^[A-Za-z0-9_.-]{16,128}$/.test(String(saved?.key || ''))
|
|
|
? String(saved.key) : firewallIdempotencyKey();
|
|
|
try {
|
|
|
sessionStorage.setItem(automaticBackupEnableStorageKey(vmId), JSON.stringify({ fingerprint, key }));
|
|
|
} catch {}
|
|
|
return key;
|
|
|
}
|
|
|
|
|
|
function clearPendingAutomaticBackupEnableKey(vmId) {
|
|
|
try { sessionStorage.removeItem(automaticBackupEnableStorageKey(vmId)); } catch {}
|
|
|
}
|
|
|
|
|
|
function automaticBackupSchedule(payload = automaticBackupPayload) {
|
|
|
const subscription = automaticBackupSubscription(payload);
|
|
|
const schedule = payload?.schedule && typeof payload.schedule === 'object'
|
|
|
? payload.schedule : subscription?.schedule && typeof subscription.schedule === 'object'
|
|
|
? subscription.schedule : subscription;
|
|
|
const frequency = String(schedule?.frequency || 'daily').toLowerCase() === 'weekly'
|
|
|
? 'weekly' : 'daily';
|
|
|
const weekday = Math.min(6, Math.max(0, Number(schedule?.weekday) || 0));
|
|
|
const retention = Number(schedule?.retention_count) === 1 ? 1 : 2;
|
|
|
return { frequency, weekday, retention };
|
|
|
}
|
|
|
|
|
|
function automaticBackupPurchased(payload = automaticBackupPayload) {
|
|
|
const billing = automaticBackupBilling(payload);
|
|
|
const subscription = automaticBackupSubscription(payload);
|
|
|
return billing?.entitlement_active === true
|
|
|
|| payload?.entitled === true || payload?.purchased === true || payload?.subscribed === true
|
|
|
|| subscription?.purchased === true || subscription?.active === true
|
|
|
|| ['active', 'pending', 'cancel_at_period_end'].includes(
|
|
|
String(subscription?.status || payload?.subscription_status || '').toLowerCase()
|
|
|
);
|
|
|
}
|
|
|
|
|
|
function renderAutomaticBackupService(vmId, payload = automaticBackupPayload) {
|
|
|
const billing = automaticBackupBilling(payload);
|
|
|
const stateTarget = byId('vm-automatic-backup-service-state');
|
|
|
const note = byId('vm-automatic-backup-service-note');
|
|
|
const enable = byId('vm-automatic-backup-enable');
|
|
|
const disable = byId('vm-automatic-backup-disable');
|
|
|
if (!stateTarget || !note || !enable || !disable) return;
|
|
|
const currency = String(billing?.currency || 'USD').toUpperCase();
|
|
|
const activationAmount = automaticBackupAmount(billing?.activation_amount);
|
|
|
const fullPrice = automaticBackupAmount(billing?.full_period_price);
|
|
|
const entitlementActive = billing?.entitlement_active === true;
|
|
|
const enabled = automaticBackupEnabled(payload);
|
|
|
const entitlementEnd = billing?.entitlement_paid_until;
|
|
|
byId('vm-automatic-backup-activation-price').textContent = automaticBackupMoney(activationAmount, currency);
|
|
|
byId('vm-automatic-backup-renewal-price').textContent = automaticBackupMoney(fullPrice, currency);
|
|
|
byId('vm-automatic-backup-entitlement-end').textContent = entitlementEnd
|
|
|
? snapshotTime(entitlementEnd) : t('instance_detail.backup.entitlement.not_purchased');
|
|
|
if (enabled && entitlementActive) {
|
|
|
stateTarget.textContent = t('instance_detail.status.enabled');
|
|
|
stateTarget.className = 'state-pill running';
|
|
|
note.textContent = t('instance_detail.backup.notice.disable_consequences_active');
|
|
|
} else if (entitlementActive) {
|
|
|
stateTarget.textContent = t('instance_detail.backup.entitlement.paid_disabled');
|
|
|
stateTarget.className = 'state-pill warning';
|
|
|
note.textContent = t('instance_detail.backup.entitlement_retained', { time: snapshotTime(entitlementEnd) });
|
|
|
} else {
|
|
|
stateTarget.textContent = t('instance_detail.status.disabled');
|
|
|
stateTarget.className = 'state-pill other';
|
|
|
note.textContent = activationAmount
|
|
|
? t('instance_detail.backup.enable_price', { activation: automaticBackupMoney(activationAmount, currency), renewal: automaticBackupMoney(fullPrice, currency) })
|
|
|
: t('instance_detail.backup.error.enable_unavailable');
|
|
|
}
|
|
|
if (automaticBackupSaving) note.textContent = t('instance_detail.backup.status.updating_service');
|
|
|
const canOperate = selectedVm()?.can_operate === true && !instanceOperationBusy();
|
|
|
enable.disabled = automaticBackupSaving || enabled || !canOperate || billing?.can_enable !== true;
|
|
|
disable.disabled = automaticBackupSaving || !enabled || !canOperate || billing?.can_disable !== true;
|
|
|
enable.textContent = automaticBackupSaving && !enabled ? t('instance_detail.backup.status.enabling') : t('instance_detail.backup.action.enable');
|
|
|
disable.textContent = automaticBackupSaving && enabled ? t('instance_detail.backup.status.disabling') : t('instance_detail.backup.action.disable');
|
|
|
}
|
|
|
|
|
|
function automaticBackupItems(payload = automaticBackupPayload) {
|
|
|
const values = Array.isArray(payload?.backups) ? payload.backups
|
|
|
: Array.isArray(payload?.items) ? payload.items : [];
|
|
|
return values.filter(item => item && typeof item === 'object');
|
|
|
}
|
|
|
|
|
|
function automaticBackupId(backup) {
|
|
|
const id = String(backup?.id ?? backup?.backup_id ?? '');
|
|
|
return /^[1-9]\d*$/.test(id) ? id : '';
|
|
|
}
|
|
|
|
|
|
function automaticBackupRestoreStorageKey(vmId) {
|
|
|
return `virt-cloud:pending-automatic-backup-restore:${state.userId || 'unknown'}:${vmId}`;
|
|
|
}
|
|
|
|
|
|
function pendingAutomaticBackupRestoreKey(vmId, backupId) {
|
|
|
let saved = null;
|
|
|
try {
|
|
|
saved = JSON.parse(sessionStorage.getItem(automaticBackupRestoreStorageKey(vmId)) || 'null');
|
|
|
} catch {}
|
|
|
const fingerprint = String(backupId);
|
|
|
const key = saved?.fingerprint === fingerprint
|
|
|
&& /^[A-Za-z0-9_.-]{16,128}$/.test(String(saved?.key || ''))
|
|
|
? String(saved.key) : firewallIdempotencyKey();
|
|
|
try {
|
|
|
sessionStorage.setItem(automaticBackupRestoreStorageKey(vmId), JSON.stringify({ fingerprint, key }));
|
|
|
} catch {}
|
|
|
return key;
|
|
|
}
|
|
|
|
|
|
function clearPendingAutomaticBackupRestoreKey(vmId) {
|
|
|
try { sessionStorage.removeItem(automaticBackupRestoreStorageKey(vmId)); } catch {}
|
|
|
}
|
|
|
|
|
|
function automaticBackupState(backup) {
|
|
|
const value = String(backup?.state || backup?.status || '').toLowerCase();
|
|
|
const labels = {
|
|
|
ready: [t('instance_detail.backup.status.restorable'), 'running'], creating: [t('instance_detail.backup.status.creating'), 'warning'],
|
|
|
queued: [t('instance_detail.backup.status.waiting'), 'warning'], failed: [t('instance_detail.backup.status.failed'), 'stopped'],
|
|
|
uncertain: [t('instance_detail.task.status.awaiting_reconciliation'), 'warning'], restoring: [t('instance_detail.backup_restore.status.restoring'), 'warning'],
|
|
|
deleting: [t('instance_detail.snapshot.status.deleting'), 'warning'], delete_uncertain: [t('instance_detail.snapshot.status.delete_reconcile'), 'warning'],
|
|
|
delete_attention: [t('instance_detail.backup.status.cleanup_admin_required'), 'stopped'],
|
|
|
};
|
|
|
return labels[value] || [t('instance_detail.status.effect_unknown'), 'other'];
|
|
|
}
|
|
|
|
|
|
function renderAutomaticBackupList(vmId, items, allowed) {
|
|
|
const list = byId('vm-automatic-backup-list');
|
|
|
if (!list) return;
|
|
|
list.replaceChildren();
|
|
|
if (!items.length) {
|
|
|
const empty = document.createElement('div');
|
|
|
empty.className = 'vm-automatic-backup-empty';
|
|
|
const title = document.createElement('strong');
|
|
|
const detail = document.createElement('span');
|
|
|
title.textContent = t('instance_detail.backup.empty.no_available_backup');
|
|
|
detail.textContent = t('instance_detail.backup.notice.schedule_utc_midnight');
|
|
|
empty.append(title, detail);
|
|
|
list.append(empty);
|
|
|
return;
|
|
|
}
|
|
|
for (const backup of items) {
|
|
|
const id = automaticBackupId(backup);
|
|
|
const [label, tone] = automaticBackupState(backup);
|
|
|
const card = document.createElement('article');
|
|
|
card.className = 'vm-automatic-backup-card';
|
|
|
const main = document.createElement('div');
|
|
|
main.className = 'vm-automatic-backup-card-main';
|
|
|
const name = document.createElement('strong');
|
|
|
name.textContent = String(backup?.name || (id ? t('instance_detail.backup.default_name_id', { id }) : t('instance_detail.operation_log.category.backup')));
|
|
|
const meta = document.createElement('small');
|
|
|
const size = snapshotSize(backup?.object_size_bytes);
|
|
|
meta.textContent = [snapshotTime(backup?.ready_at ?? backup?.created_at),
|
|
|
snapshotConsistency(backup?.consistency), size].filter(Boolean).join(' · ');
|
|
|
main.append(name, meta);
|
|
|
const status = document.createElement('span');
|
|
|
status.className = `state-pill ${tone} vm-automatic-backup-card-status`;
|
|
|
status.textContent = label;
|
|
|
card.append(main, status);
|
|
|
if (id && backup?.can_restore_original !== false
|
|
|
&& String(backup?.state || backup?.status || '').toLowerCase() === 'ready') {
|
|
|
const actions = document.createElement('div');
|
|
|
actions.className = 'vm-automatic-backup-card-actions';
|
|
|
const restore = document.createElement('button');
|
|
|
restore.type = 'button';
|
|
|
restore.className = 'button button-danger small';
|
|
|
restore.textContent = automaticBackupRestoring ? t('instance_detail.backup_restore.status.submitted') : t('instance_detail.backup_restore.action.restore_current');
|
|
|
restore.disabled = !allowed || automaticBackupRestoring;
|
|
|
restore.addEventListener('click', () => void restoreAutomaticBackup(vmId, backup));
|
|
|
actions.append(restore);
|
|
|
card.append(actions);
|
|
|
}
|
|
|
list.append(card);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function renderAutomaticBackup(vmId, payload = automaticBackupPayload) {
|
|
|
const form = byId('vm-automatic-backup-form');
|
|
|
if (!form) return;
|
|
|
const schedule = automaticBackupSchedule(payload);
|
|
|
const purchased = automaticBackupPurchased(payload);
|
|
|
const enabled = automaticBackupEnabled(payload);
|
|
|
const canConfigure = payload?.can_configure !== false
|
|
|
&& automaticBackupSubscription(payload)?.can_configure !== false;
|
|
|
const scheduleAllowed = purchased && enabled && canConfigure
|
|
|
&& selectedVm()?.can_operate === true && !instanceOperationBusy()
|
|
|
&& !automaticBackupSaving && !automaticBackupRestoring;
|
|
|
const restoreAllowed = selectedVm()?.can_operate === true
|
|
|
&& !instanceOperationBusy() && !automaticBackupSaving
|
|
|
&& !automaticBackupRestoring;
|
|
|
form.elements.frequency.value = schedule.frequency;
|
|
|
form.elements.weekday.value = String(schedule.weekday);
|
|
|
form.elements.retention_count.value = String(schedule.retention);
|
|
|
byId('vm-automatic-backup-weekday-field').hidden = schedule.frequency !== 'weekly';
|
|
|
for (const control of form.querySelectorAll('select, button')) control.disabled = !scheduleAllowed;
|
|
|
renderAutomaticBackupService(vmId, payload);
|
|
|
renderAutomaticBackupList(vmId, automaticBackupItems(payload), restoreAllowed);
|
|
|
if (!purchased) {
|
|
|
automaticBackupStatus(t('instance_detail.backup.entitlement.missing_view_price'), 'warning');
|
|
|
} else if (automaticBackupSaving) {
|
|
|
automaticBackupStatus(t('instance_detail.backup.status.updating_service'));
|
|
|
} else if (automaticBackupRestoring) {
|
|
|
automaticBackupStatus(t('instance_detail.backup_restore.status.restoring_block_other_actions'), 'warning');
|
|
|
} else if (!canConfigure) {
|
|
|
automaticBackupStatus(t('instance_detail.backup.error.service_not_modifiable'), 'warning');
|
|
|
} else if (!enabled) {
|
|
|
automaticBackupStatus(t('instance_detail.backup.notice.disabled_entitlement_retained'), 'warning');
|
|
|
} else {
|
|
|
automaticBackupStatus(t('instance_detail.backup.notice.enabled_schedule_editable'), 'success');
|
|
|
}
|
|
|
}
|
|
|
|
|
|
async function loadAutomaticBackup(vmId, force = false) {
|
|
|
if (!byId('vm-settings-section-automatic-backup')) return null;
|
|
|
if (!force && automaticBackupLoadedVmId === String(vmId) && automaticBackupPayload) {
|
|
|
renderAutomaticBackup(vmId, automaticBackupPayload);
|
|
|
return automaticBackupPayload;
|
|
|
}
|
|
|
if (automaticBackupRequest) return automaticBackupRequest;
|
|
|
automaticBackupStatus(t('instance_detail.backup.status.loading_schedule'));
|
|
|
automaticBackupError();
|
|
|
automaticBackupRequest = (async () => {
|
|
|
try {
|
|
|
const payload = await api(`/api/v1/vms/${encodeURIComponent(vmId)}/automatic-backup`);
|
|
|
if (String(selectedVm()?.api_id || '') !== String(vmId)) return null;
|
|
|
automaticBackupLoadedVmId = String(vmId);
|
|
|
automaticBackupPayload = payload || {};
|
|
|
renderAutomaticBackup(vmId, automaticBackupPayload);
|
|
|
return automaticBackupPayload;
|
|
|
} catch (error) {
|
|
|
automaticBackupLoadedVmId = null;
|
|
|
automaticBackupPayload = null;
|
|
|
automaticBackupStatus(t('instance_detail.backup.error.config_load_failed'), 'error');
|
|
|
throw error;
|
|
|
} finally {
|
|
|
automaticBackupRequest = null;
|
|
|
}
|
|
|
})();
|
|
|
return automaticBackupRequest;
|
|
|
}
|
|
|
|
|
|
function pollAutomaticBackupRestore(vmId, receipt) {
|
|
|
return watchTask(receipt, t('instance_detail.backup_restore.action.open'), {
|
|
|
onUpdate: () => automaticBackupStatus(t('instance_detail.backup_restore.notice.running'), 'warning'),
|
|
|
onTerminal: task => {
|
|
|
void (async () => {
|
|
|
automaticBackupRestoring = false;
|
|
|
await refreshMetadataAndStatus(vmId, false, true, true);
|
|
|
await loadAutomaticBackup(vmId, true).catch(() => null);
|
|
|
if (taskSucceededWithoutRecovery(task)) {
|
|
|
clearPendingAutomaticBackupRestoreKey(vmId);
|
|
|
automaticBackupStatus(t('instance_detail.backup_restore.notice.restored_current_instance'), 'success');
|
|
|
toast(t('instance_detail.backup_restore.notice.instance_restored'), 'success');
|
|
|
} else {
|
|
|
const effectUnknown = task?.recovery?.pending === true
|
|
|
|| (task?.effect_may_have_applied === true
|
|
|
&& String(task?.effect_resolution || '') === 'unknown');
|
|
|
if (!effectUnknown) clearPendingAutomaticBackupRestoreKey(vmId);
|
|
|
automaticBackupStatus(taskFailureMessage(task, t('instance_detail.backup_restore.error.failed')), 'error');
|
|
|
}
|
|
|
})();
|
|
|
},
|
|
|
onStop: reason => {
|
|
|
if (reason === 'pagehide') return;
|
|
|
automaticBackupRestoring = false;
|
|
|
void (async () => {
|
|
|
await loadAutomaticBackup(vmId, true).catch(() => null);
|
|
|
automaticBackupStatus(t('instance_detail.backup_restore.error.observer_stopped'), 'warning');
|
|
|
})();
|
|
|
},
|
|
|
});
|
|
|
}
|
|
|
|
|
|
async function restoreAutomaticBackup(vmId, backup) {
|
|
|
const id = automaticBackupId(backup);
|
|
|
if (!id || automaticBackupRestoring || automaticBackupSaving || instanceOperationBusy()) return;
|
|
|
const confirmed = await requestUserConfirmation({
|
|
|
title: t('instance_detail.backup_restore.dialog.title'),
|
|
|
message: t('instance_detail.backup.restore_confirm', { name: String(backup?.name || `#${id}`) }),
|
|
|
confirmText: t('instance_detail.backup_restore.action.confirm_overwrite'),
|
|
|
tone: 'danger',
|
|
|
});
|
|
|
if (!confirmed) return;
|
|
|
automaticBackupRestoring = true;
|
|
|
automaticBackupError();
|
|
|
renderAutomaticBackup(vmId, automaticBackupPayload);
|
|
|
const idempotencyKey = pendingAutomaticBackupRestoreKey(vmId, id);
|
|
|
try {
|
|
|
const receipt = await api(`/api/v1/vms/${encodeURIComponent(vmId)}/automatic-backup/${encodeURIComponent(id)}/restore`, {
|
|
|
headers: { 'Idempotency-Key': idempotencyKey },
|
|
|
method: 'POST', body: { confirm_restore: true },
|
|
|
expectedStatus: 202, requireTaskReceipt: true,
|
|
|
});
|
|
|
automaticBackupStatus(t('instance_detail.task.notice.accepted_view_center'), 'warning');
|
|
|
toast(t('instance_detail.backup_restore.notice.task_accepted'), 'success');
|
|
|
if (!pollAutomaticBackupRestore(vmId, receipt)) {
|
|
|
automaticBackupRestoring = false;
|
|
|
await loadAutomaticBackup(vmId, true).catch(() => null);
|
|
|
automaticBackupStatus(t('instance_detail.task.error.invalid_receipt_accepted'), 'error');
|
|
|
}
|
|
|
} catch (error) {
|
|
|
automaticBackupRestoring = false;
|
|
|
if (!firewallTransportUncertain(error)) clearPendingAutomaticBackupRestoreKey(vmId);
|
|
|
await loadAutomaticBackup(vmId, true).catch(() => null);
|
|
|
automaticBackupStatus(t('instance_detail.backup_restore.error.submit_failed'), 'error');
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function bindAutomaticBackup(vmId) {
|
|
|
const form = byId('vm-automatic-backup-form');
|
|
|
if (!form) return;
|
|
|
byId('vm-automatic-backup-enable')?.addEventListener('click', async () => {
|
|
|
const billing = automaticBackupBilling();
|
|
|
if (automaticBackupSaving || automaticBackupRestoring || instanceOperationBusy()
|
|
|
|| billing?.can_enable !== true || automaticBackupEnabled()) return;
|
|
|
const expectedAmount = automaticBackupAmount(billing?.activation_amount);
|
|
|
if (!expectedAmount) {
|
|
|
automaticBackupError(t('instance_detail.backup.error.enable_quote_invalid'));
|
|
|
return;
|
|
|
}
|
|
|
const currency = String(billing?.currency || 'USD').toUpperCase();
|
|
|
const freeForPaidPeriod = expectedAmount === '0.00';
|
|
|
const confirmed = await requestUserConfirmation({
|
|
|
title: t('instance_detail.backup.dialog.confirm_enable'),
|
|
|
message: freeForPaidPeriod
|
|
|
? t('instance_detail.backup.notice.reenable_no_charge_current_period')
|
|
|
: t('instance_detail.backup.enable_confirm_paid', { amount: automaticBackupMoney(expectedAmount, currency) }),
|
|
|
confirmText: freeForPaidPeriod ? t('instance_detail.backup.dialog.confirm_reenable') : t('instance_detail.backup.action.confirm_charge_enable'),
|
|
|
tone: freeForPaidPeriod ? 'default' : 'danger',
|
|
|
});
|
|
|
if (!confirmed) return;
|
|
|
const stateRevision = Math.max(0, Number(billing?.state_revision) || 0);
|
|
|
const fingerprint = [expectedAmount, String(billing?.price_version || ''),
|
|
|
String(stateRevision),
|
|
|
String(billing?.current_period_ends_at || billing?.entitlement_paid_until || '')].join('|');
|
|
|
const idempotencyKey = pendingAutomaticBackupEnableKey(vmId, fingerprint);
|
|
|
automaticBackupSaving = true;
|
|
|
automaticBackupError();
|
|
|
renderAutomaticBackup(vmId, automaticBackupPayload);
|
|
|
try {
|
|
|
await api(`/api/v1/vms/${encodeURIComponent(vmId)}/automatic-backup/enable`, {
|
|
|
method: 'POST',
|
|
|
headers: { 'Idempotency-Key': idempotencyKey },
|
|
|
body: {
|
|
|
expected_amount: expectedAmount,
|
|
|
expected_state_revision: stateRevision,
|
|
|
},
|
|
|
});
|
|
|
clearPendingAutomaticBackupEnableKey(vmId);
|
|
|
await loadAutomaticBackup(vmId, true);
|
|
|
toast(freeForPaidPeriod ? t('instance_detail.backup.notice.reenabled') : t('instance_detail.backup.notice.enabled_and_charged'), 'success');
|
|
|
} catch (error) {
|
|
|
const uncertain = firewallTransportUncertain(error);
|
|
|
if (!uncertain) clearPendingAutomaticBackupEnableKey(vmId);
|
|
|
automaticBackupError(t('instance_detail.backup.error.enable_failed'));
|
|
|
if (uncertain) {
|
|
|
automaticBackupStatus(t('instance_detail.task.error.uncertain_no_other_action'), 'warning');
|
|
|
} else {
|
|
|
await loadAutomaticBackup(vmId, true).catch(() => null);
|
|
|
}
|
|
|
} finally {
|
|
|
automaticBackupSaving = false;
|
|
|
if (automaticBackupPayload) renderAutomaticBackup(vmId, automaticBackupPayload);
|
|
|
}
|
|
|
});
|
|
|
byId('vm-automatic-backup-disable')?.addEventListener('click', async () => {
|
|
|
const billing = automaticBackupBilling();
|
|
|
if (automaticBackupSaving || automaticBackupRestoring || instanceOperationBusy()
|
|
|
|| billing?.can_disable !== true || !automaticBackupEnabled()) return;
|
|
|
const confirmed = await requestUserConfirmation({
|
|
|
title: t('instance_detail.backup.dialog.disable_title'),
|
|
|
message: t('instance_detail.backup.notice.disable_billing_consequences'),
|
|
|
confirmText: t('instance_detail.backup.action.confirm_disable'),
|
|
|
tone: 'danger',
|
|
|
});
|
|
|
if (!confirmed) return;
|
|
|
automaticBackupSaving = true;
|
|
|
automaticBackupError();
|
|
|
renderAutomaticBackup(vmId, automaticBackupPayload);
|
|
|
try {
|
|
|
await api(`/api/v1/vms/${encodeURIComponent(vmId)}/automatic-backup/disable`, {
|
|
|
method: 'POST', body: {},
|
|
|
});
|
|
|
await loadAutomaticBackup(vmId, true);
|
|
|
toast(t('instance_detail.backup.notice.disabled_no_renewal'), 'success');
|
|
|
} catch (error) {
|
|
|
automaticBackupError(t('instance_detail.backup.error.disable_failed'));
|
|
|
await loadAutomaticBackup(vmId, true).catch(() => null);
|
|
|
} finally {
|
|
|
automaticBackupSaving = false;
|
|
|
if (automaticBackupPayload) renderAutomaticBackup(vmId, automaticBackupPayload);
|
|
|
}
|
|
|
});
|
|
|
form.elements.frequency.addEventListener('change', () => {
|
|
|
byId('vm-automatic-backup-weekday-field').hidden = form.elements.frequency.value !== 'weekly';
|
|
|
});
|
|
|
form.addEventListener('submit', async event => {
|
|
|
event.preventDefault();
|
|
|
if (automaticBackupSaving || automaticBackupRestoring
|
|
|
|| !automaticBackupPurchased() || !automaticBackupEnabled()
|
|
|
|| instanceOperationBusy()) return;
|
|
|
const frequency = form.elements.frequency.value === 'weekly' ? 'weekly' : 'daily';
|
|
|
const weekday = Math.min(6, Math.max(0, Number(form.elements.weekday.value) || 0));
|
|
|
const retention = Number(form.elements.retention_count.value) === 1 ? 1 : 2;
|
|
|
automaticBackupSaving = true;
|
|
|
let outcome = '';
|
|
|
automaticBackupError();
|
|
|
renderAutomaticBackup(vmId, automaticBackupPayload);
|
|
|
try {
|
|
|
const payload = await api(`/api/v1/vms/${encodeURIComponent(vmId)}/automatic-backup`, {
|
|
|
method: 'PUT', body: { frequency, weekday, retention_count: retention },
|
|
|
});
|
|
|
automaticBackupPayload = {
|
|
|
...automaticBackupPayload,
|
|
|
...(payload && typeof payload === 'object' ? payload : {}),
|
|
|
schedule: payload?.schedule || { frequency, weekday, retention_count: retention },
|
|
|
};
|
|
|
automaticBackupLoadedVmId = String(vmId);
|
|
|
outcome = 'saved';
|
|
|
toast(t('instance_detail.backup.notice.schedule_saved'), 'success');
|
|
|
} catch (error) {
|
|
|
outcome = t('instance_detail.backup.error.schedule_save_failed');
|
|
|
} finally {
|
|
|
automaticBackupSaving = false;
|
|
|
if (automaticBackupPayload) renderAutomaticBackup(vmId, automaticBackupPayload);
|
|
|
if (outcome === 'saved') automaticBackupStatus(t('instance_detail.backup.notice.schedule_saved'), 'success');
|
|
|
else if (outcome) {
|
|
|
automaticBackupError(outcome);
|
|
|
automaticBackupStatus(t('instance_detail.backup.error.schedule_not_saved'), 'error');
|
|
|
}
|
|
|
}
|
|
|
});
|
|
|
}
|
|
|
|
|
|
function ipChangeStatus(message = '', type = '') {
|
|
|
const target = byId('vm-ip-change-status');
|
|
|
if (!target) return;
|
|
|
target.textContent = message;
|
|
|
target.className = `vm-settings-status ${type}`.trim();
|
|
|
target.hidden = !message;
|
|
|
}
|
|
|
|
|
|
function ipChangeError(message = '') {
|
|
|
const target = byId('vm-ip-change-error');
|
|
|
if (!target) return;
|
|
|
target.textContent = message;
|
|
|
target.hidden = !message;
|
|
|
}
|
|
|
|
|
|
function ipChangeMoney(value, currency = 'USD') {
|
|
|
const amount = Number(value);
|
|
|
if (!Number.isFinite(amount) || amount < 0) return '—';
|
|
|
return `${String(currency).toUpperCase() === 'USD' ? '$' : ''}${amount.toFixed(2)}`;
|
|
|
}
|
|
|
|
|
|
function renderIpChangeQuote(payload) {
|
|
|
const checkbox = byId('vm-ip-change-form')?.elements.confirm_purchase;
|
|
|
const submit = byId('vm-ip-change-submit');
|
|
|
if (!checkbox || !submit) return;
|
|
|
byId('vm-ip-change-price').textContent = ipChangeMoney(payload?.price, payload?.currency);
|
|
|
const allowed = payload?.can_change === true && !instanceOperationBusy()
|
|
|
&& !ipChangeSubmitting;
|
|
|
checkbox.disabled = !allowed;
|
|
|
submit.disabled = !allowed || checkbox.checked !== true;
|
|
|
}
|
|
|
|
|
|
async function loadIpChangeQuote(vmId, force = false) {
|
|
|
if (!byId('vm-ip-change-form')) return null;
|
|
|
if (!force && ipChangePayload && ipChangeLoadedVmId === String(vmId)) {
|
|
|
renderIpChangeQuote(ipChangePayload);
|
|
|
return ipChangePayload;
|
|
|
}
|
|
|
if (ipChangeRequest) return ipChangeRequest;
|
|
|
ipChangeStatus(t('instance_detail.public_ip_change.status.loading_price'));
|
|
|
ipChangeError();
|
|
|
ipChangeRequest = (async () => {
|
|
|
try {
|
|
|
const payload = await api(`/api/v1/vms/${encodeURIComponent(vmId)}/network-options`);
|
|
|
if (!payload || typeof payload !== 'object' || Array.isArray(payload)
|
|
|
|| payload.address_family !== 4 || typeof payload.price !== 'string') {
|
|
|
throw new Error(t('instance_detail.public_ip_change.error.config_response_invalid'));
|
|
|
}
|
|
|
ipChangePayload = payload;
|
|
|
ipChangeLoadedVmId = String(vmId);
|
|
|
renderIpChangeQuote(payload);
|
|
|
if (payload.can_change === true) {
|
|
|
ipChangeStatus(t('instance_detail.ip_change.price', { amount: ipChangeMoney(payload.price, payload.currency) }), 'success');
|
|
|
} else {
|
|
|
ipChangeStatus(payload.active_job
|
|
|
? t('instance_detail.task.error.operation_in_progress')
|
|
|
: t('instance_detail.public_ip_change.error.unavailable'), 'warning');
|
|
|
}
|
|
|
return payload;
|
|
|
} catch (error) {
|
|
|
ipChangePayload = null;
|
|
|
ipChangeLoadedVmId = null;
|
|
|
renderIpChangeQuote({ price: '0.00' });
|
|
|
ipChangeStatus(t('instance_detail.public_ip_change.error.config_load_failed'), 'error');
|
|
|
throw error;
|
|
|
} finally {
|
|
|
ipChangeRequest = null;
|
|
|
}
|
|
|
})();
|
|
|
return ipChangeRequest;
|
|
|
}
|
|
|
|
|
|
function ipChangeStorageKey(vmId) {
|
|
|
return `virt-cloud:pending-ip-change:${state.userId || 'unknown'}:${vmId}`;
|
|
|
}
|
|
|
|
|
|
function pendingIpChangeKey(vmId, fingerprint) {
|
|
|
let saved = null;
|
|
|
try { saved = JSON.parse(sessionStorage.getItem(ipChangeStorageKey(vmId)) || 'null'); } catch {}
|
|
|
const key = saved?.fingerprint === fingerprint
|
|
|
&& /^[A-Za-z0-9_.-]{16,128}$/.test(String(saved?.key || ''))
|
|
|
? String(saved.key) : firewallIdempotencyKey();
|
|
|
try { sessionStorage.setItem(ipChangeStorageKey(vmId), JSON.stringify({ fingerprint, key })); } catch {}
|
|
|
return key;
|
|
|
}
|
|
|
|
|
|
function clearPendingIpChangeKey(vmId) {
|
|
|
try { sessionStorage.removeItem(ipChangeStorageKey(vmId)); } catch {}
|
|
|
}
|
|
|
|
|
|
function pollIpChangeJob(vmId, receipt) {
|
|
|
return watchTask(receipt, t('instance_detail.public_ip_change.action.open'), {
|
|
|
onUpdate: () => ipChangeStatus(t('instance_detail.public_ip_change.notice.running_charged')),
|
|
|
onTerminal: task => {
|
|
|
void (async () => {
|
|
|
await refreshMetadataAndStatus(vmId, false, true, true);
|
|
|
await loadIpChangeQuote(vmId, true).catch(() => null);
|
|
|
if (taskSucceededWithoutRecovery(task)) {
|
|
|
ipChangeStatus(t('instance_detail.public_ip_change.notice.completed_ipv6_unchanged'), 'success');
|
|
|
toast(t('instance_detail.public_ip_change.notice.completed'), 'success');
|
|
|
return;
|
|
|
}
|
|
|
const base = taskFailureMessage(task, t('instance_detail.public_ip_change.error.task_failed'));
|
|
|
if (task.effect_resolution === 'not_applied') {
|
|
|
ipChangeStatus(t('instance_detail.ip_change.refunded', { message: base }), 'error');
|
|
|
} else if (task.effect_resolution === 'applied') {
|
|
|
ipChangeStatus(t('instance_detail.ip_change.applied', { message: base }), 'warning');
|
|
|
} else {
|
|
|
ipChangeStatus(t('instance_detail.ip_change.reconciling', { message: base }), 'warning');
|
|
|
}
|
|
|
})();
|
|
|
},
|
|
|
onStop: reason => {
|
|
|
if (reason === 'pagehide') return;
|
|
|
ipChangeStatus(t('instance_detail.task.error.observer_stopped_no_resubmit'), 'warning');
|
|
|
},
|
|
|
});
|
|
|
}
|
|
|
|
|
|
function bindIpChange(vmId) {
|
|
|
const form = byId('vm-ip-change-form');
|
|
|
const checkbox = form?.elements.confirm_purchase;
|
|
|
const submit = byId('vm-ip-change-submit');
|
|
|
if (!form || !checkbox || !submit) return;
|
|
|
const sync = () => {
|
|
|
const allowed = ipChangePayload?.can_change === true && !instanceOperationBusy()
|
|
|
&& !ipChangeSubmitting;
|
|
|
submit.disabled = !allowed || checkbox.checked !== true;
|
|
|
};
|
|
|
checkbox.addEventListener('change', sync);
|
|
|
form.addEventListener('submit', async event => {
|
|
|
event.preventDefault();
|
|
|
if (instanceOperationBusy() || ipChangeSubmitting
|
|
|
|| ipChangePayload?.can_change !== true) return;
|
|
|
const expectedAmount = String(ipChangePayload.price || '');
|
|
|
if (!checkbox.checked) {
|
|
|
ipChangeError(t('instance_detail.upgrade.validation.confirm_charge_restart'));
|
|
|
return;
|
|
|
}
|
|
|
const confirmed = await requestUserConfirmation({
|
|
|
title: t('instance_detail.public_ip_change.dialog.title'),
|
|
|
message: t('instance_detail.ip_change.confirm_body', { amount: ipChangeMoney(expectedAmount, ipChangePayload.currency) }),
|
|
|
confirmText: t('instance_detail.public_ip_change.action.confirm_charge'),
|
|
|
tone: 'danger',
|
|
|
});
|
|
|
if (!confirmed) return;
|
|
|
const fingerprint = `automatic|${expectedAmount}`;
|
|
|
const idempotencyKey = pendingIpChangeKey(vmId, fingerprint);
|
|
|
ipChangeSubmitting = true;
|
|
|
ipChangeError();
|
|
|
renderIpChangeQuote(ipChangePayload);
|
|
|
submit.textContent = t('instance_detail.form.status.submitting');
|
|
|
try {
|
|
|
const receipt = await api(`/api/v1/vms/${encodeURIComponent(vmId)}/network`, {
|
|
|
method: 'POST',
|
|
|
headers: { 'Idempotency-Key': idempotencyKey },
|
|
|
expectedStatus: 202,
|
|
|
requireTaskReceipt: true,
|
|
|
body: {
|
|
|
expected_amount: expectedAmount,
|
|
|
confirm_restart: true,
|
|
|
},
|
|
|
});
|
|
|
clearPendingIpChangeKey(vmId);
|
|
|
checkbox.checked = false;
|
|
|
ipChangePayload = {
|
|
|
...ipChangePayload,
|
|
|
can_change: false,
|
|
|
};
|
|
|
renderIpChangeQuote(ipChangePayload);
|
|
|
ipChangeStatus(t('instance_detail.ip_change.accepted', { amount: ipChangeMoney(expectedAmount, ipChangePayload.currency) }));
|
|
|
toast(t('instance_detail.public_ip_change.notice.task_accepted'), 'success');
|
|
|
if (!pollIpChangeJob(vmId, receipt)) {
|
|
|
ipChangeStatus(t('instance_detail.task.error.invalid_observer_protocol'), 'error');
|
|
|
}
|
|
|
} catch (error) {
|
|
|
const uncertain = firewallTransportUncertain(error);
|
|
|
const message = t('instance_detail.public_ip_change.error.submit_failed');
|
|
|
if (uncertain) {
|
|
|
ipChangeError(message);
|
|
|
ipChangeStatus(t('instance_detail.public_ip_change.error.uncertain_reconcile_same_request'), 'warning');
|
|
|
} else {
|
|
|
clearPendingIpChangeKey(vmId);
|
|
|
await loadIpChangeQuote(vmId, true).catch(() => null);
|
|
|
ipChangeError(message);
|
|
|
ipChangeStatus(t('instance_detail.public_ip_change.error.validation_failed'), 'error');
|
|
|
}
|
|
|
} finally {
|
|
|
ipChangeSubmitting = false;
|
|
|
submit.textContent = t('instance_detail.public_ip_change.dialog.confirm_paid_action');
|
|
|
if (ipChangePayload) renderIpChangeQuote(ipChangePayload);
|
|
|
}
|
|
|
});
|
|
|
}
|
|
|
|
|
|
function upgradeStatus(message = '', type = '') {
|
|
|
const target = byId('vm-upgrade-status');
|
|
|
if (!target) return;
|
|
|
target.textContent = message;
|
|
|
target.className = `vm-settings-status ${type}`.trim();
|
|
|
target.hidden = !message;
|
|
|
}
|
|
|
|
|
|
function upgradeError(message = '') {
|
|
|
const target = byId('vm-upgrade-error');
|
|
|
if (!target) return;
|
|
|
target.textContent = message;
|
|
|
target.hidden = !message;
|
|
|
}
|
|
|
|
|
|
function upgradeElement(tag, className = '', value = '') {
|
|
|
const element = document.createElement(tag);
|
|
|
if (className) element.className = className;
|
|
|
if (value !== '') element.textContent = String(value);
|
|
|
return element;
|
|
|
}
|
|
|
|
|
|
function upgradePositiveInteger(value, allowZero = false) {
|
|
|
const number = Number(value);
|
|
|
if (!Number.isSafeInteger(number) || number < (allowZero ? 0 : 1)) return null;
|
|
|
return number;
|
|
|
}
|
|
|
|
|
|
function upgradeAmount(value) {
|
|
|
const amount = typeof value === 'string' ? value.trim() : '';
|
|
|
return /^(?:0|[1-9][0-9]{0,9})\.[0-9]{2}$/.test(amount) ? amount : '';
|
|
|
}
|
|
|
|
|
|
function upgradeMoney(value, currency = 'USD') {
|
|
|
const amount = upgradeAmount(value);
|
|
|
if (!amount) return '—';
|
|
|
const code = /^[A-Z]{3}$/.test(String(currency || '').toUpperCase())
|
|
|
? String(currency).toUpperCase() : 'USD';
|
|
|
return `${code === 'USD' ? '$' : ''}${amount} ${code}`;
|
|
|
}
|
|
|
|
|
|
function upgradeMemory(value) {
|
|
|
const amount = upgradePositiveInteger(value);
|
|
|
if (amount === null) return '—';
|
|
|
return `${i18n.number(amount / 1024, { maximumFractionDigits: 1 })} GB`;
|
|
|
}
|
|
|
|
|
|
function upgradeTraffic(value) {
|
|
|
let amount = upgradePositiveInteger(value, true);
|
|
|
if (amount === null) return '—';
|
|
|
if (amount === 0) return t('instance_detail.value.unlimited');
|
|
|
const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'];
|
|
|
let unit = 0;
|
|
|
while (amount >= 1024 && unit < units.length - 1) {
|
|
|
amount /= 1024;
|
|
|
unit += 1;
|
|
|
}
|
|
|
const precision = amount >= 100 || unit === 0 ? 0 : amount >= 10 ? 1 : 2;
|
|
|
return `${amount.toFixed(precision)} ${units[unit]}`;
|
|
|
}
|
|
|
|
|
|
function normalizeUpgradeOffer(value) {
|
|
|
if (!value || typeof value !== 'object' || Array.isArray(value)
|
|
|
|| UPGRADE_OFFER_FIELDS.some(field => !Object.prototype.hasOwnProperty.call(value, field))) {
|
|
|
return null;
|
|
|
}
|
|
|
const offerId = upgradePositiveInteger(value.offer_id);
|
|
|
const name = typeof value.name === 'string' ? value.name.trim() : '';
|
|
|
const cpu = upgradePositiveInteger(value.cpu_cores);
|
|
|
const memory = upgradePositiveInteger(value.memory_mib);
|
|
|
const disk = upgradePositiveInteger(value.disk_gib);
|
|
|
const bandwidth = upgradePositiveInteger(value.bandwidth_mbps);
|
|
|
const traffic = upgradePositiveInteger(value.traffic_quota_bytes, true);
|
|
|
const validityDays = upgradePositiveInteger(value.validity_days);
|
|
|
const amount = upgradeAmount(value.amount);
|
|
|
const renewalPrice = upgradeAmount(value.renewal_price);
|
|
|
const currency = String(value.currency || '').trim().toUpperCase();
|
|
|
if (offerId === null || !name || cpu === null || memory === null || disk === null
|
|
|
|| bandwidth === null || traffic === null || validityDays === null
|
|
|
|| !amount || !renewalPrice || !/^[A-Z]{3}$/.test(currency)) {
|
|
|
return null;
|
|
|
}
|
|
|
return {
|
|
|
offer_id: offerId,
|
|
|
name,
|
|
|
cpu_cores: cpu,
|
|
|
memory_mib: memory,
|
|
|
disk_gib: disk,
|
|
|
bandwidth_mbps: bandwidth,
|
|
|
traffic_quota_bytes: traffic,
|
|
|
validity_days: validityDays,
|
|
|
amount,
|
|
|
renewal_price: renewalPrice,
|
|
|
currency,
|
|
|
};
|
|
|
}
|
|
|
|
|
|
function upgradeVmStateAllowsAutomaticRestart() {
|
|
|
const vm = selectedVm();
|
|
|
if (!vm || instanceOperationBusy(vm)) return false;
|
|
|
return ['running', 'blocked', 'shutoff', 'stopped', 'crashed'].includes(
|
|
|
String(vm.state || '').trim().toLowerCase()
|
|
|
);
|
|
|
}
|
|
|
|
|
|
function renderUpgradeCurrent(current = {}) {
|
|
|
const vm = selectedVm() || {};
|
|
|
const values = {
|
|
|
name: String(current.name || current.plan_name || vm.plan_name || t('instance_detail.upgrade.field.current_plan')),
|
|
|
cpu_cores: (() => {
|
|
|
const value = upgradePositiveInteger(current.cpu_cores ?? current.vcpu ?? vm.cpu_cores ?? vm.vcpu);
|
|
|
return value === null ? '—' : `${value} vCPU`;
|
|
|
})(),
|
|
|
memory_mib: upgradeMemory(current.memory_mib ?? vm.memory_mib),
|
|
|
disk_gib: (() => {
|
|
|
const value = Number(current.disk_gib ?? vm.disk_gib);
|
|
|
return Number.isFinite(value) && value > 0 ? `${value} GB` : '—';
|
|
|
})(),
|
|
|
bandwidth_mbps: (() => {
|
|
|
const value = upgradePositiveInteger(current.bandwidth_mbps ?? vm.bandwidth_mbps);
|
|
|
return value === null ? '—' : `${value} Mbps`;
|
|
|
})(),
|
|
|
traffic_quota_bytes: upgradeTraffic(
|
|
|
current.traffic_quota_bytes ?? vm.traffic_quota_bytes
|
|
|
),
|
|
|
};
|
|
|
document.querySelectorAll('[data-upgrade-current]').forEach(element => {
|
|
|
element.textContent = values[element.dataset.upgradeCurrent] || '—';
|
|
|
});
|
|
|
}
|
|
|
|
|
|
function upgradeControlsAllowed() {
|
|
|
if (upgradePayload?.can_upgrade !== true || !upgradeVmStateAllowsAutomaticRestart()
|
|
|
|| upgradeSubmitting || !Array.isArray(upgradePayload?.offers)
|
|
|
|| upgradePayload.offers.length === 0) return false;
|
|
|
if (!upgradePendingFingerprint) return true;
|
|
|
const selected = upgradePayload.offers.find(
|
|
|
offer => String(offer.offer_id) === upgradeSelectedOfferId
|
|
|
);
|
|
|
return selected !== undefined
|
|
|
&& `${selected.offer_id}|${selected.amount}` === upgradePendingFingerprint;
|
|
|
}
|
|
|
|
|
|
function syncUpgradeControls() {
|
|
|
const form = byId('vm-upgrade-form');
|
|
|
const checkbox = form?.elements.confirm_upgrade;
|
|
|
const submit = byId('vm-upgrade-submit');
|
|
|
const hidden = byId('vm-upgrade-offer-id');
|
|
|
if (!checkbox || !submit || !hidden) return;
|
|
|
const selected = upgradePayload?.offers?.find(
|
|
|
offer => String(offer.offer_id) === upgradeSelectedOfferId
|
|
|
) || null;
|
|
|
const allowed = upgradeControlsAllowed() && selected !== null;
|
|
|
hidden.value = selected ? String(selected.offer_id) : '';
|
|
|
checkbox.disabled = !allowed;
|
|
|
if (!allowed) checkbox.checked = false;
|
|
|
submit.disabled = !allowed || checkbox.checked !== true;
|
|
|
byId('vm-upgrade-offers')?.querySelectorAll('[data-upgrade-offer-id]').forEach(button => {
|
|
|
const active = selected !== null
|
|
|
&& button.dataset.upgradeOfferId === String(selected.offer_id);
|
|
|
button.setAttribute('aria-checked', String(active));
|
|
|
button.setAttribute('aria-pressed', String(active));
|
|
|
});
|
|
|
}
|
|
|
|
|
|
function renderUpgradeOptions(payload) {
|
|
|
const container = byId('vm-upgrade-offers');
|
|
|
if (!container) return;
|
|
|
renderUpgradeCurrent(payload?.current || {});
|
|
|
const offers = Array.isArray(payload?.offers) ? payload.offers : [];
|
|
|
if (!offers.some(offer => String(offer.offer_id) === upgradeSelectedOfferId)) {
|
|
|
upgradeSelectedOfferId = '';
|
|
|
}
|
|
|
const allowed = payload?.can_upgrade === true && upgradeVmStateAllowsAutomaticRestart()
|
|
|
&& !upgradeSubmitting && !upgradePendingFingerprint;
|
|
|
const rows = offers.map(offer => {
|
|
|
const button = upgradeElement('button', 'vm-upgrade-offer');
|
|
|
button.type = 'button';
|
|
|
button.setAttribute('role', 'radio');
|
|
|
button.dataset.upgradeOfferId = String(offer.offer_id);
|
|
|
button.disabled = !allowed;
|
|
|
button.setAttribute('aria-disabled', String(!allowed));
|
|
|
button.setAttribute('aria-checked', String(upgradeSelectedOfferId === String(offer.offer_id)));
|
|
|
button.setAttribute('aria-pressed', String(upgradeSelectedOfferId === String(offer.offer_id)));
|
|
|
button.setAttribute('aria-label', t('instance_detail.upgrade.offer_aria', { name: offer.name, cpu: offer.cpu_cores, memory: upgradeMemory(offer.memory_mib), disk: offer.disk_gib, bandwidth: offer.bandwidth_mbps, traffic: upgradeTraffic(offer.traffic_quota_bytes), amount: upgradeMoney(offer.amount, offer.currency), days: offer.validity_days, renewal: upgradeMoney(offer.renewal_price, offer.currency) }));
|
|
|
const heading = upgradeElement('span', 'vm-upgrade-offer-heading');
|
|
|
heading.append(
|
|
|
upgradeElement('strong', 'vm-upgrade-offer-name', offer.name),
|
|
|
upgradeElement('strong', 'vm-upgrade-offer-price', t('instance_detail.upgrade.current_price', { amount: upgradeMoney(offer.amount, offer.currency) })),
|
|
|
);
|
|
|
const facts = upgradeElement('span', 'vm-upgrade-offer-facts');
|
|
|
const fact = (label, value) => {
|
|
|
const item = upgradeElement('span', 'vm-upgrade-offer-fact');
|
|
|
item.append(upgradeElement('small', '', label), upgradeElement('b', '', value));
|
|
|
return item;
|
|
|
};
|
|
|
facts.append(
|
|
|
fact('CPU', `${offer.cpu_cores} vCPU`),
|
|
|
fact(t('instance_detail.upgrade.resource.memory'), upgradeMemory(offer.memory_mib)),
|
|
|
fact(t('instance_detail.storage.system_disk'), `${offer.disk_gib} GB`),
|
|
|
fact(t('instance_detail.upgrade.resource.bandwidth'), `${offer.bandwidth_mbps} Mbps`),
|
|
|
fact(t('instance_detail.traffic.period_quota'), upgradeTraffic(offer.traffic_quota_bytes)),
|
|
|
fact(t('instance_detail.upgrade.renewal_days', { days: offer.validity_days }), upgradeMoney(offer.renewal_price, offer.currency)),
|
|
|
);
|
|
|
button.append(heading, facts);
|
|
|
if (allowed) {
|
|
|
button.addEventListener('click', () => {
|
|
|
upgradeSelectedOfferId = String(offer.offer_id);
|
|
|
upgradeError();
|
|
|
syncUpgradeControls();
|
|
|
});
|
|
|
}
|
|
|
return button;
|
|
|
});
|
|
|
if (!rows.length) {
|
|
|
rows.push(upgradeElement('p', 'vm-upgrade-empty', t('instance_detail.upgrade.empty.no_available_plan')));
|
|
|
}
|
|
|
container.replaceChildren(...rows);
|
|
|
container.setAttribute('aria-busy', 'false');
|
|
|
syncUpgradeControls();
|
|
|
}
|
|
|
|
|
|
async function loadUpgradeOptions(vmId, force = false) {
|
|
|
if (!byId('vm-upgrade-form')) return null;
|
|
|
if (!force && upgradePayload && upgradeLoadedVmId === String(vmId)) {
|
|
|
renderUpgradeOptions(upgradePayload);
|
|
|
if (!upgradeVmStateAllowsAutomaticRestart()) {
|
|
|
upgradeStatus(t('instance_detail.upgrade.error.instance_busy_or_power_unknown'), 'warning');
|
|
|
} else if (upgradePendingFingerprint) {
|
|
|
upgradeStatus(t('instance_detail.upgrade.error.previous_uncertain_original_plan_only'), 'warning');
|
|
|
} else if (upgradePayload.can_upgrade === true && upgradePayload.offers.length > 0) {
|
|
|
upgradeStatus(t('instance_detail.upgrade.validation.select_target_plan'), 'success');
|
|
|
} else {
|
|
|
upgradeStatus(upgradePayload.offers.length === 0
|
|
|
? t('instance_detail.upgrade.empty.no_available_plan')
|
|
|
: t('instance_detail.upgrade.error.unavailable'), 'warning');
|
|
|
}
|
|
|
return upgradePayload;
|
|
|
}
|
|
|
if (upgradeRequest) return upgradeRequest;
|
|
|
byId('vm-upgrade-offers')?.setAttribute('aria-busy', 'true');
|
|
|
upgradeStatus(t('instance_detail.upgrade.status.loading_options'));
|
|
|
upgradeError();
|
|
|
upgradeRequest = (async () => {
|
|
|
try {
|
|
|
const payload = await api(`/api/v1/vms/${encodeURIComponent(vmId)}/upgrade-options`);
|
|
|
if (!payload || typeof payload !== 'object' || Array.isArray(payload)
|
|
|
|| !payload.current || typeof payload.current !== 'object'
|
|
|
|| Array.isArray(payload.current) || !Array.isArray(payload.offers)
|
|
|
|| typeof payload.can_upgrade !== 'boolean') {
|
|
|
throw new Error(t('instance_detail.upgrade.error.options_response_invalid'));
|
|
|
}
|
|
|
const offers = payload.offers.map(normalizeUpgradeOffer);
|
|
|
if (offers.some(offer => offer === null)) {
|
|
|
throw new Error(t('instance_detail.upgrade.error.plan_response_invalid'));
|
|
|
}
|
|
|
upgradePayload = { ...payload, offers };
|
|
|
upgradeLoadedVmId = String(vmId);
|
|
|
restorePendingUpgradeSelection(vmId);
|
|
|
renderUpgradeOptions(upgradePayload);
|
|
|
if (!upgradeVmStateAllowsAutomaticRestart()) {
|
|
|
upgradeStatus(t('instance_detail.upgrade.error.instance_busy_or_power_unknown'), 'warning');
|
|
|
} else if (upgradePendingFingerprint) {
|
|
|
upgradeStatus(t('instance_detail.upgrade.error.previous_uncertain_original_plan_only'), 'warning');
|
|
|
} else if (payload.can_upgrade === true && offers.length > 0) {
|
|
|
upgradeStatus(t('instance_detail.upgrade.validation.select_target_plan'), 'success');
|
|
|
} else {
|
|
|
upgradeStatus(offers.length === 0
|
|
|
? t('instance_detail.upgrade.empty.no_available_plan')
|
|
|
: t('instance_detail.upgrade.error.unavailable'), 'warning');
|
|
|
}
|
|
|
return upgradePayload;
|
|
|
} catch (error) {
|
|
|
upgradePayload = null;
|
|
|
upgradeLoadedVmId = null;
|
|
|
upgradeSelectedOfferId = '';
|
|
|
renderUpgradeCurrent({});
|
|
|
const container = byId('vm-upgrade-offers');
|
|
|
if (container) {
|
|
|
container.setAttribute('aria-busy', 'false');
|
|
|
container.replaceChildren(upgradeElement('p', 'vm-upgrade-empty',
|
|
|
t('instance_detail.upgrade.error.plan_load_failed')));
|
|
|
}
|
|
|
syncUpgradeControls();
|
|
|
upgradeStatus(t('instance_detail.upgrade.error.config_load_failed'), 'error');
|
|
|
throw error;
|
|
|
} finally {
|
|
|
upgradeRequest = null;
|
|
|
}
|
|
|
})();
|
|
|
return upgradeRequest;
|
|
|
}
|
|
|
|
|
|
function upgradeStorageKey(vmId) {
|
|
|
return `virt-cloud:pending-upgrade:${state.userId || 'unknown'}:${vmId}`;
|
|
|
}
|
|
|
|
|
|
function restorePendingUpgradeSelection(vmId) {
|
|
|
let saved = null;
|
|
|
try { saved = JSON.parse(sessionStorage.getItem(upgradeStorageKey(vmId)) || 'null'); } catch {}
|
|
|
const fingerprint = typeof saved?.fingerprint === 'string' ? saved.fingerprint : '';
|
|
|
const key = String(saved?.key || '');
|
|
|
if (!/^[1-9][0-9]*\|(?:0|[1-9][0-9]{0,9})\.[0-9]{2}$/.test(fingerprint)
|
|
|
|| !/^[A-Za-z0-9_.-]{16,128}$/.test(key)) return;
|
|
|
const [offerId] = fingerprint.split('|', 1);
|
|
|
if (String(upgradePayload?.current?.offer_id || '') === offerId) {
|
|
|
clearPendingUpgradeKey(vmId);
|
|
|
upgradeSelectedOfferId = '';
|
|
|
return;
|
|
|
}
|
|
|
upgradePendingFingerprint = fingerprint;
|
|
|
if (upgradePayload?.offers?.some(offer => String(offer.offer_id) === offerId)) {
|
|
|
upgradeSelectedOfferId = offerId;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function pendingUpgradeKey(vmId, fingerprint) {
|
|
|
let saved = null;
|
|
|
try { saved = JSON.parse(sessionStorage.getItem(upgradeStorageKey(vmId)) || 'null'); } catch {}
|
|
|
const key = saved?.fingerprint === fingerprint
|
|
|
&& /^[A-Za-z0-9_.-]{16,128}$/.test(String(saved?.key || ''))
|
|
|
? String(saved.key) : firewallIdempotencyKey();
|
|
|
try { sessionStorage.setItem(upgradeStorageKey(vmId), JSON.stringify({ fingerprint, key })); } catch {}
|
|
|
return key;
|
|
|
}
|
|
|
|
|
|
function clearPendingUpgradeKey(vmId) {
|
|
|
try { sessionStorage.removeItem(upgradeStorageKey(vmId)); } catch {}
|
|
|
upgradePendingFingerprint = '';
|
|
|
}
|
|
|
|
|
|
function pollInstanceUpgrade(vmId, receipt) {
|
|
|
return watchTask(receipt, t('instance_detail.upgrade.action.open'), {
|
|
|
onUpdate: () => upgradeStatus(t('instance_detail.upgrade.notice.running')),
|
|
|
onTerminal: task => {
|
|
|
void (async () => {
|
|
|
await refreshMetadataAndStatus(vmId, false, true, true);
|
|
|
clearPendingUpgradeKey(vmId);
|
|
|
await loadUpgradeOptions(vmId, true).catch(() => null);
|
|
|
if (taskSucceededWithoutRecovery(task)) {
|
|
|
upgradeStatus(t('instance_detail.upgrade.notice.completed_expand_disk'), 'success');
|
|
|
toast(t('instance_detail.upgrade.notice.completed'), 'success');
|
|
|
return;
|
|
|
}
|
|
|
const message = taskFailureMessage(task, t('instance_detail.upgrade.error.task_failed'));
|
|
|
if (task.effect_resolution === 'not_applied') {
|
|
|
upgradeStatus(t('instance_detail.upgrade.not_applied', { message }), 'error');
|
|
|
} else if (task.effect_resolution === 'applied') {
|
|
|
upgradeStatus(t('instance_detail.upgrade.applied', { message }), 'warning');
|
|
|
} else {
|
|
|
upgradeStatus(t('instance_detail.upgrade.reconciling', { message }), 'warning');
|
|
|
}
|
|
|
})();
|
|
|
},
|
|
|
onStop: reason => {
|
|
|
if (reason === 'pagehide') return;
|
|
|
upgradeStatus(t('instance_detail.task.error.observer_stopped_final_unknown'), 'warning');
|
|
|
},
|
|
|
});
|
|
|
}
|
|
|
|
|
|
function bindInstanceUpgrade(vmId) {
|
|
|
const form = byId('vm-upgrade-form');
|
|
|
const checkbox = form?.elements.confirm_upgrade;
|
|
|
const submit = byId('vm-upgrade-submit');
|
|
|
if (!form || !checkbox || !submit) return;
|
|
|
checkbox.addEventListener('change', syncUpgradeControls);
|
|
|
form.addEventListener('submit', async event => {
|
|
|
event.preventDefault();
|
|
|
if (upgradeSubmitting) return;
|
|
|
const selectedOffer = upgradePayload?.offers?.find(
|
|
|
offer => String(offer.offer_id) === upgradeSelectedOfferId
|
|
|
);
|
|
|
if (!upgradeVmStateAllowsAutomaticRestart()) {
|
|
|
upgradeError(t('instance_detail.operation.error.busy_or_power_unknown'));
|
|
|
upgradeStatus(t('instance_detail.upgrade.error.unsafe_power_state'), 'warning');
|
|
|
return;
|
|
|
}
|
|
|
if (upgradePayload?.can_upgrade !== true || !selectedOffer) {
|
|
|
upgradeError(t('instance_detail.upgrade.validation.available_plan_required'));
|
|
|
return;
|
|
|
}
|
|
|
if (!checkbox.checked) {
|
|
|
upgradeError(t('instance_detail.upgrade.validation.authorize_shutdown_charge'));
|
|
|
return;
|
|
|
}
|
|
|
const confirmed = await requestUserConfirmation({
|
|
|
title: t('instance_detail.upgrade.dialog.confirm_title'),
|
|
|
message: t('instance_detail.upgrade.confirm_body', { name: selectedOffer.name, amount: upgradeMoney(selectedOffer.amount, selectedOffer.currency), days: selectedOffer.validity_days, renewal: upgradeMoney(selectedOffer.renewal_price, selectedOffer.currency) }),
|
|
|
confirmText: t('instance_detail.upgrade.dialog.confirm_paid_title'),
|
|
|
tone: 'danger',
|
|
|
});
|
|
|
if (!confirmed) return;
|
|
|
const fingerprint = `${selectedOffer.offer_id}|${selectedOffer.amount}`;
|
|
|
if (upgradePendingFingerprint && upgradePendingFingerprint !== fingerprint) {
|
|
|
upgradeError(t('instance_detail.upgrade.error.previous_uncertain_plan_locked'));
|
|
|
return;
|
|
|
}
|
|
|
const idempotencyKey = pendingUpgradeKey(vmId, fingerprint);
|
|
|
upgradeSubmitting = true;
|
|
|
upgradeError();
|
|
|
renderUpgradeOptions(upgradePayload);
|
|
|
submit.textContent = t('instance_detail.form.status.submitting');
|
|
|
try {
|
|
|
const receipt = await api(`/api/v1/vms/${encodeURIComponent(vmId)}/upgrade`, {
|
|
|
method: 'POST',
|
|
|
headers: { 'Idempotency-Key': idempotencyKey },
|
|
|
expectedStatus: 202,
|
|
|
requireTaskReceipt: true,
|
|
|
body: {
|
|
|
offer_id: selectedOffer.offer_id,
|
|
|
expected_amount: selectedOffer.amount,
|
|
|
confirm_shutdown: true,
|
|
|
},
|
|
|
});
|
|
|
clearPendingUpgradeKey(vmId);
|
|
|
checkbox.checked = false;
|
|
|
upgradePayload = { ...upgradePayload, can_upgrade: false };
|
|
|
const vm = selectedVm();
|
|
|
if (vm) {
|
|
|
vm.state_transitioning = true;
|
|
|
vm.state_transition = 'upgrade';
|
|
|
vm.operation_transition = 'upgrade';
|
|
|
renderVmDetail(vm);
|
|
|
}
|
|
|
renderUpgradeOptions(upgradePayload);
|
|
|
upgradeStatus(t('instance_detail.upgrade.notice.task_accepted_with_restart'));
|
|
|
toast(t('instance_detail.upgrade.notice.task_accepted'), 'success');
|
|
|
if (!pollInstanceUpgrade(vmId, receipt)) {
|
|
|
upgradeStatus(t('instance_detail.task.error.invalid_observer_protocol'), 'error');
|
|
|
}
|
|
|
} catch (error) {
|
|
|
const uncertain = firewallTransportUncertain(error);
|
|
|
const message = t('instance_detail.upgrade.error.submit_failed');
|
|
|
if (uncertain) {
|
|
|
upgradePendingFingerprint = fingerprint;
|
|
|
upgradeError(message);
|
|
|
upgradeStatus(t('instance_detail.task.error.uncertain_reconcile_same_request'), 'warning');
|
|
|
} else {
|
|
|
clearPendingUpgradeKey(vmId);
|
|
|
await loadUpgradeOptions(vmId, true).catch(() => null);
|
|
|
upgradeError(message);
|
|
|
upgradeStatus(t('instance_detail.upgrade.error.validation_failed'), 'error');
|
|
|
}
|
|
|
} finally {
|
|
|
upgradeSubmitting = false;
|
|
|
submit.textContent = t('instance_detail.upgrade.dialog.confirm_paid_title');
|
|
|
if (upgradePayload) renderUpgradeOptions(upgradePayload);
|
|
|
}
|
|
|
});
|
|
|
}
|
|
|
|
|
|
function rescueTemplates(payload) {
|
|
|
const source = payload?.rescue_templates;
|
|
|
if (Array.isArray(source)) return source;
|
|
|
if (Array.isArray(source?.items)) return source.items;
|
|
|
if (Array.isArray(source?.templates)) return source.templates;
|
|
|
return [];
|
|
|
}
|
|
|
|
|
|
function rescueError(message = '') {
|
|
|
showError('rescue-error', message);
|
|
|
}
|
|
|
|
|
|
function syncRescueControls() {
|
|
|
const vm = selectedVm();
|
|
|
const allowed = vm?.can_operate === true && !instanceOperationBusy(vm)
|
|
|
&& !rescueSubmitting && rescueStatusReachable;
|
|
|
const checkbox = byId('rescue-confirm-risk');
|
|
|
const submit = byId('rescue-submit');
|
|
|
const force = byId('rescue-force-start');
|
|
|
const exit = byId('rescue-exit');
|
|
|
const confirmed = checkbox?.checked === true;
|
|
|
const templateSelected = (byId('rescue-template-id')?.value || '') !== '';
|
|
|
if (checkbox) checkbox.disabled = !allowed;
|
|
|
if (submit) submit.disabled = !allowed || !confirmed || !templateSelected || state.rescueActive || state.rescueStaged;
|
|
|
if (force) force.disabled = !allowed || !confirmed || !state.rescueStaged;
|
|
|
if (exit) exit.disabled = !allowed || !confirmed || (!state.rescueActive && !state.rescueStaged);
|
|
|
document.querySelectorAll('#rescue-template-cards button').forEach(button => {
|
|
|
button.disabled = !allowed || state.rescueActive || state.rescueStaged;
|
|
|
});
|
|
|
}
|
|
|
|
|
|
function renderRescueStatus(status = {}) {
|
|
|
state.rescueActive = status.active === true || status.rescue_mode === true;
|
|
|
state.rescueStaged = status.staged === true || status.rescue_staged === true;
|
|
|
const target = byId('rescue-status');
|
|
|
if (target) {
|
|
|
target.textContent = state.rescueActive
|
|
|
? t('instance_detail.rescue.status.active')
|
|
|
: state.rescueStaged
|
|
|
? t('instance_detail.rescue.status.premounted')
|
|
|
: t('instance_detail.rescue.status.not_mounted');
|
|
|
}
|
|
|
const force = byId('rescue-force-start');
|
|
|
const exit = byId('rescue-exit');
|
|
|
if (force) force.hidden = !state.rescueStaged;
|
|
|
if (exit) exit.hidden = !state.rescueActive && !state.rescueStaged;
|
|
|
syncRescueControls();
|
|
|
}
|
|
|
|
|
|
function renderRescueTemplates(payload) {
|
|
|
const container = byId('rescue-template-cards');
|
|
|
const input = byId('rescue-template-id');
|
|
|
if (!container || !input) return;
|
|
|
const templates = rescueTemplates(payload);
|
|
|
const catalogStatus = payload?.rescue_catalog_status;
|
|
|
const statusState = typeof catalogStatus?.state === 'string'
|
|
|
? catalogStatus.state : 'unavailable';
|
|
|
const statusMessage = t('instance_detail.rescue.error.catalog_unavailable');
|
|
|
const catalogStatusNode = byId('rescue-catalog-status');
|
|
|
if (catalogStatusNode) {
|
|
|
catalogStatusNode.dataset.state = statusState;
|
|
|
catalogStatusNode.textContent = statusMessage;
|
|
|
}
|
|
|
const selectedId = templates.some(template => String(template.id) === String(input.value))
|
|
|
? String(input.value) : '';
|
|
|
input.value = selectedId;
|
|
|
container.replaceChildren();
|
|
|
for (const template of templates) {
|
|
|
const templateId = String(template.id || '');
|
|
|
if (!templateId) continue;
|
|
|
const button = document.createElement('button');
|
|
|
button.type = 'button';
|
|
|
button.className = 'rescue-template-card';
|
|
|
button.dataset.templateId = templateId;
|
|
|
const symbol = document.createElement('span');
|
|
|
symbol.className = 'rescue-template-symbol';
|
|
|
symbol.textContent = 'ISO';
|
|
|
const name = document.createElement('strong');
|
|
|
name.textContent = String(template.name || t('instance_detail.rescue.image.unnamed'));
|
|
|
const note = document.createElement('small');
|
|
|
note.textContent = t('instance_detail.snapshot.host_verification.exact');
|
|
|
button.append(symbol, name, note);
|
|
|
button.setAttribute('aria-pressed', String(templateId === selectedId));
|
|
|
button.addEventListener('click', () => {
|
|
|
input.value = templateId;
|
|
|
container.querySelectorAll('button').forEach(option => {
|
|
|
option.setAttribute('aria-pressed', String(option === button));
|
|
|
});
|
|
|
rescueError();
|
|
|
syncRescueControls();
|
|
|
});
|
|
|
container.append(button);
|
|
|
}
|
|
|
if (!container.children.length) {
|
|
|
const empty = document.createElement('p');
|
|
|
empty.className = 'muted';
|
|
|
empty.textContent = statusMessage;
|
|
|
container.append(empty);
|
|
|
}
|
|
|
syncRescueControls();
|
|
|
}
|
|
|
|
|
|
async function loadRescue(vmId, force = false) {
|
|
|
if (!byId('rescue-form')) return null;
|
|
|
if (!force && rescueLoadedVmId === String(vmId)) return null;
|
|
|
if (rescueRequest) return rescueRequest;
|
|
|
const status = byId('rescue-status');
|
|
|
if (status) status.textContent = t('instance_detail.rescue.status.checking');
|
|
|
rescueStatusReachable = false;
|
|
|
syncRescueControls();
|
|
|
rescueRequest = (async () => {
|
|
|
try {
|
|
|
const [resourcesResult, statusResult] = await Promise.allSettled([
|
|
|
api(`/api/v1/resources?vm_id=${encodeURIComponent(vmId)}`),
|
|
|
api(`/api/v1/vms/${encodeURIComponent(vmId)}/rescue`),
|
|
|
]);
|
|
|
if (resourcesResult.status !== 'fulfilled') throw resourcesResult.reason;
|
|
|
const resources = resourcesResult.value;
|
|
|
renderRescueTemplates(resources);
|
|
|
if (statusResult.status === 'fulfilled') {
|
|
|
rescueStatusReachable = true;
|
|
|
renderRescueStatus(statusResult.value);
|
|
|
rescueLoadedVmId = String(vmId);
|
|
|
rescueError();
|
|
|
return statusResult.value;
|
|
|
}
|
|
|
rescueStatusReachable = false;
|
|
|
rescueLoadedVmId = null;
|
|
|
if (status) status.textContent = t('instance_detail.rescue.error.state_unknown_disabled');
|
|
|
rescueError(t('instance_detail.error.virtualization_unavailable'));
|
|
|
syncRescueControls();
|
|
|
return null;
|
|
|
} catch (error) {
|
|
|
rescueStatusReachable = false;
|
|
|
rescueLoadedVmId = null;
|
|
|
rescueError(t('instance_detail.rescue.error.status_load_failed_retry'));
|
|
|
if (status) status.textContent = t('instance_detail.rescue.error.status_load_failed');
|
|
|
throw error;
|
|
|
} finally {
|
|
|
rescueRequest = null;
|
|
|
}
|
|
|
})();
|
|
|
return rescueRequest;
|
|
|
}
|
|
|
|
|
|
function rescueAction(vmId, action) {
|
|
|
const vm = selectedVm();
|
|
|
if (!vm || instanceOperationBusy(vm) || rescueSubmitting) return;
|
|
|
const checkbox = byId('rescue-confirm-risk');
|
|
|
const templateId = byId('rescue-template-id')?.value || '';
|
|
|
if (!checkbox?.checked) {
|
|
|
rescueError(t('instance_detail.rescue.validation.risk_ack_required'));
|
|
|
return;
|
|
|
}
|
|
|
if (action === 'load' && !templateId) {
|
|
|
rescueError(t('instance_detail.rescue.validation.image_required'));
|
|
|
return;
|
|
|
}
|
|
|
const labels = { load: t('instance_detail.rescue.section.title'), 'force-start': t('instance_detail.rescue.action.force_enter'), exit: t('instance_detail.rescue.action.exit') };
|
|
|
const title = labels[action] || t('instance_detail.rescue.section.title');
|
|
|
const body = { ack_data_loss: true };
|
|
|
if (action === 'load') body.template_id = templateId;
|
|
|
rescueSubmitting = true;
|
|
|
rescueError();
|
|
|
syncRescueControls();
|
|
|
void (async () => {
|
|
|
try {
|
|
|
const result = await api(`/api/v1/vms/${encodeURIComponent(vmId)}/rescue${action === 'load' ? '' : `/${action}`}`, {
|
|
|
method: 'POST', body, expectedStatus: 202, requireTaskReceipt: true,
|
|
|
});
|
|
|
checkbox.checked = false;
|
|
|
const target = byId('rescue-status');
|
|
|
if (target) target.textContent = t('instance_detail.task.notice.accepted_background');
|
|
|
const observer = watchTask(result, title, {
|
|
|
onTerminal: task => {
|
|
|
rescueSubmitting = false;
|
|
|
if (!taskSucceededWithoutRecovery(task)) {
|
|
|
rescueError(taskFailureMessage(task, t('instance_detail.task.failed', { action: title })));
|
|
|
}
|
|
|
void loadRescue(vmId, true).catch(() => null);
|
|
|
},
|
|
|
onStop: reason => {
|
|
|
if (reason === 'pagehide') return;
|
|
|
rescueSubmitting = false;
|
|
|
syncRescueControls();
|
|
|
rescueError(t('instance_detail.rescue.error.observer_stopped'));
|
|
|
},
|
|
|
});
|
|
|
if (!observer) {
|
|
|
rescueError(t('instance_detail.task.error.invalid_receipt_delivered'));
|
|
|
return;
|
|
|
}
|
|
|
toast(t('instance_detail.task.notice.accepted'), 'success', title);
|
|
|
} catch (error) {
|
|
|
rescueSubmitting = false;
|
|
|
rescueError(t('instance_detail.task.submit_failed', { action: title }));
|
|
|
syncRescueControls();
|
|
|
}
|
|
|
})();
|
|
|
}
|
|
|
|
|
|
function bindRescue(vmId) {
|
|
|
const form = byId('rescue-form');
|
|
|
if (!form) return;
|
|
|
form.addEventListener('submit', event => {
|
|
|
event.preventDefault();
|
|
|
rescueAction(vmId, 'load');
|
|
|
});
|
|
|
byId('rescue-force-start')?.addEventListener('click', () => rescueAction(vmId, 'force-start'));
|
|
|
byId('rescue-exit')?.addEventListener('click', () => rescueAction(vmId, 'exit'));
|
|
|
byId('rescue-confirm-risk')?.addEventListener('change', () => {
|
|
|
rescueError();
|
|
|
syncRescueControls();
|
|
|
});
|
|
|
syncRescueControls();
|
|
|
}
|
|
|
|
|
|
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;
|
|
|
}
|
|
|
|
|
|
function syncInstanceSettingForm(form) {
|
|
|
const vm = selectedVm();
|
|
|
const taskObserving = form?.dataset.taskObserving === 'true';
|
|
|
const allowed = vm?.can_operate === true && vm?.can_settings !== false
|
|
|
&& !instanceOperationBusy(vm) && !taskObserving;
|
|
|
for (const control of form?.querySelectorAll('input, select, button') || []) {
|
|
|
control.disabled = !allowed;
|
|
|
}
|
|
|
const button = form?.querySelector('button[type="submit"]');
|
|
|
if (button) {
|
|
|
button.textContent = taskObserving
|
|
|
? t('instance_detail.task.status.accepted') : (button.dataset.originalText || t('instance_detail.form.action.submit'));
|
|
|
}
|
|
|
return allowed;
|
|
|
}
|
|
|
|
|
|
function setInstanceSettingTaskObserving(observing) {
|
|
|
document.querySelectorAll('[data-instance-setting-form]').forEach(form => {
|
|
|
if (observing) form.dataset.taskObserving = 'true';
|
|
|
else delete form.dataset.taskObserving;
|
|
|
syncInstanceSettingForm(form);
|
|
|
});
|
|
|
}
|
|
|
|
|
|
function pollInstanceSettingJob(vmId, receipt, kind, form) {
|
|
|
const label = INSTANCE_SETTING_LABELS[kind] || t('instance_detail.operation_log.category.settings');
|
|
|
setInstanceSettingTaskObserving(true);
|
|
|
const handle = watchTask(receipt, label, {
|
|
|
onUpdate: () => settingStatus(t('instance_detail.task.running', { action: label })),
|
|
|
onTerminal: task => {
|
|
|
void (async () => {
|
|
|
try {
|
|
|
await refreshMetadataAndStatus(vmId, false, true, true);
|
|
|
if (taskSucceededWithoutRecovery(task)) {
|
|
|
settingStatus(t('instance_detail.settings.completed', { setting: label }), 'success');
|
|
|
if (kind === 'password') {
|
|
|
await loadGeneratedPassword(vmId);
|
|
|
}
|
|
|
toast(t('instance_detail.settings.changed', { setting: label }), 'success');
|
|
|
return;
|
|
|
}
|
|
|
settingStatus(taskFailureMessage(task, t('instance_detail.task.failed', { action: label })), 'error');
|
|
|
if (kind === 'password') {
|
|
|
if (task.effect_resolution === 'applied') {
|
|
|
const passwordLoaded = await loadGeneratedPassword(vmId);
|
|
|
const resolvedMessage = taskFailureMessage(task, t('instance_detail.task.failed', { action: label }));
|
|
|
settingStatus(passwordLoaded ? resolvedMessage
|
|
|
: t('instance_detail.password.read_after_failure', { message: resolvedMessage }), 'error');
|
|
|
if (passwordLoaded) setGeneratedPasswordNote(t('instance_detail.password_reset.notice.failed_but_applied'));
|
|
|
} else if (task.effect_resolution === 'not_applied') {
|
|
|
setGeneratedPasswordNote(t('instance_detail.password_reset.notice.failed_not_applied_unlocked'));
|
|
|
} else {
|
|
|
setGeneratedPasswordNote(task.effect_may_have_applied || task.safe_to_resubmit === false
|
|
|
? t('instance_detail.password_reset.error.failed_locked')
|
|
|
: t('instance_detail.password_reset.error.failed_not_applied'));
|
|
|
}
|
|
|
}
|
|
|
} finally {
|
|
|
setInstanceSettingTaskObserving(false);
|
|
|
}
|
|
|
})();
|
|
|
},
|
|
|
onStop: reason => {
|
|
|
if (reason === 'pagehide') return;
|
|
|
void (async () => {
|
|
|
try {
|
|
|
await refreshMetadataAndStatus(vmId, false, true, true);
|
|
|
} finally {
|
|
|
setInstanceSettingTaskObserving(false);
|
|
|
settingStatus(t('instance_detail.settings.error.observer_stopped_refresh'), 'warning');
|
|
|
}
|
|
|
})();
|
|
|
},
|
|
|
});
|
|
|
if (!handle) {
|
|
|
void (async () => {
|
|
|
try {
|
|
|
await refreshMetadataAndStatus(vmId, false, true, true);
|
|
|
} finally {
|
|
|
setInstanceSettingTaskObserving(false);
|
|
|
settingStatus(t('instance_detail.task.invalid_receipt', { action: label }), 'error');
|
|
|
}
|
|
|
})();
|
|
|
}
|
|
|
return handle;
|
|
|
}
|
|
|
|
|
|
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(t('instance_detail.password_reset.notice.pending_background'));
|
|
|
card.hidden = false;
|
|
|
card.focus({ preventScroll: true });
|
|
|
}
|
|
|
|
|
|
async function loadGeneratedPassword(vmId) {
|
|
|
try {
|
|
|
const result = await api(`/api/v1/vms/${encodeURIComponent(vmId)}/credential`, { method: 'POST' });
|
|
|
if (typeof result?.password !== 'string' || !result.password) throw new Error(t('instance_detail.credentials.error.password_unavailable'));
|
|
|
showGeneratedPassword(result.password);
|
|
|
setGeneratedPasswordNote(t('instance_detail.password_reset.notice.succeeded'));
|
|
|
return true;
|
|
|
} catch {
|
|
|
settingStatus(t('instance_detail.password_reset.notice.succeeded_password_unreadable'), 'error');
|
|
|
return false;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function bindInstanceSettings(vmId) {
|
|
|
const requestedTab = new URLSearchParams(location.search).get('setting') || '';
|
|
|
bindInstanceSettingTabs(vmId, requestedTab);
|
|
|
bindIpChange(vmId);
|
|
|
bindInstanceUpgrade(vmId);
|
|
|
bindAutomaticBackup(vmId);
|
|
|
bindFirewallControls(vmId);
|
|
|
bindSnapshotControls(vmId);
|
|
|
bindRescue(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 || instanceOperationBusy()
|
|
|
|| form.dataset.taskObserving === 'true') 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, t('instance_detail.settings.validation.hostname_required'));
|
|
|
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, t('instance_detail.settings.validation.ssh_key_required'));
|
|
|
body.ssh_key_id = value;
|
|
|
} else return;
|
|
|
const button = form.querySelector('button[type="submit"]');
|
|
|
const checkbox = form.elements.confirm_restart;
|
|
|
let observing = false;
|
|
|
settingError(form);
|
|
|
submitting = true;
|
|
|
if (button) { button.disabled = true; button.dataset.originalText = button.textContent; button.textContent = t('instance_detail.form.status.submitting'); }
|
|
|
try {
|
|
|
const result = await api(`/api/v1/vms/${encodeURIComponent(vmId)}/settings`, {
|
|
|
method: 'POST', body, expectedStatus: 202, requireTaskReceipt: true,
|
|
|
});
|
|
|
const label = INSTANCE_SETTING_LABELS[kind] || t('instance_detail.operation_log.category.settings');
|
|
|
if (checkbox) checkbox.checked = false;
|
|
|
form.elements.hostname && (form.elements.hostname.value = kind === 'hostname' ? body.hostname : form.elements.hostname.value);
|
|
|
settingStatus(t('instance_detail.settings.accepted', { setting: label }));
|
|
|
toast(t('instance_detail.task.notice.accepted'), 'success', label);
|
|
|
observing = Boolean(pollInstanceSettingJob(vmId, result, kind, form));
|
|
|
} catch (error) {
|
|
|
settingError(form, t('instance_detail.settings.error.submit_failed'));
|
|
|
settingStatus(t('instance_detail.settings.submit_failed', { setting: INSTANCE_SETTING_LABELS[kind] || t('instance_detail.operation_log.category.settings') }), 'error');
|
|
|
await refreshMetadataAndStatus(vmId, false, true, true);
|
|
|
} finally {
|
|
|
submitting = false;
|
|
|
if (button) {
|
|
|
button.textContent = observing ? t('instance_detail.task.status.accepted') : (button.dataset.originalText || t('instance_detail.form.action.submit'));
|
|
|
if (!observing) syncInstanceSettingForm(form);
|
|
|
}
|
|
|
}
|
|
|
}));
|
|
|
byId('vm-detail-generated-password-copy')?.addEventListener('click', async () => {
|
|
|
const value = byId('vm-detail-generated-password')?.textContent || '';
|
|
|
if (!value) return;
|
|
|
try { await copyText(value); }
|
|
|
catch (error) { toast(t('common.error.copy'), '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(
|
|
|
() => toast(t('common.error.copy'), '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(t('instance_detail.metrics.notice.load_on_tab'));
|
|
|
clearVmTrafficDaily(t('instance_detail.metrics.notice.daily_traffic_load_on_tab'));
|
|
|
document.addEventListener('cloud:vm-rendered', () => {
|
|
|
if (ipChangePayload) renderIpChangeQuote(ipChangePayload);
|
|
|
syncUpgradeControls();
|
|
|
if (firewallPayload) updateFirewallEditorState();
|
|
|
if (snapshotPayload) renderVmSnapshots(vmId, snapshotPayload);
|
|
|
syncRescueControls();
|
|
|
document.querySelectorAll('[data-instance-setting-form]').forEach(
|
|
|
form => syncInstanceSettingForm(form)
|
|
|
);
|
|
|
});
|
|
|
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-ip-change')?.hidden) await loadIpChangeQuote(vmId, true);
|
|
|
if (!byId('vm-settings-section-upgrade')?.hidden) await loadUpgradeOptions(vmId, true).catch(() => null);
|
|
|
if (!byId('vm-settings-section-automatic-backup')?.hidden) await loadAutomaticBackup(vmId, true).catch(() => null);
|
|
|
if (!byId('vm-settings-section-firewall')?.hidden) await loadVmFirewall(vmId, true);
|
|
|
if (!byId('vm-settings-section-snapshots')?.hidden) await loadVmSnapshots(vmId, true);
|
|
|
if (!byId('vm-settings-section-rescue')?.hidden) await loadRescue(vmId, true).catch(() => null);
|
|
|
});
|
|
|
for (const family of [4, 6]) {
|
|
|
byId(`vm-detail-ipv${family}-copy`)?.addEventListener('click', async () => {
|
|
|
try { await copyText(vmIp(selectedVm(), family)); }
|
|
|
catch (error) { toast(t('common.error.copy'), '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();
|
|
|
for (const observer of taskObservers) observer.stop('pagehide');
|
|
|
taskObservers.clear();
|
|
|
});
|
|
|
window.addEventListener('pageshow', event => {
|
|
|
if (!event.persisted) return;
|
|
|
void loadVmStatus(vmId, { live: true, force: true }).then(vm => {
|
|
|
if (vm) setInstanceSettingTaskObserving(false);
|
|
|
});
|
|
|
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);
|
|
|
}
|
|
|
if (!byId('vm-settings-section-ip-change')?.hidden) {
|
|
|
void loadIpChangeQuote(vmId, true);
|
|
|
}
|
|
|
if (!byId('vm-settings-section-upgrade')?.hidden) {
|
|
|
void loadUpgradeOptions(vmId, true).catch(() => null);
|
|
|
}
|
|
|
if (!byId('vm-settings-section-automatic-backup')?.hidden) {
|
|
|
automaticBackupRestoring = false;
|
|
|
automaticBackupSaving = false;
|
|
|
void loadAutomaticBackup(vmId, true).catch(() => null);
|
|
|
}
|
|
|
if (!byId('vm-settings-section-rescue')?.hidden) {
|
|
|
rescueSubmitting = false;
|
|
|
void loadRescue(vmId, true).catch(() => null);
|
|
|
}
|
|
|
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', t('instance_detail.bootstrap.error.missing'));
|
|
|
}
|
|
|
}
|