You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/public/cloud/admin-instance-migration.js

241 lines
13 KiB
JavaScript

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 infoList(entries) {
const list = el('dl', 'admin-instance-details');
for (const [label, value] of entries) {
list.append(el('dt', '', label), el('dd', '', text(value)));
}
return list;
}
export function createAdminInstanceMigration({
isBusy, submitTask, notice, refresh,
} = {}) {
if (typeof submitTask !== 'function' || typeof refresh !== 'function') {
throw new TypeError('Maintenance migration dependencies are incomplete');
}
function render(payload, vmId) {
const section = el('section', 'card mb-3');
const body = el('div', 'card-body');
body.append(el('h3', 'h6 fw-semibold', '维护迁移'));
const migration = payload?.maintenance_migration;
if (migration && typeof migration === 'object') {
const progress = migration?.progress && typeof migration.progress === 'object'
? migration.progress : {};
const stateLabel = text(progress.label, '状态未知');
body.append(infoList([
['状态', stateLabel],
['迁移方向', `宿主机 #${text(migration.source_host_id)} → #${text(migration.target_host_id)} · 资源池 #${text(migration.target_resource_pool_id)}`],
['源副本策略', migration.cleanup_mode === 'delete' ? '目标验证后自动清理' : '保留并由管理员稍后清理'],
['切换时间', date(migration.cutover_at)],
['完成时间', date(migration.completed_at)],
]));
const progressSteps = Array.isArray(progress.steps) ? progress.steps : [];
if (progressSteps.length) {
const progressBox = el('div', 'mb-3');
const currentStage = progress?.current_stage;
const currentIndex = Number(currentStage?.index); const stageCount = Number(progress?.stage_count);
const heading = currentStage && Number.isInteger(currentIndex)
&& currentIndex > 0 && Number.isInteger(stageCount) && stageCount > 0
? `当前阶段 ${currentIndex}/${stageCount} · ${text(currentStage.label)}`
: text(currentStage?.label, stateLabel);
progressBox.append(el('p', 'fw-semibold fs-13 mb-2', heading));
const stepList = el('div', 'd-flex flex-wrap gap-2');
const tones = {
completed: 'text-success', running: 'text-primary',
attention_required: 'text-danger', available: 'text-warning',
interrupted: 'text-danger', skipped: 'text-muted', pending: 'text-muted',
};
for (const step of progressSteps) {
if (!step || typeof step !== 'object') continue;
const status = String(step.status || 'pending');
const item = el('span',
`d-inline-flex align-items-center gap-1 border rounded-pill px-2 py-1 fs-13 ${tones[status] || 'text-muted'}`);
item.append(el('span', 'fw-semibold', text(step.label, '未知阶段')),
el('span', '', text(step.status_label, '等待中')));
stepList.append(item);
}
progressBox.append(stepList);
if (currentStage?.key === 'transfer' && progress.byte_progress_available !== true) {
progressBox.append(el('p', 'text-muted fs-13 mb-0 mt-2',
'当前协议提供可靠的阶段进度;尚未提供可持久化的字节传输百分比。'));
}
body.append(progressBox);
}
if (migration.state === 'attention_required') {
body.append(el('p', 'alert alert-danger fs-13',
'系统不会自动重放不确定操作。请等待原操作编号收敛;只有确认可重试时,下方才会显示恢复按钮。'));
} else if (migration.source_retained === true) {
body.append(el('p', migration.recovery_action === 'reconcile_cleanup'
? 'alert alert-danger fs-13' : 'alert alert-warning fs-13',
migration.recovery_action === 'reconcile_cleanup'
? '源副本删除效果正在按原操作编号核对,资源保持占用且不会盲目重放删除。'
: '目标实例已经接管原账单、到期时间和流量周期;源宿主机副本及原公网 IPv4、IPv6 仍被保留并占用资源。'));
}
const recoveryOptions = Array.isArray(migration.recovery_options)
? migration.recovery_options.filter(option => option && typeof option === 'object'
&& /^[a-z_]+$/.test(String(option.action || ''))
&& String(option.label || '').trim()) : [];
if (recoveryOptions.length) {
const recoveryBox = el('div', 'd-flex flex-wrap justify-content-end gap-2 mb-2');
for (const option of recoveryOptions) {
const action = String(option.action); const label = String(option.label).trim();
const aborting = option.destructive === true;
const button = el('button', aborting
? 'btn btn-outline-danger btn-sm' : 'btn btn-outline-primary btn-sm', label);
button.type = 'button';
button.addEventListener('click', async () => {
if (isBusy?.() || !await globalThis.VenixAdminDangerDialog.confirm({
tone: aborting ? 'danger' : 'warning',
title: label,
message: aborting
? '本次迁移会被中止,系统将尝试把源实例恢复到迁移前的电源与自启状态。'
: `系统将创建新的“${label}”恢复任务;不会重放原任务。`,
confirmText: aborting ? '中止并恢复源实例' : '创建恢复任务',
})) return;
for (const item of recoveryBox.querySelectorAll('button')) item.disabled = true;
notice?.(`正在创建“${label}”任务,请勿重复提交。`);
try {
await submitTask({
vmId,
path: `/api/v1/admin/instances/${encodeURIComponent(vmId)}/maintenance-migrations/recover`,
body: { action, confirm_recovery: true },
title: label,
});
refresh(vmId, true);
} catch (error) {
notice?.(error.message, true); refresh(vmId, true);
} finally {
for (const item of recoveryBox.querySelectorAll('button')) item.disabled = false;
}
});
recoveryBox.append(button);
}
body.append(recoveryBox);
}
if (migration.can_cleanup === true) {
const cleanup = el('button', 'btn btn-outline-danger btn-sm', '清理源宿主机副本');
cleanup.type = 'button';
cleanup.addEventListener('click', async () => {
if (isBusy?.() || !await globalThis.VenixAdminDangerDialog.confirm({
title: '清理迁移源副本',
message: '源宿主机上的旧虚拟机及其面板托管磁盘将被永久删除;目标实例与账单不会删除。',
confirmText: '删除源副本',
})) return;
cleanup.disabled = true; notice?.('正在创建源副本清理任务,请勿重复提交。');
try {
await submitTask({
vmId,
path: `/api/v1/admin/instances/${encodeURIComponent(vmId)}/maintenance-migrations/cleanup`,
body: { confirm_source_cleanup: true },
title: '清理迁移源副本',
});
refresh(vmId, true);
} catch (error) {
notice?.(error.message, true); refresh(vmId, true);
} finally { cleanup.disabled = false; }
});
const cleanupActions = el('div', 'd-flex justify-content-end');
cleanupActions.append(cleanup); body.append(cleanupActions);
}
}
const targets = Array.isArray(payload?.migration_targets) ? payload.migration_targets : [];
const form = el('form', 'row g-2 align-items-end'); form.noValidate = true;
const hostLabel = el('label', 'col-12 col-lg-5');
hostLabel.append(el('span', 'form-label d-block', '目标宿主机'));
const host = el('select', 'form-select'); host.required = true;
host.append(new Option(targets.length ? '请选择同资源池宿主机' : '暂无可迁移宿主机', ''));
targets.forEach(target => {
const option = new Option(
`${text(target.host_name, `宿主机 #${target.host_id}`)}${target.region ? ` · ${target.region}` : ''}${target.line ? ` · ${target.line}` : ''} · ${Number(target.available_ip_count) || 1} 个可用 IP`,
String(target.host_id));
option.dataset.resourcePoolId = String(target.resource_pool_id || '');
host.append(option);
});
hostLabel.append(host);
const modeLabel = el('label', 'col-12 col-lg-5');
modeLabel.append(el('span', 'form-label d-block', '目标验证后的源副本'));
const mode = el('select', 'form-select');
mode.append(new Option('自动清理源副本(推荐)', 'delete'),
new Option('保留源副本,稍后手动清理', 'retain'));
modeLabel.append(mode);
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(hostLabel, modeLabel, actions);
const confirmLabel = el('label', 'admin-instance-settings-confirm mt-3');
const confirm = document.createElement('input'); confirm.type = 'checkbox';
confirmLabel.append(confirm, document.createTextNode(
'我确认迁移会先正常关闭源实例,目标实例使用原账单、到期时间和流量周期,但会分配新的公网 IP。'));
const feedback = el('p', 'text-muted fs-13 mb-0 mt-2');
feedback.dataset.migrationFeedback = ''; feedback.hidden = true;
const blocked = payload?.can_migrate !== true;
const migrationBlocksNew = migration?.progress?.blocks_new_migration === true;
for (const control of [host, mode, submit, confirm]) control.disabled = blocked;
if (blocked && (!migration || !migrationBlocksNew)) {
feedback.hidden = false; feedback.className = 'text-warning fs-13 mb-0 mt-2';
feedback.textContent = targets.length
? text(payload?.create_block_reason, '当前实例不能开始维护迁移。')
: '暂无具备原资源池活动成员关系、可用容量、已验证网络接入和公网 IP 的其他宿主机。';
}
form.addEventListener('submit', async event => {
event.preventDefault();
if (isBusy?.() || blocked) return;
if (!/^[1-9][0-9]*$/.test(String(host.value || ''))) {
feedback.hidden = false; feedback.className = 'text-danger fs-13 mb-0 mt-2';
feedback.textContent = '请选择目标宿主机。'; return;
}
const targetResourcePoolId = host.selectedOptions[0]?.dataset.resourcePoolId || '';
if (!/^[1-9][0-9]*$/.test(targetResourcePoolId)) {
feedback.hidden = false; feedback.className = 'text-danger fs-13 mb-0 mt-2';
feedback.textContent = '目标宿主机缺少原资源池身份,请刷新后重试。'; return;
}
if (!confirm.checked) {
feedback.hidden = false; feedback.className = 'text-danger fs-13 mb-0 mt-2';
feedback.textContent = '请确认冷迁移、原服务账本和新公网 IPv4、IPv6 规则。'; return;
}
for (const control of form.querySelectorAll('input, select, button')) control.disabled = true;
feedback.hidden = false; feedback.className = 'text-muted fs-13 mb-0 mt-2';
feedback.textContent = '正在创建 PeerMigration V3 冷迁移任务,请勿重复提交…';
try {
const receipt = await submitTask({
vmId,
path: `/api/v1/admin/instances/${encodeURIComponent(vmId)}/maintenance-migrations`,
body: { target_host_id: Number(host.value),
target_resource_pool_id: Number(targetResourcePoolId), cleanup_mode: mode.value,
confirm_maintenance_migration: true },
title: '维护迁移',
});
feedback.textContent = `维护迁移任务 #${receipt.task_id || '—'} 已接收。`;
refresh(vmId, true);
} catch (error) {
feedback.className = 'text-danger fs-13 mb-0 mt-2'; feedback.textContent = error.message;
if (error?.mutationMayHaveApplied === true) refresh(vmId, true);
else for (const control of form.querySelectorAll('input, select, button')) control.disabled = false;
}
});
body.append(form, confirmLabel, feedback); section.append(body); return section;
}
return Object.freeze({ render });
}