|
|
const assetVersion = new URL(import.meta.url).searchParams.get('v');
|
|
|
|
|
|
function versionedModuleUrl(path) {
|
|
|
const url = new URL(path, import.meta.url);
|
|
|
url.search = '';
|
|
|
if (assetVersion) url.searchParams.set('v', assetVersion);
|
|
|
return url.href;
|
|
|
}
|
|
|
|
|
|
const {
|
|
|
announceTaskAccepted, observeTask, recoveryTaskFailureNotice,
|
|
|
taskSucceededWithoutRecovery, taskUrl,
|
|
|
} = await import(versionedModuleUrl('./task-observer.js'));
|
|
|
|
|
|
const root = document.querySelector('[data-cloud-admin]');
|
|
|
const byId = id => document.getElementById(id);
|
|
|
const state = { csrf: window.ADMIN_CSRF_TOKEN || '', busy: false, epoch: 0, taskObservers: new Set() };
|
|
|
const requestRuntime = window.VenixAdminRequestRuntime.create({
|
|
|
csrfToken: () => state.csrf,
|
|
|
taskReceiptValidator: taskUrl,
|
|
|
});
|
|
|
let templateUploadController = null;
|
|
|
let catalogFilter = null;
|
|
|
let catalogEntries = [];
|
|
|
const confirmDanger = options => window.VenixAdminDangerDialog.confirm(options);
|
|
|
const REMOTE_IMPORT_STORAGE_KEY = 'virt-cloud:template-remote:v1';
|
|
|
// Permission state is rendered by the server on the page. API endpoints keep
|
|
|
// the authoritative authorization check; this only controls the UI affordances.
|
|
|
const canManage = root?.dataset.canManage === '1';
|
|
|
const collection = (payload, key = 'items') => Array.isArray(payload) ? payload : Array.isArray(payload?.[key]) ? payload[key] : Array.isArray(payload?.items) ? payload.items : [];
|
|
|
function element(tag, className = '', content) { const node = document.createElement(tag); node.className = className; if (content !== undefined) node.textContent = String(content); return node; }
|
|
|
function notice(message, error = false) { const box = byId('cloud-admin-status'); box.textContent = message; box.className = `alert ${error ? 'alert-danger' : 'alert-info'} cloud-admin-notice`; }
|
|
|
async function requestJson(path, options = {}) {
|
|
|
const method = String(options.method || 'GET').toUpperCase();
|
|
|
try {
|
|
|
if (['GET', 'HEAD'].includes(method)) {
|
|
|
return await requestRuntime.read(path, {
|
|
|
method, signal: options.signal, timeoutMs: options.timeoutMs,
|
|
|
headers: options.headers, returnMeta: true,
|
|
|
});
|
|
|
}
|
|
|
return await requestRuntime.mutate(path, {
|
|
|
method, body: options.body, signal: options.signal,
|
|
|
timeoutMs: options.timeoutMs, headers: options.headers,
|
|
|
response: 'json', returnMeta: true,
|
|
|
idempotencyKey: options.idempotencyKey,
|
|
|
});
|
|
|
} catch (error) {
|
|
|
if (error?.status === 401) location.assign('/auth/login');
|
|
|
if (error?.mutationMayHaveApplied === true) error.keepMutationLocked = true;
|
|
|
throw error;
|
|
|
}
|
|
|
}
|
|
|
async function api(path, options = {}) {
|
|
|
return (await requestJson(path, options)).payload;
|
|
|
}
|
|
|
async function acceptedTask(path, options = {}) {
|
|
|
try {
|
|
|
return await requestRuntime.mutate(path, {
|
|
|
method: options.method || 'POST', body: options.body,
|
|
|
signal: options.signal, timeoutMs: options.timeoutMs,
|
|
|
headers: options.headers, response: 'task',
|
|
|
});
|
|
|
} catch (error) {
|
|
|
if (error?.status === 401) location.assign('/auth/login');
|
|
|
if (error?.mutationMayHaveApplied === true) error.keepMutationLocked = true;
|
|
|
throw error;
|
|
|
}
|
|
|
}
|
|
|
function formList(value) { return String(value || '').split(/[\s,]+/).filter(Boolean); }
|
|
|
function remoteImportRecord(body) {
|
|
|
const canonical = JSON.stringify(body);
|
|
|
let storage = null; let record = null;
|
|
|
try {
|
|
|
storage = window.localStorage;
|
|
|
record = JSON.parse(storage?.getItem(REMOTE_IMPORT_STORAGE_KEY) || 'null');
|
|
|
} catch {}
|
|
|
if (!record || record.canonical !== canonical
|
|
|
|| !/^[A-Za-z0-9_.-]{16,128}$/.test(record.requestKey || '')) {
|
|
|
const suffix = typeof window.crypto?.randomUUID === 'function'
|
|
|
? window.crypto.randomUUID()
|
|
|
: `${Date.now()}-${Math.random().toString(36).slice(2)}`;
|
|
|
record = { canonical, requestKey: `template-remote-${suffix}` };
|
|
|
}
|
|
|
try { storage?.setItem(REMOTE_IMPORT_STORAGE_KEY, JSON.stringify(record)); }
|
|
|
catch {}
|
|
|
return record;
|
|
|
}
|
|
|
function clearRemoteImportRecord(record = null) {
|
|
|
try {
|
|
|
const storage = window.localStorage;
|
|
|
const current = JSON.parse(
|
|
|
storage?.getItem(REMOTE_IMPORT_STORAGE_KEY) || 'null'
|
|
|
);
|
|
|
if (record === null || current?.requestKey === record?.requestKey) {
|
|
|
storage.removeItem(REMOTE_IMPORT_STORAGE_KEY);
|
|
|
}
|
|
|
} catch {}
|
|
|
}
|
|
|
function catalogPath() { return root.dataset.cloudAdmin === 'rescue' ? '/api/v1/admin/rescue-templates' : '/api/v1/admin/cloud-templates'; }
|
|
|
function isRescueCatalog() { return root.dataset.cloudAdmin === 'rescue'; }
|
|
|
const startupScriptState = { epoch: 0, templateId: '', generationToken: '', revision: null, saving: false, opener: null };
|
|
|
function startupScriptNotice(message, error = false) {
|
|
|
const box = byId('template-startup-status');
|
|
|
box.textContent = message;
|
|
|
box.className = `alert ${error ? 'alert-danger' : 'alert-info'}`;
|
|
|
}
|
|
|
function startupScriptContextCurrent(templateId, epoch) {
|
|
|
return byId('template-startup-dialog').open
|
|
|
&& startupScriptState.templateId === templateId && startupScriptState.epoch === epoch;
|
|
|
}
|
|
|
function updateStartupScriptControls() {
|
|
|
const ready = startupScriptState.revision !== null;
|
|
|
byId('template-startup-script').readOnly = !canManage || !ready || startupScriptState.saving;
|
|
|
byId('template-startup-save').disabled = !canManage || !ready || startupScriptState.saving;
|
|
|
byId('template-startup-close').disabled = startupScriptState.saving;
|
|
|
byId('template-startup-bytes').textContent = `${new TextEncoder().encode(byId('template-startup-script').value.replace(/\r\n/g, '\n')).length} / 32768 字节`;
|
|
|
}
|
|
|
function closeStartupScript() {
|
|
|
if (startupScriptState.saving) return;
|
|
|
const dialog = byId('template-startup-dialog');
|
|
|
++startupScriptState.epoch;
|
|
|
startupScriptState.templateId = '';
|
|
|
startupScriptState.generationToken = '';
|
|
|
startupScriptState.revision = null;
|
|
|
byId('template-startup-script').value = '';
|
|
|
dialog.close();
|
|
|
if (startupScriptState.opener?.isConnected) startupScriptState.opener.focus();
|
|
|
startupScriptState.opener = null;
|
|
|
}
|
|
|
function applyStartupScriptPayload(payload, generationToken = '') {
|
|
|
if (!payload || typeof payload.startup_script !== 'string'
|
|
|
|| !Number.isSafeInteger(payload.revision) || payload.revision < 1
|
|
|
|| !/^[a-f0-9]{32}$/.test(payload.generation_token || '')
|
|
|
|| (generationToken && payload.generation_token !== generationToken)) {
|
|
|
throw new Error('镜像或脚本版本已变化,请刷新镜像目录后重新打开设置。');
|
|
|
}
|
|
|
byId('template-startup-script').value = payload.startup_script;
|
|
|
startupScriptState.generationToken = payload.generation_token;
|
|
|
startupScriptState.revision = payload.revision;
|
|
|
}
|
|
|
async function openStartupScript(entry, opener) {
|
|
|
if (startupScriptState.saving) return;
|
|
|
const templateId = String(entry.id);
|
|
|
const epoch = ++startupScriptState.epoch;
|
|
|
Object.assign(startupScriptState, { templateId, revision: null, generationToken: String(entry.generation_token || ''), opener });
|
|
|
byId('template-startup-title').textContent = `启动脚本 · ${entry.name || entry.id}`;
|
|
|
byId('template-startup-script').value = '';
|
|
|
startupScriptNotice('正在读取此镜像的启动脚本…');
|
|
|
updateStartupScriptControls();
|
|
|
const dialog = byId('template-startup-dialog');
|
|
|
if (!dialog.open) dialog.showModal();
|
|
|
try {
|
|
|
const payload = await api(`/api/v1/admin/cloud-templates/${encodeURIComponent(templateId)}/startup-script`);
|
|
|
if (!startupScriptContextCurrent(templateId, epoch)) return;
|
|
|
applyStartupScriptPayload(payload, startupScriptState.generationToken);
|
|
|
startupScriptNotice(canManage ? '保存后只用于随后新建实例;留空保存可停用。' : '当前管理员仅可查看此镜像的启动脚本。');
|
|
|
} catch (error) {
|
|
|
if (startupScriptContextCurrent(templateId, epoch)) startupScriptNotice(error.message, true);
|
|
|
} finally {
|
|
|
if (startupScriptContextCurrent(templateId, epoch)) updateStartupScriptControls();
|
|
|
}
|
|
|
}
|
|
|
async function saveStartupScript(event) {
|
|
|
event.preventDefault();
|
|
|
if (!canManage || startupScriptState.saving || startupScriptState.revision === null) return;
|
|
|
const script = byId('template-startup-script').value.replace(/\r\n/g, '\n');
|
|
|
if (script.includes('\0')) return startupScriptNotice('启动脚本不能包含 NUL 字符。', true);
|
|
|
if (new TextEncoder().encode(script).length > 32768) return startupScriptNotice('启动脚本不能超过 32 KiB。', true);
|
|
|
const { templateId, epoch, generationToken, revision } = startupScriptState;
|
|
|
startupScriptState.saving = true;
|
|
|
updateStartupScriptControls();
|
|
|
startupScriptNotice('正在保存启动脚本…');
|
|
|
try {
|
|
|
const payload = await api(`/api/v1/admin/cloud-templates/${encodeURIComponent(templateId)}/startup-script`, {
|
|
|
method: 'PATCH', body: { script, expected_revision: revision, generation_token: generationToken },
|
|
|
});
|
|
|
if (!startupScriptContextCurrent(templateId, epoch)) return;
|
|
|
applyStartupScriptPayload(payload, generationToken);
|
|
|
startupScriptNotice(script.length > 0 ? '启动脚本已保存,仅在随后新建实例的首次启动时执行。' : '已停用此镜像的启动脚本。');
|
|
|
} catch (error) {
|
|
|
if (startupScriptContextCurrent(templateId, epoch)) startupScriptNotice(error.message, true);
|
|
|
} finally {
|
|
|
startupScriptState.saving = false;
|
|
|
if (startupScriptContextCurrent(templateId, epoch)) updateStartupScriptControls();
|
|
|
}
|
|
|
}
|
|
|
function catalogStateView(value) {
|
|
|
const stateName = String(value || 'unknown').toLowerCase();
|
|
|
return ({
|
|
|
active: ['已就绪', 'is-ready'], degraded: ['部分可用', 'is-warning'],
|
|
|
error: ['不可用', 'is-error'], preparing: ['准备源文件', 'is-running'],
|
|
|
validating: ['首台校验', 'is-running'], distributing: ['分发中', 'is-running'],
|
|
|
source_failed: ['源文件失败', 'is-error'], source_unknown: ['源文件待核查', 'is-error'],
|
|
|
retiring: ['退役清理中', 'is-running'], retired: ['已退役', 'is-muted'],
|
|
|
importing: ['分发中', 'is-running'], syncing: ['同步中', 'is-running'],
|
|
|
deleting: ['删除中', 'is-running'], delete_failed: ['删除失败', 'is-error'],
|
|
|
}[stateName] || ['状态未知', 'is-muted']);
|
|
|
}
|
|
|
function replicaStateView(replica) {
|
|
|
if (replica?.host_record_present === false) return ['宿主机记录缺失', 'is-error'];
|
|
|
if (replica?.host_eligible !== true) return ['宿主机未就绪', 'is-muted'];
|
|
|
if (replica?.exact === true) return ['精确副本', 'is-ready'];
|
|
|
if (replica?.repair_reason === 'content_divergent') return ['内容分歧', 'is-error'];
|
|
|
const stateName = String(replica?.state || 'unknown').toLowerCase();
|
|
|
return ({
|
|
|
missing: ['缺少副本', 'is-warning'], stale: ['元数据落后', 'is-warning'],
|
|
|
pending: ['等待分发', 'is-running'], importing: ['正在分发', 'is-running'],
|
|
|
syncing: ['正在同步', 'is-running'], failed: ['失败并已锁定', 'is-error'],
|
|
|
deleting: ['正在删除', 'is-running'], delete_succeeded: ['已删除', 'is-muted'],
|
|
|
delete_failed: ['删除待核查', 'is-error'], active: ['投影不一致', 'is-error'],
|
|
|
}[stateName] || ['状态待核查', 'is-error']);
|
|
|
}
|
|
|
function catalogTime(value) {
|
|
|
const timestamp = Number(value || 0);
|
|
|
return timestamp > 0 ? new Date(timestamp * 1000).toLocaleString() : '尚未核对';
|
|
|
}
|
|
|
function compactIdentifier(value, size = 12) {
|
|
|
const text = String(value || '');
|
|
|
return text.length > size ? `${text.slice(0, size)}…` : text;
|
|
|
}
|
|
|
async function repairTemplateReplica(entry, replica, button) {
|
|
|
if (state.busy) return notice('请等待当前镜像任务完成。', true);
|
|
|
const action = String(replica?.repair_action || '');
|
|
|
if (!['import', 'metadata'].includes(action)) return;
|
|
|
const verb = action === 'metadata' ? '同步元数据' : '补齐副本';
|
|
|
if (!await confirmDanger({
|
|
|
tone: 'warning',
|
|
|
title: `${verb} · ${entry.name}`,
|
|
|
message: `系统会在 ${replica.host_name || `宿主机 #${replica.host_id}`} 创建独立任务;不会重放旧任务。`,
|
|
|
confirmText: verb,
|
|
|
})) return;
|
|
|
state.busy = true;
|
|
|
button.disabled = true;
|
|
|
try {
|
|
|
const { payload, status } = await requestJson(
|
|
|
`/api/v1/admin/cloud-templates/${encodeURIComponent(entry.id)}/replicas/${encodeURIComponent(replica.host_id)}/repair`,
|
|
|
{ method: 'POST', body: {} },
|
|
|
);
|
|
|
if (status === 200 && payload?.scheduled === false) {
|
|
|
await loadCatalog();
|
|
|
notice('副本已是目标版本,无需重复处理。');
|
|
|
return;
|
|
|
}
|
|
|
if (status !== 202 || !taskUrl(payload)) throw new Error('修复请求未返回严格的任务回执,请勿重复提交并联系管理员核查。');
|
|
|
const handle = importProgress(payload, verb, async () => {
|
|
|
await loadCatalog();
|
|
|
notice(`${verb}已完成。`);
|
|
|
});
|
|
|
if (handle) notice(`${verb}任务已接收(#${payload.task_id})。`);
|
|
|
} catch (error) {
|
|
|
notice(error.message, true);
|
|
|
button.disabled = !canManage;
|
|
|
} finally {
|
|
|
state.busy = false;
|
|
|
}
|
|
|
}
|
|
|
function replicaMatrix(entry) {
|
|
|
const details = element('details', 'cloud-template-matrix');
|
|
|
const replicas = Array.isArray(entry.replicas) ? entry.replicas : [];
|
|
|
const summaryData = entry.replica_summary || {};
|
|
|
const eligible = Number(summaryData.eligible || replicas.filter(item => item?.host_eligible === true).length);
|
|
|
const ready = Number(summaryData.ready || replicas.filter(item => item?.exact === true).length);
|
|
|
const attention = Number(summaryData.attention || Math.max(0, eligible - ready));
|
|
|
details.open = attention > 0;
|
|
|
const summary = element('summary', 'cloud-template-matrix-summary');
|
|
|
const summaryCopy = element('span');
|
|
|
summaryCopy.append(
|
|
|
element('strong', '', '宿主机副本'),
|
|
|
element('small', '', `${ready} / ${eligible} 台就绪${attention > 0 ? ` · ${attention} 台需处理` : ''}`),
|
|
|
);
|
|
|
summary.append(summaryCopy, element('span', 'cloud-template-matrix-arrow'));
|
|
|
details.append(summary);
|
|
|
if (!replicas.length) {
|
|
|
details.append(element('p', 'cloud-template-matrix-empty', '当前还没有计算节点记录。'));
|
|
|
return details;
|
|
|
}
|
|
|
const wrap = element('div', 'cloud-template-matrix-scroll');
|
|
|
const table = element('table', 'cloud-template-matrix-table');
|
|
|
const head = element('thead');
|
|
|
const headRow = element('tr');
|
|
|
for (const title of ['宿主机', '目标 / 实际', '状态', '最近核对', '操作']) headRow.append(element('th', '', title));
|
|
|
head.append(headRow);
|
|
|
const body = element('tbody');
|
|
|
for (const replica of replicas) {
|
|
|
const row = element('tr');
|
|
|
const host = element('td', 'cloud-template-host-cell'); host.setAttribute('data-label', '宿主机');
|
|
|
const hostContent = element('span', 'cloud-template-cell-content');
|
|
|
hostContent.append(element('strong', '', replica.host_name || `宿主机 #${replica.host_id}`));
|
|
|
hostContent.append(element('small', '', [replica.host_region, `#${Number(replica.host_id || 0)}`].filter(Boolean).join(' · ')));
|
|
|
host.append(hostContent);
|
|
|
const versions = element('td', 'cloud-template-version-cell'); versions.setAttribute('data-label', '目标 / 实际');
|
|
|
const versionContent = element('span', 'cloud-template-cell-content');
|
|
|
versionContent.append(element('strong', '', `r${Number(entry.revision || 0)} / ${Number(replica.revision || 0) > 0 ? `r${Number(replica.revision)}` : '—'}`));
|
|
|
versionContent.append(element('small', '', Number(replica.observed_revision || 0) > 0 ? `宿主机核对 r${Number(replica.observed_revision)}` : '暂无宿主机核对版本'));
|
|
|
versions.append(versionContent);
|
|
|
const stateCell = element('td'); stateCell.setAttribute('data-label', '状态');
|
|
|
const stateContent = element('span', 'cloud-template-cell-content');
|
|
|
const [stateLabel, stateClass] = replicaStateView(replica);
|
|
|
stateContent.append(element('span', `cloud-template-state ${stateClass}`, stateLabel));
|
|
|
const diagnostics = [replica.error_code, compactIdentifier(replica.operation_id)].filter(Boolean).join(' · ');
|
|
|
if (diagnostics) stateContent.append(element('small', 'cloud-template-diagnostic', diagnostics));
|
|
|
stateCell.append(stateContent);
|
|
|
const verified = element('td'); verified.setAttribute('data-label', '最近核对'); verified.append(element('span', 'cloud-template-cell-content', catalogTime(replica.last_verified_at)));
|
|
|
const actionCell = element('td', 'cloud-template-replica-action'); actionCell.setAttribute('data-label', '操作');
|
|
|
if (canManage && ['import', 'metadata'].includes(String(replica.repair_action || ''))) {
|
|
|
const actionLabel = replica.repair_action === 'metadata' ? '同步元数据' : '补齐副本';
|
|
|
const actionButton = element('button', 'btn btn-sm btn-outline-primary', actionLabel);
|
|
|
actionButton.type = 'button';
|
|
|
actionButton.addEventListener('click', () => repairTemplateReplica(entry, replica, actionButton));
|
|
|
actionCell.append(actionButton);
|
|
|
} else {
|
|
|
actionCell.append(element('span', 'text-muted', '—'));
|
|
|
}
|
|
|
row.append(host, versions, stateCell, verified, actionCell);
|
|
|
body.append(row);
|
|
|
}
|
|
|
table.append(head, body); wrap.append(table); details.append(wrap);
|
|
|
return details;
|
|
|
}
|
|
|
function bindCloudTemplateActions(entry, form, name, save, remove, startup) {
|
|
|
const catalogState = String(entry.state || '').toLowerCase();
|
|
|
const active = catalogState === 'active';
|
|
|
const cleanupReason = String(entry.cleanup_reason || '');
|
|
|
const partialCleanup = ['partial_import', 'partial_delete'].includes(cleanupReason);
|
|
|
form.addEventListener('submit', async event => {
|
|
|
event.preventDefault();
|
|
|
if (!active) return notice('镜像尚未完全就绪,不能修改名称。', true);
|
|
|
if (state.busy) return notice('请等待当前镜像任务完成。', true);
|
|
|
save.disabled = true; state.busy = true;
|
|
|
try {
|
|
|
const receipt = await acceptedTask(`${catalogPath()}/${encodeURIComponent(entry.id)}`, {
|
|
|
method: 'PATCH', body: { name: name.value.trim(), expected_revision: Number(entry.revision), generation_token: String(entry.generation_token || '') },
|
|
|
});
|
|
|
const handle = importProgress(receipt, '同步镜像名称', async () => { await loadCatalog(); notice('名称已保存。'); }, task => {
|
|
|
save.disabled = !canManage || !active || task.safe_to_resubmit !== true;
|
|
|
});
|
|
|
if (handle) notice(`名称同步任务已接收(#${receipt.task_id})。`);
|
|
|
} catch (error) {
|
|
|
notice(error.message, true); save.disabled = !canManage || !active || error.keepMutationLocked === true;
|
|
|
} finally { state.busy = false; }
|
|
|
});
|
|
|
startup.addEventListener('click', () => openStartupScript(entry, startup));
|
|
|
remove.addEventListener('click', async () => {
|
|
|
if (state.busy) return notice('请等待当前镜像任务完成。', true);
|
|
|
const message = cleanupReason === 'partial_import'
|
|
|
? `云镜像模板“${entry.name}”仅在部分宿主机导入成功。确定清理已存在的剩余副本?`
|
|
|
: cleanupReason === 'partial_delete'
|
|
|
? `云镜像模板“${entry.name}”仍有部分宿主机副本未删除。确定继续清理剩余副本?`
|
|
|
: cleanupReason === 'artifact_delete_attention'
|
|
|
? `云镜像模板“${entry.name}”的宿主机副本已删除,但对象存储主副本需要重新核对。确定只重试主副本清理?不会再次向宿主机发送删除请求。`
|
|
|
: `删除全局云镜像模板“${entry.name}”?删除后不能再用于新建或重装;已创建实例不受影响。`;
|
|
|
if (!await confirmDanger({
|
|
|
title: partialCleanup ? '清理云镜像残留' : '永久删除云镜像版本',
|
|
|
message,
|
|
|
requiredText: String(entry.name),
|
|
|
requiredLabel: '输入完整镜像名称',
|
|
|
confirmText: partialCleanup ? '清理残留' : '永久删除',
|
|
|
})) return;
|
|
|
remove.disabled = true; state.busy = true;
|
|
|
try {
|
|
|
const result = await api(`${catalogPath()}/${encodeURIComponent(entry.id)}`, {
|
|
|
method: 'DELETE', body: { expected_revision: Number(entry.revision), generation_token: String(entry.generation_token || '') },
|
|
|
});
|
|
|
if (result?.deleted === true) { await loadCatalog(); notice('镜像模板及其受管文件已确认删除。'); }
|
|
|
else if (result?.recovery_restarted === true) {
|
|
|
await loadCatalog();
|
|
|
notice('主副本清理已重新进入安全核对;不会再次删除宿主机副本。');
|
|
|
}
|
|
|
else {
|
|
|
importProgress(result, partialCleanup ? '清理镜像模板' : '删除镜像模板', async () => {
|
|
|
await loadCatalog(); notice(partialCleanup ? '镜像模板剩余宿主机副本已清理。' : '镜像模板及其受管文件已确认删除。');
|
|
|
});
|
|
|
notice('任务已接收,正在后台删除。');
|
|
|
}
|
|
|
} catch (error) { notice(error.message, true); remove.disabled = !canManage; }
|
|
|
finally { state.busy = false; }
|
|
|
});
|
|
|
}
|
|
|
function cloudTemplateVersion(entry) {
|
|
|
const card = element('article', 'cloud-template-version-card');
|
|
|
card.dataset.catalogEntryId = String(entry.id);
|
|
|
card.dataset.catalogState = String(entry.state || 'unknown').toLowerCase();
|
|
|
const header = element('div', 'cloud-template-version-head');
|
|
|
const identity = element('div', 'cloud-template-version-identity');
|
|
|
const badges = element('div', 'cloud-template-version-badges');
|
|
|
const [stateLabel, stateClass] = catalogStateView(entry.state);
|
|
|
badges.append(element('span', `cloud-template-state ${stateClass}`, stateLabel));
|
|
|
if (entry.is_default === true) badges.append(element('span', 'cloud-template-default', '当前默认版本'));
|
|
|
identity.append(badges, element('strong', '', entry.name || entry.id));
|
|
|
identity.append(element('small', '', `版本 ${entry.version_label || '未标记'} · 目录修订 r${Number(entry.revision || 0)}`));
|
|
|
const imageBytes = Number(entry.image_bytes || 0);
|
|
|
const master = element('div', 'cloud-template-master-meta');
|
|
|
const artifactState = String(entry.artifact?.state || 'missing');
|
|
|
master.append(
|
|
|
element('span', '', imageBytes > 0 ? `${(imageBytes / 1024 ** 3).toFixed(2)} GiB` : '大小待确认'),
|
|
|
element('span', 'admin-mono', `SHA ${compactIdentifier(entry.sha256, 14) || '—'}`),
|
|
|
element('span', 'admin-mono', `GEN ${compactIdentifier(entry.generation_token, 10) || '—'}`),
|
|
|
element('span', 'admin-mono', `MASTER ${artifactState}`),
|
|
|
);
|
|
|
header.append(identity, master);
|
|
|
const form = element('form', 'cloud-template-version-form');
|
|
|
const nameWrap = element('div', 'cloud-template-name-field');
|
|
|
const nameLabel = element('label', 'form-label', '显示名称'); nameLabel.setAttribute('for', `template-name-${entry.id}`);
|
|
|
const name = element('input', 'form-control'); name.id = `template-name-${entry.id}`; name.value = entry.name || ''; name.maxLength = 64; name.required = true;
|
|
|
const active = String(entry.state || '').toLowerCase() === 'active'; name.disabled = !canManage || !active;
|
|
|
nameWrap.append(nameLabel, name);
|
|
|
const actions = element('div', 'cloud-template-version-actions');
|
|
|
const save = element('button', 'btn btn-outline-primary', '保存名称'); save.type = 'submit'; save.disabled = !canManage || !active;
|
|
|
const startup = element('button', 'btn btn-outline-secondary', canManage ? '启动脚本' : '查看脚本'); startup.type = 'button'; startup.disabled = !active;
|
|
|
const cleanupReason = String(entry.cleanup_reason || '');
|
|
|
const partialCleanup = ['partial_import', 'partial_delete'].includes(cleanupReason);
|
|
|
const removeLabel = cleanupReason === 'artifact_delete_attention' ? '重新核对主副本' : (partialCleanup ? '清理残留' : '删除版本');
|
|
|
const remove = element('button', 'btn btn-outline-danger', removeLabel); remove.type = 'button'; remove.disabled = !canManage;
|
|
|
actions.append(save, startup, remove); form.append(nameWrap, actions);
|
|
|
bindCloudTemplateActions(entry, form, name, save, remove, startup);
|
|
|
card.append(header, form, replicaMatrix(entry));
|
|
|
return card;
|
|
|
}
|
|
|
function cloudTemplateAvailable(entry) {
|
|
|
return ['active', 'degraded'].includes(String(entry?.state || '').toLowerCase());
|
|
|
}
|
|
|
function renderCloudTemplates(list, entries) {
|
|
|
const groups = new Map();
|
|
|
for (const entry of entries) {
|
|
|
const key = String(entry.catalog_key || `${entry.os_family || '镜像'}-${entry.os_version || ''}`);
|
|
|
if (!groups.has(key)) groups.set(key, { key, family: entry.os_family || '云镜像', version: entry.os_version || '', entries: [] });
|
|
|
groups.get(key).entries.push(entry);
|
|
|
}
|
|
|
for (const group of groups.values()) {
|
|
|
const section = element('section', 'cloud-template-family');
|
|
|
const head = element('div', 'cloud-template-family-head');
|
|
|
const title = element('div'); title.append(element('h6', '', `${group.family} ${group.version}`.trim()), element('small', 'admin-mono', group.key));
|
|
|
const available = group.entries.filter(cloudTemplateAvailable).length;
|
|
|
head.append(title, element('span', 'cloud-template-version-count', `${available} 可用 / ${group.entries.length} 条记录`));
|
|
|
const versions = element('div', 'cloud-template-version-list');
|
|
|
group.entries.sort((left, right) => Number(right.is_default === true) - Number(left.is_default === true) || Number(right.created_at || 0) - Number(left.created_at || 0));
|
|
|
for (const entry of group.entries) versions.append(cloudTemplateVersion(entry));
|
|
|
section.append(head, versions); list.append(section);
|
|
|
}
|
|
|
}
|
|
|
function rescueReplicaStateView(entry, replica) {
|
|
|
const stateName = String(replica?.state || 'missing').toLowerCase();
|
|
|
if (stateName === 'deleted') return ['已清理', 'is-muted'];
|
|
|
if (stateName === 'deleting') return ['正在清理', 'is-running'];
|
|
|
if (stateName === 'delete_unknown') return ['删除效果待核查', 'is-error'];
|
|
|
if (stateName === 'delete_failed') return ['删除失败', 'is-error'];
|
|
|
if (replica?.host_record_present === false) return ['宿主机记录缺失', 'is-error'];
|
|
|
if (replica?.host_eligible !== true) return ['宿主机未就绪', 'is-muted'];
|
|
|
if (replica?.exact === true) return ['精确副本', 'is-ready'];
|
|
|
return ({
|
|
|
missing: ['缺少副本', 'is-warning'], stale: ['版本不一致', 'is-error'],
|
|
|
pending: ['等待分发', 'is-running'], importing: ['正在分发', 'is-running'],
|
|
|
import_unknown: ['导入效果待核查', 'is-error'], failed: ['导入失败', 'is-error'],
|
|
|
active: ['内容不一致', 'is-error'],
|
|
|
}[stateName] || [String(entry?.state || '') === 'retiring' ? '等待清理' : '状态待核查', 'is-error']);
|
|
|
}
|
|
|
async function repairRescueReplica(entry, replica, button) {
|
|
|
if (state.busy || replica?.repair_action !== 'import') return;
|
|
|
if (!await confirmDanger({
|
|
|
tone: 'warning',
|
|
|
title: `补齐救援 ISO · ${entry.name}`,
|
|
|
message: `系统会在 ${replica.host_name || `宿主机 #${replica.host_id}`} 创建独立分发任务,以补齐内容一致的精确副本。`,
|
|
|
confirmText: '补齐副本',
|
|
|
})) return;
|
|
|
state.busy = true; button.disabled = true;
|
|
|
try {
|
|
|
const { payload, status } = await requestJson(
|
|
|
`/api/v1/admin/rescue-templates/${encodeURIComponent(entry.id)}/replicas/${encodeURIComponent(replica.host_id)}/repair`,
|
|
|
{ method: 'POST', body: {} },
|
|
|
);
|
|
|
if (status === 200 && payload?.scheduled === false) {
|
|
|
await loadCatalog(); notice('宿主机已经具有精确副本,无需重复处理。'); return;
|
|
|
}
|
|
|
if (status !== 202 || !taskUrl(payload)) throw new Error('补齐请求未返回严格的任务回执,请勿重复提交并联系管理员核查。');
|
|
|
const handle = importProgress(payload, '补齐救援 ISO 副本', async () => {
|
|
|
await loadCatalog(); notice('救援 ISO 副本已补齐。');
|
|
|
});
|
|
|
if (handle) notice(`副本补齐任务已接收(#${payload.task_id})。`);
|
|
|
} catch (error) { notice(error.message, true); button.disabled = !canManage; }
|
|
|
finally { state.busy = false; }
|
|
|
}
|
|
|
function rescueReplicaMatrix(entry) {
|
|
|
const details = element('details', 'cloud-template-matrix');
|
|
|
const replicas = Array.isArray(entry.replicas) ? entry.replicas : [];
|
|
|
const totals = entry.replica_summary || {};
|
|
|
const summary = element('summary', 'cloud-template-matrix-summary');
|
|
|
const label = element('span');
|
|
|
label.append(
|
|
|
element('strong', '', '宿主机副本'),
|
|
|
element('small', '', `${Number(totals.ready || 0)} / ${Number(totals.eligible || 0)} 台精确`),
|
|
|
);
|
|
|
if (Number(totals.cleanup_debt || 0) > 0) label.append(element('small', 'text-danger', `${Number(totals.cleanup_debt)} 台待清理`));
|
|
|
summary.append(label, element('span', 'cloud-template-matrix-arrow'));
|
|
|
details.append(summary);
|
|
|
if (!replicas.length) {
|
|
|
details.append(element('p', 'cloud-template-matrix-empty', '尚无宿主机记录。'));
|
|
|
return details;
|
|
|
}
|
|
|
const wrap = element('div', 'cloud-template-matrix-scroll');
|
|
|
const table = element('table', 'cloud-template-matrix-table');
|
|
|
const head = element('thead'); const headRow = element('tr');
|
|
|
for (const title of ['宿主机', '目录 / 实际', '状态', '最近核对', '操作']) headRow.append(element('th', '', title));
|
|
|
head.append(headRow); const body = element('tbody');
|
|
|
for (const replica of replicas) {
|
|
|
const row = element('tr');
|
|
|
const host = element('td', 'cloud-template-host-cell'); host.setAttribute('data-label', '宿主机');
|
|
|
host.append(element('strong', '', replica.host_name || `宿主机 #${replica.host_id}`), element('small', '', replica.host_region || (replica.host_enabled ? '地区未设置' : '已停用')));
|
|
|
const versions = element('td', 'cloud-template-version-cell'); versions.setAttribute('data-label', '目录 / 实际');
|
|
|
versions.append(
|
|
|
element('strong', 'admin-mono', `r${Number(entry.revision || 0)} / r${Number(replica.revision || 0)}`),
|
|
|
element('small', 'admin-mono', `GEN ${compactIdentifier(replica.generation_token, 10) || '—'}`),
|
|
|
element('small', 'admin-mono', `OBS r${Number(replica.observed_revision || 0)} · ${compactIdentifier(replica.observed_generation_token, 10) || '—'}`),
|
|
|
);
|
|
|
const status = element('td'); status.setAttribute('data-label', '状态');
|
|
|
const statusContent = element('span', 'cloud-template-cell-content');
|
|
|
const [statusLabel, statusClass] = rescueReplicaStateView(entry, replica);
|
|
|
statusContent.append(element('span', `cloud-template-state ${statusClass}`, statusLabel));
|
|
|
const diagnostics = [replica.error_code, compactIdentifier(replica.operation_id)].filter(Boolean).join(' · ');
|
|
|
if (diagnostics) statusContent.append(element('small', 'cloud-template-diagnostic', diagnostics));
|
|
|
status.append(statusContent);
|
|
|
const verified = element('td'); verified.setAttribute('data-label', '最近核对');
|
|
|
verified.append(element('span', 'cloud-template-cell-content', catalogTime(replica.last_verified_at)));
|
|
|
const actions = element('td', 'cloud-template-replica-action'); actions.setAttribute('data-label', '操作');
|
|
|
if (canManage && replica.repair_action === 'import') {
|
|
|
const repair = element('button', 'btn btn-sm btn-outline-primary', '补齐副本'); repair.type = 'button';
|
|
|
repair.addEventListener('click', () => repairRescueReplica(entry, replica, repair)); actions.append(repair);
|
|
|
} else actions.append(element('span', 'text-muted', '—'));
|
|
|
row.append(host, versions, status, verified, actions); body.append(row);
|
|
|
}
|
|
|
table.append(head, body); wrap.append(table); details.append(wrap);
|
|
|
return details;
|
|
|
}
|
|
|
function rescueTemplateCard(entry) {
|
|
|
const card = element('article', 'cloud-template-version-card');
|
|
|
card.dataset.catalogEntryId = String(entry.id);
|
|
|
card.dataset.catalogState = String(entry.state || 'unknown').toLowerCase();
|
|
|
const header = element('div', 'cloud-template-version-head');
|
|
|
const identity = element('div', 'cloud-template-version-identity');
|
|
|
const badges = element('div', 'cloud-template-version-badges');
|
|
|
const [stateLabel, stateClass] = catalogStateView(entry.state);
|
|
|
badges.append(element('span', `cloud-template-state ${stateClass}`, stateLabel));
|
|
|
identity.append(badges, element('strong', '', entry.name || entry.id));
|
|
|
identity.append(element('small', '', `目录修订 r${Number(entry.revision || 0)} · ${catalogTime(entry.created_at)}`));
|
|
|
const metadata = element('div', 'cloud-template-master-meta');
|
|
|
const bytes = Number(entry.size_bytes || 0);
|
|
|
metadata.append(
|
|
|
element('span', '', bytes > 0 ? `${(bytes / 1024 ** 3).toFixed(2)} GiB` : '大小待确认'),
|
|
|
element('span', 'admin-mono', `SHA ${compactIdentifier(entry.sha256, 14) || '—'}`),
|
|
|
element('span', 'admin-mono', `GEN ${compactIdentifier(entry.generation_token, 10) || '—'}`),
|
|
|
element('span', 'admin-mono', `MASTER ${String(entry.artifact?.state || 'missing')}`),
|
|
|
);
|
|
|
header.append(identity, metadata);
|
|
|
const actionBar = element('div', 'cloud-rescue-version-actions');
|
|
|
const warning = element('p', 'cloud-rescue-version-note', String(entry.state || '') === 'retiring'
|
|
|
? `正在清理:${Number(entry.replica_summary?.cleanup_debt || 0)} 台宿主机仍有清理债务。`
|
|
|
: '删除后会立即停止新挂载;已经挂载救援介质的实例必须先退出救援。');
|
|
|
const remove = element('button', 'btn btn-outline-danger', String(entry.state || '') === 'retiring' ? '正在退役' : '退役并清理');
|
|
|
remove.type = 'button'; remove.disabled = !canManage || String(entry.state || '') === 'retiring';
|
|
|
remove.addEventListener('click', async () => {
|
|
|
if (state.busy || !await confirmDanger({
|
|
|
title: '退役并清理救援 ISO',
|
|
|
message: `全局救援 ISO“${entry.name}”会立即停止新挂载,并异步删除全部宿主机副本与对象存储精确版本。请输入完整名称继续。`,
|
|
|
requiredText: String(entry.name),
|
|
|
requiredLabel: '输入完整救援 ISO 名称',
|
|
|
confirmText: '退役并清理',
|
|
|
})) return;
|
|
|
state.busy = true; remove.disabled = true;
|
|
|
try {
|
|
|
const result = await api(`${catalogPath()}/${encodeURIComponent(entry.id)}`, {
|
|
|
method: 'DELETE', body: { expected_revision: Number(entry.revision), generation_token: String(entry.generation_token || '') },
|
|
|
});
|
|
|
await loadCatalog();
|
|
|
const scheduled = Array.isArray(result?.tasks) ? result.tasks.length : 0;
|
|
|
notice(scheduled > 0 ? `救援 ISO 已停止使用,并调度 ${scheduled} 个宿主机清理任务。` : '救援 ISO 已停止使用,后台将继续核对清理。');
|
|
|
} catch (error) { notice(error.message, true); remove.disabled = !canManage; }
|
|
|
finally { state.busy = false; }
|
|
|
});
|
|
|
actionBar.append(warning, remove);
|
|
|
card.append(header, actionBar, rescueReplicaMatrix(entry));
|
|
|
return card;
|
|
|
}
|
|
|
function renderRescueTemplates(list, entries) {
|
|
|
for (const entry of entries) list.append(rescueTemplateCard(entry));
|
|
|
}
|
|
|
function applyCatalogFilters() {
|
|
|
if (!catalogFilter) return;
|
|
|
const list = byId('catalog-list');
|
|
|
const entries = catalogFilter.apply(catalogEntries);
|
|
|
const visible = new Set(entries.map(entry => String(entry.id)));
|
|
|
for (const card of list.querySelectorAll('[data-catalog-entry-id]')) {
|
|
|
card.hidden = !visible.has(card.dataset.catalogEntryId);
|
|
|
}
|
|
|
for (const family of list.querySelectorAll('.cloud-template-family')) {
|
|
|
const cards = [...family.querySelectorAll('[data-catalog-entry-id]')];
|
|
|
const shown = cards.filter(card => !card.hidden).length;
|
|
|
family.hidden = shown === 0;
|
|
|
const count = family.querySelector('.cloud-template-version-count');
|
|
|
if (count) count.textContent = `显示 ${shown} / ${cards.length} 条记录`;
|
|
|
}
|
|
|
const empty = list.querySelector('[data-catalog-filter-empty]');
|
|
|
if (empty) empty.hidden = entries.length > 0;
|
|
|
}
|
|
|
function renderCatalog() {
|
|
|
const list = byId('catalog-list'); list.replaceChildren();
|
|
|
if (!catalogEntries.length) list.append(element('p', 'text-muted py-3', '暂无镜像。'));
|
|
|
else {
|
|
|
if (isRescueCatalog()) renderRescueTemplates(list, catalogEntries);
|
|
|
else renderCloudTemplates(list, catalogEntries);
|
|
|
const empty = element('p', 'text-muted py-3', '没有符合筛选条件的镜像,请调整或清空条件。');
|
|
|
empty.dataset.catalogFilterEmpty = ''; empty.hidden = true; list.append(empty);
|
|
|
}
|
|
|
applyCatalogFilters();
|
|
|
}
|
|
|
async function loadCatalog() {
|
|
|
const rescue = isRescueCatalog();
|
|
|
const epoch = ++state.epoch;
|
|
|
const list = byId('catalog-list'); list.replaceChildren();
|
|
|
notice(rescue ? '正在读取救援 ISO 目录与副本矩阵…' : '正在读取云镜像版本与副本矩阵…');
|
|
|
try {
|
|
|
const payload = await api(catalogPath()); if (epoch !== state.epoch) return;
|
|
|
const entries = collection(payload, 'templates');
|
|
|
catalogEntries = entries;
|
|
|
renderCatalog();
|
|
|
if (rescue) {
|
|
|
const available = entries.filter(entry => ['active', 'degraded'].includes(String(entry.state || ''))).length;
|
|
|
notice(`已加载 ${entries.length} 个救援 ISO:${available} 个可挂载,${entries.length - available} 个正在处理或需核查。`);
|
|
|
}
|
|
|
else {
|
|
|
const available = entries.filter(cloudTemplateAvailable).length;
|
|
|
notice(`已加载 ${entries.length} 条云镜像记录:${available} 个可用,${entries.length - available} 个不可用。`);
|
|
|
}
|
|
|
} catch (error) { if (epoch === state.epoch) notice(error.message, true); }
|
|
|
}
|
|
|
function taskFailureMessage(task, fallback) {
|
|
|
const message = task?.error || fallback;
|
|
|
const recoveryNotice = recoveryTaskFailureNotice(task);
|
|
|
if (recoveryNotice) return recoveryNotice;
|
|
|
if (task?.effect_may_have_applied) {
|
|
|
return `${message} 操作效果可能已经发生,请勿再次提交,并将任务编号交由管理员核查。`;
|
|
|
}
|
|
|
return task?.safe_to_resubmit === false
|
|
|
? `${message} 此任务不可再次提交,请联系管理员核查。` : message;
|
|
|
}
|
|
|
function importProgress(result, title = '导入镜像', onSuccess = loadCatalog, onFailure = null) {
|
|
|
announceTaskAccepted(result, { title });
|
|
|
const handle = observeTask(result, {
|
|
|
onUpdate: () => notice(`${title}任务正在后台执行。`),
|
|
|
onTerminal: task => {
|
|
|
if (taskSucceededWithoutRecovery(task)) {
|
|
|
void Promise.resolve(onSuccess()).catch(error => notice(error.message, true));
|
|
|
} else {
|
|
|
notice(taskFailureMessage(task, `${title}失败。`), true);
|
|
|
if (typeof onFailure === 'function') void Promise.resolve(onFailure(task)).catch(error => notice(error.message, true));
|
|
|
}
|
|
|
},
|
|
|
onStop: reason => {
|
|
|
if (reason === 'deadline') notice('自动观察已停止。任务仍在后台执行,请通过任务中心 API 刷新结果。');
|
|
|
},
|
|
|
});
|
|
|
if (!handle.url) {
|
|
|
notice(`${title}任务已接收,但任务回执协议无效。请勿再次提交,并联系管理员核查。`, true);
|
|
|
return null;
|
|
|
}
|
|
|
state.taskObservers.add(handle);
|
|
|
void handle.done.finally(() => state.taskObservers.delete(handle));
|
|
|
return handle;
|
|
|
}
|
|
|
async function importTemplate(event) {
|
|
|
event.preventDefault(); if (state.busy) return;
|
|
|
const sha256 = byId('template-sha256').value.trim().toLowerCase();
|
|
|
if (sha256 && !/^[a-f0-9]{64}$/.test(sha256)) return notice('SHA-256 可留空;如果填写,请输入完整的 64 位十六进制校验值。', true);
|
|
|
const body = { name: byId('template-name').value.trim(), url: byId('template-url').value.trim() };
|
|
|
if (sha256) body.sha256 = sha256;
|
|
|
const record = remoteImportRecord(body);
|
|
|
const button = byId('template-import-button'); state.busy = true; button.disabled = true;
|
|
|
notice('正在下载、校验并保存官方云镜像;中断后会保留同一导入记录。');
|
|
|
try {
|
|
|
const result = await api('/api/v1/admin/cloud-template-imports/remote', {
|
|
|
method: 'POST', body, idempotencyKey: record.requestKey,
|
|
|
timeoutMs: 3600000,
|
|
|
});
|
|
|
clearRemoteImportRecord(record);
|
|
|
byId('template-import').reset();
|
|
|
await templateUploadController?.refresh();
|
|
|
if (importProgress(result, '导入云镜像', async () => {
|
|
|
await loadCatalog(); notice('镜像导入已完成。');
|
|
|
})) notice('官方镜像已保存,宿主机分发任务已接收。');
|
|
|
}
|
|
|
catch (error) {
|
|
|
await templateUploadController?.refresh();
|
|
|
notice(error.message, true);
|
|
|
} finally { state.busy = false; button.disabled = !canManage; }
|
|
|
}
|
|
|
async function importRescue(event) {
|
|
|
event.preventDefault();
|
|
|
if (state.busy) return;
|
|
|
const name = byId('rescue-name').value.trim();
|
|
|
const url = byId('rescue-url').value.trim();
|
|
|
const sha256 = byId('rescue-sha256').value.trim().toLowerCase();
|
|
|
if (!name || name.length > 64) return notice('请填写 1 至 64 个字符的救援镜像名称。', true);
|
|
|
if (sha256 && !/^[a-f0-9]{64}$/.test(sha256)) return notice('SHA-256 可留空;如果填写,请输入完整的 64 位十六进制校验值。', true);
|
|
|
try {
|
|
|
const parsed = new URL(url);
|
|
|
if (parsed.protocol !== 'https:' || (parsed.port && parsed.port !== '443') || parsed.username || parsed.password || parsed.hash || !parsed.pathname.toLowerCase().endsWith('.iso')) throw new Error();
|
|
|
} catch { return notice('请填写无需账号、使用 443 端口并以 .iso 结尾的 HTTPS 直链。', true); }
|
|
|
const body = { name, url }; if (sha256) body.sha256 = sha256;
|
|
|
const button = byId('rescue-import-button'); state.busy = true; button.disabled = true;
|
|
|
notice('正在隔离下载并保存救援 ISO,请勿重复提交…');
|
|
|
try {
|
|
|
const result = await api(catalogPath(), { method: 'POST', body });
|
|
|
byId('rescue-import').reset();
|
|
|
if (result?.validation_scheduled === true && taskUrl(result)) {
|
|
|
const handle = importProgress(result, '首台宿主机校验', async () => {
|
|
|
await loadCatalog(); notice('首台宿主机校验完成,正在向其余宿主机分发。');
|
|
|
});
|
|
|
if (handle) notice(`救援 ISO 已进入隔离目录,首台校验任务已接收(#${result.task_id})。`);
|
|
|
} else {
|
|
|
await loadCatalog();
|
|
|
notice('救援 ISO 已进入隔离目录;首台校验未立即调度,后台协调器会继续核对。');
|
|
|
}
|
|
|
} catch (error) { notice(error.message, true); }
|
|
|
finally { state.busy = false; button.disabled = !canManage; }
|
|
|
}
|
|
|
async function initialize(expectedKind) {
|
|
|
if (!root || root.dataset.cloudAdmin !== expectedKind) return;
|
|
|
window.addEventListener('pagehide', event => {
|
|
|
if (!event.persisted) catalogFilter?.destroy();
|
|
|
templateUploadController?.destroy();
|
|
|
for (const observer of state.taskObservers) observer.stop('pagehide');
|
|
|
state.taskObservers.clear();
|
|
|
});
|
|
|
try {
|
|
|
if (byId('catalog-filter')) {
|
|
|
const { mountAdminCatalogFilter } = await import(versionedModuleUrl('./admin-catalog-filter.js'));
|
|
|
catalogFilter = mountAdminCatalogFilter({ form: byId('catalog-filter'),
|
|
|
count: byId('catalog-filter-count'), onChange: applyCatalogFilters });
|
|
|
}
|
|
|
const session = await api('/api/v1/session');
|
|
|
state.csrf = session.csrf_token || state.csrf;
|
|
|
if (!session.admin) throw new Error('需要管理员权限。');
|
|
|
if (!state.csrf) throw new Error('会话令牌缺失,请重新登录。');
|
|
|
if (expectedKind === 'templates') {
|
|
|
const { mountTemplateUpload } = await import(versionedModuleUrl('./admin-template-upload.js'));
|
|
|
templateUploadController = mountTemplateUpload({
|
|
|
requestRuntime, notice, confirmDanger, canManage,
|
|
|
isBusy: () => state.busy,
|
|
|
setBusy: value => { state.busy = value; },
|
|
|
onRemoteSettled: () => clearRemoteImportRecord(),
|
|
|
onTask: (task, sourceKind = 'upload') => {
|
|
|
const remote = sourceKind === 'remote';
|
|
|
const title = remote ? '导入官方云镜像' : '导入本地云镜像';
|
|
|
if (importProgress(task, title, async () => {
|
|
|
await loadCatalog();
|
|
|
notice(remote ? '官方云镜像导入完成。'
|
|
|
: '本地云镜像上传并导入完成。');
|
|
|
})) notice(remote ? '官方镜像已保存,导入任务已接收。'
|
|
|
: '文件已直传对象存储,导入任务已接收。');
|
|
|
},
|
|
|
});
|
|
|
byId('template-import')?.addEventListener('submit', importTemplate); byId('template-catalog-refresh')?.addEventListener('click', loadCatalog); byId('template-startup-form').addEventListener('submit', saveStartupScript); byId('template-startup-close').addEventListener('click', closeStartupScript); byId('template-startup-script').addEventListener('input', updateStartupScriptControls); byId('template-startup-dialog').addEventListener('cancel', event => { event.preventDefault(); closeStartupScript(); }); await loadCatalog();
|
|
|
return;
|
|
|
}
|
|
|
byId('rescue-import')?.addEventListener('submit', importRescue); byId('rescue-catalog-refresh')?.addEventListener('click', loadCatalog); await loadCatalog();
|
|
|
} catch (error) { notice(error.message, true); }
|
|
|
}
|
|
|
export { initialize };
|