mirror of
https://github.com/vatesfr/xen-orchestra.git
synced 2026-12-03 05:42:41 -06:00
Compare commits
24 Commits
docs/incre
...
feat/rest-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
576d0670d5 | ||
|
|
8eaa4c507a | ||
|
|
f22c27b863 | ||
|
|
3e8658c906 | ||
|
|
7b7fab8366 | ||
|
|
22bcc37439 | ||
|
|
5ca2958d2a | ||
|
|
205ae67940 | ||
|
|
addfdd5475 | ||
|
|
5512fc65a6 | ||
|
|
1f8f265afc | ||
|
|
c0e7843274 | ||
|
|
c893471c5e | ||
|
|
6f91a90299 | ||
|
|
41b290f166 | ||
|
|
2475403b11 | ||
|
|
0ae5d39aa5 | ||
|
|
77b00ff871 | ||
|
|
ed86fbec17 | ||
|
|
1e6a049072 | ||
|
|
032159a609 | ||
|
|
a5295c6731 | ||
|
|
c8260fb259 | ||
|
|
756d7fa940 |
@@ -25,6 +25,17 @@ const task = new Task({
|
||||
const { reason } = event
|
||||
}
|
||||
},
|
||||
|
||||
// only for a detached task, inherited by its subtasks
|
||||
//
|
||||
// if true, a subtask created after the abort of its parent is aborted, and ended, right away: running it rejects
|
||||
// with the abort reason without calling its function, so the remaining steps of an aborted task are skipped
|
||||
skipSubtasksAfterAbort: false,
|
||||
|
||||
// if true, this subtask does not follow the abort of its parent, so that it still runs after an abort
|
||||
//
|
||||
// meant for the cleanup steps of an aborted task
|
||||
cleanup: false,
|
||||
})
|
||||
|
||||
// this field is settable once before being observed
|
||||
@@ -38,9 +49,12 @@ task.id
|
||||
// - failure
|
||||
task.status
|
||||
|
||||
// Triggers the abort signal associated to the task.
|
||||
// Triggers the abort signal associated to the task, and the ones of its subtasks.
|
||||
//
|
||||
// This simply requests the task to abort, it will be up to the task to handle or not this signal.
|
||||
// A running task is only requested to abort: it is up to its function to handle or not this signal.
|
||||
//
|
||||
// A task that is not running ends right away as failed, with `reason` as result, and running it afterwards rejects
|
||||
// with `reason` without calling its function. See `skipSubtasksAfterAbort` for the subtasks created after the abort.
|
||||
task.abort(reason)
|
||||
|
||||
// if fn rejects, the task will be marked as failed
|
||||
|
||||
@@ -41,6 +41,17 @@ const task = new Task({
|
||||
const { reason } = event
|
||||
}
|
||||
},
|
||||
|
||||
// only for a detached task, inherited by its subtasks
|
||||
//
|
||||
// if true, a subtask created after the abort of its parent is aborted, and ended, right away: running it rejects
|
||||
// with the abort reason without calling its function, so the remaining steps of an aborted task are skipped
|
||||
skipSubtasksAfterAbort: false,
|
||||
|
||||
// if true, this subtask does not follow the abort of its parent, so that it still runs after an abort
|
||||
//
|
||||
// meant for the cleanup steps of an aborted task
|
||||
cleanup: false,
|
||||
})
|
||||
|
||||
// this field is settable once before being observed
|
||||
@@ -54,9 +65,12 @@ task.id
|
||||
// - failure
|
||||
task.status
|
||||
|
||||
// Triggers the abort signal associated to the task.
|
||||
// Triggers the abort signal associated to the task, and the ones of its subtasks.
|
||||
//
|
||||
// This simply requests the task to abort, it will be up to the task to handle or not this signal.
|
||||
// A running task is only requested to abort: it is up to its function to handle or not this signal.
|
||||
//
|
||||
// A task that is not running ends right away as failed, with `reason` as result, and running it afterwards rejects
|
||||
// with `reason` without calling its function. See `skipSubtasksAfterAbort` for the subtasks created after the abort.
|
||||
task.abort(reason)
|
||||
|
||||
// if fn rejects, the task will be marked as failed
|
||||
|
||||
@@ -35,6 +35,17 @@ function define(object, property, value) {
|
||||
|
||||
const noop = Function.prototype
|
||||
|
||||
// aborts `controller` when `signal` is aborted, right away if it already is
|
||||
//
|
||||
// `signal.aborted` must be checked: the abort event of an already aborted signal is never dispatched again
|
||||
function followSignal(signal, controller) {
|
||||
if (signal.aborted) {
|
||||
controller.abort(signal.reason)
|
||||
} else {
|
||||
signal.addEventListener('abort', () => controller.abort(signal.reason), { once: true })
|
||||
}
|
||||
}
|
||||
|
||||
const FAILURE = 'failure'
|
||||
const PENDING = 'pending'
|
||||
const SUCCESS = 'success'
|
||||
@@ -86,11 +97,12 @@ class Task {
|
||||
}
|
||||
}
|
||||
|
||||
// These two properties should not be used outside the class
|
||||
// These properties should not be used outside the class
|
||||
//
|
||||
// To ensure compatibility between multiple versions of this lib, they are kept public for now
|
||||
_abortController = new AbortController()
|
||||
_onProgress
|
||||
_skipSubtasksAfterAbort = false
|
||||
|
||||
get id() {
|
||||
// Use a compact, sortable, string representation of the creation date,
|
||||
@@ -110,18 +122,26 @@ class Task {
|
||||
return this.#status
|
||||
}
|
||||
|
||||
constructor({ properties, onProgress } = {}) {
|
||||
// `skipSubtasksAfterAbort` (root task only, inherited by its subtasks): a subtask created after the abort is
|
||||
// aborted right away, so the steps of an aborted task are skipped.
|
||||
//
|
||||
// `cleanup`: this subtask does not follow the abort of its parent, so that it still runs after an abort.
|
||||
constructor({ properties, onProgress, cleanup = false, skipSubtasksAfterAbort = false } = {}) {
|
||||
this.#startData = { properties }
|
||||
|
||||
// the parent signal this task's abort follows, once its own listener is registered
|
||||
let parentSignal
|
||||
if (onProgress !== undefined) {
|
||||
this._onProgress = onProgress
|
||||
this._skipSubtasksAfterAbort = skipSubtasksAfterAbort
|
||||
} else {
|
||||
const parent = getTask()
|
||||
if (parent !== undefined) {
|
||||
const { signal } = parent._abortController
|
||||
signal.addEventListener('abort', () => {
|
||||
this._abortController.abort(signal.reason)
|
||||
})
|
||||
// `_skipSubtasksAfterAbort` is missing on a task created by an older version of this library
|
||||
this._skipSubtasksAfterAbort = parent._skipSubtasksAfterAbort === true
|
||||
if (!cleanup) {
|
||||
parentSignal = parent._abortController.signal
|
||||
}
|
||||
|
||||
this._onProgress = parent._onProgress
|
||||
this.#startData.parentId = parent.id
|
||||
@@ -138,10 +158,23 @@ class Task {
|
||||
this.#emit('abortionRequested', { reason: signal.reason })
|
||||
|
||||
if (!this.#running) {
|
||||
this.#endedByAbort = true
|
||||
this.#end(FAILURE, signal.reason)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
if (parentSignal !== undefined) {
|
||||
if (this._skipSubtasksAfterAbort) {
|
||||
// after the listener above: a task created under an aborted parent is aborted, and ended, right away (its
|
||||
// `run()` then rejects without calling its function), as if its parent had been aborted just after its creation
|
||||
followSignal(parentSignal, this._abortController)
|
||||
} else {
|
||||
parentSignal.addEventListener('abort', () => {
|
||||
this._abortController.abort(parentSignal.reason)
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
abort(reason) {
|
||||
@@ -192,8 +225,14 @@ class Task {
|
||||
return result
|
||||
}
|
||||
|
||||
#endedByAbort = false
|
||||
#running = false
|
||||
async runInside(fn) {
|
||||
// aborted before it could run, either directly or because it was created under an aborted parent
|
||||
if (this.#endedByAbort) {
|
||||
throw this._abortController.signal.reason
|
||||
}
|
||||
|
||||
assert.equal(this.status, PENDING)
|
||||
assert.equal(this.#running, false)
|
||||
this.#running = true
|
||||
|
||||
@@ -175,6 +175,213 @@ describe('Task', function () {
|
||||
})
|
||||
})
|
||||
|
||||
describe('subtask of an aborted task', function () {
|
||||
// events of `subtask`, in the order they were emitted to the root task
|
||||
const subtaskEventTypes = (task, subtask) => task.$events.filter(_ => _.id === subtask.id).map(_ => _.type)
|
||||
|
||||
describe('without skipSubtasksAfterAbort', function () {
|
||||
it('runs when created after the abort, as before this option existed', async function () {
|
||||
const task = createTask()
|
||||
|
||||
await task.run(async () => {
|
||||
task.abort()
|
||||
|
||||
assert.equal(
|
||||
await Task.run(() => {
|
||||
assert.equal(Task.abortSignal.aborted, false)
|
||||
return 'done'
|
||||
}),
|
||||
'done'
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
it('is aborted when its parent is aborted while it runs', async function () {
|
||||
const task = createTask()
|
||||
|
||||
await task.run(() =>
|
||||
Task.run(() => {
|
||||
task.abort()
|
||||
assert.equal(Task.abortSignal.aborted, true)
|
||||
})
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
describe('with skipSubtasksAfterAbort', function () {
|
||||
it('does not run when created after the abort', async function () {
|
||||
const task = createTask({ skipSubtasksAfterAbort: true })
|
||||
const reason = {}
|
||||
let called = false
|
||||
let subtask
|
||||
|
||||
await task.run(async () => {
|
||||
task.abort(reason)
|
||||
|
||||
subtask = new Task()
|
||||
await assert.rejects(
|
||||
subtask.run(() => {
|
||||
called = true
|
||||
}),
|
||||
error => error === reason
|
||||
)
|
||||
})
|
||||
|
||||
assert.equal(called, false)
|
||||
assert.equal(subtask.status, 'failure')
|
||||
assert.deepEqual(subtaskEventTypes(task, subtask), ['start', 'abortionRequested', 'end'])
|
||||
const end = task.$events.findLast(_ => _.id === subtask.id)
|
||||
assert.equal(end.status, 'failure')
|
||||
assert.equal(end.result, reason)
|
||||
})
|
||||
|
||||
it('does not run a step started with Task.run() after the abort', async function () {
|
||||
const task = createTask({ skipSubtasksAfterAbort: true })
|
||||
let called = false
|
||||
|
||||
await task.run(async () => {
|
||||
task.abort()
|
||||
|
||||
await assert.rejects(
|
||||
Task.run({ properties: { name: 'step' } }, () => {
|
||||
called = true
|
||||
}),
|
||||
{ name: 'AbortError' }
|
||||
)
|
||||
})
|
||||
|
||||
assert.equal(called, false)
|
||||
})
|
||||
|
||||
it('does not run when created before the abort and run after it', async function () {
|
||||
const task = createTask({ skipSubtasksAfterAbort: true })
|
||||
const reason = {}
|
||||
let called = false
|
||||
let subtask
|
||||
|
||||
await task.run(async () => {
|
||||
subtask = new Task()
|
||||
task.abort(reason)
|
||||
|
||||
await assert.rejects(
|
||||
subtask.run(() => {
|
||||
called = true
|
||||
}),
|
||||
error => error === reason
|
||||
)
|
||||
})
|
||||
|
||||
assert.equal(called, false)
|
||||
assert.equal(subtask.status, 'failure')
|
||||
assert.deepEqual(subtaskEventTypes(task, subtask), ['start', 'abortionRequested', 'end'])
|
||||
})
|
||||
|
||||
it('is inherited by the subtasks of the subtasks', async function () {
|
||||
const task = createTask({ skipSubtasksAfterAbort: true })
|
||||
let called = false
|
||||
|
||||
await task.run(() =>
|
||||
Task.run(async () => {
|
||||
task.abort()
|
||||
|
||||
await assert.rejects(
|
||||
Task.run(() => {
|
||||
called = true
|
||||
}),
|
||||
{ name: 'AbortError' }
|
||||
)
|
||||
}).catch(noop)
|
||||
)
|
||||
|
||||
assert.equal(called, false)
|
||||
})
|
||||
|
||||
it('is ignored on a subtask', async function () {
|
||||
const task = createTask()
|
||||
|
||||
await task.run(async () => {
|
||||
task.abort()
|
||||
|
||||
assert.equal(await Task.run({ skipSubtasksAfterAbort: true }, () => Task.run(() => 'done')), 'done')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
it('still throws when run after it ended for another reason', async function () {
|
||||
const task = createTask()
|
||||
task.start()
|
||||
task.success()
|
||||
|
||||
await assert.rejects(task.run(noop), { name: 'AssertionError' })
|
||||
})
|
||||
})
|
||||
|
||||
describe('cleanup subtask', function () {
|
||||
it('runs when created after the abort', async function () {
|
||||
const task = createTask({ skipSubtasksAfterAbort: true })
|
||||
let subtask
|
||||
|
||||
await task.run(async () => {
|
||||
task.abort()
|
||||
|
||||
subtask = new Task({ cleanup: true })
|
||||
const result = await subtask.run(() => {
|
||||
assert.equal(Task.abortSignal.aborted, false)
|
||||
return 'cleaned'
|
||||
})
|
||||
assert.equal(result, 'cleaned')
|
||||
})
|
||||
|
||||
assert.equal(subtask.status, 'success')
|
||||
})
|
||||
|
||||
it('runs through Task.run() with the cleanup option', async function () {
|
||||
const task = createTask({ skipSubtasksAfterAbort: true })
|
||||
|
||||
await task.run(async () => {
|
||||
task.abort()
|
||||
|
||||
assert.equal(await Task.run({ properties: { name: 'clean-vm' }, cleanup: true }, () => 'cleaned'), 'cleaned')
|
||||
})
|
||||
})
|
||||
|
||||
it('is not aborted when its parent is aborted while it runs', async function () {
|
||||
const task = createTask({ skipSubtasksAfterAbort: true })
|
||||
|
||||
await task.run(() =>
|
||||
Task.run({ cleanup: true }, () => {
|
||||
task.abort()
|
||||
assert.equal(Task.abortSignal.aborted, false)
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('lets its own subtasks run normally', async function () {
|
||||
const task = createTask({ skipSubtasksAfterAbort: true })
|
||||
|
||||
await task.run(async () => {
|
||||
task.abort()
|
||||
|
||||
const result = await Task.run({ cleanup: true }, () => Task.run(() => 'done'))
|
||||
assert.equal(result, 'done')
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
describe('without abort', function () {
|
||||
it('emits the same events for a task and its subtasks', async function () {
|
||||
const task = createTask()
|
||||
|
||||
await task.run(() => Task.run({ properties: { name: 'step' } }, () => Task.run(() => 'foo')))
|
||||
|
||||
assert.deepEqual(
|
||||
task.$events.map(_ => _.type),
|
||||
['start', 'start', 'start', 'end', 'end', 'end']
|
||||
)
|
||||
assert.equal(task.status, 'success')
|
||||
})
|
||||
})
|
||||
|
||||
describe('#failure()', function () {
|
||||
const error = new Error()
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@vates/types",
|
||||
"private": false,
|
||||
"version": "3.1.0",
|
||||
"version": "3.2.0",
|
||||
"main": "./dist/index.mjs",
|
||||
"exports": {
|
||||
".": {
|
||||
|
||||
@@ -101,6 +101,21 @@ export interface EditVifProps {
|
||||
txChecksumming?: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Properties accepted by {@link Xapi.editNetwork}: the fields of `XoNetwork` it can change.
|
||||
*
|
||||
* `nbd` and `insecureNbd` cannot both be true: `editNetwork` throws `invalidParameters` when they are.
|
||||
*/
|
||||
export interface EditNetworkProps {
|
||||
automatic?: boolean
|
||||
defaultIsLocked?: boolean
|
||||
insecureNbd?: boolean
|
||||
MTU?: number
|
||||
name_description?: string
|
||||
name_label?: string
|
||||
nbd?: boolean
|
||||
}
|
||||
|
||||
export type XcpPatches = {
|
||||
changelog?: {
|
||||
author: string
|
||||
@@ -335,6 +350,7 @@ export interface Xapi {
|
||||
checkLimits?: (limits: Record<string, number>, vm: XenApiVmWrapped) => Promise<void>
|
||||
): Promise<void>
|
||||
editVif(id: XoVif['id'], props: EditVifProps): Promise<void>
|
||||
editNetwork(id: XoNetwork['id'], props: EditNetworkProps): Promise<void>
|
||||
startVm(
|
||||
id: XoVm['id'],
|
||||
opts?: {
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.19.0",
|
||||
"@vates/types": "^3.1.0",
|
||||
"@vates/types": "^3.2.0",
|
||||
"rimraf": "^6.0.1",
|
||||
"typescript": "~5.6",
|
||||
"typescript-eslint": "^8.61.0"
|
||||
|
||||
@@ -5,5 +5,12 @@ export default {
|
||||
update: {
|
||||
tags: true,
|
||||
other_config: true,
|
||||
automatic: true,
|
||||
defaultIsLocked: true,
|
||||
insecureNbd: true,
|
||||
MTU: true,
|
||||
name_description: true,
|
||||
name_label: true,
|
||||
nbd: true,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -8,9 +8,28 @@ export type SupportedResource = XoAclSupportedResource<SupportedActionsByResourc
|
||||
export type SupportedActions<T extends SupportedResource> = XoAclSupportedActions<SupportedActionsByResource, T>
|
||||
export type TPrivilege<T extends SupportedResource> = XoAclPrivilege<SupportedActionsByResource, T>
|
||||
|
||||
export const UNKNOWN = Symbol('UNKNOWN')
|
||||
|
||||
/**
|
||||
* Lists the top-level fields read by a selector.
|
||||
*/
|
||||
function getSelectorFields(node: CM.Node): string[] {
|
||||
if (node instanceof CM.Property || node instanceof CM.TruthyProperty) {
|
||||
return [node.name]
|
||||
}
|
||||
if (node instanceof CM.Not) {
|
||||
return getSelectorFields(node.child)
|
||||
}
|
||||
if (node instanceof CM.And || node instanceof CM.Or) {
|
||||
return node.children.flatMap(getSelectorFields)
|
||||
}
|
||||
return node instanceof CM.Null ? [] : ['*']
|
||||
}
|
||||
|
||||
export class Privilege<T extends SupportedResource> {
|
||||
#action: TPrivilege<T>['action']
|
||||
#selector?: (object: object) => boolean
|
||||
#selectorFields: string[] = []
|
||||
#resource: TPrivilege<T>['resource']
|
||||
#effect: TPrivilege<T>['effect']
|
||||
|
||||
@@ -28,9 +47,14 @@ export class Privilege<T extends SupportedResource> {
|
||||
Privilege.checkActionIsValid(resource, action)
|
||||
|
||||
this.#action = action
|
||||
this.#selector = selector !== undefined ? CM.parse(selector).createPredicate() : undefined
|
||||
this.#resource = resource
|
||||
this.#effect = effect
|
||||
|
||||
if (selector !== undefined) {
|
||||
const node = CM.parse(selector)
|
||||
this.#selector = node.createPredicate()
|
||||
this.#selectorFields = getSelectorFields(node)
|
||||
}
|
||||
}
|
||||
|
||||
get effect() {
|
||||
@@ -44,11 +68,20 @@ export class Privilege<T extends SupportedResource> {
|
||||
return this.#action === '*' || this.#action === action || action.startsWith(`${this.#action}:`)
|
||||
}
|
||||
|
||||
#matchSelector(object: object) {
|
||||
#matchSelector(object: object, knownFields?: string[]) {
|
||||
if (this.#selector === undefined) {
|
||||
return true
|
||||
}
|
||||
|
||||
// `*` is a term not bound to a property (e.g. `foo`), it may match any field, including missing ones
|
||||
// The `*` check is there to handle the case where a `*` field would exist
|
||||
if (
|
||||
knownFields !== undefined &&
|
||||
this.#selectorFields.some(field => field === '*' || !(field in object || knownFields.includes(field)))
|
||||
) {
|
||||
return UNKNOWN
|
||||
}
|
||||
|
||||
return this.#selector(object)
|
||||
}
|
||||
|
||||
@@ -60,11 +93,12 @@ export class Privilege<T extends SupportedResource> {
|
||||
action: SupportedActions<Resource>
|
||||
resource: Resource
|
||||
object: object
|
||||
}): boolean {
|
||||
knownFields?: string[]
|
||||
}): boolean | typeof UNKNOWN {
|
||||
return (
|
||||
this.#matchResource(constraint.resource) &&
|
||||
this.#matchAction(constraint.action) &&
|
||||
this.#matchSelector(constraint.object)
|
||||
this.#matchSelector(constraint.object, constraint.knownFields)
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
SupportedActions,
|
||||
SupportedActionsByResource,
|
||||
SupportedResource,
|
||||
UNKNOWN,
|
||||
} from './class/privilege.mjs'
|
||||
|
||||
// Export all types constructed using SUPPORTED_ACTIONS_BY_RESOURCE
|
||||
@@ -23,6 +24,7 @@ export type AnyPrivilegeOnParam = {
|
||||
resource: Resource
|
||||
action: SupportedActions<Resource>
|
||||
objects: object | object[]
|
||||
knownFields?: string[]
|
||||
}
|
||||
}[SupportedResource]
|
||||
|
||||
@@ -32,12 +34,14 @@ export function hasPrivilegeOn<T extends SupportedResource>({
|
||||
resource,
|
||||
objects,
|
||||
userPrivileges,
|
||||
knownFields,
|
||||
}: {
|
||||
user: XoUser
|
||||
resource: T
|
||||
action: SupportedActions<T>
|
||||
objects: object | object[]
|
||||
userPrivileges: AnyPrivilege[]
|
||||
knownFields?: string[]
|
||||
}) {
|
||||
// Function that will be called outside of the module
|
||||
// We cannot be sure types are respected
|
||||
@@ -63,7 +67,7 @@ export function hasPrivilegeOn<T extends SupportedResource>({
|
||||
return true
|
||||
}
|
||||
|
||||
const effectsByObject = new Map<object, Privilege<T>['effect'][]>()
|
||||
const effectsByObject = new Map<object, { known: boolean; effect: Privilege<T>['effect'] }[]>()
|
||||
if (Array.isArray(objects)) {
|
||||
objects.forEach(obj => effectsByObject.set(obj, []))
|
||||
} else {
|
||||
@@ -74,20 +78,49 @@ export function hasPrivilegeOn<T extends SupportedResource>({
|
||||
const privilege = new CPrivilege(userPrivilege as Privilege<typeof userPrivilege.resource>)
|
||||
|
||||
for (const [object, effects] of effectsByObject.entries()) {
|
||||
if (!privilege.match({ action, resource, object })) {
|
||||
const result = privilege.match({ action, resource, object, knownFields })
|
||||
if (!result) {
|
||||
continue
|
||||
}
|
||||
effects.push(privilege.effect)
|
||||
effects.push({ known: result !== UNKNOWN, effect: privilege.effect })
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
Array.from(effectsByObject.values()).some(
|
||||
effects => effects.length === 0 || effects.some(effect => effect === 'deny')
|
||||
)
|
||||
) {
|
||||
return false
|
||||
let isUndecidable = false
|
||||
for (const effects of effectsByObject.values()) {
|
||||
let hasAllow = false
|
||||
let hasKnownAllow = false
|
||||
let hasUnknownDeny = false
|
||||
|
||||
for (const { known, effect } of effects) {
|
||||
if (effect === 'allow') {
|
||||
hasAllow = true
|
||||
hasKnownAllow ||= known
|
||||
} else if (known) {
|
||||
return false
|
||||
} else {
|
||||
hasUnknownDeny = true
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasAllow) {
|
||||
return false
|
||||
}
|
||||
|
||||
// do not throw yet: another object may still be known to be denied
|
||||
if (hasUnknownDeny || !hasKnownAllow) {
|
||||
isUndecidable = true
|
||||
}
|
||||
}
|
||||
|
||||
if (isUndecidable) {
|
||||
const error: Error & { code?: string } = new Error(
|
||||
`The privilege couldn't be decided because the object is missing fields the selectors need. action: ${action}, resource: ${resource}`
|
||||
)
|
||||
error.code = 'RBAC_UNKNOWN_RESULT'
|
||||
throw error
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -101,6 +134,7 @@ export function getMissingPrivileges(params: AnyPrivilegeOnParam[], userPrivileg
|
||||
action: param.action as SupportedActions<typeof param.resource>,
|
||||
objects: param.objects,
|
||||
userPrivileges,
|
||||
knownFields: param.knownFields,
|
||||
})
|
||||
)
|
||||
.map(({ action, objects, resource }) => {
|
||||
@@ -142,6 +176,7 @@ export function filterObjectsWithPrivilege<Resource extends SupportedResource, O
|
||||
action: SupportedActions<Resource>
|
||||
objects: Object[]
|
||||
userPrivileges: AnyPrivilege[]
|
||||
knownFields?: string[]
|
||||
}) {
|
||||
return param.objects.filter(obj => hasPrivilegeOn({ ...param, objects: obj }))
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import assert from 'node:assert'
|
||||
import type { Branded } from '@vates/types/common'
|
||||
import type { XoUser } from '@vates/types/xo'
|
||||
|
||||
import { Privilege } from '../class/privilege.mjs'
|
||||
import { Privilege, UNKNOWN } from '../class/privilege.mjs'
|
||||
import type { Privilege as TPrivilege } from '../index.mjs'
|
||||
import {
|
||||
filterObjectsWithPrivilege,
|
||||
@@ -81,6 +81,108 @@ suite('Privilege.match behavior', () => {
|
||||
const vmImportPrivilege = new Privilege({ action: 'import:vm', resource: 'sr', effect: 'allow' })
|
||||
assert.strictEqual(vmImportPrivilege.match({ resource: 'sr', action: 'import:vdi:url', object }), false)
|
||||
})
|
||||
|
||||
suite('on a partial object', () => {
|
||||
const ownVmPrivilege = new Privilege({
|
||||
action: 'read',
|
||||
resource: 'vm',
|
||||
selector: 'creation:creator:2',
|
||||
effect: 'allow',
|
||||
})
|
||||
const partialObject = { id: 'alma' }
|
||||
|
||||
test('Should not match a missing property if known fields are not provided', () => {
|
||||
assert.strictEqual(ownVmPrivilege.match({ resource: 'vm', action: 'read', object: partialObject }), false)
|
||||
})
|
||||
|
||||
test('Should not match a missing property if it is a known field', () => {
|
||||
assert.strictEqual(
|
||||
ownVmPrivilege.match({
|
||||
resource: 'vm',
|
||||
action: 'read',
|
||||
object: partialObject,
|
||||
knownFields: ['id', 'creation'],
|
||||
}),
|
||||
false
|
||||
)
|
||||
})
|
||||
|
||||
test('Should return UNKNOWN if the selector uses an unknown field', () => {
|
||||
assert.strictEqual(
|
||||
ownVmPrivilege.match({ resource: 'vm', action: 'read', object: partialObject, knownFields: ['id'] }),
|
||||
UNKNOWN
|
||||
)
|
||||
})
|
||||
|
||||
test('Should not match because of the resource even if the selector is unknown', () => {
|
||||
assert.strictEqual(
|
||||
ownVmPrivilege.match({ resource: 'host', action: 'read', object: partialObject, knownFields: ['id'] }),
|
||||
false
|
||||
)
|
||||
})
|
||||
|
||||
test('Should not match because of the action even if the selector is unknown', () => {
|
||||
assert.strictEqual(
|
||||
ownVmPrivilege.match({ resource: 'vm', action: 'start', object: partialObject, knownFields: ['id'] }),
|
||||
false
|
||||
)
|
||||
})
|
||||
|
||||
test('Should match without selector', () => {
|
||||
assert.strictEqual(
|
||||
privilege.match({ resource: 'vm', action: 'read', object: partialObject, knownFields: [] }),
|
||||
true
|
||||
)
|
||||
})
|
||||
|
||||
test('Should resolve a field present on the object even if it is not listed', () => {
|
||||
assert.strictEqual(
|
||||
ownVmPrivilege.match({
|
||||
resource: 'vm',
|
||||
action: 'read',
|
||||
object: { creation: { creator: '2' } },
|
||||
knownFields: [],
|
||||
}),
|
||||
true
|
||||
)
|
||||
})
|
||||
|
||||
test('Should resolve a field provided by a getter', () => {
|
||||
class Vm {
|
||||
get creation() {
|
||||
return { creator: '2' }
|
||||
}
|
||||
}
|
||||
|
||||
assert.strictEqual(
|
||||
ownVmPrivilege.match({ resource: 'vm', action: 'read', object: new Vm(), knownFields: [] }),
|
||||
true
|
||||
)
|
||||
})
|
||||
|
||||
test('Should return UNKNOWN on a term not bound to a property', () => {
|
||||
const bareTermPrivilege = new Privilege({ action: 'read', resource: 'vm', selector: 'alma', effect: 'allow' })
|
||||
|
||||
assert.strictEqual(
|
||||
bareTermPrivilege.match({ resource: 'vm', action: 'read', object: partialObject, knownFields: ['id'] }),
|
||||
UNKNOWN
|
||||
)
|
||||
})
|
||||
|
||||
test('Should return UNKNOWN if one of the fields is unknown, even if the others decide the result', () => {
|
||||
const orPrivilege = new Privilege({
|
||||
action: 'read',
|
||||
resource: 'vm',
|
||||
selector: '|(id:alma creation:creator:2)',
|
||||
effect: 'allow',
|
||||
})
|
||||
|
||||
assert.strictEqual(
|
||||
orPrivilege.match({ resource: 'vm', action: 'read', object: partialObject, knownFields: ['id'] }),
|
||||
UNKNOWN
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
suite('ACL V2 behavior', async () => {
|
||||
@@ -397,6 +499,205 @@ suite('ACL V2 behavior', async () => {
|
||||
assert.strictEqual(vms.length, 2)
|
||||
})
|
||||
})
|
||||
|
||||
suite('partial objects behavior', () => {
|
||||
const UNKNOWN_RESULT = { code: 'RBAC_UNKNOWN_RESULT' }
|
||||
|
||||
const vmReadAll = {
|
||||
id: privilegeId,
|
||||
action: 'read',
|
||||
resource: 'vm',
|
||||
effect: 'allow',
|
||||
roleId,
|
||||
} satisfies TPrivilege<'vm'>
|
||||
const vmReadOwn = {
|
||||
id: privilegeId,
|
||||
action: 'read',
|
||||
resource: 'vm',
|
||||
selector: `creation:creator:${user.id}`,
|
||||
effect: 'allow',
|
||||
roleId,
|
||||
} satisfies TPrivilege<'vm'>
|
||||
const vmDenyReadOnPool = {
|
||||
id: privilegeId,
|
||||
action: 'read',
|
||||
resource: 'vm',
|
||||
selector: '$pool:2',
|
||||
effect: 'deny',
|
||||
roleId,
|
||||
} satisfies TPrivilege<'vm'>
|
||||
|
||||
const partialVm = { id: 'partial-vm' }
|
||||
const partialVmOnDeniedPool = { id: 'partial-vm-denied', $pool: '2' }
|
||||
|
||||
suite('hasPrivilegeOn', () => {
|
||||
test('Should always return true for admin', () => {
|
||||
assert.strictEqual(
|
||||
hasPrivilegeOn({
|
||||
user: admin,
|
||||
action: 'read',
|
||||
resource: 'vm',
|
||||
objects: partialVm,
|
||||
knownFields: ['id'],
|
||||
userPrivileges: [vmReadOwn],
|
||||
}),
|
||||
true
|
||||
)
|
||||
})
|
||||
|
||||
test('Should keep the current behavior if known fields are not provided', () => {
|
||||
assert.strictEqual(
|
||||
hasPrivilegeOn({ user, action: 'read', resource: 'vm', objects: partialVm, userPrivileges: [vmReadOwn] }),
|
||||
false
|
||||
)
|
||||
})
|
||||
|
||||
test('Should throw if the only allow privilege is unknown', () => {
|
||||
assert.throws(
|
||||
() =>
|
||||
hasPrivilegeOn({
|
||||
user,
|
||||
action: 'read',
|
||||
resource: 'vm',
|
||||
objects: partialVm,
|
||||
knownFields: ['id'],
|
||||
userPrivileges: [vmReadOwn],
|
||||
}),
|
||||
UNKNOWN_RESULT
|
||||
)
|
||||
})
|
||||
|
||||
test('Should return false if the unknown field is known to be absent', () => {
|
||||
assert.strictEqual(
|
||||
hasPrivilegeOn({
|
||||
user,
|
||||
action: 'read',
|
||||
resource: 'vm',
|
||||
objects: partialVm,
|
||||
knownFields: ['id', 'creation'],
|
||||
userPrivileges: [vmReadOwn],
|
||||
}),
|
||||
false
|
||||
)
|
||||
})
|
||||
|
||||
test('Should return true if an allow privilege is known even if another one is unknown', () => {
|
||||
assert.strictEqual(
|
||||
hasPrivilegeOn({
|
||||
user,
|
||||
action: 'read',
|
||||
resource: 'vm',
|
||||
objects: partialVm,
|
||||
knownFields: ['id'],
|
||||
userPrivileges: [vmReadOwn, vmReadAll],
|
||||
}),
|
||||
true
|
||||
)
|
||||
})
|
||||
|
||||
test('Should throw if a deny privilege is unknown, even with a known allow privilege', () => {
|
||||
assert.throws(
|
||||
() =>
|
||||
hasPrivilegeOn({
|
||||
user,
|
||||
action: 'read',
|
||||
resource: 'vm',
|
||||
objects: partialVm,
|
||||
knownFields: ['id'],
|
||||
userPrivileges: [vmReadAll, vmDenyReadOnPool],
|
||||
}),
|
||||
UNKNOWN_RESULT
|
||||
)
|
||||
})
|
||||
|
||||
test('Should return true if a deny privilege is known not to match', () => {
|
||||
assert.strictEqual(
|
||||
hasPrivilegeOn({
|
||||
user,
|
||||
action: 'read',
|
||||
resource: 'vm',
|
||||
objects: partialVm,
|
||||
knownFields: ['id', '$pool'],
|
||||
userPrivileges: [vmReadAll, vmDenyReadOnPool],
|
||||
}),
|
||||
true
|
||||
)
|
||||
})
|
||||
|
||||
test('Should return false if a deny privilege is known to match, even with an unknown allow privilege', () => {
|
||||
assert.strictEqual(
|
||||
hasPrivilegeOn({
|
||||
user,
|
||||
action: 'read',
|
||||
resource: 'vm',
|
||||
objects: partialVmOnDeniedPool,
|
||||
knownFields: ['id', '$pool'],
|
||||
userPrivileges: [vmReadOwn, vmDenyReadOnPool],
|
||||
}),
|
||||
false
|
||||
)
|
||||
})
|
||||
|
||||
test('Should return false if one of the objects is known to be denied, even if another one is unknown', () => {
|
||||
assert.strictEqual(
|
||||
hasPrivilegeOn({
|
||||
user,
|
||||
action: 'read',
|
||||
resource: 'vm',
|
||||
objects: [partialVm, partialVmOnDeniedPool],
|
||||
knownFields: ['id'],
|
||||
userPrivileges: [vmReadAll, vmDenyReadOnPool],
|
||||
}),
|
||||
false
|
||||
)
|
||||
})
|
||||
|
||||
test('Should throw if the other objects are allowed and one is unknown', () => {
|
||||
assert.throws(
|
||||
() =>
|
||||
hasPrivilegeOn({
|
||||
user,
|
||||
action: 'read',
|
||||
resource: 'vm',
|
||||
objects: [{ id: 'allowed-vm', $pool: '1' }, partialVm],
|
||||
knownFields: ['id'],
|
||||
userPrivileges: [vmReadAll, vmDenyReadOnPool],
|
||||
}),
|
||||
UNKNOWN_RESULT
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
suite('getMissingPrivileges', () => {
|
||||
test('Should throw if a privilege is unknown', () => {
|
||||
assert.throws(
|
||||
() =>
|
||||
getMissingPrivileges(
|
||||
[{ user, action: 'read', resource: 'vm', objects: partialVm, knownFields: ['id'] }],
|
||||
[vmReadOwn]
|
||||
),
|
||||
UNKNOWN_RESULT
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
suite('filterObjectsWithPrivilege', () => {
|
||||
test('Should throw if a privilege is unknown on one of the objects', () => {
|
||||
assert.throws(
|
||||
() =>
|
||||
filterObjectsWithPrivilege({
|
||||
user,
|
||||
action: 'read',
|
||||
resource: 'vm',
|
||||
objects: [partialVm],
|
||||
knownFields: ['id'],
|
||||
userPrivileges: [vmReadOwn],
|
||||
}),
|
||||
UNKNOWN_RESULT
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
suite('getActionStrings', () => {
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
"tar-stream": "^3.1.8",
|
||||
"@types/tar-stream": "^3.1.4",
|
||||
"tmp": "^0.2.1",
|
||||
"@vates/types": "^3.1.0"
|
||||
"@vates/types": "^3.2.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@xen-orchestra/log": "^1.0.0",
|
||||
|
||||
@@ -21,6 +21,9 @@ export class HealthCheckVmBackup {
|
||||
const xapi = this.#xapi
|
||||
const restoredId = restoredVm.uuid
|
||||
|
||||
// the health check stops waiting once the backup is aborted; the caller removes the restored VM
|
||||
const signal = Task.abortSignal
|
||||
|
||||
// remove vifs
|
||||
await Promise.all(restoredVm.$VIFs.map(vif => xapi.callAsync('VIF.destroy', vif.$ref)))
|
||||
const waitForScript = restoredVm.tags.includes('xo-backup-health-check-xenstore')
|
||||
@@ -33,6 +36,7 @@ export class HealthCheckVmBackup {
|
||||
// start Vm
|
||||
|
||||
await xapi.callAsync(
|
||||
signal,
|
||||
'VM.start',
|
||||
restoredVm.$ref,
|
||||
false, // Start paused?
|
||||
@@ -51,6 +55,7 @@ export class HealthCheckVmBackup {
|
||||
// wait for the 'Running' event to be really stored in local xapi object cache
|
||||
|
||||
restoredVm = await xapi.waitObjectState(restoredVm.$ref, vm => vm.power_state === 'Running', {
|
||||
signal,
|
||||
timeout: remainingTimeout,
|
||||
timeoutMessage: refOrUuid =>
|
||||
`local xapi did not get Running state for VM ${refOrUuid} after ${timeout / 1000} second`,
|
||||
@@ -61,6 +66,7 @@ export class HealthCheckVmBackup {
|
||||
|
||||
// wait for the guest tools to be detected
|
||||
await xapi.waitObjectState(restoredVm.guest_metrics, gm => gm?.PV_drivers_detected, {
|
||||
signal,
|
||||
timeout: remainingTimeout,
|
||||
timeoutMessage: refOrUuid =>
|
||||
`timeout reached while waiting for ${refOrUuid} to report the driver version through the Xen tools. Please check or update the Xen tools.`,
|
||||
@@ -77,6 +83,7 @@ export class HealthCheckVmBackup {
|
||||
(vm.xenstore_data['vm-data/xo-backup-health-check'] === 'success' ||
|
||||
vm.xenstore_data['vm-data/xo-backup-health-check'] === 'failure'),
|
||||
{
|
||||
signal,
|
||||
timeout: remainingTimeout,
|
||||
timeoutMessage: refOrUuid =>
|
||||
`timeout reached while waiting for ${refOrUuid} to report the startup script execution.`,
|
||||
|
||||
52
@xen-orchestra/backups/HealthCheckVmBackup.test.mjs
Normal file
52
@xen-orchestra/backups/HealthCheckVmBackup.test.mjs
Normal file
@@ -0,0 +1,52 @@
|
||||
import { describe, it } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { Task } from '@vates/task'
|
||||
|
||||
import { HealthCheckVmBackup } from './HealthCheckVmBackup.mjs'
|
||||
|
||||
describe('HealthCheckVmBackup#run() after an abort', () => {
|
||||
it('stops waiting for the restored VM without waiting for its timeout', async () => {
|
||||
// resolved once the restored VM is started
|
||||
const { promise: pStarted, resolve: onStarted } = Promise.withResolvers()
|
||||
const xapi = {
|
||||
callAsync: async (...args) => {
|
||||
if (args.includes('VM.start')) {
|
||||
onStarted()
|
||||
}
|
||||
},
|
||||
// the restored VM never reaches the expected state: only an abort can end the wait
|
||||
waitObjectState: (ref, predicate, { signal } = {}) =>
|
||||
new Promise((resolve, reject) => {
|
||||
// as `Xapi#waitObjectState()` does, rejects right away when already aborted
|
||||
if (signal?.aborted) {
|
||||
reject(signal.reason)
|
||||
} else {
|
||||
signal?.addEventListener('abort', () => reject(signal.reason), { once: true })
|
||||
}
|
||||
}),
|
||||
}
|
||||
const healthCheck = new HealthCheckVmBackup({
|
||||
restoredVm: { $ref: 'vm-ref', $VIFs: [], tags: [], uuid: 'vm-uuid' },
|
||||
timeout: 60e3,
|
||||
xapi,
|
||||
})
|
||||
|
||||
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
|
||||
const result = await vmTask
|
||||
.run(async () => {
|
||||
const pRun = healthCheck.run()
|
||||
await pStarted
|
||||
vmTask.abort()
|
||||
return Promise.race([
|
||||
pRun.then(
|
||||
() => 'resolved',
|
||||
error => error.name
|
||||
),
|
||||
new Promise(resolve => setTimeout(resolve, 1e3, 'still waiting')),
|
||||
])
|
||||
})
|
||||
.catch(error => error.name)
|
||||
|
||||
assert.equal(result, 'AbortError')
|
||||
})
|
||||
})
|
||||
@@ -3,6 +3,7 @@ import assert from 'node:assert'
|
||||
import { formatFilenameDate } from './_filenameDate.mjs'
|
||||
import { importIncrementalVm } from './_incrementalVm.mjs'
|
||||
import { liveMountXapiLabels } from './liveMountXapiLabels.mjs'
|
||||
import { destroyOnAbort } from './_destroyOnAbort.mjs'
|
||||
import { watchStreamSize } from './_watchStreamSize.mjs'
|
||||
import { decorateClass } from '@vates/decorate-with'
|
||||
import { Task } from '@vates/task'
|
||||
@@ -425,6 +426,13 @@ export class ImportVmBackup {
|
||||
}
|
||||
backup = await adapter.readFullVmBackup(metadata)
|
||||
watchStreamSize(backup, sizeContainer)
|
||||
|
||||
// the restore stops once aborted (e.g. the health check of an aborted backup): a full backup is a stream that
|
||||
// `VM_import()` sends as is, destroying it fails the import, and XAPI drops the partial VM
|
||||
//
|
||||
// set up as soon as the stream exists, so that an abort landing before the import starts, or leaving the transfer
|
||||
// subtask unable to run, still closes it (a file handle or an S3 request)
|
||||
$defer(destroyOnAbort(backup, Task.abortSignal))
|
||||
} else {
|
||||
assert.strictEqual(metadata.mode, 'delta')
|
||||
|
||||
@@ -451,12 +459,21 @@ export class ImportVmBackup {
|
||||
additionalVmTag !== undefined && vm.add_tags(additionalVmTag),
|
||||
])
|
||||
|
||||
const vmRef = isFull
|
||||
? await xapi.VM_import(backup, srRef, onVmCreation)
|
||||
: await importIncrementalVm(backup, await xapi.getRecord('SR', srRef), {
|
||||
newMacAddresses,
|
||||
vmNamePrefix,
|
||||
})
|
||||
const signal = Task.abortSignal
|
||||
let vmRef
|
||||
try {
|
||||
vmRef = isFull
|
||||
? await xapi.VM_import(backup, srRef, onVmCreation)
|
||||
: await importIncrementalVm(backup, await xapi.getRecord('SR', srRef), {
|
||||
newMacAddresses,
|
||||
signal,
|
||||
vmNamePrefix,
|
||||
})
|
||||
} catch (error) {
|
||||
// the error of the destroyed stream: report the abort instead
|
||||
signal?.throwIfAborted()
|
||||
throw error
|
||||
}
|
||||
let size = 0
|
||||
if (isFull) {
|
||||
size = sizeContainer.size
|
||||
|
||||
@@ -304,3 +304,109 @@ describe('ImportVmBackup#_reuseNearestSnapshot()', () => {
|
||||
await assert.rejects(() => importer._reuseNearestSnapshot(new Set([SYSTEM.uuid])), /would transfer the disk/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('ImportVmBackup#run() after an abort', () => {
|
||||
// a full restore whose steps `xapi` and `adapter` are controlled by the test: it reads `xva` and imports it with
|
||||
// `VM_import()`, which, as the XAPI one does, reads its input until it ends and fails when the input fails
|
||||
async function makeFullRestore({ onOpen, onSrLookup } = {}) {
|
||||
const { PassThrough } = await import('node:stream')
|
||||
const xva = new PassThrough()
|
||||
// `importing` is resolved once `VM_import()` reads the stream
|
||||
const { promise: importing, resolve: onImport } = Promise.withResolvers()
|
||||
const state = { imported: false, importing }
|
||||
const importer = new ImportVmBackup({
|
||||
adapter: {
|
||||
_handler: { _remote: {} },
|
||||
readFullVmBackup: async () => {
|
||||
await onOpen?.()
|
||||
return xva
|
||||
},
|
||||
},
|
||||
metadata: { ...makeMetadata(), mode: 'full' },
|
||||
srUuid: DEFAULT_SR,
|
||||
xapi: {
|
||||
call: async () => {
|
||||
await onSrLookup?.()
|
||||
return 'OpaqueRef:sr'
|
||||
},
|
||||
VM_import: stream =>
|
||||
new Promise((resolve, reject) => {
|
||||
state.imported = true
|
||||
onImport()
|
||||
stream.on('error', () => reject(new Error('premature close'))).resume()
|
||||
}),
|
||||
},
|
||||
})
|
||||
return { importer, state, xva }
|
||||
}
|
||||
|
||||
// the outcome of `run()`, `'still running'` if it does not settle within a second
|
||||
const outcomeOf = pRun =>
|
||||
Promise.race([
|
||||
pRun.then(
|
||||
() => 'resolved',
|
||||
error => error.name
|
||||
),
|
||||
new Promise(resolve => setTimeout(resolve, 1e3, 'still running')),
|
||||
])
|
||||
|
||||
it('stops the import of a full backup and fails with the abort', async () => {
|
||||
const { Task } = await import('@vates/task')
|
||||
const { importer, state } = await makeFullRestore()
|
||||
|
||||
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
|
||||
const result = await vmTask
|
||||
.run(async () => {
|
||||
const pRun = importer.run()
|
||||
await state.importing
|
||||
vmTask.abort()
|
||||
return outcomeOf(pRun)
|
||||
})
|
||||
.catch(error => error.name)
|
||||
|
||||
assert.equal(result, 'AbortError')
|
||||
})
|
||||
|
||||
it('stops a full restore aborted before its import has started, and destroys its stream', async () => {
|
||||
const { Task } = await import('@vates/task')
|
||||
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
|
||||
// the abort lands during the lookup of the SR, after the transfer subtask started
|
||||
const { importer, xva } = await makeFullRestore({ onSrLookup: () => vmTask.abort() })
|
||||
|
||||
const result = await vmTask.run(() => outcomeOf(importer.run())).catch(error => error.name)
|
||||
|
||||
assert.equal(result, 'AbortError')
|
||||
assert.equal(xva.destroyed, true)
|
||||
})
|
||||
|
||||
it('destroys the stream of a full backup when the abort lands while it is opened', async () => {
|
||||
const { Task } = await import('@vates/task')
|
||||
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
|
||||
// the transfer subtask is then created under an aborted task: it fails without running
|
||||
const { importer, state, xva } = await makeFullRestore({ onOpen: () => vmTask.abort() })
|
||||
|
||||
const result = await vmTask.run(() => outcomeOf(importer.run())).catch(error => error.name)
|
||||
|
||||
assert.equal(result, 'AbortError')
|
||||
assert.equal(state.imported, false)
|
||||
assert.equal(xva.destroyed, true, 'the stream (a file handle or an S3 request) is not left open')
|
||||
})
|
||||
|
||||
it('restores a full backup outside a task, as the proxy does', async t => {
|
||||
// `golike-defer` logs the errors of the deferred functions instead of rejecting with them
|
||||
const logError = t.mock.method(console, 'error', () => {})
|
||||
const { importer, xva } = await makeFullRestore()
|
||||
importer._xapi.VM_import = async stream => {
|
||||
stream.resume()
|
||||
throw new Error('stop after the import')
|
||||
}
|
||||
xva.end()
|
||||
|
||||
// the error of the import, not one of the abort handling, which has no signal to listen to
|
||||
await assert.rejects(importer.run(), { message: 'stop after the import' })
|
||||
assert.deepEqual(
|
||||
logError.mock.calls.map(call => String(call.arguments[0])),
|
||||
[]
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -317,6 +317,34 @@ describe('RemoteAdapter#writeVhd validated by checkDisk', { concurrency: 1 }, ()
|
||||
assert.deepEqual(await handler.list(basePath, { ignoreMissing: true }), useVhdDirectory ? ['data'] : [])
|
||||
assert.deepEqual(await handler.list(`${basePath}/data`, { ignoreMissing: true }), [])
|
||||
})
|
||||
|
||||
test(`${mode}: an aborted write stops and leaves no disk behind`, async () => {
|
||||
const adapter = await getAdapter({ useVhdDirectory })
|
||||
const path = `${basePath}/${adapter.getVhdFileName('base')}`
|
||||
const controller = new AbortController()
|
||||
const read = []
|
||||
// the backup is aborted once the first block has been read
|
||||
class AbortedDisk extends MockDisk {
|
||||
async readBlock(index) {
|
||||
read.push(index)
|
||||
if (read.length === 1) {
|
||||
controller.abort()
|
||||
}
|
||||
return super.readBlock(index)
|
||||
}
|
||||
}
|
||||
|
||||
await assert.rejects(
|
||||
adapter.writeVhd(path, new AbortedDisk(8, [0, 1, 2, 3, 4, 5, 6, 7], 0x11), {
|
||||
signal: controller.signal,
|
||||
uuid: uniqueIdBuffer(),
|
||||
}),
|
||||
{ name: 'AbortError' }
|
||||
)
|
||||
|
||||
assert.deepEqual(await handler.list(basePath, { ignoreMissing: true }), useVhdDirectory ? ['data'] : [])
|
||||
assert.deepEqual(await handler.list(`${basePath}/data`, { ignoreMissing: true }), [])
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
|
||||
@@ -687,12 +687,14 @@ export class RemoteAdapter {
|
||||
return path
|
||||
}
|
||||
|
||||
async writeVhd(path, disk, { validator = noop, writeBlockConcurrency, uuid, parentUuid, parentPath } = {}) {
|
||||
// `signal` stops the write once aborted: the partial disk is then removed
|
||||
async writeVhd(path, disk, { signal, validator = noop, writeBlockConcurrency, uuid, parentUuid, parentPath } = {}) {
|
||||
const handler = this._handler
|
||||
|
||||
if (this.useVhdDirectory()) {
|
||||
return await writeToVhdDirectory({
|
||||
disk,
|
||||
signal,
|
||||
target: {
|
||||
handler,
|
||||
path,
|
||||
@@ -705,7 +707,11 @@ export class RemoteAdapter {
|
||||
},
|
||||
})
|
||||
} else {
|
||||
const stream = await toVhdStream(disk, { uuid, parentUuid, parentPath })
|
||||
const stream = await toVhdStream(disk, { signal, uuid, parentUuid, parentPath })
|
||||
// the stream starts reading the disk before the output stream is piped (`outputStream()` creates it first): an
|
||||
// error in between (an abort, a read error) must not be emitted without listener, which would crash the process
|
||||
// the pipeline still fails with this error, kept by the stream
|
||||
stream.on('error', noop)
|
||||
const size = await this.outputStream(path, stream, {
|
||||
validator,
|
||||
// no checksum for VHDs, because they will be invalidated by
|
||||
|
||||
@@ -178,6 +178,8 @@ process.on('message', async message => {
|
||||
? await Task.run(
|
||||
{
|
||||
properties: { name: 'backup run', ...message.data.jobData },
|
||||
// the steps of an aborted backup are skipped, as when the backup runs in the main thread
|
||||
skipSubtasksAfterAbort: true,
|
||||
onProgress: data =>
|
||||
emitMessage({
|
||||
data,
|
||||
|
||||
28
@xen-orchestra/backups/_destroyOnAbort.mjs
Normal file
28
@xen-orchestra/backups/_destroyOnAbort.mjs
Normal file
@@ -0,0 +1,28 @@
|
||||
const noop = Function.prototype
|
||||
|
||||
/**
|
||||
* Destroys `stream` with the reason of `signal` once it is aborted, right away if it already is.
|
||||
*
|
||||
* Nothing may be listening to the stream when it is destroyed: an error event without a listener would crash the
|
||||
* process, so a noop listener is added.
|
||||
*
|
||||
* @param {import('node:stream').Readable} stream
|
||||
* @param {AbortSignal} [signal] nothing is done without a signal, e.g. a restore run outside a task
|
||||
* @returns {() => void} removes the abort listener
|
||||
*/
|
||||
export function destroyOnAbort(stream, signal) {
|
||||
if (signal === undefined) {
|
||||
return noop
|
||||
}
|
||||
|
||||
stream.on('error', noop)
|
||||
|
||||
const onAbort = () => stream.destroy(signal.reason)
|
||||
if (signal.aborted) {
|
||||
onAbort()
|
||||
return noop
|
||||
}
|
||||
|
||||
signal.addEventListener('abort', onAbort, { once: true })
|
||||
return () => signal.removeEventListener('abort', onAbort)
|
||||
}
|
||||
50
@xen-orchestra/backups/_destroyOnAbort.test.mjs
Normal file
50
@xen-orchestra/backups/_destroyOnAbort.test.mjs
Normal file
@@ -0,0 +1,50 @@
|
||||
import { describe, it } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { PassThrough } from 'node:stream'
|
||||
|
||||
import { destroyOnAbort } from './_destroyOnAbort.mjs'
|
||||
|
||||
describe('destroyOnAbort()', () => {
|
||||
it('does nothing without a signal', () => {
|
||||
const stream = new PassThrough()
|
||||
|
||||
destroyOnAbort(stream, undefined)()
|
||||
|
||||
assert.equal(stream.destroyed, false)
|
||||
assert.equal(stream.listenerCount('error'), 0)
|
||||
})
|
||||
|
||||
it('destroys the stream right away when the signal is already aborted', () => {
|
||||
const stream = new PassThrough()
|
||||
const reason = new Error('aborted')
|
||||
|
||||
destroyOnAbort(stream, AbortSignal.abort(reason))
|
||||
|
||||
assert.equal(stream.destroyed, true)
|
||||
assert.equal(stream.errored, reason)
|
||||
})
|
||||
|
||||
it('destroys the stream once aborted, without crashing when nothing listens to it', async () => {
|
||||
const stream = new PassThrough()
|
||||
const controller = new AbortController()
|
||||
const reason = new Error('aborted')
|
||||
|
||||
destroyOnAbort(stream, controller.signal)
|
||||
controller.abort(reason)
|
||||
// the error event is emitted on the next tick: an unhandled one would crash the test process
|
||||
await new Promise(resolve => setImmediate(resolve))
|
||||
|
||||
assert.equal(stream.destroyed, true)
|
||||
assert.equal(stream.errored, reason)
|
||||
})
|
||||
|
||||
it('returns a function that stops listening to the signal', () => {
|
||||
const stream = new PassThrough()
|
||||
const controller = new AbortController()
|
||||
|
||||
destroyOnAbort(stream, controller.signal)()
|
||||
controller.abort()
|
||||
|
||||
assert.equal(stream.destroyed, false)
|
||||
})
|
||||
})
|
||||
@@ -32,7 +32,9 @@ export async function exportIncrementalVm(vm, baseVdis = {}, { signal, nbdConcur
|
||||
const disks = {}
|
||||
const vdis = {}
|
||||
const vbds = {}
|
||||
await abortableMap(signal, vm.$VBDs, async (signal, vbd) => {
|
||||
// the signal given to the callback stops the other initializations when one fails; the disks keep `signal`, which
|
||||
// must keep reaching them once the export is built
|
||||
await abortableMap(signal, vm.$VBDs, async (_initSignal, vbd) => {
|
||||
let vdi
|
||||
if (vbd.type !== 'Disk' || !(vdi = vbd.$VDI)) {
|
||||
// Ignore this VBD.
|
||||
@@ -68,6 +70,7 @@ export async function exportIncrementalVm(vm, baseVdis = {}, { signal, nbdConcur
|
||||
baseRef: baseVdi?.$ref,
|
||||
nbdConcurrency,
|
||||
preferNbd,
|
||||
signal,
|
||||
})
|
||||
await disks[vdiRef].init()
|
||||
})
|
||||
@@ -84,6 +87,7 @@ export async function exportIncrementalVm(vm, baseVdis = {}, { signal, nbdConcur
|
||||
xapi: vm.$xapi,
|
||||
nbdConcurrency,
|
||||
preferNbd,
|
||||
signal,
|
||||
})
|
||||
await disks[vdiRef].init()
|
||||
}
|
||||
|
||||
@@ -40,6 +40,9 @@ export const VmsRemote = class RemoteVmsBackupRunner extends Abstract {
|
||||
}
|
||||
|
||||
async run() {
|
||||
// abort signal of the backup run: once aborted, no new VM backup starts and no VM backup is retried
|
||||
const signal = Task.abortSignal
|
||||
|
||||
const job = this._job
|
||||
const schedule = this._schedule
|
||||
const settings = this._settings
|
||||
@@ -81,6 +84,10 @@ export const VmsRemote = class RemoteVmsBackupRunner extends Abstract {
|
||||
const nTriesByVmId = {}
|
||||
|
||||
const handleVm = async vmUuid => {
|
||||
if (signal?.aborted) {
|
||||
return
|
||||
}
|
||||
|
||||
if (nTriesByVmId[vmUuid] === undefined) {
|
||||
nTriesByVmId[vmUuid] = 0
|
||||
}
|
||||
@@ -143,9 +150,10 @@ export const VmsRemote = class RemoteVmsBackupRunner extends Abstract {
|
||||
nbVmsDone++
|
||||
return task.success(result)
|
||||
}
|
||||
if (isLastRun) {
|
||||
// once aborted, the VM backup is not retried: it failed because of the abort, whatever its error
|
||||
if (isLastRun || signal?.aborted) {
|
||||
nbVmsDone++
|
||||
return task.failure(taskError)
|
||||
return task.failure(signal?.aborted ? signal.reason : taskError)
|
||||
}
|
||||
Task.set('progress', Math.round((nbVmsDone * 100) / nbVms))
|
||||
// don't end the task
|
||||
|
||||
73
@xen-orchestra/backups/_runners/VmsRemote.test.mjs
Normal file
73
@xen-orchestra/backups/_runners/VmsRemote.test.mjs
Normal file
@@ -0,0 +1,73 @@
|
||||
import { describe, it } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { Task } from '@vates/task'
|
||||
|
||||
import { FullRemote } from './_vmRunners/FullRemote.mjs'
|
||||
import { VmsRemote } from './VmsRemote.mjs'
|
||||
|
||||
// a VM backup that runs until the run is aborted, as a transfer does
|
||||
const backupUntilAborted = () =>
|
||||
new Promise((resolve, reject) => {
|
||||
const signal = Task.abortSignal
|
||||
if (signal.aborted) {
|
||||
reject(signal.reason)
|
||||
} else {
|
||||
signal.addEventListener('abort', () => reject(signal.reason), { once: true })
|
||||
}
|
||||
})
|
||||
|
||||
function createRunner({ vms, settings = {} }) {
|
||||
const sourceAdapter = {
|
||||
listAllVms: async () => vms,
|
||||
listVmBackups: async () => [{ mode: 'full', vm: {} }],
|
||||
}
|
||||
return new VmsRemote({
|
||||
config: { snapshotNameLabelTpl: '[XO Backup {job.name}] {vm.name_label}' },
|
||||
getAdapter: async remoteId => ({ value: remoteId === 'source' ? sourceAdapter : {}, dispose() {} }),
|
||||
getConnectedRecord: async () => {
|
||||
throw new Error('no record in these tests')
|
||||
},
|
||||
job: {
|
||||
id: 'job',
|
||||
mode: 'full',
|
||||
name: 'job',
|
||||
remotes: { id: { __or: ['source', 'target'] } },
|
||||
settings: { '': { concurrency: 1, ...settings } },
|
||||
sourceRemote: 'source',
|
||||
},
|
||||
schedule: { id: 'schedule' },
|
||||
})
|
||||
}
|
||||
|
||||
// runs the runner inside a root task, aborted once the first VM backup has started
|
||||
async function runAndAbort(runner, calls) {
|
||||
const events = []
|
||||
const root = new Task({ skipSubtasksAfterAbort: true, onProgress: event => events.push(event) })
|
||||
const pRun = root.run(() => runner.run())
|
||||
|
||||
while ((calls.vm1 ?? 0) === 0) {
|
||||
await new Promise(resolve => setImmediate(resolve))
|
||||
}
|
||||
root.abort()
|
||||
await pRun.catch(() => {})
|
||||
|
||||
return events.filter(_ => _.type === 'start' && _.properties?.type === 'VM').map(_ => _.properties.id)
|
||||
}
|
||||
|
||||
describe('VmsRemote#run() after an abort', () => {
|
||||
it('does not start the backup of the next VMs, nor retry the aborted one', async t => {
|
||||
const calls = {}
|
||||
t.mock.method(FullRemote.prototype, 'run', function () {
|
||||
calls[this._vmUuid] = (calls[this._vmUuid] ?? 0) + 1
|
||||
return this._vmUuid === 'vm1' ? backupUntilAborted() : Promise.resolve()
|
||||
})
|
||||
|
||||
const vmTaskIds = await runAndAbort(
|
||||
createRunner({ vms: ['vm1', 'vm2'], settings: { nRetriesVmBackupFailures: 2 } }),
|
||||
calls
|
||||
)
|
||||
|
||||
assert.deepEqual(calls, { vm1: 1 }, 'the aborted VM is not retried and the second VM is not backed up')
|
||||
assert.deepEqual(vmTaskIds, ['vm1'], 'no task is created for the VMs not started')
|
||||
})
|
||||
})
|
||||
@@ -63,6 +63,9 @@ export const VmsXapi = class VmsXapiBackupRunner extends Abstract {
|
||||
}
|
||||
|
||||
async run() {
|
||||
// abort signal of the backup run: once aborted, no new VM backup starts and no VM backup is retried
|
||||
const signal = Task.abortSignal
|
||||
|
||||
const job = this._job
|
||||
|
||||
// FIXME: proper SimpleIdPattern handling
|
||||
@@ -143,6 +146,10 @@ export const VmsXapi = class VmsXapiBackupRunner extends Abstract {
|
||||
await asyncEach(
|
||||
[...vms].filter(vm => batchIds.has(vm.uuid)),
|
||||
async vm => {
|
||||
if (signal?.aborted) {
|
||||
return
|
||||
}
|
||||
|
||||
const { task } = getVmTask(vm.uuid, vm.name_label)
|
||||
|
||||
const vmSettings = { ...settings, ...allSettings[vm.uuid] }
|
||||
@@ -205,9 +212,14 @@ export const VmsXapi = class VmsXapiBackupRunner extends Abstract {
|
||||
const queue = new Set(snapshotedVmIds)
|
||||
|
||||
const handleVm = vmUuid => {
|
||||
if (signal?.aborted) {
|
||||
return
|
||||
}
|
||||
|
||||
const vmBackupFailed = async (error, task) => {
|
||||
if (isLastRun) {
|
||||
return task.failure(error)
|
||||
// once aborted, the VM backup is not retried: it failed because of the abort, whatever its error
|
||||
if (isLastRun || signal?.aborted) {
|
||||
return task.failure(signal?.aborted ? signal.reason : error)
|
||||
} else {
|
||||
// don't end the task
|
||||
task.warning(`Retry the VM backup due to an error`, {
|
||||
|
||||
89
@xen-orchestra/backups/_runners/VmsXapi.test.mjs
Normal file
89
@xen-orchestra/backups/_runners/VmsXapi.test.mjs
Normal file
@@ -0,0 +1,89 @@
|
||||
import { describe, it } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { Task } from '@vates/task'
|
||||
|
||||
import { VmsXapi } from './VmsXapi.mjs'
|
||||
|
||||
// a VM backup that runs until the run is aborted, as a transfer does
|
||||
const backupUntilAborted = () =>
|
||||
new Promise((resolve, reject) => {
|
||||
const signal = Task.abortSignal
|
||||
if (signal.aborted) {
|
||||
reject(signal.reason)
|
||||
} else {
|
||||
signal.addEventListener('abort', () => reject(signal.reason), { once: true })
|
||||
}
|
||||
})
|
||||
|
||||
function createRunner({ backups, settings = {} }) {
|
||||
const runner = new VmsXapi({
|
||||
config: { snapshotNameLabelTpl: '[XO Backup {job.name}] {vm.name_label}' },
|
||||
getAdapter: () => {
|
||||
throw new Error('no remote in these tests')
|
||||
},
|
||||
getConnectedRecord: async (type, id) => ({ $type: type, uuid: id, name_label: id }),
|
||||
job: {
|
||||
id: 'job',
|
||||
mode: 'full',
|
||||
name: 'job',
|
||||
settings: { '': { concurrency: 1, ...settings } },
|
||||
srs: { id: 'sr' },
|
||||
vms: { id: { __or: Object.keys(backups) } },
|
||||
},
|
||||
schedule: { id: 'schedule' },
|
||||
})
|
||||
|
||||
const calls = Object.fromEntries(Object.keys(backups).map(id => [id, 0]))
|
||||
runner._getVmBackup = (mode, { vm }) => ({
|
||||
run: () => {
|
||||
++calls[vm.uuid]
|
||||
return backups[vm.uuid]()
|
||||
},
|
||||
})
|
||||
|
||||
return { runner, calls }
|
||||
}
|
||||
|
||||
// runs the runner inside a root task, aborted once the first VM backup has started
|
||||
async function runAndAbort(runner, calls) {
|
||||
const events = []
|
||||
const root = new Task({ skipSubtasksAfterAbort: true, onProgress: event => events.push(event) })
|
||||
const pRun = root.run(() => runner.run())
|
||||
|
||||
while (calls.vm1 === 0) {
|
||||
await new Promise(resolve => setImmediate(resolve))
|
||||
}
|
||||
root.abort()
|
||||
await pRun.catch(() => {})
|
||||
|
||||
const vmTaskIds = events.filter(_ => _.type === 'start' && _.properties?.type === 'VM').map(_ => _.properties.id)
|
||||
return { events, vmTaskIds }
|
||||
}
|
||||
|
||||
describe('VmsXapi#run() after an abort', () => {
|
||||
it('does not start the backup of the next VMs', async () => {
|
||||
const { runner, calls } = createRunner({
|
||||
backups: { vm1: backupUntilAborted, vm2: async () => {} },
|
||||
})
|
||||
|
||||
const { vmTaskIds } = await runAndAbort(runner, calls)
|
||||
|
||||
assert.equal(calls.vm2, 0, 'the second VM is not backed up')
|
||||
assert.deepEqual(vmTaskIds, ['vm1'], 'no task is created for the VMs not started')
|
||||
})
|
||||
|
||||
it('does not retry the aborted VM', async () => {
|
||||
const { runner, calls } = createRunner({
|
||||
backups: { vm1: backupUntilAborted },
|
||||
settings: { nRetriesVmBackupFailures: 2 },
|
||||
})
|
||||
|
||||
const { events } = await runAndAbort(runner, calls)
|
||||
|
||||
assert.equal(calls.vm1, 1, 'the aborted VM backup is not run again')
|
||||
const vmTaskId = events.find(_ => _.type === 'start' && _.properties?.id === 'vm1').id
|
||||
const vmEnd = events.find(_ => _.type === 'end' && _.id === vmTaskId)
|
||||
assert.equal(vmEnd.status, 'failure')
|
||||
assert.equal(vmEnd.result.name, 'AbortError')
|
||||
})
|
||||
})
|
||||
@@ -3,6 +3,7 @@ import { createLogger } from '@xen-orchestra/log'
|
||||
import { AbstractRemote } from './_AbstractRemote.mjs'
|
||||
import { FullRemoteWriter } from '../_writers/FullRemoteWriter.mjs'
|
||||
import { forkStreamUnpipe } from '../_forkStreamUnpipe.mjs'
|
||||
import { destroyOnAbort } from '../../_destroyOnAbort.mjs'
|
||||
import { watchStreamSize } from '../../_watchStreamSize.mjs'
|
||||
import { AggregatedFullRemoteWriter } from '../_writers/AggregatedFullRemoteWriter.mjs'
|
||||
import { Task } from '@vates/task'
|
||||
@@ -23,6 +24,7 @@ export const FullRemote = class FullRemoteVmBackupRunner extends AbstractRemote
|
||||
const nbTransferrableVms = transferList.length
|
||||
let nbTransferredVms = 0
|
||||
for (const metadata of transferList) {
|
||||
Task.abortSignal?.throwIfAborted()
|
||||
const stream = this._throttleStream(await this._sourceRemoteAdapter.readFullVmBackup(metadata))
|
||||
const sizeContainer = watchStreamSize(stream)
|
||||
let checksum
|
||||
@@ -36,6 +38,9 @@ export const FullRemote = class FullRemoteVmBackupRunner extends AbstractRemote
|
||||
// a single writer can consume the stream itself: no need to fork it
|
||||
const isForked = this._writers.size > 1
|
||||
|
||||
// the source is a plain stream: destroying it stops the reading and makes the writers fail
|
||||
const stopDestroyOnAbort = destroyOnAbort(stream, Task.abortSignal)
|
||||
|
||||
// @todo shouldn't transfer backup if it will be deleted by retention policy (higher retention on source than destination)
|
||||
await this._callWriters(
|
||||
writer =>
|
||||
@@ -51,7 +56,7 @@ export const FullRemote = class FullRemoteVmBackupRunner extends AbstractRemote
|
||||
sizeContainer,
|
||||
}),
|
||||
'writer.run()'
|
||||
)
|
||||
).finally(stopDestroyOnAbort)
|
||||
// for healthcheck
|
||||
this._vm = metadata.vm
|
||||
nbTransferredVms++
|
||||
|
||||
119
@xen-orchestra/backups/_runners/_vmRunners/FullRemote.test.mjs
Normal file
119
@xen-orchestra/backups/_runners/_vmRunners/FullRemote.test.mjs
Normal file
@@ -0,0 +1,119 @@
|
||||
import { describe, it } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { PassThrough } from 'node:stream'
|
||||
import { Task } from '@vates/task'
|
||||
|
||||
import { FullRemote } from './FullRemote.mjs'
|
||||
|
||||
const makeRunner = props => Object.assign(Object.create(FullRemote.prototype), props)
|
||||
|
||||
describe('FullRemote#_run() after an abort', () => {
|
||||
it('stops reading the source backup', async () => {
|
||||
const source = new PassThrough()
|
||||
// resolved once the writer reads the stream
|
||||
const { promise: pWriting, resolve: onWriting } = Promise.withResolvers()
|
||||
const runner = makeRunner({
|
||||
_computeTransferList: async () => [{ timestamp: 0, vm: {}, vmSnapshot: {} }],
|
||||
_sourceRemoteAdapter: {
|
||||
readFullVmBackup: async () => source,
|
||||
readFullVmBackupChecksum: async () => {
|
||||
throw new Error('no checksum')
|
||||
},
|
||||
},
|
||||
_throttleStream: stream => stream,
|
||||
_writers: new Set([
|
||||
{
|
||||
// a writer which writes until its input ends or fails
|
||||
run: ({ stream }) =>
|
||||
new Promise((resolve, reject) => {
|
||||
onWriting()
|
||||
stream.on('error', reject).on('end', resolve).resume()
|
||||
}),
|
||||
},
|
||||
]),
|
||||
})
|
||||
|
||||
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
|
||||
const result = await vmTask
|
||||
.run(async () => {
|
||||
const pRun = runner._run()
|
||||
await pWriting
|
||||
vmTask.abort()
|
||||
return Promise.race([
|
||||
pRun.then(
|
||||
() => 'resolved',
|
||||
error => error.name
|
||||
),
|
||||
new Promise(resolve => setTimeout(resolve, 1e3, 'still reading')),
|
||||
])
|
||||
})
|
||||
.catch(error => error.name)
|
||||
|
||||
assert.equal(result, 'AbortError')
|
||||
})
|
||||
|
||||
it('destroys the source stream when the abort came while the source was being opened', async () => {
|
||||
// nothing listens to its errors: destroying it must not crash the process
|
||||
const source = new PassThrough()
|
||||
let written = false
|
||||
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
|
||||
const runner = makeRunner({
|
||||
_computeTransferList: async () => [{ timestamp: 0, vm: {}, vmSnapshot: {} }],
|
||||
_sourceRemoteAdapter: {
|
||||
readFullVmBackup: async () => source,
|
||||
readFullVmBackupChecksum: async () => {
|
||||
// the abort lands during the awaits that precede the registration of the listener
|
||||
vmTask.abort()
|
||||
throw new Error('no checksum')
|
||||
},
|
||||
},
|
||||
_throttleStream: stream => stream,
|
||||
_writers: new Set([
|
||||
{
|
||||
run: async () => {
|
||||
written = true
|
||||
},
|
||||
},
|
||||
]),
|
||||
})
|
||||
|
||||
// the writers do not consume the stream: only the abort handling can close it
|
||||
await vmTask.run(() => runner._run()).catch(() => {})
|
||||
|
||||
assert.equal(source.destroyed, true)
|
||||
assert.equal(written, true)
|
||||
})
|
||||
|
||||
it('does not open the source of the next backup once aborted', async () => {
|
||||
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
|
||||
let opened = 0
|
||||
const runner = makeRunner({
|
||||
_computeTransferList: async () => [
|
||||
{ timestamp: 0, vm: {}, vmSnapshot: {} },
|
||||
{ timestamp: 1, vm: {}, vmSnapshot: {} },
|
||||
],
|
||||
_sourceRemoteAdapter: {
|
||||
readFullVmBackup: async () => {
|
||||
++opened
|
||||
// nothing listens to its errors: destroying it must not crash the process
|
||||
return new PassThrough()
|
||||
},
|
||||
readFullVmBackupChecksum: async () => 'checksum',
|
||||
},
|
||||
_throttleStream: stream => stream,
|
||||
_writers: new Set([
|
||||
{
|
||||
run: async () => {
|
||||
vmTask.abort()
|
||||
},
|
||||
},
|
||||
]),
|
||||
})
|
||||
|
||||
await assert.rejects(
|
||||
vmTask.run(() => runner._run()),
|
||||
{ name: 'AbortError' }
|
||||
)
|
||||
assert.equal(opened, 1)
|
||||
})
|
||||
})
|
||||
@@ -1,4 +1,5 @@
|
||||
import { createLogger } from '@xen-orchestra/log'
|
||||
import { Task } from '@vates/task'
|
||||
|
||||
import { forkStreamUnpipe } from '../_forkStreamUnpipe.mjs'
|
||||
import { FullRemoteWriter } from '../_writers/FullRemoteWriter.mjs'
|
||||
@@ -55,6 +56,8 @@ export const FullXapi = class FullXapiVmBackupRunner extends AbstractXapi {
|
||||
(
|
||||
await this._xapi.VM_export(exportedVm.$ref, {
|
||||
compress: Boolean(compression) && (compression === 'native' ? 'gzip' : 'zstd'),
|
||||
// the export stream fails once the backup is aborted, which stops the writers
|
||||
signal: Task.abortSignal,
|
||||
useSnapshot: false,
|
||||
})
|
||||
).body
|
||||
|
||||
68
@xen-orchestra/backups/_runners/_vmRunners/FullXapi.test.mjs
Normal file
68
@xen-orchestra/backups/_runners/_vmRunners/FullXapi.test.mjs
Normal file
@@ -0,0 +1,68 @@
|
||||
import { describe, it } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { PassThrough } from 'node:stream'
|
||||
import { Task } from '@vates/task'
|
||||
|
||||
import { FullXapi } from './FullXapi.mjs'
|
||||
|
||||
const makeRunner = props => Object.assign(Object.create(FullXapi.prototype), props)
|
||||
|
||||
describe('FullXapi#_copy() after an abort', () => {
|
||||
it('stops the XAPI export, and settles only once its writers have settled', async () => {
|
||||
let exportOpts
|
||||
// resolved once the XAPI export is called
|
||||
const { promise: pExport, resolve: onExport } = Promise.withResolvers()
|
||||
let writerSettledAt
|
||||
const body = new PassThrough()
|
||||
const runner = makeRunner({
|
||||
job: {},
|
||||
_vm: { uuid: 'vm-uuid' },
|
||||
_exportedVm: { $ref: 'snapshot-ref', $getDisks: async () => [] },
|
||||
_throttleStream: stream => stream,
|
||||
_xapi: {
|
||||
// as the HTTP export does: the body fails once the signal is aborted
|
||||
VM_export: async (ref, opts) => {
|
||||
exportOpts = opts
|
||||
onExport()
|
||||
opts.signal?.addEventListener('abort', () => body.destroy(opts.signal.reason), { once: true })
|
||||
return { body }
|
||||
},
|
||||
},
|
||||
_writers: new Set([
|
||||
{
|
||||
// a writer that needs some time to clean up after its input failed
|
||||
run: ({ stream }) =>
|
||||
new Promise((resolve, reject) => {
|
||||
stream.on('error', error =>
|
||||
setTimeout(() => {
|
||||
writerSettledAt = Date.now()
|
||||
reject(error)
|
||||
}, 100)
|
||||
)
|
||||
stream.resume()
|
||||
}),
|
||||
},
|
||||
]),
|
||||
})
|
||||
|
||||
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
|
||||
let copyRejectedAt
|
||||
await vmTask
|
||||
.run(async () => {
|
||||
const pCopy = runner._copy()
|
||||
await pExport
|
||||
assert.ok(exportOpts.signal instanceof AbortSignal, 'the export gets the abort signal')
|
||||
|
||||
vmTask.abort()
|
||||
await assert.rejects(pCopy, { name: 'AbortError' })
|
||||
copyRejectedAt = Date.now()
|
||||
})
|
||||
.catch(error => {
|
||||
if (error.name !== 'AbortError') {
|
||||
throw error
|
||||
}
|
||||
})
|
||||
|
||||
assert.ok(writerSettledAt <= copyRejectedAt, 'the copy settles after its writers')
|
||||
})
|
||||
})
|
||||
@@ -85,6 +85,8 @@ class IncrementalRemoteVmBackupRunner extends AbstractRemote {
|
||||
const nbTransferrableVms = transferList.length
|
||||
let nbTransferredVms = 0
|
||||
for (const metadata of transferList) {
|
||||
// an abort during the previous VM's writer steps: its disks would be opened and never closed
|
||||
Task.abortSignal?.throwIfAborted()
|
||||
assert.strictEqual(metadata.mode, 'delta')
|
||||
const incrementalExport = await this._sourceRemoteAdapter.readIncrementalVmBackup(metadata, undefined, {
|
||||
useChain: false,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { describe, it } from 'node:test'
|
||||
import { Task } from '@vates/task'
|
||||
|
||||
import { IncrementalRemote } from './IncrementalRemote.mjs'
|
||||
|
||||
@@ -43,3 +44,42 @@ describe('IncrementalRemote prepare()', () => {
|
||||
assert.equal(aggWriter.props.schedule, schedule)
|
||||
})
|
||||
})
|
||||
|
||||
describe('IncrementalRemote#_run() after an abort', () => {
|
||||
it('does not open the disks of the next backup once aborted', async () => {
|
||||
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
|
||||
let opened = 0
|
||||
// a real instance: `_run()` uses a private method
|
||||
const runner = Object.assign(makeRunner({ schedule: { id: 'schedule-id' } }), {
|
||||
_computeTransferList: async () => [
|
||||
{ mode: 'delta', timestamp: 0, vm: {}, vmSnapshot: {} },
|
||||
{ mode: 'delta', timestamp: 1, vm: {}, vmSnapshot: {} },
|
||||
],
|
||||
_selectBaseVm: async () => {},
|
||||
_sourceRemoteAdapter: {
|
||||
getVhdDirectoryCompression: () => undefined,
|
||||
readIncrementalVmBackup: async () => {
|
||||
++opened
|
||||
return { disks: {}, vbds: {}, vdis: {}, vifs: {}, vm: {}, vtpms: {} }
|
||||
},
|
||||
},
|
||||
_writers: new Set([
|
||||
{
|
||||
getVhdDirectoryCompression: () => undefined,
|
||||
prepare: async () => {},
|
||||
transfer: async () => {},
|
||||
// the abort lands during the writer steps of the first backup
|
||||
cleanup: async () => {
|
||||
vmTask.abort()
|
||||
},
|
||||
},
|
||||
]),
|
||||
})
|
||||
|
||||
await assert.rejects(
|
||||
vmTask.run(() => runner._run()),
|
||||
{ name: 'AbortError' }
|
||||
)
|
||||
assert.equal(opened, 1)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -55,6 +55,8 @@ export const IncrementalXapi = class IncrementalXapiVmBackupRunner extends Abstr
|
||||
const deltaExport = await exportIncrementalVm(exportedVm, baseVdis, {
|
||||
nbdConcurrency: this._settings.nbdConcurrency,
|
||||
preferNbd: this._settings.preferNbd,
|
||||
// the reads of the disks stop once the backup is aborted
|
||||
signal: Task.abortSignal,
|
||||
})
|
||||
|
||||
const isVhdDifferencing = {}
|
||||
|
||||
@@ -233,6 +233,7 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
|
||||
const snapshotRef = await vm[settings.checkpointSnapshot ? '$checkpoint' : '$snapshot']({
|
||||
ignoredVdisTag: '[NOBAK]',
|
||||
name_label: TEMP_SNAPSHOT_NAME,
|
||||
signal: Task.abortSignal,
|
||||
unplugVusbs: true,
|
||||
})
|
||||
this.timestamp = Date.now()
|
||||
@@ -381,7 +382,9 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
|
||||
const xapi = this._xapi
|
||||
|
||||
const vdiCandidates = {}
|
||||
const vdiUuids = this._vm.$VBDs.map(({ VDI }) => VDI)
|
||||
// only disks: an empty CD drive has an empty VDI ref, which would match the
|
||||
// snapshot_of of every VDI that is not a snapshot
|
||||
const vdiUuids = this._vm.$VBDs.filter(({ type }) => type === 'Disk').map(({ VDI }) => VDI)
|
||||
Object.values(xapi.objects.indexes.type.VDI)
|
||||
.filter(_ => !!_) // filter nullish
|
||||
.filter(({ other_config, snapshot_of }) => {
|
||||
@@ -400,21 +403,20 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
|
||||
|
||||
this._jobSnapshotVdis = Object.values(vdiCandidates)
|
||||
|
||||
// For VMs with no disks, retention must be tracked directly on VM snapshots
|
||||
// since there are no VDIs to anchor the discovery.
|
||||
if (vdiUuids.length === 0) {
|
||||
this._disklessJobSnapshotVms = this._vm.$snapshots
|
||||
.filter(Boolean)
|
||||
.filter(
|
||||
({ other_config, $snapshot_of }) =>
|
||||
$snapshot_of !== undefined &&
|
||||
other_config[JOB_ID] === jobId &&
|
||||
other_config[VM_UUID] === this._vm.uuid &&
|
||||
other_config[COPY_OF] === undefined
|
||||
)
|
||||
} else {
|
||||
this._disklessJobSnapshotVms = []
|
||||
}
|
||||
// also harvest each of the snapshot chain without any disk
|
||||
// a VBD missing from the cache may be a disk: such a snapshot is skipped
|
||||
// here, since it could also be reachable (and destroyed) through its VDIs
|
||||
const hasNoDisk = ({ $VBDs }) => $VBDs.every(vbd => vbd !== undefined && vbd.type !== 'Disk')
|
||||
this._disklessJobSnapshotVms = this._vm.$snapshots
|
||||
.filter(Boolean)
|
||||
.filter(
|
||||
snapshot =>
|
||||
snapshot.$snapshot_of !== undefined &&
|
||||
snapshot.other_config[JOB_ID] === jobId &&
|
||||
snapshot.other_config[VM_UUID] === this._vm.uuid &&
|
||||
snapshot.other_config[COPY_OF] === undefined &&
|
||||
hasNoDisk(snapshot)
|
||||
)
|
||||
}
|
||||
|
||||
async _removeUnusedSnapshots() {
|
||||
@@ -450,7 +452,13 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
|
||||
.pop()
|
||||
|
||||
// remove older snapshot schedule per schedule
|
||||
const snapshotsPerSchedule = groupBy(this._jobSnapshotVdis, _ => _.other_config[SCHEDULE_ID])
|
||||
// a VM snapshot without any disk is not reachable via its VDIs: both kinds
|
||||
// share the same retention, so they are grouped by datetime together
|
||||
const jobSnapshots = [
|
||||
...this._jobSnapshotVdis.map(vdi => ({ other_config: vdi.other_config, vdi })),
|
||||
...disklessVmSnapshots.map(vm => ({ other_config: vm.other_config, vm })),
|
||||
]
|
||||
const snapshotsPerSchedule = groupBy(jobSnapshots, _ => _.other_config[SCHEDULE_ID])
|
||||
await asyncMap(Object.entries(snapshotsPerSchedule), async ([scheduleId, snapshots]) => {
|
||||
const snapshotPerDatetime = groupBy(snapshots, _ => _.other_config[DATETIME])
|
||||
|
||||
@@ -473,7 +481,18 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
|
||||
) {
|
||||
return
|
||||
}
|
||||
const vdis = snapshotPerDatetime[datetime]
|
||||
const entries = snapshotPerDatetime[datetime]
|
||||
await asyncEach(
|
||||
// VM snapshots without any disk: nothing to resolve, destroy them directly
|
||||
entries.filter(({ vm }) => vm !== undefined),
|
||||
async ({ vm: { $ref } }) => {
|
||||
this._forgetExportedVm($ref)
|
||||
await xapi.VM_destroy($ref)
|
||||
}
|
||||
)
|
||||
// snapshots reached through their VDIs: resolve the VM snapshot via the
|
||||
// VBDs, or destroy the VDIs alone when no VM is attached (CBT, orphans)
|
||||
const vdis = entries.filter(({ vdi }) => vdi !== undefined).map(({ vdi }) => vdi)
|
||||
let vm
|
||||
// if there is an attached VM => destroy the VM (Non CBT backups)
|
||||
for (const vdi of vdis) {
|
||||
@@ -527,34 +546,6 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
|
||||
})
|
||||
})
|
||||
|
||||
// Retention for VMs with no disks: VM snapshots are not reachable via VDIs
|
||||
if (disklessVmSnapshots.length > 0) {
|
||||
const snapshotsPerSchedule = groupBy(disklessVmSnapshots, _ => _.other_config[SCHEDULE_ID])
|
||||
await asyncEach(Object.entries(snapshotsPerSchedule), async ([scheduleId, snapshots]) => {
|
||||
// we only have one snapshot per date time since it's at the VM level
|
||||
const snapshotPerDatetime = Object.fromEntries(snapshots.map(s => [s.other_config[DATETIME], s.$ref]))
|
||||
const datetimes = Object.keys(snapshotPerDatetime).sort()
|
||||
const settings = {
|
||||
...baseSettings,
|
||||
...allSettings[scheduleId],
|
||||
...allSettings[this._vm.uuid],
|
||||
}
|
||||
const retention = settings.snapshotRetention ?? 0
|
||||
await asyncEach(getOldEntries(retention, datetimes), async datetime => {
|
||||
if (
|
||||
this.job.mode === 'delta' &&
|
||||
lastExportedSnapshotDateTime !== undefined &&
|
||||
datetime === lastExportedSnapshotDateTime
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
this._forgetExportedVm(snapshotPerDatetime[datetime])
|
||||
await xapi.VM_destroy(snapshotPerDatetime[datetime])
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// list and remove the snapshot were the jobs failed between
|
||||
// makesnapshot and update_other_config
|
||||
const snapshots = this._vm.$snapshots.filter(_ => !!_).filter(({ name_label }) => name_label === TEMP_SNAPSHOT_NAME)
|
||||
|
||||
@@ -2,9 +2,10 @@ import { describe, it } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
|
||||
import { formatDateTime } from '@xen-orchestra/xapi'
|
||||
import { Task } from '@vates/task'
|
||||
|
||||
import { AbstractXapi } from './_AbstractXapi.mjs'
|
||||
import { DATETIME, EXPORTED_SUCCESSFULLY, JOB_ID, SCHEDULE_ID } from '../../_otherConfig.mjs'
|
||||
import { DATETIME, EXPORTED_SUCCESSFULLY, JOB_ID, SCHEDULE_ID, VM_UUID } from '../../_otherConfig.mjs'
|
||||
|
||||
// Build an AbstractXapi instance without running its heavy constructor, then
|
||||
// assign only the fields the method under test reads.
|
||||
@@ -657,3 +658,197 @@ describe('run() purges the snapshot data only while the snapshot exists', () =>
|
||||
assert.deepEqual(calls.vmDestroyed, [], 'the live VM must never be destroyed')
|
||||
})
|
||||
})
|
||||
|
||||
describe('after an abort', () => {
|
||||
it('_snapshot() passes the abort signal to the snapshot', async () => {
|
||||
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
|
||||
let received
|
||||
const runner = makeRunner({
|
||||
_settings: { bypassVdiChainsCheck: true },
|
||||
_vm: {
|
||||
$ref: 'vm-ref',
|
||||
uuid: 'vm-uuid',
|
||||
$snapshot: async opts => {
|
||||
received = opts
|
||||
// the backup is aborted while the snapshot is being taken
|
||||
vmTask.abort()
|
||||
throw new Error('stop after the snapshot call')
|
||||
},
|
||||
},
|
||||
_xapi: {},
|
||||
_mustDoSnapshot: async () => true,
|
||||
})
|
||||
|
||||
await vmTask.run(() => assert.rejects(runner._snapshot(), /stop after the snapshot call/)).catch(() => {})
|
||||
|
||||
assert.ok(received.signal instanceof AbortSignal, 'the snapshot gets a signal')
|
||||
assert.equal(received.signal.aborted, true, 'the snapshot gets the abort signal of the backup')
|
||||
})
|
||||
|
||||
it('run() still applies the retention and restores the blocked operations, but skips the health check', async () => {
|
||||
const calls = []
|
||||
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
|
||||
const runner = makeRunner({
|
||||
_settings: { offlineBackup: false, snapshotRetention: 0 },
|
||||
_vm: {
|
||||
uuid: 'live-uuid',
|
||||
power_state: 'Halted',
|
||||
blocked_operations: {},
|
||||
update_blocked_operations: async ops => {
|
||||
calls.push(Object.values(ops).every(_ => _ === null) ? 'unblock' : 'block')
|
||||
},
|
||||
$call: async () => {},
|
||||
},
|
||||
_writers: new Set([{ beforeBackup: async () => {}, afterBackup: async () => calls.push('afterBackup') }]),
|
||||
_xapi: {},
|
||||
_cleanMetadata: async () => {},
|
||||
_fetchJobSnapshots: async () => {},
|
||||
_selectBaseVm: async () => {},
|
||||
_removeUnusedSnapshots: async () => calls.push('removeUnusedSnapshots'),
|
||||
_removeSnapshotData: async () => calls.push('removeSnapshotData'),
|
||||
_healthCheck: async () => calls.push('healthCheck'),
|
||||
_snapshot: async function () {
|
||||
this._exportedVm = { $ref: 'snapshot-ref', is_a_snapshot: true }
|
||||
},
|
||||
// a transfer, aborted while it runs
|
||||
_copy: () =>
|
||||
new Promise((resolve, reject) => {
|
||||
const signal = Task.abortSignal
|
||||
signal.addEventListener('abort', () => reject(signal.reason), { once: true })
|
||||
setImmediate(() => {
|
||||
calls.push('abort')
|
||||
vmTask.abort()
|
||||
})
|
||||
}),
|
||||
})
|
||||
|
||||
await vmTask.run(() => assert.rejects(runner.run(), { name: 'AbortError' })).catch(() => {})
|
||||
|
||||
assert.deepEqual(calls, [
|
||||
'block',
|
||||
'removeUnusedSnapshots',
|
||||
'abort',
|
||||
'removeUnusedSnapshots',
|
||||
'removeSnapshotData',
|
||||
'unblock',
|
||||
'afterBackup',
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('_fetchJobSnapshots() diskless VM snapshot detection', () => {
|
||||
const makeFetchRunner = ({ vmVbds, snapshotVbds }) => {
|
||||
const jobSnapshot = {
|
||||
$ref: 'snap-ref',
|
||||
$snapshot_of: {},
|
||||
$VBDs: snapshotVbds,
|
||||
other_config: { [JOB_ID]: 'job-1', [VM_UUID]: 'vm-uuid', [DATETIME]: '20240101T00:00:00Z' },
|
||||
}
|
||||
return makeRunner({
|
||||
_jobId: 'job-1',
|
||||
_vm: { uuid: 'vm-uuid', $VBDs: vmVbds, $snapshots: [jobSnapshot] },
|
||||
_xapi: { objects: { indexes: { type: { VDI: {} } } } },
|
||||
})
|
||||
}
|
||||
const trackedSnapshotRefs = runner => runner._disklessJobSnapshotVms.map(({ $ref }) => $ref)
|
||||
|
||||
it('tracks VM snapshots of a VM with only an empty CD drive', async () => {
|
||||
const cdDrive = { type: 'CD', VDI: 'OpaqueRef:NULL' }
|
||||
const runner = makeFetchRunner({ vmVbds: [cdDrive], snapshotVbds: [cdDrive] })
|
||||
|
||||
await runner._fetchJobSnapshots()
|
||||
|
||||
assert.deepEqual(trackedSnapshotRefs(runner), ['snap-ref'], 'a CD drive must not prevent the diskless retention')
|
||||
})
|
||||
|
||||
it('tracks VM snapshots of a VM whose only disk is [NOBAK]', async () => {
|
||||
// the ignored disk is on the VM, but not on its snapshot
|
||||
const runner = makeFetchRunner({ vmVbds: [{ type: 'Disk', VDI: 'nobak-vdi-ref' }], snapshotVbds: [] })
|
||||
|
||||
await runner._fetchJobSnapshots()
|
||||
|
||||
assert.deepEqual(trackedSnapshotRefs(runner), ['snap-ref'], 'a snapshot without disk must be tracked at VM level')
|
||||
})
|
||||
|
||||
it('does not use the diskless retention for a snapshot with a disk', async () => {
|
||||
const runner = makeFetchRunner({
|
||||
vmVbds: [{ type: 'Disk', VDI: 'vdi-ref' }],
|
||||
snapshotVbds: [{ type: 'Disk', VDI: 'snapshot-vdi-ref' }],
|
||||
})
|
||||
|
||||
await runner._fetchJobSnapshots()
|
||||
|
||||
assert.deepEqual(trackedSnapshotRefs(runner), [], 'this snapshot is handled through its VDIs')
|
||||
})
|
||||
|
||||
it('does not use the diskless retention when a VBD of the snapshot is not in the cache', async () => {
|
||||
const runner = makeFetchRunner({ vmVbds: [{ type: 'Disk', VDI: 'vdi-ref' }], snapshotVbds: [undefined] })
|
||||
|
||||
await runner._fetchJobSnapshots()
|
||||
|
||||
assert.deepEqual(trackedSnapshotRefs(runner), [], 'an unknown VBD may be a disk')
|
||||
})
|
||||
})
|
||||
|
||||
describe('_removeUnusedSnapshots() applies one retention across VDI-reached and diskless snapshots', () => {
|
||||
// A VM that switched between "no backed up disk" and "at least one disk"
|
||||
// has snapshots of both kinds: the retention must apply to their union, not
|
||||
// keep `snapshotRetention` snapshots of each kind.
|
||||
const OLD_DATETIME = '20240101T00:00:00Z'
|
||||
const NEW_DATETIME = '20240102T00:00:00Z'
|
||||
|
||||
const makeSwitchedRunner = ({ oldIsDiskless }) => {
|
||||
const destroyed = []
|
||||
|
||||
const disklessSnapshot = datetime => ({
|
||||
$ref: 'vm-diskless',
|
||||
other_config: { [DATETIME]: datetime, [SCHEDULE_ID]: 'schedule-1' },
|
||||
})
|
||||
const snapshotVm = { $ref: 'vm-with-disk', is_control_domain: false, $snapshot_of: 'live-vm-ref', other_config: {} }
|
||||
const vdiSnapshot = datetime => ({
|
||||
$ref: 'vdi-with-disk',
|
||||
other_config: { [DATETIME]: datetime, [SCHEDULE_ID]: 'schedule-1' },
|
||||
$VBDs: [{ $VM: snapshotVm }],
|
||||
})
|
||||
|
||||
const vm = disklessSnapshot(oldIsDiskless ? OLD_DATETIME : NEW_DATETIME)
|
||||
const vdi = vdiSnapshot(oldIsDiskless ? NEW_DATETIME : OLD_DATETIME)
|
||||
const registry = { [vm.$ref]: vm, [vdi.$ref]: vdi }
|
||||
|
||||
const runner = makeRunner({
|
||||
_vm: { uuid: 'live-uuid', $snapshots: [] },
|
||||
_baseSettings: { snapshotRetention: 1 },
|
||||
_jobSnapshotVdis: [vdi],
|
||||
_disklessJobSnapshotVms: [vm],
|
||||
job: { mode: 'full', settings: {} },
|
||||
_xapi: {
|
||||
barrier: async () => {},
|
||||
getObject: ref => registry[ref],
|
||||
VM_destroy: async ref => {
|
||||
destroyed.push(ref)
|
||||
},
|
||||
VDI_destroy: async ref => {
|
||||
destroyed.push(ref)
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
return { runner, destroyed }
|
||||
}
|
||||
|
||||
it('removes the older diskless snapshot once a disk was added', async () => {
|
||||
const { runner, destroyed } = makeSwitchedRunner({ oldIsDiskless: true })
|
||||
|
||||
await runner._removeUnusedSnapshots()
|
||||
|
||||
assert.deepEqual(destroyed, ['vm-diskless'], 'only the older, diskless, snapshot should be removed')
|
||||
})
|
||||
|
||||
it('removes the older snapshot with a disk once the VM became diskless', async () => {
|
||||
const { runner, destroyed } = makeSwitchedRunner({ oldIsDiskless: false })
|
||||
|
||||
await runner._removeUnusedSnapshots()
|
||||
|
||||
assert.deepEqual(destroyed, ['vm-with-disk'], 'only the older snapshot, reached through its VDI, should be removed')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -161,8 +161,24 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
|
||||
this._prepare = task.wrapInside(this._prepare)
|
||||
this.transfer = task.wrapInside(this.transfer)
|
||||
this.healthCheck = task.wrapInside(this.healthCheck)
|
||||
this.cleanup = task.wrapInside(this.cleanup)
|
||||
this.afterBackup = task.wrap(this.afterBackup)
|
||||
|
||||
// `cleanup()` applies the retention once the backup has been written: an abort that arrives after the transfer
|
||||
// has already ended the task, the retention then runs in a cleanup subtask, which the abort does not stop
|
||||
const cleanupInTask = task.wrapInside(this.cleanup)
|
||||
const cleanup = this.cleanup
|
||||
this.cleanup = function () {
|
||||
return task.status === 'pending'
|
||||
? cleanupInTask.apply(this, arguments)
|
||||
: Task.run({ properties: { name: 'retention' }, cleanup: true }, () => cleanup.apply(this, arguments))
|
||||
}
|
||||
|
||||
// `afterBackup()` cleans the VM directory and releases its lock: it must run even when the task has already
|
||||
// ended because the transfer failed or was aborted, outside of it then
|
||||
const afterBackupInTask = task.wrap(this.afterBackup)
|
||||
const afterBackup = this.afterBackup
|
||||
this.afterBackup = function () {
|
||||
return task.status === 'pending' ? afterBackupInTask.apply(this, arguments) : afterBackup.apply(this, arguments)
|
||||
}
|
||||
|
||||
return this._prepare()
|
||||
}
|
||||
@@ -265,6 +281,8 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
|
||||
}
|
||||
let size = 0
|
||||
await Task.run({ properties: { name: 'transfer' } }, async () => {
|
||||
// stops the writes once the backup is aborted
|
||||
const signal = Task.abortSignal
|
||||
await asyncEach(
|
||||
Object.entries(deltaExport.disks),
|
||||
async ([diskRef, disk]) => {
|
||||
@@ -285,6 +303,7 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
|
||||
// no checksum for VHDs, because they will be invalidated by
|
||||
// merges and chains
|
||||
checksum: false,
|
||||
signal,
|
||||
validator: tmpPath => checkDisk(handler, tmpPath),
|
||||
writeBlockConcurrency: this._config.writeBlockConcurrency,
|
||||
uuid: packUuid(vdi.uuid),
|
||||
@@ -300,6 +319,11 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
|
||||
|
||||
return { size }
|
||||
})
|
||||
|
||||
// the metadata makes the backup restorable: it is not written for an aborted backup, whose disks are removed by
|
||||
// the clean-vm of `afterBackup()`
|
||||
Task.abortSignal?.throwIfAborted()
|
||||
|
||||
metadataContent.tags = await this.getLongTermRetentionTags(metadataContent)
|
||||
metadataContent.size = size // @todo return exactly the size written by this writer
|
||||
this._metadataFileName = await adapter.writeVmBackupMetadata(vm.uuid, metadataContent)
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
import { describe, it } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { Task } from '@vates/task'
|
||||
|
||||
import { IncrementalRemoteWriter } from './IncrementalRemoteWriter.mjs'
|
||||
|
||||
// a writer on a fake remote, whose transfer fails as an aborted transfer does
|
||||
function createWriter() {
|
||||
const calls = { cleanVm: 0, cleanVmOptions: [], deletedEntries: [], lockDisposed: false }
|
||||
const writer = new IncrementalRemoteWriter({
|
||||
adapter: {
|
||||
deleteDeltaVmBackups: async backups => {
|
||||
calls.deletedEntries.push(...backups.map(_ => _._filename))
|
||||
},
|
||||
handler: {
|
||||
mktree: async () => {},
|
||||
lock: async () => ({
|
||||
dispose: async () => {
|
||||
calls.lockDisposed = true
|
||||
},
|
||||
}),
|
||||
},
|
||||
cleanVm: async (vmDir, options) => {
|
||||
++calls.cleanVm
|
||||
calls.cleanVmOptions.push(options)
|
||||
return {}
|
||||
},
|
||||
},
|
||||
config: { disableMergeWorker: true },
|
||||
job: { id: 'job', mode: 'delta' },
|
||||
remoteId: 'remote',
|
||||
schedule: { id: 'schedule' },
|
||||
settings: {},
|
||||
vmUuid: 'vm',
|
||||
})
|
||||
|
||||
// what `prepare()` wraps in its "export" task
|
||||
writer._prepare = async () => {
|
||||
// the backups past the retention
|
||||
writer._oldEntries = [{ _filename: 'old1.json' }, { _filename: 'old2.json' }]
|
||||
}
|
||||
writer.transfer = () =>
|
||||
new Promise((resolve, reject) => {
|
||||
const signal = Task.abortSignal
|
||||
if (signal.aborted) {
|
||||
reject(signal.reason)
|
||||
} else {
|
||||
signal.addEventListener('abort', () => reject(signal.reason), { once: true })
|
||||
}
|
||||
})
|
||||
|
||||
return { calls, writer }
|
||||
}
|
||||
|
||||
// the steps of a VM backup for this writer, in the order `_AbstractXapi#run()` calls them
|
||||
async function runSteps(writer, { abort, afterTransfer = () => {} }) {
|
||||
const events = []
|
||||
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress: event => events.push(event) })
|
||||
let afterBackupError
|
||||
|
||||
await vmTask
|
||||
.run(async () => {
|
||||
await writer.beforeBackup()
|
||||
try {
|
||||
await writer.prepare({ isFull: true })
|
||||
const pTransfer = writer.transfer()
|
||||
abort(vmTask)
|
||||
await pTransfer
|
||||
afterTransfer(vmTask)
|
||||
await writer.cleanup()
|
||||
} finally {
|
||||
// `$defer` of `_AbstractXapi#run()`
|
||||
await writer.afterBackup().catch(error => {
|
||||
afterBackupError = error
|
||||
})
|
||||
}
|
||||
})
|
||||
.catch(() => {})
|
||||
|
||||
return { afterBackupError, events }
|
||||
}
|
||||
|
||||
describe('IncrementalRemoteWriter#afterBackup()', () => {
|
||||
it('cleans the VM directory and releases the lock after a failed transfer', async () => {
|
||||
const { calls, writer } = createWriter()
|
||||
|
||||
const { afterBackupError } = await runSteps(writer, {
|
||||
// a transfer that fails for another reason than an abort
|
||||
abort: vmTask => setImmediate(() => vmTask._abortController.abort(new Error('target unreachable'))),
|
||||
})
|
||||
|
||||
assert.equal(afterBackupError, undefined)
|
||||
assert.equal(calls.cleanVm, 2, 'clean-vm runs before and after the backup')
|
||||
assert.equal(calls.lockDisposed, true)
|
||||
})
|
||||
|
||||
it('cleans the VM directory and releases the lock after an abort, in a clean-vm subtask', async () => {
|
||||
const { calls, writer } = createWriter()
|
||||
|
||||
const { afterBackupError, events } = await runSteps(writer, {
|
||||
abort: vmTask => setImmediate(() => vmTask.abort()),
|
||||
})
|
||||
|
||||
assert.equal(afterBackupError, undefined)
|
||||
assert.equal(calls.cleanVm, 2, 'clean-vm runs before and after the backup')
|
||||
assert.equal(calls.lockDisposed, true)
|
||||
|
||||
const cleanVmIds = events.filter(_ => _.type === 'start' && _.properties?.name === 'clean-vm').map(_ => _.id)
|
||||
assert.equal(cleanVmIds.length, 2)
|
||||
const lastCleanVmEnd = events.find(_ => _.type === 'end' && _.id === cleanVmIds[1])
|
||||
assert.equal(lastCleanVmEnd.status, 'success')
|
||||
})
|
||||
|
||||
it('releases the lock when the clean-vm after the backup fails', async () => {
|
||||
const { calls, writer } = createWriter()
|
||||
writer.transfer = async () => {}
|
||||
const cleanVm = writer._cleanVm
|
||||
writer._cleanVm = function (options) {
|
||||
return options.cleanup ? Promise.reject(new Error('clean-vm failed')) : cleanVm.call(this, options)
|
||||
}
|
||||
|
||||
const { afterBackupError } = await runSteps(writer, { abort: () => {} })
|
||||
|
||||
assert.equal(afterBackupError?.message, 'clean-vm failed')
|
||||
assert.equal(calls.lockDisposed, true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('IncrementalRemoteWriter clean-vm and abort', () => {
|
||||
it('merges before and after the backup when it is not aborted', async () => {
|
||||
const { calls, writer } = createWriter()
|
||||
|
||||
writer.transfer = async () => {}
|
||||
await runSteps(writer, { abort: () => {} })
|
||||
|
||||
assert.deepEqual(
|
||||
calls.cleanVmOptions.map(_ => _.merge),
|
||||
[true, true]
|
||||
)
|
||||
})
|
||||
|
||||
it('still merges in the cleanup made after an abort, which is not stopped (level 1)', async () => {
|
||||
const { calls, writer } = createWriter()
|
||||
|
||||
await runSteps(writer, { abort: vmTask => setImmediate(() => vmTask.abort()) })
|
||||
|
||||
assert.deepEqual(
|
||||
calls.cleanVmOptions.map(_ => _.merge),
|
||||
[true, true]
|
||||
)
|
||||
})
|
||||
|
||||
it('aborts the clean-vm made before the transfer with the backup', async () => {
|
||||
const { calls, writer } = createWriter()
|
||||
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
|
||||
let signal
|
||||
writer._adapter.cleanVm = async () => {
|
||||
signal = Task.abortSignal
|
||||
vmTask.abort()
|
||||
++calls.cleanVm
|
||||
return {}
|
||||
}
|
||||
|
||||
await vmTask.run(() => writer.beforeBackup())
|
||||
|
||||
assert.equal(signal.aborted, true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('IncrementalRemoteWriter#cleanup() and abort', () => {
|
||||
it('applies the retention in the export task when the backup is not aborted', async () => {
|
||||
const { calls, writer } = createWriter()
|
||||
writer.transfer = async () => {}
|
||||
|
||||
const { events } = await runSteps(writer, { abort: () => {} })
|
||||
|
||||
assert.deepEqual(calls.deletedEntries, ['old2.json', 'old1.json'])
|
||||
assert.equal(
|
||||
events.some(_ => _.type === 'start' && _.properties?.name === 'retention'),
|
||||
false,
|
||||
'no retention subtask'
|
||||
)
|
||||
})
|
||||
|
||||
it('still applies the retention when the abort arrives after the transfer, in a retention subtask', async () => {
|
||||
const { calls, writer } = createWriter()
|
||||
writer.transfer = async () => {}
|
||||
|
||||
const { afterBackupError, events } = await runSteps(writer, {
|
||||
abort: () => {},
|
||||
afterTransfer: vmTask => vmTask.abort(),
|
||||
})
|
||||
|
||||
assert.equal(afterBackupError, undefined)
|
||||
assert.deepEqual(calls.deletedEntries, ['old2.json', 'old1.json'])
|
||||
const retentionStart = events.find(_ => _.type === 'start' && _.properties?.name === 'retention')
|
||||
assert.notEqual(retentionStart, undefined)
|
||||
const retentionEnd = events.find(_ => _.type === 'end' && _.id === retentionStart.id)
|
||||
assert.equal(retentionEnd.status, 'success')
|
||||
})
|
||||
|
||||
it('does not apply the retention when the transfer is aborted', async () => {
|
||||
const { calls, writer } = createWriter()
|
||||
|
||||
await runSteps(writer, { abort: vmTask => setImmediate(() => vmTask.abort()) })
|
||||
|
||||
assert.deepEqual(calls.deletedEntries, [])
|
||||
})
|
||||
})
|
||||
|
||||
describe('IncrementalRemoteWriter#transfer() after an abort', () => {
|
||||
it('stops writing the disks and writes no metadata', async () => {
|
||||
const writes = []
|
||||
let metadataWritten = false
|
||||
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
|
||||
const writer = new IncrementalRemoteWriter({
|
||||
adapter: {
|
||||
getVhdFileName: basename => `${basename}.vhd`,
|
||||
handler: { readFile: async () => Promise.reject(new Error('no such file')) },
|
||||
listVmBackups: async () => [],
|
||||
writeVhd: async (path, disk, { signal }) => {
|
||||
if (signal?.aborted) {
|
||||
throw signal.reason
|
||||
}
|
||||
writes.push(path)
|
||||
// the backup is aborted once the first disk has been written
|
||||
vmTask.abort()
|
||||
return 1
|
||||
},
|
||||
writeVmBackupMetadata: async () => {
|
||||
metadataWritten = true
|
||||
},
|
||||
},
|
||||
config: {},
|
||||
job: { id: 'job', mode: 'delta' },
|
||||
remoteId: 'remote',
|
||||
schedule: { id: 'schedule' },
|
||||
settings: { diskPerVmConcurrency: 1 },
|
||||
vmUuid: 'vm',
|
||||
})
|
||||
const disk = { close: async () => {} }
|
||||
const deltaExport = {
|
||||
disks: { vdi1: disk, vdi2: disk },
|
||||
vbds: {},
|
||||
vdis: { vdi1: { uuid: 'uuid1', $snapshot_of$uuid: 'src1' }, vdi2: { uuid: 'uuid2', $snapshot_of$uuid: 'src2' } },
|
||||
vifs: {},
|
||||
vm: { uuid: 'vm' },
|
||||
vtpms: {},
|
||||
}
|
||||
|
||||
await vmTask
|
||||
.run(() =>
|
||||
writer.transfer({
|
||||
deltaExport,
|
||||
isVhdDifferencing: { vdi1: false, vdi2: false },
|
||||
timestamp: 0,
|
||||
vm: { uuid: 'vm' },
|
||||
vmSnapshot: {},
|
||||
})
|
||||
)
|
||||
.catch(() => {})
|
||||
|
||||
assert.equal(writes.length, 1, 'the second disk is not written')
|
||||
assert.equal(metadataWritten, false, 'no metadata is written for an aborted backup')
|
||||
})
|
||||
})
|
||||
@@ -327,11 +327,20 @@ export class IncrementalXapiWriter extends MixinXapiWriter(AbstractIncrementalWr
|
||||
})
|
||||
this._prepare = task.wrapInside(this._prepare)
|
||||
this.transfer = task.wrapInside(this.transfer)
|
||||
// `cleanup()` applies the retention once the backup has been written: an abort that arrives after the transfer
|
||||
// has already ended the task, the retention then runs in a cleanup subtask, which the abort does not stop
|
||||
let cleanupInTask
|
||||
if (this._healthCheckSr !== undefined) {
|
||||
this.cleanup = task.wrapInside(this.cleanup)
|
||||
cleanupInTask = task.wrapInside(this.cleanup)
|
||||
this.healthCheck = task.wrap(this.healthCheck)
|
||||
} else {
|
||||
this.cleanup = task.wrap(this.cleanup)
|
||||
cleanupInTask = task.wrap(this.cleanup)
|
||||
}
|
||||
const cleanup = this.cleanup
|
||||
this.cleanup = function () {
|
||||
return task.status === 'pending'
|
||||
? cleanupInTask.apply(this, arguments)
|
||||
: Task.run({ properties: { name: 'retention' }, cleanup: true }, () => cleanup.apply(this, arguments))
|
||||
}
|
||||
|
||||
return this._prepare(isFull)
|
||||
@@ -504,6 +513,8 @@ export class IncrementalXapiWriter extends MixinXapiWriter(AbstractIncrementalWr
|
||||
let targetVmRef
|
||||
await Task.run({ properties: { name: 'transfer' } }, async () => {
|
||||
targetVmRef = await importIncrementalVm(this.#decorateVmMetadata(deltaExport, timestamp), sr, {
|
||||
// the import is stopped once the backup is aborted, and the VM and VDIs it created are destroyed
|
||||
signal: Task.abortSignal,
|
||||
targetRef: this._targetVmRef,
|
||||
})
|
||||
// this also ensure the data are up to date on the snapshot
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
import { describe, it } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { Task } from '@vates/task'
|
||||
|
||||
import { IncrementalXapiWriter } from './IncrementalXapiWriter.mjs'
|
||||
|
||||
// a writer whose retention is recorded instead of destroying the old replicas
|
||||
function createWriter({ healthCheckSr } = {}) {
|
||||
const calls = { deleteOldEntries: 0, deleteOrphanVdis: 0 }
|
||||
const writer = new IncrementalXapiWriter({
|
||||
config: {},
|
||||
healthCheckSr,
|
||||
job: { id: 'job' },
|
||||
schedule: { id: 'schedule' },
|
||||
settings: {},
|
||||
sr: { name_label: 'sr', uuid: 'sr' },
|
||||
vmUuid: 'vm',
|
||||
})
|
||||
|
||||
// what `prepare()` wraps in its "export" task
|
||||
writer._prepare = async () => {}
|
||||
writer.transfer = async () => {}
|
||||
writer._deleteOldEntries = async () => {
|
||||
++calls.deleteOldEntries
|
||||
}
|
||||
writer._deleteOrphanVdis = async () => {
|
||||
++calls.deleteOrphanVdis
|
||||
}
|
||||
|
||||
return { calls, writer }
|
||||
}
|
||||
|
||||
// the steps of a VM backup for this writer, in the order `IncrementalXapi#_copy()` calls them
|
||||
async function runSteps(writer, { afterTransfer = () => {} } = {}) {
|
||||
const events = []
|
||||
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress: event => events.push(event) })
|
||||
let cleanupError
|
||||
|
||||
await vmTask
|
||||
.run(async () => {
|
||||
await writer.prepare({ isFull: true })
|
||||
await writer.transfer()
|
||||
afterTransfer(vmTask)
|
||||
await writer.cleanup().catch(error => {
|
||||
cleanupError = error
|
||||
})
|
||||
})
|
||||
.catch(() => {})
|
||||
|
||||
return { cleanupError, events }
|
||||
}
|
||||
|
||||
const retentionTaskOf = events => events.find(_ => _.type === 'start' && _.properties?.name === 'retention')
|
||||
|
||||
for (const [label, healthCheckSr] of [
|
||||
['without health check', undefined],
|
||||
['with health check', { uuid: 'health-check-sr' }],
|
||||
]) {
|
||||
describe(`IncrementalXapiWriter#cleanup() and abort, ${label}`, () => {
|
||||
it('applies the retention in the export task when the backup is not aborted', async () => {
|
||||
const { calls, writer } = createWriter({ healthCheckSr })
|
||||
|
||||
const { cleanupError, events } = await runSteps(writer)
|
||||
|
||||
assert.equal(cleanupError, undefined)
|
||||
assert.deepEqual(calls, { deleteOldEntries: 1, deleteOrphanVdis: 1 })
|
||||
assert.equal(retentionTaskOf(events), undefined, 'no retention subtask')
|
||||
})
|
||||
|
||||
it('still applies the retention when the abort arrives after the transfer, in a retention subtask', async () => {
|
||||
const { calls, writer } = createWriter({ healthCheckSr })
|
||||
|
||||
const { cleanupError, events } = await runSteps(writer, { afterTransfer: vmTask => vmTask.abort() })
|
||||
|
||||
assert.equal(cleanupError, undefined)
|
||||
assert.deepEqual(calls, { deleteOldEntries: 1, deleteOrphanVdis: 1 })
|
||||
const retentionStart = retentionTaskOf(events)
|
||||
assert.notEqual(retentionStart, undefined)
|
||||
const retentionEnd = events.find(_ => _.type === 'end' && _.id === retentionStart.id)
|
||||
assert.equal(retentionEnd.status, 'success')
|
||||
})
|
||||
})
|
||||
}
|
||||
@@ -26,9 +26,12 @@ export const MixinRemoteWriter = (BaseClass = Object) =>
|
||||
this._vmBackupDir = getVmBackupDir(rest.vmUuid)
|
||||
}
|
||||
|
||||
async _cleanVm(options) {
|
||||
// `cleanup`: the clean-vm is a cleanup subtask, it also runs after the backup has been aborted. Otherwise it is
|
||||
// not started once the backup is aborted, but a merge already running is not interrupted: `cleanVm()` does not
|
||||
// read the signal
|
||||
async _cleanVm({ cleanup = false, ...options }) {
|
||||
try {
|
||||
return await Task.run({ properties: { name: 'clean-vm' } }, () => {
|
||||
return await Task.run({ properties: { name: 'clean-vm' }, cleanup }, () => {
|
||||
return this._adapter.cleanVm(this._vmBackupDir, {
|
||||
...options,
|
||||
logInfo: info,
|
||||
@@ -72,8 +75,13 @@ export const MixinRemoteWriter = (BaseClass = Object) =>
|
||||
const { handler } = this._adapter
|
||||
const synchronousMerge = this._settings.mergeBackupsSynchronously
|
||||
const willMergeInWorker = !synchronousMerge && !disableMergeWorker && typeof handler.getRealPath === 'function'
|
||||
const { merge } = await this._cleanVm({ remove: true, merge: !willMergeInWorker })
|
||||
await this.#lock.dispose()
|
||||
let merge
|
||||
try {
|
||||
// part of the cleanup: it also runs after an abort, merge included (skipping it is a level 2 abort)
|
||||
;({ merge } = await this._cleanVm({ cleanup: true, remove: true, merge: !willMergeInWorker }))
|
||||
} finally {
|
||||
await this.#lock.dispose()
|
||||
}
|
||||
|
||||
if (merge && willMergeInWorker) {
|
||||
const taskFile =
|
||||
|
||||
@@ -48,13 +48,20 @@ export const MixinXapiWriter = (BaseClass = Object) =>
|
||||
if (await this.#isAlreadyOnHealthCheckSr(baseVm)) {
|
||||
healthCheckVmRef = await Task.run(
|
||||
{ properties: { name: 'cloning-vm' } },
|
||||
async () => await xapi.callAsync('VM.clone', this._targetVmRef, `Health Check - ${baseVm.name_label}`)
|
||||
async () =>
|
||||
await xapi.callAsync(
|
||||
Task.abortSignal,
|
||||
'VM.clone',
|
||||
this._targetVmRef,
|
||||
`Health Check - ${baseVm.name_label}`
|
||||
)
|
||||
)
|
||||
} else {
|
||||
healthCheckVmRef = await Task.run(
|
||||
{ properties: { name: 'copying-vm' } },
|
||||
async () =>
|
||||
await xapi.callAsync(
|
||||
Task.abortSignal,
|
||||
'VM.copy',
|
||||
this._targetVmRef,
|
||||
`Health Check - ${baseVm.name_label}`,
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import { describe, it } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import { Task } from '@vates/task'
|
||||
|
||||
import { FullXapiWriter } from './FullXapiWriter.mjs'
|
||||
|
||||
describe('MixinXapiWriter#healthCheck() after an abort', () => {
|
||||
it('passes the abort signal to the copy of the replica', async () => {
|
||||
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
|
||||
const calls = []
|
||||
const xapi = {
|
||||
getObject: ref => ({ $ref: ref, $xapi: xapi, name_label: 'replica' }),
|
||||
VM_getDisks: async () => [],
|
||||
callAsync: async (...args) => {
|
||||
calls.push(args)
|
||||
// the backup is aborted while the replica is being copied
|
||||
vmTask.abort()
|
||||
throw new Error('stop after the copy call')
|
||||
},
|
||||
}
|
||||
const writer = new FullXapiWriter({
|
||||
config: {},
|
||||
healthCheckSr: { $ref: 'OpaqueRef:health-check-sr', uuid: 'health-check-sr' },
|
||||
job: { id: 'job' },
|
||||
schedule: { id: 'schedule' },
|
||||
settings: { healthCheckTimeout: '10m' },
|
||||
sr: { $xapi: xapi, name_label: 'sr', uuid: 'sr' },
|
||||
vmUuid: 'vm',
|
||||
})
|
||||
writer._targetVmRef = 'OpaqueRef:replica'
|
||||
// the replica is not on the health check SR: it is copied there
|
||||
xapi.VM_getDisks = async () => ['OpaqueRef:vdi']
|
||||
xapi.getObject = ref =>
|
||||
ref === 'OpaqueRef:vdi' ? { $SR: { uuid: 'sr' } } : { $ref: ref, $xapi: xapi, name_label: 'replica' }
|
||||
|
||||
await vmTask.run(() => assert.rejects(writer.healthCheck(), /stop after the copy call/)).catch(() => {})
|
||||
|
||||
const [[signal, method]] = calls
|
||||
assert.ok(signal instanceof AbortSignal, 'the copy gets a signal')
|
||||
assert.equal(signal.aborted, true, 'the copy gets the abort signal of the backup')
|
||||
assert.equal(method, 'VM.copy')
|
||||
})
|
||||
})
|
||||
@@ -13,6 +13,7 @@
|
||||
- [Of created VMs](#of-created-vms-and-their-associated-vdis)
|
||||
- [Task logs](#task-logs)
|
||||
- [During backup](#during-backup)
|
||||
- [Aborted backup](#aborted-backup)
|
||||
- [During restoration](#during-restoration)
|
||||
- [API](#api)
|
||||
- [Run description object](#run-description-object)
|
||||
@@ -240,6 +241,41 @@ job.start(data: { mode: Mode, reportWhen: ReportWhen })
|
||||
└─ job.end
|
||||
```
|
||||
|
||||
### Aborted backup
|
||||
|
||||
When the backup runs in the xo-server process (`backups.disableWorkers`), it can be aborted from its task. The abort is
|
||||
always an `AbortError`, and it changes the task log above as follows:
|
||||
|
||||
```
|
||||
job.start(data: { mode: Mode, reportWhen: ReportWhen })
|
||||
├─ task.info(message: 'abort requested', data: { type: 'abortRequested', userId: string }) // when requested by a user
|
||||
├─ task.abortionRequested(reason: AbortError)
|
||||
├─ task.start(data: { type: 'VM', id: string, name_label?: string }) // VM being backed up
|
||||
│ ├─ task.abortionRequested(reason: AbortError)
|
||||
│ ├─ task.start(message: 'export', data: { … })
|
||||
│ │ ├─ task.start(message: 'transfer')
|
||||
│ │ │ └─ task.end(status: 'failure', result: AbortError) // the transfer stops
|
||||
│ │ └─ task.end(status: 'failure', result: AbortError)
|
||||
│ ├─ task.start(message: 'clean-vm') // cleanup subtask, still run
|
||||
│ │ └─ task.end
|
||||
│ └─ task.end(status: 'failure', result: AbortError)
|
||||
│ // no task for the VMs not started yet, no retry, no health check
|
||||
└─ job.end(status: 'failure', result: AbortError)
|
||||
```
|
||||
|
||||
- A step started as a subtask once the run is aborted fails right away, without running (the root task of the run
|
||||
is created with `skipSubtasksAfterAbort: true` in `@vates/task`).
|
||||
- The cleanup still runs: snapshot retention, removal of the snapshot data, restore of the VM's blocked operations,
|
||||
and the writers' `afterBackup()`. `clean-vm` (and the merge it runs) is a cleanup subtask (`cleanup: true` in
|
||||
`@vates/task`), which the abort does not stop.
|
||||
- The metadata of an incremental backup is not written, so the aborted backup is never listed as restorable; its disks
|
||||
are removed by `clean-vm`.
|
||||
- The retention of the backups (or replicas) only applies once the new one has been written. When the abort arrives
|
||||
after the transfer, the `export` task has already ended: the retention runs in a `retention` cleanup subtask of the VM
|
||||
task, before `clean-vm`.
|
||||
- In the backup logs and reports, a task that failed after an abort was requested on it (`abortionRequested`) has the
|
||||
status `interrupted`, and does not make its parent `failure`.
|
||||
|
||||
### During restoration
|
||||
|
||||
```
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
"@vates/nbd-client": "^3.7.2",
|
||||
"@vates/parse-duration": "^0.1.1",
|
||||
"@vates/task": "^0.7.0",
|
||||
"@vates/types": "^3.1.0",
|
||||
"@vates/types": "^3.2.0",
|
||||
"@xen-orchestra/async-map": "^0.1.5",
|
||||
"@xen-orchestra/disk-transform": "^1.3.4",
|
||||
"@xen-orchestra/fs": "^4.11.0",
|
||||
@@ -70,7 +70,7 @@
|
||||
"typescript": "^5.9.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@xen-orchestra/xapi": "^10.0.0"
|
||||
"@xen-orchestra/xapi": "^10.1.0"
|
||||
},
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"author": {
|
||||
|
||||
@@ -2,6 +2,11 @@
|
||||
|
||||
## **next**
|
||||
|
||||
- [VM/Network] Add possibility to delete a VIF (PR [#10726](https://github.com/vatesfr/xen-orchestra/pull/10726))
|
||||
- [Web-Core/VtsErrorModal] Add an optional details log viewer, unified icon (PR [#10536](https://github.com/vatesfr/xen-orchestra/pull/10536))
|
||||
|
||||
## **0.28.0** (2026/12/01)
|
||||
|
||||
- [VDIs] The used space of a VDI now includes its whole snapshot chain instead of only its last layer, which showed almost 0% for disks with snapshots. It is shown as a size, without usage bar or free space (PR [#10116](https://github.com/vatesfr/xen-orchestra/pull/10116))
|
||||
- [Web-Core/UiCircleProgressBar] Add a brand accent and an option to hide the value (PR [#10849](https://github.com/vatesfr/xen-orchestra/pull/10849))
|
||||
- [Tables] Cells fit on one line: long names are cut in the middle, extra tags go under "+N" and long texts end with "…" (PR [#10850](https://github.com/vatesfr/xen-orchestra/pull/10850))
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@xen-orchestra/lite",
|
||||
"version": "0.27.0",
|
||||
"version": "0.28.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "GIT_HEAD=$(git rev-parse HEAD) vite",
|
||||
@@ -27,13 +27,13 @@
|
||||
"@types/file-saver": "^2.0.7",
|
||||
"@types/lodash-es": "^4.17.12",
|
||||
"@types/node": "^18.19.80",
|
||||
"@vates/types": "^3.1.0",
|
||||
"@vates/types": "^3.2.0",
|
||||
"@vitejs/plugin-vue": "^6.0.0",
|
||||
"@vue/tsconfig": "^0.9.0",
|
||||
"@vueuse/core": "^14.0.0",
|
||||
"@vueuse/math": "^14.0.0",
|
||||
"@vueuse/shared": "^14.0.0",
|
||||
"@xen-orchestra/web-core": "^0.66.1",
|
||||
"@xen-orchestra/web-core": "^0.67.0",
|
||||
"complex-matcher": "^1.1.1",
|
||||
"d3-time-format": "^4.1.0",
|
||||
"decorator-synchronized": "^0.6.0",
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import type { XenApiNetwork } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { useNetworkDeleteJob } from '@/modules/network/jobs/network-delete.job.ts'
|
||||
import { useDeleteModal } from '@core/composables/modals/use-delete-modal.ts'
|
||||
import { useErrorModal } from '@core/composables/modals/use-error-modal.ts'
|
||||
import { useRouteQuery } from '@core/composables/route-query.composable.ts'
|
||||
import { useOverlay } from '@core/packages/overlay/use-overlay.ts'
|
||||
import { toComputed } from '@core/utils/to-computed.util.ts'
|
||||
import type { MaybeRefOrGetter } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
@@ -23,12 +23,7 @@ export function useNetworkDelete(rawNetworks: MaybeRefOrGetter<XenApiNetwork[]>)
|
||||
|
||||
const { open: openNetworkDeleteModal } = useDeleteModal()
|
||||
|
||||
const { open: openNetworkDeleteErrorModal } = useOverlay({
|
||||
component: () => import('@core/components/modal/VtsErrorModal.vue'),
|
||||
events: {
|
||||
onClose: true,
|
||||
},
|
||||
})
|
||||
const { open: openNetworkDeleteErrorModal } = useErrorModal()
|
||||
|
||||
function deleteNetworks() {
|
||||
if (!canDeleteNetworks.value) {
|
||||
|
||||
@@ -25,6 +25,7 @@
|
||||
<script lang="ts" setup>
|
||||
import type { XenApiNetwork, XenApiVif, XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { useVifConnection } from '@/modules/vif/composables/use-vif-connection.composable.ts'
|
||||
import { useVifDelete } from '@/modules/vif/composables/use-vif-delete.composable.ts'
|
||||
import { useVifEdit } from '@/modules/vif/composables/use-vif-edit.composable.ts'
|
||||
import { useNetworkStore } from '@/stores/xen-api/network.store.ts'
|
||||
import { useVifStore } from '@/stores/xen-api/vif.store.ts'
|
||||
@@ -106,6 +107,8 @@ const { HeadCells, BodyCells } = useVifColumns({
|
||||
vm: () => vm,
|
||||
})
|
||||
|
||||
const { deleteVifs, canDeleteVifs, isDeletingVifs, deleteVifsErrorMessage } = useVifDelete(() => [vif])
|
||||
|
||||
const connectionAction = useMapper(
|
||||
() => (vif.currently_attached ? CONNECTION_ACTION.DISCONNECT : CONNECTION_ACTION.CONNECT),
|
||||
() => ({
|
||||
@@ -143,6 +146,15 @@ const { HeadCells, BodyCells } = useVifColumns({
|
||||
actions: [
|
||||
{ label: t('action:edit'), icon: 'action:edit', onClick: () => goToVifEdit(vif) } satisfies ActionItem,
|
||||
connectionAction.value,
|
||||
{
|
||||
label: t('action:delete'),
|
||||
icon: 'action:delete',
|
||||
onClick: () => deleteVifs(),
|
||||
disabled: !canDeleteVifs.value,
|
||||
busy: isDeletingVifs.value,
|
||||
hint: canDeleteVifs.value ? undefined : deleteVifsErrorMessage.value,
|
||||
accent: 'danger',
|
||||
} satisfies ActionItem,
|
||||
],
|
||||
}),
|
||||
}
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
<template>
|
||||
<VtsDeleteButton
|
||||
:hint="deleteVifsErrorMessage"
|
||||
:disabled="!canDeleteVifs"
|
||||
:busy="isDeletingVifs"
|
||||
@click="deleteVifs()"
|
||||
/>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import type { XenApiVif } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { useVifDelete } from '@/modules/vif/composables/use-vif-delete.composable.ts'
|
||||
import VtsDeleteButton from '@core/components/delete-button/VtsDeleteButton.vue'
|
||||
|
||||
const { vif } = defineProps<{
|
||||
vif: XenApiVif
|
||||
}>()
|
||||
|
||||
const { deleteVifs, canDeleteVifs, isDeletingVifs, deleteVifsErrorMessage } = useVifDelete(() => [vif])
|
||||
</script>
|
||||
@@ -3,6 +3,7 @@
|
||||
<template v-if="vif" #actions>
|
||||
<VifEditButton :vif />
|
||||
<VifConnectionToggleButton v-if="vm" :vif :vm />
|
||||
<VifDeleteButton :vif />
|
||||
</template>
|
||||
<template v-if="vif" #default>
|
||||
<!-- VIF -->
|
||||
@@ -110,6 +111,7 @@
|
||||
<script setup lang="ts">
|
||||
import type { XenApiVif } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import VifConnectionToggleButton from '@/modules/vif/components/actions/connection/VifConnectionToggleButton.vue'
|
||||
import VifDeleteButton from '@/modules/vif/components/actions/delete/VifDeleteButton.vue'
|
||||
import VifEditButton from '@/modules/vif/components/actions/edit/VifEditButton.vue'
|
||||
import { isTxChecksummingEnabled } from '@/modules/vif/utils/vif-tx-checksumming.util.ts'
|
||||
import { useNetworkStore } from '@/stores/xen-api/network.store.ts'
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import type { XenApiVif } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { useVifDeleteJob } from '@/modules/vif/jobs/vif-delete.job.ts'
|
||||
import { useDeleteModal } from '@core/composables/modals/use-delete-modal.ts'
|
||||
import { useRouteQuery } from '@core/composables/route-query.composable.ts'
|
||||
import { toComputed } from '@core/utils/to-computed.util.ts'
|
||||
import type { MaybeRefOrGetter } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
export function useVifDelete(rawVifs: MaybeRefOrGetter<XenApiVif[]>) {
|
||||
const vifs = toComputed(rawVifs)
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const selectedVifId = useRouteQuery('id')
|
||||
|
||||
const {
|
||||
run,
|
||||
canRun: canDeleteVifs,
|
||||
isRunning: isDeletingVifs,
|
||||
errorMessage: deleteVifsErrorMessage,
|
||||
} = useVifDeleteJob(vifs)
|
||||
|
||||
const { open } = useDeleteModal()
|
||||
|
||||
function deleteVifs() {
|
||||
const count = vifs.value.length
|
||||
|
||||
return open({
|
||||
props: {
|
||||
subject: t('n-vifs', { n: count }),
|
||||
confirmLabel: t('action:delete-n-vifs', { n: count }),
|
||||
},
|
||||
events: {
|
||||
onConfirm: () => {
|
||||
const isSelectedVifDeleted = vifs.value.some(vif => vif.uuid === selectedVifId.value)
|
||||
|
||||
run({
|
||||
detached: true,
|
||||
onSuccess: () => {
|
||||
if (isSelectedVifDeleted) {
|
||||
selectedVifId.value = ''
|
||||
}
|
||||
},
|
||||
})
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
return { deleteVifs, canDeleteVifs, isDeletingVifs, deleteVifsErrorMessage }
|
||||
}
|
||||
37
@xen-orchestra/lite/src/modules/vif/jobs/vif-delete.job.ts
Normal file
37
@xen-orchestra/lite/src/modules/vif/jobs/vif-delete.job.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import { vifsArg } from '@/modules/vif/jobs/vif-args.ts'
|
||||
import { useXenApiStore } from '@/stores/xen-api.store.ts'
|
||||
import { defineJob, JobError, JobRunningError } from '@core/packages/job'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
export const useVifDeleteJob = defineJob('vif.delete', [vifsArg], () => {
|
||||
const xapi = useXenApiStore().getXapi()
|
||||
const { t } = useI18n()
|
||||
|
||||
return {
|
||||
async run(vifs) {
|
||||
const results = await Promise.allSettled(vifs.map(vif => xapi.vif.delete(vif.$ref)))
|
||||
|
||||
results.forEach((result, index) => {
|
||||
if (result.status === 'rejected') {
|
||||
console.error(`Failed to delete VIF ${vifs[index].uuid}:`, result.reason)
|
||||
}
|
||||
})
|
||||
|
||||
return results
|
||||
},
|
||||
|
||||
validate: (isRunning, vifs) => {
|
||||
if (vifs.length === 0) {
|
||||
throw new JobError(t('job:vif-delete:missing-vif'))
|
||||
}
|
||||
|
||||
if (isRunning) {
|
||||
throw new JobRunningError(t('job:delete:in-progress'))
|
||||
}
|
||||
|
||||
if (vifs.some(vif => vif.currently_attached)) {
|
||||
throw new JobError(t('vif-connected'))
|
||||
}
|
||||
},
|
||||
}
|
||||
})
|
||||
13
@xen-orchestra/lite/src/route-map.d.ts
vendored
13
@xen-orchestra/lite/src/route-map.d.ts
vendored
@@ -499,6 +499,13 @@ declare module 'vue-router/auto-routes' {
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/modal/vts-error-modal': RouteRecordInfo<
|
||||
'/story/web-core/modal/vts-error-modal',
|
||||
'/story/web-core/modal/vts-error-modal',
|
||||
Record<never, never>,
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/number-input/vts-number-input': RouteRecordInfo<
|
||||
'/story/web-core/number-input/vts-number-input',
|
||||
'/story/web-core/number-input/vts-number-input',
|
||||
@@ -1737,6 +1744,12 @@ declare module 'vue-router/auto-routes' {
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/modal/vts-error-modal.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/modal/vts-error-modal'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/number-input/vts-number-input.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/number-input/vts-number-input'
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
# Usage
|
||||
|
||||
Open the modal with `useErrorModal`.
|
||||
|
||||
```vue-script
|
||||
import { useErrorModal } from '@core/composables/modals/use-error-modal.ts'
|
||||
|
||||
const { open: openErrorModal } = useErrorModal()
|
||||
|
||||
try {
|
||||
// ...
|
||||
} catch (error) {
|
||||
void openErrorModal({
|
||||
props: {
|
||||
title: 'Unable to create cluster',
|
||||
error: 'An error occurred',
|
||||
details: error,
|
||||
},
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
The `details` prop is displayed below the message, even when the `content` slot is overridden:
|
||||
|
||||
```vue-template
|
||||
<VtsErrorModal title="Unable to delete network" :details @close="close()">
|
||||
<template #content>Custom error message</template>
|
||||
</VtsErrorModal>
|
||||
```
|
||||
@@ -0,0 +1,60 @@
|
||||
<template>
|
||||
<ComponentStory
|
||||
v-slot="{ properties, settings }"
|
||||
:params="[
|
||||
prop('title').str().required().preset('Unable to create cluster').widget(),
|
||||
prop('error').str().preset('An error occurred').widget(),
|
||||
prop('details')
|
||||
.type('string | object')
|
||||
.preset(details1)
|
||||
.widget(object())
|
||||
.help('When set, displayed in a log entry viewer below the error message'),
|
||||
event('close'),
|
||||
slot('content').help('Replaces the error message. The details are still displayed below it'),
|
||||
setting('contentSlotContent').widget(text()).help('Leave empty to use the error prop'),
|
||||
]"
|
||||
:presets
|
||||
>
|
||||
<VtsErrorModal class="story" v-bind="properties">
|
||||
<template v-if="settings.contentSlotContent" #content>{{ settings.contentSlotContent }}</template>
|
||||
</VtsErrorModal>
|
||||
</ComponentStory>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { event, prop, setting, slot } from '@/libs/story/story-param.ts'
|
||||
import { object, text } from '@/libs/story/story-widget.ts'
|
||||
import VtsErrorModal from '@core/components/modal/VtsErrorModal.vue'
|
||||
|
||||
const details1 = {
|
||||
code: 'HOST_NOT_ENOUGH_FREE_MEMORY',
|
||||
params: ['8589934592', '2147483648'],
|
||||
call: {
|
||||
method: 'VM.start',
|
||||
params: ['OpaqueRef:3f2a9c1e-7b4d-4e8a-9f6c-2d1b5a8e7c90', false, false],
|
||||
},
|
||||
}
|
||||
|
||||
const details2 =
|
||||
'TypeError: Failed to fetch\n at fetchApi (rest-api.ts:42:11)\n at async createCluster (cluster-create.job.ts:88:5)'
|
||||
|
||||
const presets = {
|
||||
'Without details': {
|
||||
props: { details: undefined },
|
||||
},
|
||||
'With details object': {
|
||||
props: { details: details1 },
|
||||
},
|
||||
'With details string': {
|
||||
props: { details: details2 },
|
||||
},
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
.story {
|
||||
position: relative;
|
||||
height: 100%;
|
||||
}
|
||||
</style>
|
||||
@@ -34,7 +34,7 @@
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.19.0",
|
||||
"@types/node": "^22.3.0",
|
||||
"@vates/types": "^3.1.0",
|
||||
"@vates/types": "^3.2.0",
|
||||
"rimraf": "^6.0.0",
|
||||
"typescript": "~5.6.3",
|
||||
"typescript-eslint": "^8.61.0"
|
||||
|
||||
@@ -36,7 +36,7 @@
|
||||
"xo-common": "^0.11.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vates/types": "^3.1.0"
|
||||
"@vates/types": "^3.2.0"
|
||||
},
|
||||
"scripts": {
|
||||
"postversion": "npm publish --access public",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"private": true,
|
||||
"name": "@xen-orchestra/proxy",
|
||||
"version": "0.35.1",
|
||||
"version": "0.35.2",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"description": "XO Proxy used to remotely execute backup jobs",
|
||||
"keywords": [
|
||||
@@ -40,7 +40,7 @@
|
||||
"@xen-orchestra/mixin": "^0.2.1",
|
||||
"@xen-orchestra/mixins": "^0.24.0",
|
||||
"@xen-orchestra/self-signed": "^0.2.1",
|
||||
"@xen-orchestra/xapi": "^10.0.0",
|
||||
"@xen-orchestra/xapi": "^10.1.0",
|
||||
"ajv": "^8.0.3",
|
||||
"app-conf": "^3.0.0",
|
||||
"async-iterator-to-stream": "^1.1.0",
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
"main": "./dist/index.mjs",
|
||||
"name": "@xen-orchestra/rest-api",
|
||||
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/@xen-orchestra/rest-api",
|
||||
"version": "0.43.0",
|
||||
"version": "0.43.1",
|
||||
"description": "REST API to manage your XOA",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"private": false,
|
||||
@@ -38,14 +38,14 @@
|
||||
"@vates/async-each": "^1.0.3",
|
||||
"@vates/obfuscate": "^0.2.0",
|
||||
"@vates/task": "^0.7.0",
|
||||
"@vates/types": "^3.1.0",
|
||||
"@vates/types": "^3.2.0",
|
||||
"@xen-orchestra/acl": "^1.9.0",
|
||||
"@xen-orchestra/backups": "^1.0.1",
|
||||
"@xen-orchestra/cron": "^1.0.7",
|
||||
"@xen-orchestra/log": "^1.0.0",
|
||||
"@xen-orchestra/qcow2": "^1.4.1",
|
||||
"@xen-orchestra/vmdk": "^1.0.0",
|
||||
"@xen-orchestra/xapi": "^10.0.0",
|
||||
"@xen-orchestra/xapi": "^10.1.0",
|
||||
"complex-matcher": "^1.1.1",
|
||||
"fast-xml-parser": "^5.10.1",
|
||||
"golike-defer": "^0.5.1",
|
||||
|
||||
@@ -13,6 +13,7 @@ import { mcpGateMiddleware } from './middlewares/mcp-gate.middleware.mjs'
|
||||
import { type OpenAPIV3 } from 'openapi-types'
|
||||
import { createExternalRouter, sendObjects } from './router/external-router.mjs'
|
||||
import { BASE_URL } from './helpers/utils.helper.mjs'
|
||||
import { rejectCrossSiteMutation } from './middlewares/csrf.middleware.mjs'
|
||||
|
||||
export { sendObjects }
|
||||
|
||||
@@ -55,6 +56,7 @@ export default function setupRestApi(express: Express, xoApp: XoApp) {
|
||||
express.use(BASE_URL, setupApiContext(xoApp))
|
||||
express.use(BASE_URL, logMiddleware)
|
||||
express.use(BASE_URL, mcpGateMiddleware)
|
||||
express.use(BASE_URL, rejectCrossSiteMutation)
|
||||
|
||||
RegisterRoutes(express)
|
||||
|
||||
|
||||
@@ -9,6 +9,7 @@ import type { AuthenticatedRequest } from '../helpers/helper.type.mjs'
|
||||
import { iocContainer } from '../ioc/ioc.mjs'
|
||||
import { RestApi } from '../rest-api/rest-api.mjs'
|
||||
import { ACL_MIDDLEWARE_NAME } from './acl.middleware.mjs'
|
||||
import { parseBasicCredentials } from './basic-auth.helper.mjs'
|
||||
import type { SecurityName } from '@vates/types'
|
||||
const log = createLogger('xo:rest-api:authentication')
|
||||
|
||||
@@ -73,7 +74,7 @@ export function setupApiContext(xoApp: XoApp) {
|
||||
return next(new ApiError('Malformed Authorization header', 400))
|
||||
}
|
||||
|
||||
const [username, password] = Buffer.from(encoded, 'base64').toString().split(':')
|
||||
const { username, password } = parseBasicCredentials(encoded)
|
||||
Object.assign(credentials, { username, password, otp: query.otp })
|
||||
res.locals.authType = 'basic'
|
||||
}
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
/**
|
||||
* Extracts the credentials from the base64 payload of a `Authorization: Basic` header.
|
||||
*
|
||||
* Per RFC 7617 §2, the user-id cannot contain a colon but the password can: split on the
|
||||
* first colon only and keep the remainder as the password.
|
||||
*/
|
||||
export function parseBasicCredentials(encoded: string): { username: string; password: string | undefined } {
|
||||
const decoded = Buffer.from(encoded, 'base64').toString()
|
||||
const index = decoded.indexOf(':')
|
||||
if (index === -1) {
|
||||
return { username: decoded, password: undefined }
|
||||
}
|
||||
return { username: decoded.slice(0, index), password: decoded.slice(index + 1) }
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { describe, it } from 'node:test'
|
||||
|
||||
import { parseBasicCredentials } from './basic-auth.helper.mjs'
|
||||
|
||||
const encode = (value: string) => Buffer.from(value).toString('base64')
|
||||
|
||||
describe('parseBasicCredentials()', () => {
|
||||
it('splits username and password', () => {
|
||||
assert.deepEqual(parseBasicCredentials(encode('user:pass')), { username: 'user', password: 'pass' })
|
||||
})
|
||||
|
||||
it('keeps colons found in the password', () => {
|
||||
assert.deepEqual(parseBasicCredentials(encode('user:a:b')), { username: 'user', password: 'a:b' })
|
||||
assert.deepEqual(parseBasicCredentials(encode('user::')), { username: 'user', password: ':' })
|
||||
})
|
||||
|
||||
it('supports an empty password', () => {
|
||||
assert.deepEqual(parseBasicCredentials(encode('user:')), { username: 'user', password: '' })
|
||||
})
|
||||
|
||||
it('has no password when there is no colon', () => {
|
||||
assert.deepEqual(parseBasicCredentials(encode('user')), { username: 'user', password: undefined })
|
||||
})
|
||||
})
|
||||
31
@xen-orchestra/rest-api/src/middlewares/csrf.middleware.mts
Normal file
31
@xen-orchestra/rest-api/src/middlewares/csrf.middleware.mts
Normal file
@@ -0,0 +1,31 @@
|
||||
import type { NextFunction, Response, Request } from 'express'
|
||||
import { ApiError } from '../helpers/error.helper.mjs'
|
||||
|
||||
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS'])
|
||||
|
||||
function isCrossSite(req: Request): boolean {
|
||||
const secFetchSite = req.headers['sec-fetch-site']
|
||||
if (secFetchSite !== undefined) {
|
||||
return secFetchSite === 'cross-site'
|
||||
}
|
||||
|
||||
const { origin } = req.headers
|
||||
if (origin !== undefined) {
|
||||
try {
|
||||
return new URL(origin).host !== req.headers.host
|
||||
} catch (error) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
export function rejectCrossSiteMutation(req: Request, res: Response, next: NextFunction) {
|
||||
// res.locals.authType is setup by authentication.middleware#setupApiContext
|
||||
if (!SAFE_METHODS.has(req.method) && res.locals.authType === 'token' && isCrossSite(req)) {
|
||||
return next(new ApiError('cross-site request rejected', 403))
|
||||
}
|
||||
|
||||
next()
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { describe, it } from 'node:test'
|
||||
import { Request, Response } from 'express'
|
||||
|
||||
import { ApiError } from '../helpers/error.helper.mjs'
|
||||
import { rejectCrossSiteMutation } from './csrf.middleware.mjs'
|
||||
|
||||
const run = (method: string, opts: { authType?: 'token' | 'basic'; headers?: Request['headers'] }) => {
|
||||
const req = { method, headers: opts.headers ?? {} } as Request
|
||||
const res = { locals: { authType: 'authType' in opts ? opts.authType : 'token' } } as unknown as Response
|
||||
let next: unknown
|
||||
|
||||
rejectCrossSiteMutation(req, res, (err?: unknown) => {
|
||||
next = err
|
||||
})
|
||||
return next
|
||||
}
|
||||
|
||||
const UNSAFE = ['POST', 'PUT', 'PATCH', 'DELETE']
|
||||
|
||||
describe('rejectCrossSiteMutation', () => {
|
||||
describe('lets through', () => {
|
||||
it('a safe method, even cross-site with a cookie', () => {
|
||||
assert.equal(run('GET', { headers: { 'sec-fetch-site': 'cross-site' } }), undefined)
|
||||
})
|
||||
|
||||
for (const method of UNSAFE) {
|
||||
it(`${method} authenticated by basic, even cross-site`, () => {
|
||||
assert.equal(run(method, { authType: 'basic', headers: { 'sec-fetch-site': 'cross-site' } }), undefined)
|
||||
})
|
||||
it(`${method} unauthenticated, even cross-site`, () => {
|
||||
assert.equal(run(method, { authType: undefined, headers: { 'sec-fetch-site': 'cross-site' } }), undefined)
|
||||
})
|
||||
it(`${method} cookie + Sec-Fetch-Site same-origin`, () => {
|
||||
assert.equal(run(method, { headers: { 'sec-fetch-site': 'same-origin' } }), undefined)
|
||||
})
|
||||
it(`${method} cookie + Sec-Fetch-Site same-site`, () => {
|
||||
assert.equal(run(method, { headers: { 'sec-fetch-site': 'same-site' } }), undefined)
|
||||
})
|
||||
it(`${method} cookie + Sec-Fetch-Site none`, () => {
|
||||
assert.equal(run(method, { headers: { 'sec-fetch-site': 'none' } }), undefined)
|
||||
})
|
||||
it(`${method} cookie + no metadata (xo-cli, curl)`, () => {
|
||||
assert.equal(run(method, { headers: {} }), undefined)
|
||||
})
|
||||
it(`${method} cookie + Origin matches Host`, () => {
|
||||
assert.equal(run(method, { headers: { origin: 'https://xo.example.com', host: 'xo.example.com' } }), undefined)
|
||||
})
|
||||
it(`${method} cookie: Sec-Fetch-Site wins over a mismatching Origin`, () => {
|
||||
assert.equal(
|
||||
run(method, {
|
||||
headers: { 'sec-fetch-site': 'same-origin', origin: 'https://evil.com', host: 'xo.example.com' },
|
||||
}),
|
||||
undefined
|
||||
)
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
describe('rejects (403)', () => {
|
||||
const assertRejected = (error: unknown) => {
|
||||
assert.ok(error instanceof ApiError)
|
||||
assert.equal((error as ApiError).status, 403)
|
||||
}
|
||||
|
||||
for (const method of UNSAFE) {
|
||||
it(`${method} cookie + Sec-Fetch-Site cross-site`, () => {
|
||||
assertRejected(run(method, { headers: { 'sec-fetch-site': 'cross-site' } }))
|
||||
})
|
||||
it(`${method} cookie + Origin host != Host`, () => {
|
||||
assertRejected(run(method, { headers: { origin: 'https://evil.com', host: 'xo.example.com' } }))
|
||||
})
|
||||
it(`${method} cookie + malformed Origin (fail closed)`, () => {
|
||||
assertRejected(run(method, { headers: { origin: 'null', host: 'xo.example.com' } }))
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -1,9 +1,11 @@
|
||||
import {
|
||||
Body,
|
||||
Delete,
|
||||
Example,
|
||||
Extension,
|
||||
Get,
|
||||
Middlewares,
|
||||
Patch,
|
||||
Path,
|
||||
Put,
|
||||
Query,
|
||||
@@ -16,8 +18,9 @@ import {
|
||||
} from 'tsoa'
|
||||
import { inject } from 'inversify'
|
||||
import { provide } from 'inversify-binding-decorators'
|
||||
import { Request as ExRequest } from 'express'
|
||||
import type { XoAlarm, XoMessage, XoNetwork, XoTask } from '@vates/types'
|
||||
import { invalidParameters } from 'xo-common/api-errors.js'
|
||||
import { json, NextFunction, Request as ExRequest, Response as ExResponse } from 'express'
|
||||
import type { EditNetworkProps, XoAlarm, XoMessage, XoNetwork, XoTask } from '@vates/types'
|
||||
|
||||
import { AlarmService } from '../alarms/alarm.service.mjs'
|
||||
import { escapeUnsafeComplexMatcher } from '../helpers/utils.helper.mjs'
|
||||
@@ -26,6 +29,8 @@ import { network, networkIds, partialNetworks } from '../open-api/oa-examples/ne
|
||||
import {
|
||||
badRequestResp,
|
||||
forbiddenOperationResp,
|
||||
internalServerErrorResp,
|
||||
invalidParameters as invalidParametersResp,
|
||||
noContentResp,
|
||||
notFoundResp,
|
||||
unauthorizedResp,
|
||||
@@ -36,7 +41,60 @@ import type { SendObjects } from '../helpers/helper.type.mjs'
|
||||
import { XapiXoController } from '../abstract-classes/xapi-xo-controller.mjs'
|
||||
import { messageIds, partialMessages } from '../open-api/oa-examples/message.oa-example.mjs'
|
||||
import { partialTasks, taskIds } from '../open-api/oa-examples/task.oa-example.mjs'
|
||||
import { acl } from '../middlewares/acl.middleware.mjs'
|
||||
import { acl, actionsFromBody } from '../middlewares/acl.middleware.mjs'
|
||||
import type { AuthenticatedRequest } from '../helpers/helper.type.mjs'
|
||||
|
||||
// the fields come from EditNetworkProps, so a field added there reaches the body too; MTU and insecureNbd
|
||||
// are redeclared only to carry their tsoa JSDoc (validation and description in the OpenAPI spec)
|
||||
type UpdateNetworkRequestBody = Omit<EditNetworkProps, 'MTU' | 'insecureNbd'> & {
|
||||
/**
|
||||
* @isInt
|
||||
* @minimum 68 the MTU must be at least 68 (RFC 791)
|
||||
*/
|
||||
MTU?: number
|
||||
/**
|
||||
* NBD in clear, only on a network dedicated to backups. Mutually exclusive with `nbd`
|
||||
*/
|
||||
insecureNbd?: boolean
|
||||
}
|
||||
|
||||
// the privileges a PATCH checks: update:<field> for each field in the body, and the other NBD
|
||||
// purpose when one is set, since the XAPI side removes it (setNbdPurposes in
|
||||
// xo-server/src/xapi/mixins/networking.mjs): nbd: true removes insecure_nbd, insecureNbd: true removes nbd
|
||||
export function updateNetworkActions({ req }: { req: AuthenticatedRequest }) {
|
||||
const actions = actionsFromBody<'network'>([
|
||||
'update:automatic',
|
||||
'update:defaultIsLocked',
|
||||
'update:insecureNbd',
|
||||
'update:MTU',
|
||||
'update:name_description',
|
||||
'update:name_label',
|
||||
'update:nbd',
|
||||
])({ req })
|
||||
const body: UpdateNetworkRequestBody = req.body
|
||||
if (body.insecureNbd === true) {
|
||||
actions.push('update:nbd')
|
||||
}
|
||||
if (body.nbd === true) {
|
||||
actions.push('update:insecureNbd')
|
||||
}
|
||||
return actions
|
||||
}
|
||||
|
||||
// runs before acl(): a body with no gated field gets no privilege checked, so it is refused here, for a missing
|
||||
// network too. Refusing it in the handler, after the ACL has resolved the network, would answer 404 for a missing
|
||||
// network and 422 for an existing one, which tells them apart
|
||||
export function refuseEmptyUpdate(req: AuthenticatedRequest, _res: ExResponse, next: NextFunction) {
|
||||
if (updateNetworkActions({ req }).length > 0) {
|
||||
return next()
|
||||
}
|
||||
// the api-errors factories throw, so the error is caught to reach next()
|
||||
try {
|
||||
invalidParameters('the body must contain at least one field to update')
|
||||
} catch (error) {
|
||||
return next(error)
|
||||
}
|
||||
}
|
||||
|
||||
@Route('networks')
|
||||
@Security('*')
|
||||
@@ -94,6 +152,56 @@ export class NetworkController extends XapiXoController<XoNetwork> {
|
||||
return this.getObject(id as XoNetwork['id'])
|
||||
}
|
||||
|
||||
/**
|
||||
* Partial update of a network: only the fields present in the body are modified.
|
||||
*
|
||||
* Changing `MTU` unplugs and replugs the network's PIFs and the VIFs of its running VMs: their
|
||||
* traffic is briefly interrupted.
|
||||
* `nbd` and `insecureNbd` are mutually exclusive; setting one to `false` only removes that purpose.
|
||||
* `automatic` adds the network to new VMs automatically; `defaultIsLocked` blocks the traffic of
|
||||
* VIFs with no allowed IP.
|
||||
* A body with none of the fields below is refused with a 422, whether or not the network exists.
|
||||
*
|
||||
* Required privilege per field provided in the body:
|
||||
* - resource: network, action: update:<field>
|
||||
* - and with `nbd: true`, also resource: network, action: update:insecureNbd (it removes the
|
||||
* insecure NBD purpose); with `insecureNbd: true`, also action: update:nbd (it removes the NBD purpose)
|
||||
*
|
||||
* @example id "9fe12ca3-d75d-cfb0-492e-cfd2bc6c568f"
|
||||
* @example body { "name_label": "backups", "MTU": 9000, "insecureNbd": true }
|
||||
*/
|
||||
@Extension('x-mcp-exposure', 'confirm')
|
||||
@Patch('{id}')
|
||||
@Middlewares([
|
||||
json(),
|
||||
refuseEmptyUpdate,
|
||||
acl({
|
||||
resource: 'network',
|
||||
actions: updateNetworkActions,
|
||||
objectId: 'params.id',
|
||||
}),
|
||||
])
|
||||
@SuccessResponse(noContentResp.status, noContentResp.description)
|
||||
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
|
||||
@Response(notFoundResp.status, notFoundResp.description)
|
||||
@Response(invalidParametersResp.status, invalidParametersResp.description)
|
||||
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
|
||||
async updateNetwork(@Path() id: string, @Body() body: UpdateNetworkRequestBody): Promise<void> {
|
||||
const networkId = id as XoNetwork['id']
|
||||
const { automatic, defaultIsLocked, insecureNbd, MTU, name_description, name_label, nbd } = body
|
||||
|
||||
// forward only the declared fields: the ACL above checked their privileges and the NBD purpose each one removes
|
||||
await this.getXapi(networkId).editNetwork(networkId, {
|
||||
automatic,
|
||||
defaultIsLocked,
|
||||
insecureNbd,
|
||||
MTU,
|
||||
name_description,
|
||||
name_label,
|
||||
nbd,
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Required privilege:
|
||||
* - resource: network, action: delete
|
||||
|
||||
@@ -0,0 +1,90 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { describe, it, mock } from 'node:test'
|
||||
import { getMissingPrivileges, type AnyPrivilege, type AnyPrivilegeOnParam } from '@xen-orchestra/acl'
|
||||
import type { XoUser } from '@vates/types'
|
||||
import type { NextFunction, Response } from 'express'
|
||||
import { invalidParameters } from 'xo-common/api-errors.js'
|
||||
|
||||
import { NetworkController, refuseEmptyUpdate, updateNetworkActions } from './network.controller.mjs'
|
||||
import type { AuthenticatedRequest } from '../helpers/helper.type.mjs'
|
||||
import type { RestApi } from '../rest-api/rest-api.mjs'
|
||||
|
||||
const user = { id: 'user-1', permission: 'none' } as XoUser
|
||||
const network = { id: 'network-1' }
|
||||
const NETWORK_ID = '9fe12ca3-d75d-cfb0-492e-cfd2bc6c568f'
|
||||
|
||||
function missingPrivileges(body: object, userPrivileges: AnyPrivilege[]) {
|
||||
const req = { body } as AuthenticatedRequest
|
||||
const params = updateNetworkActions({ req }).map(
|
||||
action => ({ user, resource: 'network', action, objects: [network] }) as AnyPrivilegeOnParam
|
||||
)
|
||||
return getMissingPrivileges(params, userPrivileges)
|
||||
}
|
||||
|
||||
describe('updateNetworkActions', () => {
|
||||
it('refuses insecureNbd: true to a user with only update:insecureNbd, as it removes the nbd purpose', () => {
|
||||
const privileges = [
|
||||
{ id: 'privilege-1', resource: 'network', action: 'update:insecureNbd', effect: 'allow', roleId: 'role-1' },
|
||||
] as unknown as AnyPrivilege[]
|
||||
|
||||
const missing = missingPrivileges({ insecureNbd: true }, privileges)
|
||||
|
||||
assert.equal(missing.length, 1)
|
||||
assert.equal(missing[0].action, 'update:nbd')
|
||||
})
|
||||
})
|
||||
|
||||
describe('refuseEmptyUpdate', () => {
|
||||
it('refuses an empty body with a 422 before the ACL resolves the network', () => {
|
||||
const next = mock.fn()
|
||||
|
||||
refuseEmptyUpdate({ body: {} } as AuthenticatedRequest, {} as Response, next as NextFunction)
|
||||
|
||||
assert.equal(next.mock.callCount(), 1)
|
||||
assert.ok(invalidParameters.is(next.mock.calls[0].arguments[0]))
|
||||
})
|
||||
})
|
||||
|
||||
describe('NetworkController.updateNetwork', () => {
|
||||
it('forwards only the seven declared fields to editNetwork, with the id the route got', async () => {
|
||||
const editCalls: unknown[][] = []
|
||||
const restApi = {
|
||||
xoApp: {
|
||||
getXapi: () => ({
|
||||
editNetwork: async (...args: unknown[]) => {
|
||||
editCalls.push(args)
|
||||
},
|
||||
}),
|
||||
},
|
||||
} as unknown as RestApi
|
||||
const controller = new NetworkController(restApi, {} as never)
|
||||
// not an object literal passed inline: an extra key is only allowed on a value, not on a fresh literal
|
||||
const body = {
|
||||
automatic: true,
|
||||
defaultIsLocked: false,
|
||||
insecureNbd: false,
|
||||
MTU: 9000,
|
||||
name_description: 'description',
|
||||
name_label: 'label',
|
||||
nbd: true,
|
||||
notAField: 'dropped',
|
||||
}
|
||||
|
||||
await controller.updateNetwork(NETWORK_ID, body)
|
||||
|
||||
assert.deepEqual(editCalls, [
|
||||
[
|
||||
NETWORK_ID,
|
||||
{
|
||||
automatic: true,
|
||||
defaultIsLocked: false,
|
||||
insecureNbd: false,
|
||||
MTU: 9000,
|
||||
name_description: 'description',
|
||||
name_label: 'label',
|
||||
nbd: true,
|
||||
},
|
||||
],
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -1,10 +1,62 @@
|
||||
import { invalidParameters } from 'xo-common/api-errors.js'
|
||||
|
||||
import type { CreateBondedNetworkBody, CreateInternalNetworkBody, CreateNetworkBody } from '../pools/pool.type.mjs'
|
||||
import type { ReplaceKey } from '../helpers/helper.type.mjs'
|
||||
import type { AuthenticatedRequest, ReplaceKey } from '../helpers/helper.type.mjs'
|
||||
import type { NextFunction, Response as ExResponse } from 'express'
|
||||
import type { RestApi } from '../rest-api/rest-api.mjs'
|
||||
import type { Xapi, XenApiNetworkWrapped, XoNetwork, XoPool } from '@vates/types'
|
||||
|
||||
type NetworkCreateNames = Pick<
|
||||
CreateNetworkBody,
|
||||
'name' | 'name_label' | 'description' | 'name_description' | 'mtu' | 'MTU'
|
||||
>
|
||||
|
||||
// maps the names the create routes accept to the ones xapi.createNetwork reads (name, description, mtu), and
|
||||
// refuses a body giving both spellings of one field or no name. The create routes call it before their task
|
||||
// starts, so the refusal is a 422 and not a failed task
|
||||
export function normalizeNetworkCreateBody<T extends NetworkCreateNames>(body: T) {
|
||||
const { name, name_label, description, name_description, mtu, MTU, ...rest } = body
|
||||
|
||||
if (name !== undefined && name_label !== undefined) {
|
||||
throw invalidParameters('give either name or name_label, not both')
|
||||
}
|
||||
if (description !== undefined && name_description !== undefined) {
|
||||
throw invalidParameters('give either description or name_description, not both')
|
||||
}
|
||||
if (mtu !== undefined && MTU !== undefined) {
|
||||
throw invalidParameters('give either mtu or MTU, not both')
|
||||
}
|
||||
|
||||
const networkName = name_label ?? name
|
||||
if (networkName === undefined) {
|
||||
throw invalidParameters('name_label is required')
|
||||
}
|
||||
|
||||
return {
|
||||
...rest,
|
||||
name: networkName,
|
||||
description: name_description ?? description,
|
||||
mtu: MTU ?? mtu,
|
||||
}
|
||||
}
|
||||
|
||||
// runs before acl(): acl() awaits its object callback outside any try, and Express 4 does not catch that rejection,
|
||||
// so a refusal thrown there would hang the request. Checked here, the callback below can't throw
|
||||
export function refuseInvalidNetworkCreateBody(req: AuthenticatedRequest, _res: ExResponse, next: NextFunction) {
|
||||
try {
|
||||
normalizeNetworkCreateBody(req.body)
|
||||
} catch (error) {
|
||||
return next(error)
|
||||
}
|
||||
next()
|
||||
}
|
||||
|
||||
// the ACL checks the privileges against the names xapi reads, so the selectors written on name, description and
|
||||
// mtu match whatever spelling the client used
|
||||
export function networkCreateAclObject({ req }: { req: AuthenticatedRequest }) {
|
||||
return normalizeNetworkCreateBody(req.body)
|
||||
}
|
||||
|
||||
export class NetworkService {
|
||||
#restApi: RestApi
|
||||
|
||||
@@ -12,9 +64,12 @@ export class NetworkService {
|
||||
this.#restApi = restApi
|
||||
}
|
||||
|
||||
// body must come from normalizeNetworkCreateBody
|
||||
async create(
|
||||
poolId: XoPool['id'],
|
||||
body: ReplaceKey<CreateNetworkBody, 'pif', 'pifId'> | CreateBondedNetworkBody | CreateInternalNetworkBody
|
||||
body: (ReplaceKey<CreateNetworkBody, 'pif', 'pifId'> | CreateBondedNetworkBody | CreateInternalNetworkBody) & {
|
||||
name: string
|
||||
}
|
||||
): Promise<XoNetwork['id']> {
|
||||
const { nbd, insecureNbd, ...rest } = body
|
||||
if (nbd && insecureNbd) {
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { describe, it } from 'node:test'
|
||||
import { invalidParameters } from 'xo-common/api-errors.js'
|
||||
|
||||
import { networkCreateAclObject, normalizeNetworkCreateBody } from './network.service.mjs'
|
||||
|
||||
describe('normalizeNetworkCreateBody', () => {
|
||||
it('maps name_label, name_description and MTU to the names xapi.createNetwork reads', () => {
|
||||
const body = normalizeNetworkCreateBody({
|
||||
name_label: 'label',
|
||||
name_description: 'description',
|
||||
MTU: 9000,
|
||||
vlan: 0,
|
||||
})
|
||||
|
||||
assert.deepEqual(body, { name: 'label', description: 'description', mtu: 9000, vlan: 0 })
|
||||
})
|
||||
|
||||
it('still accepts the deprecated name, description and mtu', () => {
|
||||
const body = normalizeNetworkCreateBody({ name: 'label', description: 'description', mtu: 1450 })
|
||||
|
||||
assert.deepEqual(body, { name: 'label', description: 'description', mtu: 1450 })
|
||||
})
|
||||
|
||||
it('refuses a body giving both spellings of one field', () => {
|
||||
assert.throws(() => normalizeNetworkCreateBody({ name: 'a', name_label: 'b' }), invalidParameters.is)
|
||||
assert.throws(
|
||||
() => normalizeNetworkCreateBody({ name_label: 'a', description: 'b', name_description: 'c' }),
|
||||
invalidParameters.is
|
||||
)
|
||||
assert.throws(() => normalizeNetworkCreateBody({ name_label: 'a', mtu: 1450, MTU: 9000 }), invalidParameters.is)
|
||||
})
|
||||
|
||||
it('refuses a body with no name', () => {
|
||||
assert.throws(() => normalizeNetworkCreateBody({ name_description: 'description' }), invalidParameters.is)
|
||||
})
|
||||
|
||||
it('gives the ACL the old keys for a body sent with the new names', () => {
|
||||
const req = { body: { name_label: 'label', name_description: 'description', MTU: 9000 } }
|
||||
|
||||
assert.deepEqual(networkCreateAclObject({ req } as never), { name: 'label', description: 'description', mtu: 9000 })
|
||||
})
|
||||
})
|
||||
@@ -95,7 +95,12 @@ import { PoolService } from './pool.service.mjs'
|
||||
import { BASE_URL, escapeUnsafeComplexMatcher, NDJSON_CONTENT_TYPE } from '../helpers/utils.helper.mjs'
|
||||
import { messageIds, partialMessages } from '../open-api/oa-examples/message.oa-example.mjs'
|
||||
import type { CreateActionReturnType } from '../abstract-classes/base-controller.mjs'
|
||||
import { NetworkService } from '../networks/network.service.mjs'
|
||||
import {
|
||||
NetworkService,
|
||||
networkCreateAclObject,
|
||||
normalizeNetworkCreateBody,
|
||||
refuseInvalidNetworkCreateBody,
|
||||
} from '../networks/network.service.mjs'
|
||||
import { v2vStartResult } from '../open-api/oa-examples/v2v.oa-example.mjs'
|
||||
import { V2V_TASK_PROPERTY } from '@vates/types'
|
||||
import { V2vService, V2V_TASK_NAME } from '../v2v/v2v.service.mjs'
|
||||
@@ -180,8 +185,8 @@ export class PoolController extends XapiXoController<XoPool> {
|
||||
*
|
||||
* @example id "355ee47d-ff4c-4924-3db2-fd86ae629676"
|
||||
* @example body {
|
||||
* "name": "awes0me_network",
|
||||
* "description": "random description",
|
||||
* "name_label": "awes0me_network",
|
||||
* "name_description": "random description",
|
||||
* "pif": "ad15b2c8-3d9a-194e-c43a-e3dcda74b256",
|
||||
* "vlan": 0
|
||||
* }
|
||||
@@ -192,10 +197,11 @@ export class PoolController extends XapiXoController<XoPool> {
|
||||
@Post('{id}/actions/create_network')
|
||||
@Middlewares([
|
||||
json(),
|
||||
refuseInvalidNetworkCreateBody,
|
||||
acl([
|
||||
// these two rights are a bit redundant, but for now this is the only way to restrict network creation on a given pool
|
||||
{ resource: 'pool', action: 'create:network', objectId: 'params.id' },
|
||||
{ resource: 'network', action: 'create', object: ({ req }) => req.body },
|
||||
{ resource: 'network', action: 'create', object: networkCreateAclObject },
|
||||
]),
|
||||
])
|
||||
@Tags('networks')
|
||||
@@ -211,8 +217,8 @@ export class PoolController extends XapiXoController<XoPool> {
|
||||
@Query() sync?: boolean
|
||||
): CreateActionReturnType<{ id: Unbrand<XoNetwork>['id'] }> {
|
||||
const poolId = id as XoPool['id']
|
||||
const { pif, ...rest } = normalizeNetworkCreateBody(body)
|
||||
const action = async () => {
|
||||
const { pif, ...rest } = body
|
||||
const networkId = await this.#networkService.create(poolId, { pifId: pif as XoPif['id'], ...rest })
|
||||
|
||||
return { id: networkId }
|
||||
@@ -236,8 +242,8 @@ export class PoolController extends XapiXoController<XoPool> {
|
||||
*
|
||||
* @example id "355ee47d-ff4c-4924-3db2-fd86ae629676"
|
||||
* @example body {
|
||||
* "name": "awes0me_bonded_network",
|
||||
* "description": "random description",
|
||||
* "name_label": "awes0me_bonded_network",
|
||||
* "name_description": "random description",
|
||||
* "pifIds": ["ad15b2c8-3d9a-194e-c43a-e3dcda74b256", "7b6bed50-26b2-bd27-8f3a-1b5a81989a92"],
|
||||
* "bondMode": "lacp"
|
||||
* }
|
||||
@@ -248,9 +254,10 @@ export class PoolController extends XapiXoController<XoPool> {
|
||||
@Post('{id}/actions/create_bonded_network')
|
||||
@Middlewares([
|
||||
json(),
|
||||
refuseInvalidNetworkCreateBody,
|
||||
acl([
|
||||
{ resource: 'pool', action: 'create:network', objectId: 'params.id' },
|
||||
{ resource: 'network', action: 'create', object: ({ req }) => req.body },
|
||||
{ resource: 'network', action: 'create', object: networkCreateAclObject },
|
||||
]),
|
||||
])
|
||||
@Tags('networks')
|
||||
@@ -266,8 +273,8 @@ export class PoolController extends XapiXoController<XoPool> {
|
||||
@Query() sync?: boolean
|
||||
): CreateActionReturnType<{ id: Unbrand<XoNetwork>['id'] }> {
|
||||
const poolId = id as XoPool['id']
|
||||
const { pifIds, ...rest } = normalizeNetworkCreateBody(body)
|
||||
const action = async () => {
|
||||
const { pifIds, ...rest } = body
|
||||
const networkId = await this.#networkService.create(poolId, { pifIds: pifIds as XoPif['id'][], ...rest })
|
||||
|
||||
return { id: networkId }
|
||||
@@ -291,8 +298,8 @@ export class PoolController extends XapiXoController<XoPool> {
|
||||
*
|
||||
* @example id "355ee47d-ff4c-4924-3db2-fd86ae629676"
|
||||
* @example body {
|
||||
* "name": "awes0me_internal_network",
|
||||
* "description": "random description"
|
||||
* "name_label": "awes0me_internal_network",
|
||||
* "name_description": "random description"
|
||||
* }
|
||||
*/
|
||||
@Example(taskLocation)
|
||||
@@ -301,9 +308,10 @@ export class PoolController extends XapiXoController<XoPool> {
|
||||
@Post('{id}/actions/create_internal_network')
|
||||
@Middlewares([
|
||||
json(),
|
||||
refuseInvalidNetworkCreateBody,
|
||||
acl([
|
||||
{ resource: 'pool', action: 'create:network', objectId: 'params.id' },
|
||||
{ resource: 'network', action: 'create', object: ({ req }) => req.body },
|
||||
{ resource: 'network', action: 'create', object: networkCreateAclObject },
|
||||
]),
|
||||
])
|
||||
@Tags('networks')
|
||||
@@ -319,8 +327,9 @@ export class PoolController extends XapiXoController<XoPool> {
|
||||
@Query() sync?: boolean
|
||||
): CreateActionReturnType<{ id: Unbrand<XoNetwork>['id'] }> {
|
||||
const poolId = id as XoPool['id']
|
||||
const networkBody = normalizeNetworkCreateBody(body)
|
||||
const action = async () => {
|
||||
const networkId = await this.#networkService.create(poolId, body)
|
||||
const networkId = await this.#networkService.create(poolId, networkBody)
|
||||
|
||||
return { id: networkId }
|
||||
}
|
||||
|
||||
@@ -12,13 +12,28 @@ import type {
|
||||
} from '@vates/types'
|
||||
import { Unbrand } from '../open-api/common/response.common.mjs'
|
||||
|
||||
// the names are the ones PATCH /networks/{id} takes (name_label, name_description, MTU); name, description and mtu
|
||||
// are the names these routes took before and still work. tsoa cannot express "exactly one of", so name and
|
||||
// name_label are both optional here and normalizeNetworkCreateBody (network.service.mts) refuses a body with neither
|
||||
type BaseCreateNetworkBody = {
|
||||
name: string
|
||||
/**
|
||||
* @deprecated use `name_label`
|
||||
*/
|
||||
name?: string
|
||||
name_label?: string
|
||||
/**
|
||||
* @deprecated use `name_description`
|
||||
*/
|
||||
description?: string
|
||||
name_description?: string
|
||||
/**
|
||||
* @deprecated use `MTU`
|
||||
*/
|
||||
mtu?: number
|
||||
/**
|
||||
* @default 1500
|
||||
*/
|
||||
mtu?: number
|
||||
MTU?: number
|
||||
nbd?: boolean
|
||||
/**
|
||||
* NBD in clear, only on a network dedicated to backups. Mutually exclusive with `nbd`
|
||||
|
||||
@@ -89,7 +89,7 @@ const CONTROLLER_PREFIXES = {
|
||||
* 'config.annotation'?: string,
|
||||
* 'config.instanceUuid'?: string,
|
||||
* 'config.firmware'?: string,
|
||||
* 'config.bootOptions.efiSecureBootEnabled'?: unknown,
|
||||
* 'config.bootOptions'?: { efiSecureBootEnabled?: unknown },
|
||||
* 'config.template'?: unknown,
|
||||
* 'config.hardware.numCPU'?: unknown,
|
||||
* 'config.hardware.memoryMB'?: unknown,
|
||||
@@ -379,7 +379,7 @@ export function buildInventory({
|
||||
annotation: properties['config.annotation'],
|
||||
instanceUuid: properties['config.instanceUuid'],
|
||||
firmware: firmware === 'efi' ? 'uefi' : firmware,
|
||||
secureBoot: isTrue(properties['config.bootOptions.efiSecureBootEnabled']),
|
||||
secureBoot: isTrue(properties['config.bootOptions']?.efiSecureBootEnabled),
|
||||
isTemplate: isTrue(properties['config.template']),
|
||||
cpus: toNumber(properties['config.hardware.numCPU']),
|
||||
memory: memoryMb === undefined ? undefined : memoryMb * 1024 * 1024,
|
||||
|
||||
@@ -1,7 +1,14 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { describe, it } from 'node:test'
|
||||
|
||||
import { countSnapshots, findDatacenter, parseDevices, parseGuestNics, parseVlan } from './_inventory.mjs'
|
||||
import {
|
||||
buildInventory,
|
||||
countSnapshots,
|
||||
findDatacenter,
|
||||
parseDevices,
|
||||
parseGuestNics,
|
||||
parseVlan,
|
||||
} from './_inventory.mjs'
|
||||
|
||||
// shaped as the SOAP library returns them: the nested references and types are not normalized
|
||||
const typed = (type, value) => ({ attributes: { 'xsi:type': type }, ...value })
|
||||
@@ -202,3 +209,37 @@ describe('findDatacenter', function () {
|
||||
assert.equal(findDatacenter('group-a', loop, datacenterIds), undefined)
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildInventory', function () {
|
||||
const EMPTY = {
|
||||
about: {},
|
||||
datacenters: {},
|
||||
clusters: {},
|
||||
hosts: {},
|
||||
datastores: {},
|
||||
networks: {},
|
||||
portgroups: {},
|
||||
folders: {},
|
||||
computeResources: {},
|
||||
}
|
||||
|
||||
it('reads secure boot from the boot options, absent before vSphere 6.5', function () {
|
||||
const { vms } = buildInventory({
|
||||
...EMPTY,
|
||||
vms: {
|
||||
'vm-65': { 'config.bootOptions': { efiSecureBootEnabled: 'true' } },
|
||||
// ESXi 6.0: the boot options have no `efiSecureBootEnabled`
|
||||
'vm-60': { 'config.bootOptions': { bootDelay: '0' } },
|
||||
'vm-none': {},
|
||||
},
|
||||
})
|
||||
assert.deepEqual(
|
||||
vms.map(({ id, secureBoot }) => ({ id, secureBoot })),
|
||||
[
|
||||
{ id: 'vm-65', secureBoot: true },
|
||||
{ id: 'vm-60', secureBoot: false },
|
||||
{ id: 'vm-none', secureBoot: false },
|
||||
]
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -623,7 +623,9 @@ export default class Esxi extends EventEmitter {
|
||||
'config.annotation',
|
||||
'config.instanceUuid',
|
||||
'config.firmware',
|
||||
'config.bootOptions.efiSecureBootEnabled',
|
||||
// the whole object rather than `config.bootOptions.efiSecureBootEnabled`: that property only
|
||||
// exists since vSphere 6.5, and an unknown path fails the whole request (InvalidProperty)
|
||||
'config.bootOptions',
|
||||
'config.template',
|
||||
'config.hardware.numCPU',
|
||||
'config.hardware.memoryMB',
|
||||
@@ -1134,9 +1136,11 @@ export default class Esxi extends EventEmitter {
|
||||
* @returns {Promise<object>} the `info` of the successful task
|
||||
*/
|
||||
async snapshot(vmId, name, description, { signal, timeout = 30 * 60e3 } = {}) {
|
||||
// not `CreateSnapshotEx_Task`: it only exists since vSphere 8 (absent from the WSDL of older
|
||||
// hosts), and its only addition, the quiesce spec, is not used
|
||||
return this.#runTask(
|
||||
'CreateSnapshotEx_Task',
|
||||
{ _this: vmId, name, description, memory: false },
|
||||
'CreateSnapshot_Task',
|
||||
{ _this: vmId, name, description, memory: false, quiesce: false },
|
||||
{ signal, timeout }
|
||||
)
|
||||
}
|
||||
|
||||
@@ -696,7 +696,7 @@ describe('tasks', function () {
|
||||
const controller = new AbortController()
|
||||
const { esxi, vimClient } = await connectedEsxi({
|
||||
responses: {
|
||||
CreateSnapshotEx_Task: () => startedTask(),
|
||||
CreateSnapshot_Task: () => startedTask(),
|
||||
RetrievePropertiesEx: () => {
|
||||
controller.abort()
|
||||
return taskInfo('running')
|
||||
|
||||
@@ -59,6 +59,7 @@ Testing uses **Vitest 5** with a single `unit` project (see `vitest.config.ts`):
|
||||
| `test/expect-loader.ts` | `hasLoader(wrapper)`: whether a `UiLoader` is rendered; `expectLoaderInsteadOf(wrapper, findContent)`: a `UiLoader` shown and the content it stands for empty (also used by XO 6) |
|
||||
| `test/select.ts` | `openSelect`, `findShownSelections`, `findSelectOptionLabels`, `pickSelectOption(wrapper, label, { detailed? })`: opens a `VtsSelect`, reads the selection it shows, reads or picks its options (`detailed`: the option shows details after its label); `chooseSelectOption(wrapper, label, { container?, detailed? })`: opens the select inside `container`, then picks the option (also used by XO 6) |
|
||||
| `test/is-placeholder-shown.ts` | `isPlaceholderShown(field)`: whether a readonly input shows its placeholder in place of its value |
|
||||
| `test/can-focus-input.ts` | `canFocusInput(wrapper)`: whether the first input of a wrapper attached to the document takes the focus, which an `inert` ancestor prevents |
|
||||
| `test/inject-or-throw.ts` | `injectOrThrow(key)`: `inject(key)`, throwing when nothing provides it |
|
||||
| `test/mount-with-setup.ts` | `mountWithSetup(setup, { global?, attachTo? })`: mounts a component whose `setup` sets up what its render needs below it (a select, a provided context) and returns that render (XO 6 wraps it with its config); `mountWithSetupResult(setup, options)`: the same, keeping what `setup` builds (a form, a composable's return), `setup` returning `{ result, render }`, returns `{ wrapper, result }`; `mountComposableUnderSetup(setup, composable, options)`: runs `composable` (given what `setup` returned) in a child of the component whose `setup` provides what it injects, returns `{ provided, result }` |
|
||||
| `test/mount-with-select.ts` | `renderSelect(id, { accent?, ref? }, slots?)`: renders the `VtsSelect` of a select id, `neutral` accent by default; `mountSelect`: a `VtsSelect` of string sources, its config, accent, wrapper message, option slot and a callback receiving the mounted select |
|
||||
|
||||
@@ -46,7 +46,7 @@ const columnTransition = `grid-template-columns ${PANEL_TRANSITION_DURATION}ms`
|
||||
display: grid;
|
||||
grid-template-columns: minmax(0, 1fr) 0;
|
||||
grid-template-rows: minmax(0, 1fr);
|
||||
overflow: hidden;
|
||||
overflow: clip;
|
||||
|
||||
.content {
|
||||
overflow-y: auto;
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
import VtsLayoutSidebar from '@core/components/layout/VtsLayoutSidebar.vue'
|
||||
import { useRightSidebarStore } from '@core/packages/sidebar'
|
||||
import { canFocusInput } from '@core-test/can-focus-input.ts'
|
||||
import { createGlobalTestConfig } from '@core-test/create-global-test-config.ts'
|
||||
import { mount } from '@vue/test-utils'
|
||||
import { h, nextTick } from 'vue'
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear()
|
||||
})
|
||||
|
||||
function mountSidebar({ isExpanded }: { isExpanded: boolean }) {
|
||||
localStorage.setItem('sidebar.right.expanded', String(isExpanded))
|
||||
|
||||
return mount(VtsLayoutSidebar, {
|
||||
props: { side: 'right' },
|
||||
slots: { default: () => h('input') },
|
||||
global: createGlobalTestConfig(),
|
||||
attachTo: document.body,
|
||||
})
|
||||
}
|
||||
|
||||
it('lets the focus into an expanded sidebar', () => {
|
||||
expect(canFocusInput(mountSidebar({ isExpanded: true }))).toBe(true)
|
||||
})
|
||||
|
||||
it('keeps the focus out of a collapsed sidebar', () => {
|
||||
expect(canFocusInput(mountSidebar({ isExpanded: false }))).toBe(false)
|
||||
})
|
||||
|
||||
it('lets the focus in once the sidebar expands', async () => {
|
||||
const wrapper = mountSidebar({ isExpanded: false })
|
||||
|
||||
useRightSidebarStore().toggleExpand(true)
|
||||
await nextTick()
|
||||
|
||||
expect(canFocusInput(wrapper)).toBe(true)
|
||||
})
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<div :class="className" class="vts-layout-sidebar">
|
||||
<div :class="className" class="vts-layout-sidebar" :inert="!sidebar.isExpanded">
|
||||
<VtsResizeHandle v-if="showResizeHandle" :position="resizeHandlePosition" :resizable="sidebar" />
|
||||
<div v-if="slots.header || (showLock && !ui.isSmall)" class="header">
|
||||
<div v-if="slots.header" class="start">
|
||||
@@ -35,7 +35,12 @@
|
||||
import VtsResizeHandle from '@core/components/resize-handle/VtsResizeHandle.vue'
|
||||
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
|
||||
import { vTooltip } from '@core/directives/tooltip.directive.ts'
|
||||
import { type SidebarSide, useLeftSidebarStore, useRightSidebarStore } from '@core/packages/sidebar'
|
||||
import {
|
||||
SIDEBAR_TRANSITION_DURATION,
|
||||
type SidebarSide,
|
||||
useLeftSidebarStore,
|
||||
useRightSidebarStore,
|
||||
} from '@core/packages/sidebar'
|
||||
import { useUiStore } from '@core/stores/ui.store.ts'
|
||||
import { IK_MENU_ACTION_HANDLER } from '@core/utils/injection-keys.util.ts'
|
||||
import { toVariants } from '@core/utils/to-variants.util.ts'
|
||||
@@ -68,6 +73,8 @@ const showResizeHandle = computed(() => !ui.isSmall && sidebar.value.isExpanded)
|
||||
|
||||
const resizeHandlePosition = computed(() => (side === 'left' ? 'end' : 'start'))
|
||||
|
||||
const slideTransition = `margin-inline ${SIDEBAR_TRANSITION_DURATION}ms, transform ${SIDEBAR_TRANSITION_DURATION}ms`
|
||||
|
||||
provide(IK_MENU_ACTION_HANDLER, () => {
|
||||
if (ui.isSmall) {
|
||||
sidebar.value.toggleExpand(false)
|
||||
@@ -93,9 +100,7 @@ const className = computed(() => [
|
||||
background-color: var(--color-neutral-background-secondary);
|
||||
width: v-bind('sidebar.cssWidth');
|
||||
z-index: 1010;
|
||||
transition:
|
||||
margin-inline 0.25s,
|
||||
transform 0.25s;
|
||||
transition: v-bind(slideTransition);
|
||||
|
||||
&.bordered {
|
||||
&.side--left {
|
||||
|
||||
@@ -1,13 +1,29 @@
|
||||
<template>
|
||||
<UiModal accent="danger" icon="status:danger-picto" @dismiss="emit('close')" @confirm="emit('close')">
|
||||
<UiModal
|
||||
class="vts-error-modal"
|
||||
accent="danger"
|
||||
icon="status:info-picto"
|
||||
@dismiss="emit('close')"
|
||||
@confirm="emit('close')"
|
||||
>
|
||||
<template #title>
|
||||
{{ title }}
|
||||
</template>
|
||||
|
||||
<template #content>
|
||||
<slot name="content">
|
||||
{{ error }}
|
||||
</slot>
|
||||
<div class="content">
|
||||
<slot name="content">
|
||||
{{ error }}
|
||||
</slot>
|
||||
<UiLogEntryViewer
|
||||
v-if="details !== undefined"
|
||||
:label="t('see-details')"
|
||||
:content="details"
|
||||
accent="danger"
|
||||
size="small"
|
||||
class="details"
|
||||
/>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<template #buttons>
|
||||
@@ -20,12 +36,14 @@
|
||||
|
||||
<script lang="ts" setup>
|
||||
import VtsOverlayConfirmButton from '@core/components/overlay/VtsOverlayConfirmButton.vue'
|
||||
import UiLogEntryViewer from '@core/components/ui/log-entry-viewer/UiLogEntryViewer.vue'
|
||||
import UiModal from '@core/components/ui/modal/UiModal.vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
defineProps<{
|
||||
title: string
|
||||
error?: string
|
||||
details?: string | object
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -38,3 +56,19 @@ defineSlots<{
|
||||
|
||||
const { t } = useI18n()
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
.vts-error-modal {
|
||||
.content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.8rem;
|
||||
}
|
||||
|
||||
.details {
|
||||
text-align: start;
|
||||
/* The small action buttons must not overflow the scrollable modal content */
|
||||
overflow-x: clip;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
import VtsSidePanel from '@core/components/panel/VtsSidePanel.vue'
|
||||
import { canFocusInput } from '@core-test/can-focus-input.ts'
|
||||
import { createGlobalTestConfig } from '@core-test/create-global-test-config.ts'
|
||||
import { mount } from '@vue/test-utils'
|
||||
import { h } from 'vue'
|
||||
|
||||
beforeEach(() => {
|
||||
localStorage.clear()
|
||||
})
|
||||
|
||||
function mountPanel({ hasSelection }: { hasSelection: boolean }) {
|
||||
localStorage.setItem('panel.locked', 'false')
|
||||
|
||||
return mount(VtsSidePanel, {
|
||||
props: { hasSelection, persistent: true },
|
||||
slots: { default: () => h('input') },
|
||||
global: createGlobalTestConfig(),
|
||||
attachTo: document.body,
|
||||
})
|
||||
}
|
||||
|
||||
it('lets the focus into a panel that a selection expands', () => {
|
||||
expect(canFocusInput(mountPanel({ hasSelection: true }))).toBe(true)
|
||||
})
|
||||
|
||||
it('keeps the focus out of a collapsed panel', () => {
|
||||
expect(canFocusInput(mountPanel({ hasSelection: false }))).toBe(false)
|
||||
})
|
||||
|
||||
it('lets the focus in once a selection expands the panel', async () => {
|
||||
const wrapper = mountPanel({ hasSelection: false })
|
||||
|
||||
await wrapper.setProps({ hasSelection: true })
|
||||
|
||||
expect(canFocusInput(wrapper)).toBe(true)
|
||||
})
|
||||
@@ -1,6 +1,6 @@
|
||||
<!-- v5 -->
|
||||
<template>
|
||||
<div class="vts-side-panel" :class="{ mobile: uiStore.isSmall }">
|
||||
<div class="vts-side-panel" :class="{ mobile: uiStore.isSmall }" :inert="!panelStore.isExpanded">
|
||||
<VtsResizeHandle v-if="showResizeHandle" position="start" :resizable="panelStore" />
|
||||
<VtsPanel
|
||||
:closable="isClosable"
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<template>
|
||||
<UiInfo
|
||||
v-tooltip="iconOnly ? currentStatus.text : false"
|
||||
class="vts-status"
|
||||
:accent="currentStatus.accent"
|
||||
:role="iconOnly ? 'img' : undefined"
|
||||
:aria-label="iconOnly ? currentStatus.text : undefined"
|
||||
@@ -73,3 +74,13 @@ const currentStatus = useMapper<Status, { text: string; accent: InfoAccent }>(
|
||||
false
|
||||
)
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
.ui-info.vts-status {
|
||||
align-items: center;
|
||||
|
||||
:deep(.icon) {
|
||||
transform: none;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<!-- v9 -->
|
||||
<template>
|
||||
<div class="ui-checkbox">
|
||||
<label :class="classNames" class="checkbox-label" v-bind="wrapperAttrs">
|
||||
<label :class="[classNames, { 'has-label': slots.default }]" class="checkbox-label" v-bind="wrapperAttrs">
|
||||
<input
|
||||
v-model="checkboxModel"
|
||||
:disabled="isDisabled"
|
||||
@@ -79,6 +79,14 @@ const attrs = useAttrs()
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
|
||||
&.has-label {
|
||||
align-items: flex-start;
|
||||
|
||||
.fake-checkbox {
|
||||
margin-block-start: 0.4rem;
|
||||
}
|
||||
}
|
||||
|
||||
.fake-checkbox {
|
||||
--checkbox-mark-color: var(--color-neutral-background-primary);
|
||||
position: relative;
|
||||
|
||||
@@ -36,13 +36,14 @@ const isDisabled = useDisabled(() => disabled)
|
||||
.ui-radio-button {
|
||||
--radio-dot-color: var(--color-neutral-background-primary);
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
align-items: flex-start;
|
||||
gap: 0.8rem;
|
||||
|
||||
.radio {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
flex-shrink: 0;
|
||||
margin-block-start: 0.4rem;
|
||||
border-radius: 50%;
|
||||
color: var(--radio-color);
|
||||
transition:
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useTimestamp } from '@vueuse/core'
|
||||
import { createSharedComposable, useTimestamp } from '@vueuse/core'
|
||||
import { computed, type MaybeRefOrGetter, toValue } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
@@ -23,12 +23,15 @@ const timeThresholds: TimeThreshold[] = [
|
||||
[Infinity, 'year'],
|
||||
]
|
||||
|
||||
// One timer for all the users, which can be a list of a thousand items. It stops when the last user is unmounted
|
||||
const useSharedTimestamp = createSharedComposable(() => useTimestamp({ interval: 1000 }))
|
||||
|
||||
export function useTimeAgo(referenceDate: MaybeRefOrGetter<Date | number | string>) {
|
||||
const { locale } = useI18n()
|
||||
|
||||
const formatter = computed(() => new Intl.RelativeTimeFormat(locale.value, { numeric: 'auto' }))
|
||||
|
||||
const now = useTimestamp({ interval: 1000 })
|
||||
const now = useSharedTimestamp()
|
||||
|
||||
const referenceTime = computed(() => new Date(toValue(referenceDate)).getTime())
|
||||
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import { useTimeAgo } from '@core/composables/locale-time-ago.composable.ts'
|
||||
import { mountComposable } from '@core-test/mount-composable.ts'
|
||||
import { nextTick } from 'vue'
|
||||
|
||||
const NOW = new Date('2026-01-01T12:00:00Z').getTime()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers({ now: NOW })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
function mountTimeAgo(referenceDate: number) {
|
||||
return mountComposable(() => ({ timeAgo: useTimeAgo(referenceDate) })).wrapper
|
||||
}
|
||||
|
||||
it('formats the time elapsed since the reference date', () => {
|
||||
expect(mountTimeAgo(NOW - 30_000).vm.timeAgo).toBe('30 seconds ago')
|
||||
expect(mountTimeAgo(NOW - 2 * 60 * 60_000).vm.timeAgo).toBe('2 hours ago')
|
||||
})
|
||||
|
||||
it('updates as time goes by', async () => {
|
||||
const wrapper = mountTimeAgo(NOW - 30_000)
|
||||
|
||||
vi.advanceTimersByTime(60_000)
|
||||
await nextTick()
|
||||
|
||||
expect(wrapper.vm.timeAgo).toBe('1 minute ago')
|
||||
})
|
||||
|
||||
it('shares one timer between all its users, until the last one is unmounted', () => {
|
||||
const timerCount = vi.getTimerCount()
|
||||
|
||||
const first = mountTimeAgo(NOW)
|
||||
|
||||
expect(vi.getTimerCount()).toBe(timerCount + 1)
|
||||
|
||||
const second = mountTimeAgo(NOW)
|
||||
|
||||
expect(vi.getTimerCount()).toBe(timerCount + 1)
|
||||
|
||||
first.unmount()
|
||||
|
||||
expect(vi.getTimerCount()).toBe(timerCount + 1)
|
||||
|
||||
second.unmount()
|
||||
|
||||
expect(vi.getTimerCount()).toBe(timerCount)
|
||||
})
|
||||
@@ -0,0 +1,10 @@
|
||||
import { useOverlay } from '@core/packages/overlay/use-overlay.ts'
|
||||
|
||||
export function useErrorModal() {
|
||||
return useOverlay({
|
||||
component: () => import('@core/components/modal/VtsErrorModal.vue'),
|
||||
events: {
|
||||
onClose: true,
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -95,7 +95,7 @@ function handleBackdropClick() {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-x: hidden;
|
||||
overflow-x: clip;
|
||||
}
|
||||
|
||||
.header {
|
||||
|
||||
@@ -1049,7 +1049,6 @@
|
||||
"s3-endpoint-sample": "مثال: s3.us-west-1.amazonaws.com",
|
||||
"scan-pifs": "فحص PIF",
|
||||
"schedule": "الجدول الزمني",
|
||||
"schedules": "الجداول الزمنية",
|
||||
"secret": "السر",
|
||||
"secure-boot": "الإقلاع الآمن",
|
||||
"see-details": "عرض التفاصيل",
|
||||
|
||||
@@ -1190,7 +1190,6 @@
|
||||
"s3-endpoint-sample": "Příklad: s3.us-west-1.amazonaws.com",
|
||||
"scan-pifs": "Skenovat fyzická rozhraní",
|
||||
"schedule": "Plán",
|
||||
"schedules": "Plány",
|
||||
"secret": "Tajemství",
|
||||
"secure-boot": "Secure boot",
|
||||
"see-details": "Viz podrobnosti",
|
||||
|
||||
@@ -1117,7 +1117,6 @@
|
||||
"s3-endpoint-sample": "Eksempel: s3.us-west-1.amazonaws.com",
|
||||
"scan-pifs": "Skan PIF'er",
|
||||
"schedule": "Tidsplan",
|
||||
"schedules": "Tidsplaner",
|
||||
"secret": "Hemmelighed",
|
||||
"secure-boot": "Secure boot",
|
||||
"see-details": "Se detaljer",
|
||||
|
||||
@@ -745,7 +745,6 @@
|
||||
"s3-backup-repository": "S3-Backupdepot",
|
||||
"scan-pifs": "PIFs scannen",
|
||||
"schedule": "Zeitplan",
|
||||
"schedules": "Zeitpläne",
|
||||
"secure-boot": "Secure Boot",
|
||||
"see-details": "Details anzeigen",
|
||||
"select-compression": "Kompression auswählen",
|
||||
|
||||
@@ -1065,6 +1065,7 @@
|
||||
"multi-pathing": "Multi-pathing",
|
||||
"multiple-schedules": "Multiple schedules",
|
||||
"multiple-schedules-advice": "We advise splitting a backup job with multiple schedules into multiple backup jobs with one schedule each.",
|
||||
"multiple-schedules-split-in-xo5": "Multiple schedules: split into one job per schedule in XO 5",
|
||||
"must-be-at-least-n": "Must be at least {n}.",
|
||||
"n-blocking": "1 blocking | {n} blocking",
|
||||
"n-bonded-networks": "1 bonded network | {n} bonded networks",
|
||||
@@ -1507,7 +1508,6 @@
|
||||
"save-xo-config": "Save XO config",
|
||||
"scan-pifs": "Scan PIFs",
|
||||
"schedule": "Schedule",
|
||||
"schedules": "Schedules",
|
||||
"scope": "Scope",
|
||||
"scope-preview": "Scope preview",
|
||||
"scope-type": "Scope type",
|
||||
@@ -1566,6 +1566,7 @@
|
||||
"snapshot-mode:with-memory-description": "Includes the VM's memory state. The VM will be briefly suspended during the snapshot.",
|
||||
"snapshot-revert-snapshot-before": "Take a snapshot of the VM before reverting",
|
||||
"snapshot-revert-warning": "This will restore the VM to the selected snapshot state. Any changes made since then (data, configuration, and disk state) will be lost. This action cannot be undone.",
|
||||
"snapshot-settings-disabled-offline-backup": "Snapshot settings are disabled because offline backup shuts down the VMs instead of taking a snapshot.",
|
||||
"snapshot-synchronisation": "Snapshot synchronisation",
|
||||
"snapshot-vdis": "Snapshot VDIs",
|
||||
"snapshots": "Snapshots",
|
||||
|
||||
@@ -817,7 +817,6 @@
|
||||
"s3-backup-repository": "Repositorio S3 de salvaguardas",
|
||||
"scan-pifs": "Escanear PIFs",
|
||||
"schedule": "Planificación",
|
||||
"schedules": "Planificaciones",
|
||||
"secure-boot": "Arranque seguro",
|
||||
"see-details": "Ver detalles",
|
||||
"select-compression": "Elige modo de compression",
|
||||
|
||||
@@ -1049,7 +1049,6 @@
|
||||
"s3-endpoint-sample": "مثال: s3.us-west-1.amazonaws.com",
|
||||
"scan-pifs": "اسکن PIFها",
|
||||
"schedule": "زمانبندی",
|
||||
"schedules": "زمانبندیها",
|
||||
"secret": "رمز",
|
||||
"secure-boot": "بوت امن",
|
||||
"see-details": "مشاهده جزئیات",
|
||||
|
||||
@@ -1049,7 +1049,6 @@
|
||||
"s3-endpoint-sample": "Esimerkki: s3.us-west-1.amazonaws.com",
|
||||
"scan-pifs": "Skannaa PIF:t",
|
||||
"schedule": "Aikataulu",
|
||||
"schedules": "Aikataulut",
|
||||
"secret": "Salaisuus",
|
||||
"secure-boot": "Suojattu käynnistys",
|
||||
"see-details": "Katso tiedot",
|
||||
|
||||
@@ -1065,6 +1065,7 @@
|
||||
"multi-pathing": "Multi-pathing",
|
||||
"multiple-schedules": "Plusieurs planifications",
|
||||
"multiple-schedules-advice": "Nous vous conseillons de diviser un job de sauvegarde à plusieurs planifications en plusieurs jobs ayant chacun une seule planification.",
|
||||
"multiple-schedules-split-in-xo5": "Plusieurs planifications : diviser en un job par planification dans XO 5",
|
||||
"must-be-at-least-n": "Doit être au moins {n}.",
|
||||
"n-blocking": "0 bloquante | 1 bloquante | {n} bloquantes",
|
||||
"n-bonded-networks": "1 réseau lié | {n} réseaux liés",
|
||||
@@ -1507,7 +1508,6 @@
|
||||
"save-xo-config": "Sauvegarder la config XO",
|
||||
"scan-pifs": "Scan PIFs",
|
||||
"schedule": "Planification",
|
||||
"schedules": "Planifications",
|
||||
"scope": "Périmètre",
|
||||
"scope-preview": "Aperçu du périmètre",
|
||||
"scope-type": "Type de périmètre",
|
||||
@@ -1566,6 +1566,7 @@
|
||||
"snapshot-mode:with-memory-description": "Inclut l'état de la mémoire de la VM. La VM sera brièvement suspendue pendant le snapshot.",
|
||||
"snapshot-revert-snapshot-before": "Créer un instantané de la VM avant la restauration",
|
||||
"snapshot-revert-warning": "La VM sera restaurée à l'état de l'instantané sélectionné. Tous les changements effectués depuis (données, configuration et état des disques) seront perdus. Cette action est irréversible.",
|
||||
"snapshot-settings-disabled-offline-backup": "Les paramètres de snapshot sont désactivés car la sauvegarde hors ligne éteint les VMs au lieu de faire un snapshot.",
|
||||
"snapshot-synchronisation": "Synchronisation des snapshots",
|
||||
"snapshot-vdis": "VDIs snapshot",
|
||||
"snapshots": "Instantanés",
|
||||
|
||||
@@ -1049,7 +1049,6 @@
|
||||
"s3-endpoint-sample": "Esempio: s3.us-west-1.amazonaws.com",
|
||||
"scan-pifs": "Scansiona PIF",
|
||||
"schedule": "Pianificazione",
|
||||
"schedules": "Pianificazioni",
|
||||
"secret": "Segreto",
|
||||
"secure-boot": "Secure boot",
|
||||
"see-details": "Vedi i dettagli",
|
||||
|
||||
@@ -1049,7 +1049,6 @@
|
||||
"s3-endpoint-sample": "例: s3.us-west-1.amazonaws.com",
|
||||
"scan-pifs": "PIF をスキャン",
|
||||
"schedule": "スケジュール",
|
||||
"schedules": "スケジュール",
|
||||
"secret": "シークレット",
|
||||
"secure-boot": "セキュアブート",
|
||||
"see-details": "詳細を表示",
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user