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/tests/AdminOperationsCancelBehavi...

365 lines
22 KiB
JavaScript

import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import vm from 'node:vm';
const source = await readFile(new URL('../public/cloud/admin-operations.js', import.meta.url), 'utf8');
class Node {
constructor(tag = 'div') {
this.tagName = tag.toUpperCase(); this.children = []; this.dataset = {}; this.parentNode = null;
this.attributes = new Map(); this.listeners = new Map(); this.hidden = false;
this.disabled = false; this.isConnected = true; this.open = false; this.value = '';
this._text = ''; this.style = { setProperty() {}, removeProperty() {} };
const classes = new Set();
this.classList = { add: value => classes.add(value), remove: value => classes.delete(value), contains: value => classes.has(value) };
}
set textContent(value) { this.replaceChildren(); this._text = String(value); }
get textContent() { return this._text + this.children.map(child => child.textContent).join(''); }
set innerHTML(_) { throw new Error('Task content must never be interpreted as HTML.'); }
get options() { return this.children; }
append(...children) {
for (const child of children) {
if (child.parentNode) child.parentNode.children = child.parentNode.children.filter(node => node !== child);
child.parentNode = this; child.isConnected = this.isConnected; this.children.push(child);
}
}
add(option) { this.append(option); }
replaceChildren(...children) {
this._text = '';
for (const child of this.children) { child.parentNode = null; child.isConnected = false; }
this.children = []; this.append(...children);
}
setAttribute(key, value) { this.attributes.set(key, String(value)); }
getAttribute(key) { return this.attributes.get(key) ?? null; }
addEventListener(name, listener) {
const listeners = this.listeners.get(name) || []; listeners.push(listener); this.listeners.set(name, listeners);
}
dispatch(name, fields = {}) {
const event = { target: this, currentTarget: this, button: 0, defaultPrevented: false,
preventDefault() { this.defaultPrevented = true; }, ...fields };
for (const listener of this.listeners.get(name) || []) listener(event);
}
closest(selector) {
if (selector === '[data-operation-stop-auto]' && this.dataset.operationStopAuto) return this;
if (selector === '[data-operation-detail]' && this.dataset.operationDetail) return this;
if (selector === 'a[href]' && this.tagName === 'A' && this.getAttribute('href')) return this;
return null;
}
querySelector(selector) {
if (selector.startsWith('[data-operation-detail="')) {
const id = selector.slice(24, -2);
return this.walk().find(node => node.dataset.operationDetail === id) || null;
}
return null;
}
walk() { return [this, ...this.children.flatMap(child => child.walk())]; }
focus() {}
getBoundingClientRect() { return { left: 0, right: 500, top: 0, bottom: 800 }; }
showModal() { this.open = true; }
close() { this.open = false; }
}
class SelectNode extends Node {}
class OptionNode extends Node {
constructor(label, value) { super('option'); this.textContent = label; this.value = String(value); }
}
const flush = async () => { for (let turn = 0; turn < 30; turn += 1) await Promise.resolve(); };
const token = 'a'.repeat(64);
const planId = 'b'.repeat(64);
function job(id, changes = {}) {
return {
id: String(id), operation_id: 'c'.repeat(32), kind: 'snapshot_delete', status: 'uncertain',
can_inspect: true, inspect_reason: '可读取 Agent 状态',
can_stop_auto_reconcile: true, stop_auto_reconcile_reason: '可停止面板后续领取与重试', attempts: 4,
can_force_delete: false, force_delete_reason: '当前任务不是可升级的删除任务',
error: '等待核对结果', phase: '正在删除快照', host_id: '7', host_name: '测试宿主机',
region: 'test', actor_id: '1', actor_name: '管理员', actor_email: 'a***@example.test',
owner_id: '2', owner_name: '用户', owner_email: 'u***@example.test', instance_id: '9',
instance_name: 'vm-test', instance_uuid: '11111111-1111-4111-8111-111111111111',
instance_status: 'deleting', order_id: null, created_at: 1000, updated_at: 1010,
dispatched_at: 1001, available_at: 1000, lease_until: 0, attention: true,
attention_reason: 'uncertain', links: { instance: null, billing: null },
display: { kind: '删除快照', status: '待核对', attention: '等待结果核对', lease: '无执行租约' },
...changes,
};
}
function page(items = [job(41)]) {
return {
items, pagination: { page: 1, per_page: 20, total: items.length, total_pages: 1, from: items.length ? 1 : 0, to: items.length },
summary: { total: items.length, attention: items.length, failed: 0, uncertain: items.length, queued_delayed: 0, lease_expired: 0 },
filters: { status: 'attention', kind: '', host_id: null, q: '', page: 1, per_page: 20 },
hosts: [{ id: '7', name: '测试宿主机', region: 'test' }], kinds: [{ value: 'snapshot_delete', label: '删除快照' }], generated_at: 1000,
};
}
function inspection(changes = {}) {
return {
operation_id: 'c'.repeat(32), operation_status: 'uncertain', checked_at: '2026-10-18T01:02:03Z',
outcome: 'uncertain', summary_code: 'evidence_incomplete', error_code: 'must_not_be_rendered',
abort_job: { available: false }, cleanup: { available: false, step_codes: [] }, ...changes,
};
}
function detail(item = job(41), inspected = null) {
return { job: item, notes: [], ...(inspected ? { inspection: inspected } : {}) };
}
function fixture(canManage) {
const ids = [
'admin-operations-bootstrap', 'operation-detail', 'operation-detail-body', 'operation-detail-close',
'operation-detail-inspect', 'operation-detail-stop-auto', 'operation-detail-force-delete', 'operation-detail-abort-job',
'operation-detail-cleanup', 'operation-detail-inspection', 'operation-detail-links',
'operation-detail-state', 'operation-detail-title', 'operations-body', 'operations-count',
'operations-health-body', 'operations-health-refresh', 'operations-health-state', 'operations-host',
'operations-kind', 'operations-next', 'operations-notice', 'operations-page-label',
'operations-pagination', 'operations-previous', 'operations-refresh', 'operations-reset',
'operations-shown-filters', 'operations-filter', 'operations-summary-total',
'operations-summary-failed', 'operations-summary-uncertain', 'operations-summary-delayed',
];
const nodes = Object.fromEntries(ids.map(id => [id, id === 'operations-filter' ? new Node('form') : new Node(id === 'operation-detail' ? 'dialog' : 'div')]));
for (const id of ['operation-detail-inspect', 'operation-detail-stop-auto', 'operation-detail-force-delete', 'operation-detail-abort-job', 'operation-detail-cleanup', 'operation-detail-inspection']) nodes[id].hidden = true;
const detailBody = new Node('section'); detailBody.append(nodes['operation-detail-state'], nodes['operation-detail-body'], nodes['operation-detail-inspection']);
const detailFooter = new Node('footer');
detailFooter.append(nodes['operation-detail-inspect'], nodes['operation-detail-stop-auto'], nodes['operation-detail-force-delete'], nodes['operation-detail-abort-job'], nodes['operation-detail-cleanup'], nodes['operation-detail-links']);
nodes['admin-operations-bootstrap'].textContent = JSON.stringify(page());
nodes['operations-filter'].elements = { namedItem: key => {
const map = { q: new Node('input'), status: new SelectNode('select'), kind: nodes['operations-kind'], host_id: nodes['operations-host'], per_page: new SelectNode('select') };
map.status.value = 'attention'; map.per_page.value = '20'; return map[key];
} };
const root = new Node('main'); root.dataset.canManage = canManage ? '1' : '0';
const document = new Node(); document.hidden = true; document.visibilityState = 'hidden'; document.documentElement = new Node(); document.body = new Node();
document.getElementById = id => nodes[id]?.isConnected ? nodes[id] : null;
document.createElement = tag => tag === 'select' ? new SelectNode(tag) : new Node(tag);
document.querySelector = selector => selector === '[data-admin-operations]' ? root : null;
const window = new Node(); window.ADMIN_CSRF_TOKEN = 'csrf-test-token'; window.scrollX = 0; window.scrollY = 0;
window.confirmMessages = []; window.confirmResult = true;
window.confirm = message => { window.confirmMessages.push(String(message)); return window.confirmResult; };
window.VenixDrawerMotion = { openDrawerWithMotion(dialog) { dialog.open = true; }, closeDrawerWithMotion(dialog) { dialog.open = false; return Promise.resolve(true); } };
const location = { origin: 'https://example.test', href: 'https://example.test/admin/operations' };
const history = { state: null, pushState(value, _, url) { this.state = value; location.href = String(url); }, replaceState(value) { this.state = value; } };
const requests = [];
const fetch = (url, options) => new Promise((resolve, reject) => requests.push({ url: String(url), options, resolve, reject, settled: false }));
vm.runInNewContext(source, { document, window, location, history, URL, Node, HTMLSelectElement: SelectNode, Option: OptionNode,
AbortController, fetch, setTimeout: () => 1, clearTimeout() {}, requestAnimationFrame: callback => callback(), console },
{ filename: 'admin-operations.js' });
return {
nodes, root, requests, window,
async click(target) {
if (target.dataset.operationStopAuto || target.dataset.operationDetail) root.dispatch('click', { target });
else target.dispatch('click', { target });
await flush();
},
async respond(payload, request = requests.find(item => !item.settled), status = 200) {
assert.ok(request, 'A response requires an outstanding request.'); request.settled = true;
request.resolve({ status, ok: status >= 200 && status < 300, json: async () => payload }); await flush();
},
};
}
function findRowButton(test, attribute, value) {
return test.nodes['operations-body'].walk().find(node => node.dataset[attribute] === String(value)) || null;
}
function visibleOperationButtons(test) {
return ['operation-detail-inspect', 'operation-detail-stop-auto', 'operation-detail-force-delete', 'operation-detail-abort-job', 'operation-detail-cleanup']
.filter(id => !test.nodes[id].hidden);
}
async function loadAndOpen(test) {
await test.click(test.nodes['operations-refresh']); await test.respond(page());
const detailButton = findRowButton(test, 'operationDetail', 41); assert.ok(detailButton);
await test.click(detailButton);
const request = test.requests.find(item => !item.settled && item.url.endsWith('/api/v1/admin/operations/jobs/41'));
await test.respond(detail(), request);
}
// Read-only administrators never receive any operational control, even when
// a forged job payload advertises capabilities.
{
const test = fixture(false);
await test.click(test.nodes['operations-refresh']); await test.respond(page());
assert.equal(findRowButton(test, 'operationStopAuto', 41), null);
await test.click(findRowButton(test, 'operationDetail', 41));
await test.respond(detail(job(41), inspection({ summary_code: 'cleanup_required',
cleanup: { available: true, plan_id: planId, step_codes: ['destroy_domain'] } })));
assert.deepEqual(visibleOperationButtons(test), []);
}
// Stopping automatic reconciliation uses its own semantic endpoint and makes
// clear that it cannot stop an already dispatched libvirt call.
{
const test = fixture(true);
await test.click(test.nodes['operations-refresh']); await test.respond(page());
const stop = findRowButton(test, 'operationStopAuto', 41); assert.ok(stop);
assert.equal(stop.textContent, '停止自动核对');
test.window.confirmResult = false; await test.click(stop);
assert.equal(test.requests.some(request => !request.settled && request.options.method === 'POST'), false);
test.window.confirmResult = true; await test.click(stop);
const mutation = test.requests.find(request => !request.settled && request.options.method === 'POST');
assert.equal(mutation.url, '/api/v1/admin/operations/jobs/41/stop-auto');
assert.equal(mutation.options.body, '{}');
assert.match(test.window.confirmMessages.at(-1), /不会停止已经下发的 libvirt 调用/);
await test.respond(detail(job(41, { status: 'cancelled', can_stop_auto_reconcile: false,
error: '管理员已停止自动核对' })), mutation);
const refresh = test.requests.find(request => !request.settled && request.options.method === 'GET');
await test.respond(page([job(41, { status: 'cancelled', can_stop_auto_reconcile: false })]), refresh);
assert.equal(findRowButton(test, 'operationStopAuto', 41), null);
assert.match(test.nodes['operations-notice'].textContent, /不表示 libvirt 调用已经停止/);
}
// A read-only inspection can expose one matching backup job action. The token
// is sent back to the server but is never rendered in the drawer.
{
const test = fixture(true); await loadAndOpen(test);
assert.deepEqual(visibleOperationButtons(test).sort(), ['operation-detail-inspect', 'operation-detail-stop-auto'].sort());
await test.click(test.nodes['operation-detail-inspect']);
const inspectRequest = test.requests.find(request => !request.settled && request.url.endsWith('/inspect'));
assert.equal(inspectRequest.options.method, 'POST'); assert.equal(inspectRequest.options.body, '{}');
const abortInspection = inspection({ summary_code: 'abortable_job_active',
abort_job: { available: true, kind: 'backup', inspection_token: token } });
await test.respond(detail(job(41), abortInspection), inspectRequest);
assert.deepEqual(visibleOperationButtons(test).sort(),
['operation-detail-inspect', 'operation-detail-stop-auto', 'operation-detail-abort-job'].sort());
assert.equal(test.nodes['operation-detail-cleanup'].hidden, true);
assert.match(test.nodes['operation-detail-inspection'].textContent, /在线备份作业/);
assert.doesNotMatch(test.nodes['operation-detail-inspection'].textContent, new RegExp(token));
await test.click(test.nodes['operation-detail-abort-job']);
const abortRequest = test.requests.find(request => !request.settled && request.url.endsWith('/abort-job'));
assert.deepEqual(JSON.parse(abortRequest.options.body), { inspection_token: token });
await test.respond(detail(job(41), inspection()), abortRequest);
const refresh = test.requests.find(request => !request.settled && request.options.method === 'GET');
await test.respond(page(), refresh);
assert.match(test.nodes['operations-notice'].textContent, /仍需核对终态/);
}
// Cleanup is available only after inspection supplies a valid plan and known
// step codes. The second confirmation shows the mapped plan, never raw tokens,
// paths, error codes or enum values.
{
const test = fixture(true); await loadAndOpen(test);
await test.click(test.nodes['operation-detail-inspect']);
const inspectRequest = test.requests.find(request => !request.settled && request.url.endsWith('/inspect'));
const cleanupInspection = inspection({ summary_code: 'cleanup_required', error_code: '/private/secret/libvirt-error',
error: '存储卷状态需要管理员核对',
cleanup: { available: true, plan_id: planId, step_codes: ['destroy_domain', 'delete_nvram', 'persist_cleanup_metadata'],
steps: ['/private/secret/domain.xml'] } });
await test.respond(detail(job(41), cleanupInspection), inspectRequest);
assert.deepEqual(visibleOperationButtons(test).sort(),
['operation-detail-inspect', 'operation-detail-stop-auto', 'operation-detail-cleanup'].sort());
assert.equal(test.nodes['operation-detail-abort-job'].hidden, true);
const rendered = test.nodes['operation-detail-inspection'].textContent;
assert.match(rendered, /停止仍在运行的虚拟机/); assert.match(rendered, /删除虚拟机 NVRAM/);
assert.match(rendered, /清除已完成磁盘切换的待清理标记/);
assert.match(rendered, /存储卷状态需要管理员核对/);
for (const forbidden of [planId, '/private/secret', 'destroy_domain', 'delete_nvram', 'persist_cleanup_metadata']) assert.doesNotMatch(rendered, new RegExp(forbidden));
test.window.confirmResult = false; await test.click(test.nodes['operation-detail-cleanup']);
assert.equal(test.requests.some(request => !request.settled && request.url.endsWith('/cleanup')), false);
test.window.confirmResult = true; await test.click(test.nodes['operation-detail-cleanup']);
const cleanupRequest = test.requests.find(request => !request.settled && request.url.endsWith('/cleanup'));
assert.deepEqual(JSON.parse(cleanupRequest.options.body), { plan_id: planId });
assert.match(test.window.confirmMessages.at(-1), /二次确认/);
assert.match(test.window.confirmMessages.at(-1), /停止仍在运行的虚拟机/);
assert.doesNotMatch(test.window.confirmMessages.at(-1), new RegExp(planId));
await test.respond(detail(job(41), inspection({ summary_code: 'operation_succeeded', outcome: 'succeeded', operation_status: 'succeeded' })), cleanupRequest);
const refresh = test.requests.find(request => !request.settled && request.options.method === 'GET');
await test.respond(page(), refresh);
}
// Force delete appears only for the server-authorized force-required state and
// creates a fresh task with explicit data-loss acknowledgement. A fresh
// inspection may expose one safer action alongside it.
{
const forceJob = job(41, { kind: 'delete', status: 'needs_attention',
can_stop_auto_reconcile: false, can_force_delete: true,
force_delete_reason: '需要明确确认数据丢失风险', error: '需要强制删除' });
const test = fixture(true);
await test.click(test.nodes['operations-refresh']); await test.respond(page([forceJob]));
await test.click(findRowButton(test, 'operationDetail', 41));
await test.respond(detail(forceJob, inspection({ summary_code: 'cleanup_required',
cleanup: { available: true, plan_id: planId, step_codes: ['undefine_domain'] } })));
assert.deepEqual(visibleOperationButtons(test).sort(),
['operation-detail-inspect', 'operation-detail-force-delete', 'operation-detail-cleanup'].sort());
assert.ok(visibleOperationButtons(test).length <= 3);
test.window.confirmResult = false;
await test.click(test.nodes['operation-detail-force-delete']);
assert.equal(test.requests.some(request => !request.settled && request.url.endsWith('/force-delete')), false);
test.window.confirmResult = true;
await test.click(test.nodes['operation-detail-force-delete']);
const forceRequest = test.requests.find(request => !request.settled && request.url.endsWith('/force-delete'));
assert.equal(forceRequest.options.method, 'POST');
assert.deepEqual(JSON.parse(forceRequest.options.body), { ack_data_loss: true });
assert.match(test.window.confirmMessages.at(-1), /未刷入磁盘的数据可能永久丢失/);
await test.respond({ prior_job_id: '41', job_id: '42', operation_id: 'd'.repeat(32), status: 'queued' }, forceRequest);
const listRequest = test.requests.find(request => !request.settled && request.url.includes('/api/v1/admin/operations?'));
await test.respond(page([job(41, { kind: 'delete', status: 'needs_attention',
can_stop_auto_reconcile: false, can_force_delete: false,
error: '强制删除任务已排队' })]), listRequest);
const detailRequest = test.requests.find(request => !request.settled
&& request.url.endsWith('/api/v1/admin/operations/jobs/41'));
await test.respond(detail(job(41, { kind: 'delete', status: 'needs_attention',
can_stop_auto_reconcile: false, can_force_delete: false,
error: '强制删除任务已排队' })), detailRequest);
assert.equal(test.nodes['operation-detail-force-delete'].hidden, true);
}
// A force-required task may instead have a matching abortable libvirt job.
// Inspection and the safer abort remain available beside explicit force.
{
const forceJob = job(51, { kind: 'delete', status: 'needs_attention',
can_stop_auto_reconcile: false, can_force_delete: true,
force_delete_reason: '需要明确确认数据丢失风险', error: '需要强制删除' });
const test = fixture(true);
await test.click(test.nodes['operations-refresh']); await test.respond(page([forceJob]));
await test.click(findRowButton(test, 'operationDetail', 51));
await test.respond(detail(forceJob, inspection({ summary_code: 'abortable_job_active',
abort_job: { available: true, kind: 'backup', inspection_token: token } })));
assert.deepEqual(visibleOperationButtons(test).sort(),
['operation-detail-inspect', 'operation-detail-force-delete', 'operation-detail-abort-job'].sort());
assert.ok(visibleOperationButtons(test).length <= 3);
}
// Conflicting or malformed Agent capabilities cannot produce a destructive
// button, and raw unknown fields are not echoed.
{
const test = fixture(true); await loadAndOpen(test);
await test.click(test.nodes['operation-detail-inspect']);
const request = test.requests.find(item => !item.settled && item.url.endsWith('/inspect'));
await test.respond(detail(job(41), inspection({ summary_code: 'cleanup_required',
abort_job: { available: true, kind: 'backup', inspection_token: token },
cleanup: { available: true, plan_id: planId, step_codes: ['unknown/delete/path'] } })), request);
assert.equal(test.nodes['operation-detail-abort-job'].hidden, true);
assert.equal(test.nodes['operation-detail-cleanup'].hidden, true);
assert.match(test.nodes['operation-detail-state'].textContent, /已禁用/);
assert.doesNotMatch(test.nodes['operation-detail-inspection'].textContent, /unknown\/delete\/path/);
}
// Without the CSRF token no inspection or mutation request is sent.
{
const test = fixture(true); await loadAndOpen(test);
test.window.ADMIN_CSRF_TOKEN = '';
await test.click(test.nodes['operation-detail-inspect']);
assert.equal(test.requests.some(request => !request.settled && request.options.method === 'POST'), false);
assert.match(test.nodes['operation-detail-state'].textContent, /安全令牌缺失/);
}
// Durable Agent causes are shown only through a fixed server-side label. The
// machine code itself is not copied into the administrator drawer.
{
const causeJob = job(41, {
agent_cause_code: 'external_snapshot_cleanup_required',
agent_cause_label: '检测到原生外部快照或回滚元数据;请先在宿主机安全完成外部快照清理,再立即核对',
});
const test = fixture(true);
await test.click(test.nodes['operations-refresh']); await test.respond(page([causeJob]));
await test.click(findRowButton(test, 'operationDetail', 41));
await test.respond(detail(causeJob));
assert.match(test.nodes['operation-detail-body'].textContent, /先在宿主机安全完成外部快照清理/);
assert.doesNotMatch(test.nodes['operation-detail-body'].textContent,
/external_snapshot_cleanup_required/);
}
console.log('Admin operation inspect, stop-auto, abort-job and confirmed-cleanup UI semantics passed.');