|
|
function el(tag, className = '', text) {
|
|
|
const node = document.createElement(tag);
|
|
|
node.className = className;
|
|
|
if (text !== undefined) node.textContent = String(text);
|
|
|
return node;
|
|
|
}
|
|
|
|
|
|
function text(...values) {
|
|
|
return values.find(value => value !== null && value !== undefined && String(value).trim() !== '') ?? '—';
|
|
|
}
|
|
|
|
|
|
function date(value) {
|
|
|
if (!value) return '未记录';
|
|
|
const numeric = Number(value);
|
|
|
const timestamp = Number.isFinite(numeric) ? numeric * (numeric < 1e12 ? 1000 : 1) : Date.parse(value);
|
|
|
const parsed = new Date(timestamp);
|
|
|
return Number.isFinite(parsed.getTime())
|
|
|
? parsed.toLocaleString('zh-CN', { hour12: false }) : '未记录';
|
|
|
}
|
|
|
|
|
|
function bytes(value) {
|
|
|
const number = Number(value);
|
|
|
if (value === null || value === undefined || !Number.isFinite(number) || number < 0) return '未记录';
|
|
|
if (number === 0) return '0 B';
|
|
|
const exponent = Math.min(4, Math.floor(Math.log(number) / Math.log(1024)));
|
|
|
return `${(number / 1024 ** exponent).toLocaleString('zh-CN', { maximumFractionDigits: 2 })} ${['B', 'KiB', 'MiB', 'GiB', 'TiB'][exponent]}`;
|
|
|
}
|
|
|
|
|
|
function infoList(entries) {
|
|
|
const list = el('dl', 'admin-instance-details');
|
|
|
for (const [label, value] of entries) {
|
|
|
list.append(el('dt', '', label));
|
|
|
const dd = el('dd');
|
|
|
dd.append(value instanceof Node ? value : document.createTextNode(String(text(value))));
|
|
|
list.append(dd);
|
|
|
}
|
|
|
return list;
|
|
|
}
|
|
|
|
|
|
function backupStatus(value) {
|
|
|
return ({
|
|
|
creating: ['正在备份', 'warning'], ready: ['可恢复', 'success'],
|
|
|
restoring: ['正在恢复', 'warning'], failed: ['备份失败', 'danger'],
|
|
|
uncertain: ['效果待核对', 'danger'], deleting: ['正在删除', 'warning'],
|
|
|
delete_uncertain: ['删除待核对', 'danger'],
|
|
|
delete_attention: ['清理需人工处理', 'danger'], deleted: ['已删除', 'secondary'],
|
|
|
})[String(value || '').toLowerCase()] || ['状态未知', 'secondary'];
|
|
|
}
|
|
|
|
|
|
function backupConsistency(value) {
|
|
|
return value === 'filesystem' ? '文件系统一致' : '崩溃一致';
|
|
|
}
|
|
|
|
|
|
function backupTargets(payload, backup) {
|
|
|
const values = Array.isArray(backup?.restore_targets) ? backup.restore_targets
|
|
|
: (Array.isArray(payload?.restore_targets) ? payload.restore_targets
|
|
|
: (Array.isArray(payload?.target_hosts) ? payload.target_hosts : []));
|
|
|
return values.filter(value => value && typeof value === 'object'
|
|
|
&& /^[1-9][0-9]*$/.test(String(value.host_id ?? value.id ?? '')));
|
|
|
}
|
|
|
|
|
|
export function createAdminInstanceBackups({
|
|
|
byId, actions, createMigration, onNotice,
|
|
|
} = {}) {
|
|
|
if (typeof byId !== 'function' || typeof actions?.enqueue !== 'function'
|
|
|
|| typeof createMigration !== 'function') {
|
|
|
throw new TypeError('Instance backup dependencies are incomplete');
|
|
|
}
|
|
|
const { read, enqueue, commit, blockMessage } = actions;
|
|
|
const state = {
|
|
|
currentId: null, request: null, mutationRequest: null, observer: null,
|
|
|
serial: 0, loadedFor: null,
|
|
|
libraryRequest: null, libraryObserver: null, librarySerial: 0,
|
|
|
libraryPage: 1, libraryPagination: { page: 1, total_pages: 1, total: 0 },
|
|
|
libraryClosing: false, libraryOpener: null, libraryScroll: null, started: false,
|
|
|
};
|
|
|
|
|
|
function feedback(section, message, tone = 'muted') {
|
|
|
const node = section.querySelector('[data-backup-feedback]');
|
|
|
if (!node) return;
|
|
|
node.hidden = !message; node.className = `text-${tone} fs-13 mb-2`; node.textContent = message || '';
|
|
|
}
|
|
|
|
|
|
function libraryNotice(message, error = false) {
|
|
|
const node = byId('backup-library-notice');
|
|
|
if (!node) return;
|
|
|
node.hidden = !message; node.className = error ? 'alert alert-danger' : 'alert alert-info';
|
|
|
node.textContent = message || ''; node.setAttribute('role', error ? 'alert' : 'status');
|
|
|
}
|
|
|
|
|
|
function mutationUrl(vmId, backupId, action = '', library = false) {
|
|
|
const base = library ? `/api/v1/admin/backups/${encodeURIComponent(backupId)}`
|
|
|
: `/api/v1/admin/instances/${encodeURIComponent(vmId)}/backups/${encodeURIComponent(backupId)}`;
|
|
|
return action ? `${base}/${action}` : base;
|
|
|
}
|
|
|
|
|
|
function surfaceNotice(message, error, library) {
|
|
|
if (library) libraryNotice(message, error); else onNotice?.(message, error);
|
|
|
}
|
|
|
|
|
|
function refreshSurface(vmId, library) {
|
|
|
if (library) loadLibrary(state.libraryPage, true); else load(vmId, true);
|
|
|
}
|
|
|
|
|
|
function watchInstanceTask(vmId, receipt, title) {
|
|
|
const serial = state.serial; const taskId = receipt?.task_id || '—';
|
|
|
const handle = actions.watch(receipt, {
|
|
|
title,
|
|
|
onResult: ({ succeeded, message }) => {
|
|
|
if (serial !== state.serial || state.currentId !== String(vmId)) return;
|
|
|
state.observer = null;
|
|
|
onNotice?.(message, !succeeded);
|
|
|
load(vmId, true);
|
|
|
},
|
|
|
onStop: reason => {
|
|
|
if (state.observer === handle) state.observer = null;
|
|
|
if (reason === 'pagehide' || reason === 'closed' || reason === 'replaced'
|
|
|
|| serial !== state.serial) return;
|
|
|
onNotice?.(`${title}任务 #${taskId} 的自动观察已停止,请在任务记录查看最终结果。`, true);
|
|
|
load(vmId, true);
|
|
|
},
|
|
|
});
|
|
|
if (!handle.url) {
|
|
|
onNotice?.('任务已接收,但任务回执协议无效。请勿重复提交,并联系管理员核查。', true);
|
|
|
return;
|
|
|
}
|
|
|
state.observer?.stop('replaced'); state.observer = handle;
|
|
|
}
|
|
|
|
|
|
function watchLibraryTask(receipt, title) {
|
|
|
const serial = state.librarySerial; const taskId = receipt?.task_id || '—';
|
|
|
const handle = actions.watch(receipt, {
|
|
|
title,
|
|
|
onResult: ({ succeeded, message }) => {
|
|
|
if (serial !== state.librarySerial || !byId('backup-library')?.open) return;
|
|
|
state.libraryObserver = null;
|
|
|
libraryNotice(message, !succeeded);
|
|
|
loadLibrary(state.libraryPage, true);
|
|
|
},
|
|
|
onStop: reason => {
|
|
|
if (state.libraryObserver === handle) state.libraryObserver = null;
|
|
|
if (reason === 'pagehide' || reason === 'closed' || reason === 'replaced'
|
|
|
|| serial !== state.librarySerial) return;
|
|
|
libraryNotice(`${title}任务 #${taskId} 的自动观察已停止,请在任务记录查看最终结果。`, true);
|
|
|
loadLibrary(state.libraryPage, true);
|
|
|
},
|
|
|
});
|
|
|
if (!handle.url) {
|
|
|
libraryNotice('任务已接收,但任务回执协议无效。请勿重复提交,并联系管理员核查。', true);
|
|
|
return;
|
|
|
}
|
|
|
state.libraryObserver?.stop('replaced'); state.libraryObserver = handle;
|
|
|
}
|
|
|
|
|
|
async function submitTask({ vmId, path, body, title, library = false }) {
|
|
|
if (state.mutationRequest) throw new Error('已有备份或迁移操作正在提交,请稍后重试。');
|
|
|
const controller = new AbortController(); state.mutationRequest = controller;
|
|
|
try {
|
|
|
const receipt = await enqueue(path, body, controller, 'POST');
|
|
|
if (library) watchLibraryTask(receipt, title); else watchInstanceTask(vmId, receipt, title);
|
|
|
return receipt;
|
|
|
} finally {
|
|
|
if (state.mutationRequest === controller) state.mutationRequest = null;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
const migration = createMigration({
|
|
|
isBusy: () => Boolean(state.mutationRequest),
|
|
|
submitTask,
|
|
|
notice: onNotice,
|
|
|
refresh: (id, force = false) => { load(id, force); },
|
|
|
});
|
|
|
|
|
|
async function deleteObject(vmId, backup, controller, library = false) {
|
|
|
const payload = await commit(
|
|
|
mutationUrl(vmId, backup.id, '', library), undefined, controller, 'DELETE',
|
|
|
);
|
|
|
if (payload?.deleted !== true && payload?.requires_reconciliation !== true
|
|
|
&& payload?.requires_attention !== true) {
|
|
|
const error = new Error('删除回执状态无效,请勿重复删除,先刷新核对。');
|
|
|
error.mutationMayHaveApplied = true;
|
|
|
error.safeToRetry = false;
|
|
|
throw error;
|
|
|
}
|
|
|
return payload;
|
|
|
}
|
|
|
|
|
|
function deleteButton(vmId, backup, library = false) {
|
|
|
const reconcile = backup.delete_action === 'reconcile';
|
|
|
const button = el('button', reconcile ? 'btn btn-warning btn-sm' : 'btn btn-outline-danger btn-sm',
|
|
|
reconcile ? '核对删除状态' : '删除备份');
|
|
|
button.type = 'button';
|
|
|
button.addEventListener('click', async () => {
|
|
|
if (state.mutationRequest || backup.can_delete !== true) return;
|
|
|
if (!reconcile && !await globalThis.VenixAdminDangerDialog.confirm({
|
|
|
title: '永久删除云备份',
|
|
|
message: `对象存储中的备份“${String(backup.name || backup.id)}”及其精确系统盘对象将被删除,且无法恢复。请输入备份名称继续。`,
|
|
|
requiredText: String(backup.name || backup.id),
|
|
|
requiredLabel: '输入完整备份名称',
|
|
|
confirmText: '永久删除',
|
|
|
})) return;
|
|
|
const controller = new AbortController(); state.mutationRequest = controller; button.disabled = true;
|
|
|
surfaceNotice(reconcile
|
|
|
? '正在核对准确对象版本;只有两次间隔证据一致才会创建新的删除代次。'
|
|
|
: '正在删除对象存储备份,请勿重复提交。', false, library);
|
|
|
try {
|
|
|
const result = await deleteObject(vmId, backup, controller, library);
|
|
|
surfaceNotice(result.deleted === true ? '备份对象已确认删除。'
|
|
|
: (result.requires_attention === true
|
|
|
? '自动清理已达到三次上限,请到对象存储的“对象清理异常”中核查。'
|
|
|
: '删除结果仍不确定;系统将按稳定证据继续受控核对。'), result.deleted !== true, library);
|
|
|
refreshSurface(vmId, library);
|
|
|
} catch (error) {
|
|
|
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
|
|
|
surfaceNotice(error.message, true, library); refreshSurface(vmId, library);
|
|
|
} finally {
|
|
|
if (state.mutationRequest === controller) state.mutationRequest = null;
|
|
|
button.disabled = false;
|
|
|
}
|
|
|
});
|
|
|
return button;
|
|
|
}
|
|
|
|
|
|
function cleanupButton(vmId, backup, library = false) {
|
|
|
const button = el('button', 'btn btn-outline-warning btn-sm', '核对并清理临时工作区');
|
|
|
button.type = 'button';
|
|
|
button.addEventListener('click', async () => {
|
|
|
if (state.mutationRequest || backup.can_cleanup_workspace !== true) return;
|
|
|
button.disabled = true;
|
|
|
surfaceNotice('正在读取原备份操作的最新宿主机证据并创建精确清理任务。', false, library);
|
|
|
try {
|
|
|
const receipt = await submitTask({
|
|
|
vmId,
|
|
|
path: `/api/v1/admin/backups/${encodeURIComponent(backup.id)}/cleanup-workspace`,
|
|
|
body: {}, title: '清理备份工作区', library,
|
|
|
});
|
|
|
surfaceNotice(`工作区清理任务 #${receipt.task_id || '—'} 已接收。`, false, library);
|
|
|
refreshSurface(vmId, library);
|
|
|
} catch (error) {
|
|
|
surfaceNotice(error.message, true, library); refreshSurface(vmId, library);
|
|
|
} finally { button.disabled = false; }
|
|
|
});
|
|
|
return button;
|
|
|
}
|
|
|
|
|
|
function restoreForm(vmId, backup, targets, mutationBlocked, library = false) {
|
|
|
const form = el('form', 'mt-3'); form.noValidate = true;
|
|
|
const grid = el('div', 'row g-2');
|
|
|
const hostLabel = el('label', 'col-12 col-lg-6');
|
|
|
hostLabel.append(el('span', 'form-label d-block', '恢复到宿主机'));
|
|
|
const host = el('select', 'form-select'); host.name = 'target_host_id'; host.required = true;
|
|
|
host.append(new Option(targets.length ? '请选择目标宿主机' : '暂无符合条件的宿主机', ''));
|
|
|
for (const target of targets) {
|
|
|
const id = String(target.host_id ?? target.id);
|
|
|
const name = text(target.host_name, target.name, `宿主机 #${id}`);
|
|
|
const region = String(target.region || target.region_name || '').trim();
|
|
|
const available = Number(target.available_ip_count ?? target.available_count);
|
|
|
const suffix = Number.isFinite(available) ? ` · ${available} 个可用 IP` : '';
|
|
|
const source = target.is_source_host === true ? ' · 原宿主机' : '';
|
|
|
host.append(new Option(`${name}${region ? ` · ${region}` : ''}${source}${suffix}`, id));
|
|
|
}
|
|
|
host.disabled = mutationBlocked || targets.length === 0; hostLabel.append(host);
|
|
|
const nameLabel = el('label', 'col-12 col-lg-6');
|
|
|
nameLabel.append(el('span', 'form-label d-block', '新实例名称'));
|
|
|
const name = el('input', 'form-control');
|
|
|
name.name = 'name'; name.type = 'text'; name.maxLength = 63;
|
|
|
name.placeholder = `${String(backup.name || 'backup').slice(0, 48)}-restore`;
|
|
|
name.required = true; name.disabled = mutationBlocked || targets.length === 0;
|
|
|
nameLabel.append(name); grid.append(hostLabel, nameLabel); form.append(grid);
|
|
|
const confirmLabel = el('label', 'admin-instance-settings-confirm mt-3');
|
|
|
const confirm = document.createElement('input');
|
|
|
confirm.type = 'checkbox'; confirm.name = 'confirm_new_instance';
|
|
|
confirm.disabled = mutationBlocked || targets.length === 0;
|
|
|
confirmLabel.append(confirm, document.createTextNode(
|
|
|
'我确认这会创建一台免计费的独立新实例,使用 br0 并分配全新公网 IP;不会继承原 IP、账单、到期时间或流量周期。'));
|
|
|
form.append(confirmLabel);
|
|
|
const resultFeedback = el('p', 'text-muted fs-13 mb-2');
|
|
|
resultFeedback.dataset.restoreFeedback = ''; resultFeedback.hidden = true;
|
|
|
resultFeedback.setAttribute('role', 'status'); form.append(resultFeedback);
|
|
|
const actions = el('div', 'd-flex justify-content-end mt-2');
|
|
|
const submit = el('button', 'btn btn-primary btn-sm', '创建恢复实例');
|
|
|
submit.type = 'submit'; submit.disabled = mutationBlocked || targets.length === 0;
|
|
|
actions.append(submit); form.append(actions);
|
|
|
form.addEventListener('submit', async event => {
|
|
|
event.preventDefault();
|
|
|
if (state.mutationRequest || mutationBlocked) return;
|
|
|
const targetHostId = String(host.value || ''); const instanceName = String(name.value || '').trim();
|
|
|
const show = (message, tone = 'danger') => {
|
|
|
resultFeedback.hidden = false; resultFeedback.className = `text-${tone} fs-13 mb-2`;
|
|
|
resultFeedback.textContent = message;
|
|
|
};
|
|
|
if (!/^[1-9][0-9]*$/.test(targetHostId)) return show('请选择目标宿主机。');
|
|
|
if (!/^[A-Za-z0-9][A-Za-z0-9_.-]{0,62}$/.test(instanceName)) {
|
|
|
return show('新实例名称需为 1 至 63 位英文、数字、点、下划线或连字符,并以英文或数字开头。');
|
|
|
}
|
|
|
if (!confirm.checked) return show('请确认新实例、br0 和全新公网 IP 的恢复规则。');
|
|
|
for (const control of form.querySelectorAll('input, select, button')) control.disabled = true;
|
|
|
show('正在预留目标资源并创建恢复任务,请勿重复提交…', 'muted');
|
|
|
try {
|
|
|
const receipt = await submitTask({
|
|
|
vmId,
|
|
|
path: mutationUrl(vmId, backup.id, 'restore', library),
|
|
|
body: { target_host_id: Number(targetHostId), name: instanceName, confirm_new_instance: true },
|
|
|
title: '备份恢复', library,
|
|
|
});
|
|
|
show(`恢复任务 #${receipt.task_id || '—'} 已接收。`, 'muted');
|
|
|
surfaceNotice('恢复任务已接收;目标资源会保持预留,直到任务得到明确结果。', false, library);
|
|
|
refreshSurface(vmId, library);
|
|
|
} catch (error) {
|
|
|
show(error.message);
|
|
|
if (error?.mutationMayHaveApplied === true) {
|
|
|
surfaceNotice(error.message, true, library); refreshSurface(vmId, library);
|
|
|
} else {
|
|
|
for (const control of form.querySelectorAll('input, select, button')) control.disabled = false;
|
|
|
if (!targets.length) { host.disabled = true; submit.disabled = true; confirm.disabled = true; }
|
|
|
}
|
|
|
}
|
|
|
});
|
|
|
return form;
|
|
|
}
|
|
|
|
|
|
function renderInstance(payload, vmId) {
|
|
|
const panel = byId('instance-panel-backups'); panel.replaceChildren();
|
|
|
const intro = el('div', 'alert alert-info');
|
|
|
intro.append(el('strong', 'd-block mb-1', '可移植系统盘备份'),
|
|
|
document.createTextNode('备份上传到已验证的对象存储,不修改源实例。恢复会在所选宿主机创建独立实例;可选择原宿主机或其他合格宿主机,并统一接入 br0、分配全新公网 IP。'));
|
|
|
panel.append(intro, migration.render(payload, vmId));
|
|
|
const create = el('section', 'card mb-3'); const createBody = el('div', 'card-body');
|
|
|
createBody.append(el('h3', 'h6 fw-semibold', '创建备份'));
|
|
|
const form = el('form', 'row g-2 align-items-end'); form.noValidate = true;
|
|
|
const nameLabel = el('label', 'col-12 col-lg-6');
|
|
|
nameLabel.append(el('span', 'form-label d-block', '备份名称'));
|
|
|
const name = el('input', 'form-control'); name.name = 'name'; name.type = 'text';
|
|
|
name.required = true; name.maxLength = 64; name.placeholder = '例如 迁移前备份'; nameLabel.append(name);
|
|
|
const consistencyLabel = el('label', 'col-12 col-lg-4');
|
|
|
consistencyLabel.append(el('span', 'form-label d-block', '一致性模式'));
|
|
|
const consistency = el('select', 'form-select'); consistency.name = 'consistency_mode';
|
|
|
consistency.append(new Option('自动(优先文件系统一致)', 'filesystem', true, true),
|
|
|
new Option('强制崩溃一致(不冻结文件系统)', 'crash'));
|
|
|
consistencyLabel.append(consistency, el('small', 'form-text text-muted',
|
|
|
'自动模式在 QGA 不可用时降级为崩溃一致;备份列表会显示最终实际使用的一致性模式。'));
|
|
|
const actions = el('div', 'col-12 col-lg-2 d-grid');
|
|
|
const submit = el('button', 'btn btn-primary', '开始备份'); submit.type = 'submit'; actions.append(submit);
|
|
|
form.append(nameLabel, consistencyLabel, actions);
|
|
|
const createFeedback = el('p', 'text-muted fs-13 mb-0 mt-2');
|
|
|
createFeedback.dataset.backupFeedback = ''; createFeedback.hidden = true;
|
|
|
createFeedback.setAttribute('role', 'status');
|
|
|
createBody.append(form, createFeedback); create.append(createBody); panel.append(create);
|
|
|
const mutationBlocked = payload?.active_job?.blocks_mutation === true || payload?.can_create !== true;
|
|
|
if (mutationBlocked) {
|
|
|
for (const control of form.querySelectorAll('input, select, button')) control.disabled = true;
|
|
|
const reason = payload?.active_job?.blocks_mutation === true
|
|
|
? blockMessage(payload.active_job, '创建备份')
|
|
|
: text(payload?.create_block_reason, payload?.message, '当前实例或对象存储尚未满足备份条件。');
|
|
|
feedback(createBody, reason, 'warning');
|
|
|
}
|
|
|
form.addEventListener('submit', async event => {
|
|
|
event.preventDefault();
|
|
|
if (state.mutationRequest || mutationBlocked) return;
|
|
|
const backupName = String(name.value || '').trim();
|
|
|
if (!backupName || [...backupName].length > 64) {
|
|
|
feedback(createBody, '请输入 1 至 64 个字符的备份名称。', 'danger'); return;
|
|
|
}
|
|
|
for (const control of form.querySelectorAll('input, select, button')) control.disabled = true;
|
|
|
feedback(createBody, '正在创建对象存储备份任务,请勿重复提交…');
|
|
|
try {
|
|
|
const receipt = await submitTask({
|
|
|
vmId,
|
|
|
path: `/api/v1/admin/instances/${encodeURIComponent(vmId)}/backups`,
|
|
|
body: { name: backupName,
|
|
|
consistency_mode: consistency.value === 'crash' ? 'crash' : 'filesystem' },
|
|
|
title: '创建备份',
|
|
|
});
|
|
|
feedback(createBody, `备份任务 #${receipt.task_id || '—'} 已接收。`);
|
|
|
onNotice?.('备份任务已接收;大容量系统盘可能需要较长时间,请在任务记录查看进度。');
|
|
|
load(vmId, true);
|
|
|
} catch (error) {
|
|
|
feedback(createBody, error.message, 'danger');
|
|
|
if (error?.mutationMayHaveApplied === true) {
|
|
|
onNotice?.(error.message, true); load(vmId, true);
|
|
|
} else {
|
|
|
for (const control of form.querySelectorAll('input, select, button')) control.disabled = false;
|
|
|
}
|
|
|
}
|
|
|
});
|
|
|
const heading = el('div', 'd-flex align-items-center justify-content-between gap-2 mb-2');
|
|
|
heading.append(el('h3', 'h6 fw-semibold mb-0', '已有备份'));
|
|
|
const refresh = el('button', 'btn btn-light btn-sm', '刷新'); refresh.type = 'button';
|
|
|
refresh.addEventListener('click', () => load(vmId, true)); heading.append(refresh); panel.append(heading);
|
|
|
const backups = Array.isArray(payload?.backups) ? payload.backups : [];
|
|
|
if (!backups.length) {
|
|
|
panel.append(el('p', 'text-muted py-3', '暂无可恢复的对象存储备份。')); return;
|
|
|
}
|
|
|
for (const backup of backups) {
|
|
|
const card = el('article', 'card mb-3'); const cardBody = el('div', 'card-body');
|
|
|
const title = el('div', 'd-flex align-items-start justify-content-between gap-2 flex-wrap');
|
|
|
title.append(el('h4', 'h6 fw-semibold mb-0', text(backup.name, `备份 #${backup.id}`)));
|
|
|
const [statusLabel, tone] = backupStatus(backup.state);
|
|
|
title.append(el('span', `badge bg-${tone}-subtle text-${tone}-emphasis`, statusLabel));
|
|
|
cardBody.append(title, infoList([
|
|
|
['一致性', backupConsistency(backup.consistency)],
|
|
|
['对象大小', backup.object_size_bytes === null || backup.object_size_bytes === undefined
|
|
|
? '等待完成' : bytes(backup.object_size_bytes)],
|
|
|
['虚拟磁盘容量', backup.virtual_size_bytes === null || backup.virtual_size_bytes === undefined
|
|
|
? '等待完成' : bytes(backup.virtual_size_bytes)],
|
|
|
['完整性校验', /^[a-f0-9]{64}$/.test(String(backup.sha256 || '')) ? 'SHA-256 已记录' : '等待校验'],
|
|
|
['创建时间', date(backup.created_at)], ['可恢复时间', date(backup.ready_at)],
|
|
|
]));
|
|
|
if (backup.error) cardBody.append(el('p', 'text-danger fs-13', backup.error));
|
|
|
if (backup.cleanup_pending === true) {
|
|
|
cardBody.append(el('p', 'text-warning fs-13',
|
|
|
'远端备份已完整保存并可恢复,但源宿主机的临时工作区仍待清理;清理不会重复上传或修改备份对象。'));
|
|
|
if (backup.can_cleanup_workspace === true) {
|
|
|
const cleanupActions = el('div', 'd-flex justify-content-end mb-3');
|
|
|
cleanupActions.append(cleanupButton(vmId, backup)); cardBody.append(cleanupActions);
|
|
|
}
|
|
|
}
|
|
|
if (backup.state === 'uncertain') {
|
|
|
cardBody.append(el('p', 'alert alert-warning fs-13 mb-0',
|
|
|
'备份效果尚未确认。系统会保留任务和对象边界,请勿重复创建或恢复,先完成任务核对。'));
|
|
|
} else if (backup.state === 'delete_uncertain' || backup.state === 'deleting') {
|
|
|
cardBody.append(el('p', 'alert alert-warning fs-13',
|
|
|
'删除结果尚未确认。系统会在两次间隔核对确认同一对象后创建新的删除代次。'));
|
|
|
if (backup.can_delete === true) {
|
|
|
const deleteActions = el('div', 'd-flex justify-content-end');
|
|
|
deleteActions.append(deleteButton(vmId, backup)); cardBody.append(deleteActions);
|
|
|
}
|
|
|
} else if (backup.state === 'delete_attention') {
|
|
|
cardBody.append(el('p', 'alert alert-danger fs-13 mb-0',
|
|
|
'对象清理已达到自动重试上限,请在“对象存储 -> 对象清理异常”中核查并手动恢复。'));
|
|
|
} else if (backup.state === 'ready') {
|
|
|
const targets = backupTargets(payload, backup);
|
|
|
if (targets.length) cardBody.append(restoreForm(vmId, backup, targets,
|
|
|
payload?.can_restore === false || payload?.active_job?.blocks_mutation === true));
|
|
|
else cardBody.append(el('p', 'text-warning fs-13 mb-0',
|
|
|
'暂无满足容量、存储、br0 网络和可用公网 IP 条件的宿主机。'));
|
|
|
}
|
|
|
if (['ready', 'failed'].includes(backup.state) && backup.can_delete === true) {
|
|
|
const deleteActions = el('div', 'd-flex justify-content-end mt-3');
|
|
|
deleteActions.append(deleteButton(vmId, backup)); cardBody.append(deleteActions);
|
|
|
}
|
|
|
card.append(cardBody); panel.append(card);
|
|
|
}
|
|
|
}
|
|
|
|
|
|
async function load(vmId, force = false) {
|
|
|
if (state.currentId !== String(vmId)) state.currentId = String(vmId);
|
|
|
if (!force && state.loadedFor === String(vmId)) return;
|
|
|
state.request?.abort('replaced');
|
|
|
const controller = new AbortController(); const serial = state.serial;
|
|
|
state.request = controller;
|
|
|
const panel = byId('instance-panel-backups');
|
|
|
panel.replaceChildren(el('p', 'text-muted py-3', '正在读取对象存储备份…'));
|
|
|
try {
|
|
|
const payload = await read(`/api/v1/admin/instances/${encodeURIComponent(vmId)}/backups`, controller);
|
|
|
if (controller.signal.aborted || serial !== state.serial || state.currentId !== String(vmId)) return;
|
|
|
state.loadedFor = String(vmId); renderInstance(payload, String(vmId));
|
|
|
} catch (error) {
|
|
|
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
|
|
|
if (serial === state.serial) {
|
|
|
panel.replaceChildren(el('p', 'alert alert-danger', `${error.message} 请刷新后重试。`));
|
|
|
}
|
|
|
} finally {
|
|
|
if (state.request === controller) state.request = null;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function renderLibrary(payload) {
|
|
|
const container = byId('backup-library-items'); container.replaceChildren();
|
|
|
const items = Array.isArray(payload?.items) ? payload.items : [];
|
|
|
const canManage = payload?.can_manage === true;
|
|
|
if (!items.length) container.append(el('p', 'text-muted py-3', '备份库中暂无对象。'));
|
|
|
for (const backup of items) {
|
|
|
const source = backup?.source && typeof backup.source === 'object' ? backup.source : {};
|
|
|
const vmId = String(source.instance_id || '');
|
|
|
const card = el('article', 'card mb-3'); const cardBody = el('div', 'card-body');
|
|
|
const heading = el('div', 'd-flex align-items-start justify-content-between gap-2 flex-wrap');
|
|
|
heading.append(el('h3', 'h6 fw-semibold mb-0', text(backup.name, `备份 #${backup.id}`)));
|
|
|
const [label, tone] = backupStatus(backup.state);
|
|
|
heading.append(el('span', `badge bg-${tone}-subtle text-${tone}-emphasis`, label));
|
|
|
const sourceLabel = source.deleted === true ? '源实例已删除'
|
|
|
: `源实例 ${text(source.name, `#${vmId}`)}`;
|
|
|
cardBody.append(heading, infoList([
|
|
|
['来源', `${sourceLabel} · ID ${text(vmId)} · 用户 ${text(source.user_id)}`],
|
|
|
['源宿主机', `${text(source.host_name, `#${source.host_id}`)}${source.region ? ` · ${source.region}` : ''}`],
|
|
|
['一致性', backupConsistency(backup.consistency)], ['对象大小', bytes(backup.object_size_bytes)],
|
|
|
['虚拟磁盘容量', bytes(backup.virtual_size_bytes)], ['创建时间', date(backup.created_at)],
|
|
|
]));
|
|
|
if (source.deleted === true) {
|
|
|
cardBody.append(el('p', 'alert alert-warning fs-13',
|
|
|
'源实例已删除;该备份仍由独立目录保留,可恢复为新实例或确认删除。'));
|
|
|
}
|
|
|
if (backup.cleanup_pending === true) {
|
|
|
cardBody.append(el('p', 'text-warning fs-13', '远端备份可恢复,但源宿主机的临时工作区仍需核对。'));
|
|
|
if (backup.can_cleanup_workspace === true) {
|
|
|
const cleanupActions = el('div', 'd-flex justify-content-end mb-3');
|
|
|
cleanupActions.append(cleanupButton(vmId, backup, true)); cardBody.append(cleanupActions);
|
|
|
}
|
|
|
}
|
|
|
if (backup.error) cardBody.append(el('p', 'text-danger fs-13', backup.error));
|
|
|
const targets = backupTargets(payload, backup);
|
|
|
if (backup.state === 'ready') {
|
|
|
if (targets.length) cardBody.append(restoreForm(vmId, backup, targets, !canManage, true));
|
|
|
else cardBody.append(el('p', 'text-warning fs-13',
|
|
|
'暂无满足容量、存储、br0 网络和可用公网 IP 条件的宿主机。'));
|
|
|
}
|
|
|
if (backup.can_delete === true) {
|
|
|
const actions = el('div', 'd-flex justify-content-end mt-3');
|
|
|
actions.append(deleteButton(vmId, backup, true)); cardBody.append(actions);
|
|
|
} else if (!canManage
|
|
|
&& ['ready', 'failed', 'deleting', 'delete_uncertain', 'delete_attention'].includes(backup.state)) {
|
|
|
cardBody.append(el('p', 'text-muted fs-12 mb-0',
|
|
|
'当前管理员仅可查看,超级管理员才可以恢复或删除备份。'));
|
|
|
}
|
|
|
card.append(cardBody); container.append(card);
|
|
|
}
|
|
|
const pagination = payload?.pagination || {};
|
|
|
state.libraryPagination = {
|
|
|
page: Number(pagination.page) || 1,
|
|
|
total_pages: Number(pagination.total_pages) || 1,
|
|
|
total: Number(pagination.total) || 0,
|
|
|
};
|
|
|
state.libraryPage = state.libraryPagination.page;
|
|
|
byId('backup-library-page').textContent
|
|
|
= `第 ${state.libraryPagination.page} / ${state.libraryPagination.total_pages} 页 · 共 ${state.libraryPagination.total} 个`;
|
|
|
byId('backup-library-previous').disabled = state.libraryPagination.page <= 1;
|
|
|
byId('backup-library-next').disabled
|
|
|
= state.libraryPagination.page >= state.libraryPagination.total_pages;
|
|
|
}
|
|
|
|
|
|
async function loadLibrary(page = 1, force = false) {
|
|
|
const dialog = byId('backup-library');
|
|
|
if (!dialog?.open) return;
|
|
|
const normalizedPage = Math.max(1, Number(page) || 1);
|
|
|
if (!force && state.libraryRequest) return;
|
|
|
state.libraryRequest?.abort('replaced');
|
|
|
const controller = new AbortController(); const serial = state.librarySerial;
|
|
|
state.libraryRequest = controller;
|
|
|
libraryNotice('正在读取有界分页的对象存储备份目录…');
|
|
|
try {
|
|
|
const payload = await read(
|
|
|
`/api/v1/admin/backups?page=${encodeURIComponent(normalizedPage)}&per_page=20`, controller);
|
|
|
if (controller.signal.aborted || serial !== state.librarySerial || !dialog.open) return;
|
|
|
renderLibrary(payload); libraryNotice('');
|
|
|
} catch (error) {
|
|
|
if (controller.signal.aborted && controller.signal.reason !== 'timeout') return;
|
|
|
if (serial === state.librarySerial) libraryNotice(`${error.message} 请稍后重试。`, true);
|
|
|
} finally {
|
|
|
if (state.libraryRequest === controller) state.libraryRequest = null;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
function cancelInstance(reason = 'cancelled') {
|
|
|
state.serial += 1; state.request?.abort(reason); state.request = null;
|
|
|
state.mutationRequest?.abort(reason); state.mutationRequest = null;
|
|
|
state.observer?.stop(reason); state.observer = null;
|
|
|
state.loadedFor = null; state.currentId = null;
|
|
|
}
|
|
|
|
|
|
function cancelLibrary(reason = 'cancelled') {
|
|
|
state.librarySerial += 1; state.libraryRequest?.abort(reason); state.libraryRequest = null;
|
|
|
state.mutationRequest?.abort(reason); state.mutationRequest = null;
|
|
|
state.libraryObserver?.stop(reason); state.libraryObserver = null;
|
|
|
}
|
|
|
|
|
|
function finishLibraryClose() {
|
|
|
state.libraryClosing = false;
|
|
|
document.documentElement.classList.remove('admin-instance-detail-open');
|
|
|
document.body.style.removeProperty('--admin-instance-scroll-top');
|
|
|
if (state.libraryScroll) {
|
|
|
window.scrollTo({ left: state.libraryScroll.x, top: state.libraryScroll.y, behavior: 'instant' });
|
|
|
state.libraryScroll = null;
|
|
|
}
|
|
|
if (state.libraryOpener?.isConnected) state.libraryOpener.focus({ preventScroll: true });
|
|
|
state.libraryOpener = null;
|
|
|
}
|
|
|
|
|
|
function closeLibrary() {
|
|
|
const dialog = byId('backup-library');
|
|
|
if (state.libraryClosing || !dialog?.open) return;
|
|
|
cancelLibrary('closed'); state.libraryClosing = true;
|
|
|
void window.VenixDrawerMotion.closeDrawerWithMotion(dialog).then(closed => {
|
|
|
if (closed) finishLibraryClose(); else state.libraryClosing = false;
|
|
|
});
|
|
|
}
|
|
|
|
|
|
function openLibrary(opener) {
|
|
|
if (state.libraryClosing) return;
|
|
|
state.libraryOpener = opener; state.libraryPage = 1;
|
|
|
const dialog = byId('backup-library');
|
|
|
const body = dialog.querySelector('.admin-instance-drawer-body'); if (body) body.scrollTop = 0;
|
|
|
byId('backup-library-items').replaceChildren(); libraryNotice('正在读取备份库…');
|
|
|
if (!dialog.open) {
|
|
|
state.libraryScroll = { x: window.scrollX, y: window.scrollY };
|
|
|
document.body.style.setProperty('--admin-instance-scroll-top', `${-state.libraryScroll.y}px`);
|
|
|
document.documentElement.classList.add('admin-instance-detail-open');
|
|
|
window.VenixDrawerMotion.openDrawerWithMotion(dialog);
|
|
|
}
|
|
|
loadLibrary(1, true);
|
|
|
}
|
|
|
|
|
|
const handlers = {
|
|
|
close: closeLibrary,
|
|
|
previous: () => loadLibrary(state.libraryPagination.page - 1, true),
|
|
|
next: () => loadLibrary(state.libraryPagination.page + 1, true),
|
|
|
cancel: event => { event.preventDefault(); closeLibrary(); },
|
|
|
click: event => {
|
|
|
const dialog = byId('backup-library');
|
|
|
if (event.target !== dialog) return;
|
|
|
const rect = dialog.getBoundingClientRect();
|
|
|
if (event.clientX < rect.left || event.clientX > rect.right
|
|
|
|| event.clientY < rect.top || event.clientY > rect.bottom) closeLibrary();
|
|
|
},
|
|
|
popstate: closeLibrary,
|
|
|
pagehide: () => { cancelInstance('pagehide'); cancelLibrary('pagehide'); },
|
|
|
pageshow: event => { if (event.persisted) closeLibrary(); },
|
|
|
};
|
|
|
|
|
|
function start() {
|
|
|
if (state.started) return;
|
|
|
state.started = true;
|
|
|
const dialog = byId('backup-library');
|
|
|
byId('backup-library-close').addEventListener('click', handlers.close);
|
|
|
byId('backup-library-previous').addEventListener('click', handlers.previous);
|
|
|
byId('backup-library-next').addEventListener('click', handlers.next);
|
|
|
dialog.addEventListener('cancel', handlers.cancel); dialog.addEventListener('click', handlers.click);
|
|
|
window.addEventListener('popstate', handlers.popstate);
|
|
|
window.addEventListener('pagehide', handlers.pagehide);
|
|
|
window.addEventListener('pageshow', handlers.pageshow);
|
|
|
}
|
|
|
|
|
|
function dispose() {
|
|
|
if (!state.started) return;
|
|
|
cancelInstance('disposed'); closeLibrary(); state.started = false;
|
|
|
const dialog = byId('backup-library');
|
|
|
byId('backup-library-close').removeEventListener('click', handlers.close);
|
|
|
byId('backup-library-previous').removeEventListener('click', handlers.previous);
|
|
|
byId('backup-library-next').removeEventListener('click', handlers.next);
|
|
|
dialog.removeEventListener('cancel', handlers.cancel); dialog.removeEventListener('click', handlers.click);
|
|
|
window.removeEventListener('popstate', handlers.popstate);
|
|
|
window.removeEventListener('pagehide', handlers.pagehide);
|
|
|
window.removeEventListener('pageshow', handlers.pageshow);
|
|
|
}
|
|
|
|
|
|
return Object.freeze({
|
|
|
start,
|
|
|
load,
|
|
|
cancel: cancelInstance,
|
|
|
openLibrary,
|
|
|
closeLibrary,
|
|
|
dispose,
|
|
|
});
|
|
|
}
|