Compare commits

..

39 Commits

Author SHA1 Message Date
Pavel Borecki
aadbb6b082 feat(web-stack/i18n): update Czech 2026-12-04 20:12:10 +00:00
Joris K
7c91201a13 feat(lite): align the VMs tables and the VM actions with XO 6 (#10936) 2026-12-04 18:30:16 +01:00
Mathieu
7ce3ab25b4 feat(rest-api): handle RBAC in SSE stream (#10640)
* feat(rest-api): handle RBAC in SSE stream
2026-12-04 17:10:52 +01:00
Alex Castillo González
1ac19fa505 fix(backups/merge-worker): don't exit when a queued task is already removed (#10763) 2026-12-04 16:56:28 +01:00
amouillard-vates
61ca0dc276 feat(xo6): sr dedicated page vdis tab (#10142)
* feat(xo6): sr dedicated page vdis tab

* Add tests

* Share findTabs helper

* Fix changelog

* Remove useless comments

* Uniform context check

* Rename VdiVmLinks to VmLinksList

* Refactor fromContext as computed

* Move vmNames to composable

* Rename sidepanel cards

* Add tests

* Add tests + rewrite clearer doc

* Use new UiLinkList

* Guidelines fix

* Share VDI page context checks and VM icon logic

Extract the fromContext comparisons repeated across the VDI table, side panel
cards, detail configuration and breadcrumb into useVdiPageContext, and reuse
getVmIcon in VmLinkList (which also adds the busy state).

* Add SR link to the VDI breadcrumb

From the SR context, the VDI page breadcrumb now links the SR to its VDIs tab,
in the scope of its pool.

* Update VDI tests

Cover the SR breadcrumb link, the VDI side panel, useVdiPageContext and the VmLinkList busy icon, and share the
VDI configuration collection mocks between the composable and card tests.

* Review fixes
2026-12-04 16:24:23 +01:00
Enée DI IORIO
916af50a24 feat(web-core): add UiAccordion compound components (#9446) 2026-12-04 15:56:52 +01:00
Joris K
9c4d46b4e2 feat(web-core): collapse the table actions into a menu when they overflow (#10992) 2026-12-04 15:55:56 +01:00
spacotte-vates
5a396dee40 feat(rest-api): add support for deprecated decorator for registerResrRoutes (#10990) 2026-12-04 12:00:51 +01:00
Joris K
51e28ac007 feat(lite): 0.28.1 (#10988) 2026-12-04 10:49:35 +01:00
Marie Garde
2e5fd612e1 feat(lite): Add disable reason on lite fields (#10963)
* feat(lite): Add disable reason on lite fields

* fix changelog
2026-12-04 10:41:42 +01:00
Marie Garde
f9fc483115 feat(xo6): add disable reason in XO6 (#10962)
* add disable reason for xo6

* fix test

* update best practice

* refacto for PR
2026-12-04 10:28:24 +01:00
Marie Garde
6d42a4e3d7 feat(web-core): add disable reason on DS (#10958)
* feat(xo6): add disable reason on DS

* add changelog

* fix aria describe by
2026-12-04 10:12:22 +01:00
spacotte-vates
6a222f2bb0 fix(xo-server): keep server statuses in sync with the live connections (#10834)
* fix(xo-server): keep server statuses in sync with the live connections

* fix review Ayoub

* fix rebase

* fix review mpiton

* Add missing bugfix in changelog

---------

Co-authored-by: Mathieu Piton <mathieu.piton@vates.tech>
2026-12-04 08:15:21 +01:00
spacotte-vates
5b854557e9 feat(backups): add sizeOnDisk for backup archives (#10685)
* feat(backups): add size on disk info for backup archives

* finish work

* update changelog

* first round of fixes

* add isDifferencing

* fix review Ayoub & Florent

* fix comment Florent

* fix review Ayoub & Florent

* fix rebase

* fix review Florent & Ayoub
2026-12-03 17:48:48 +01:00
Florent BEAUCHAMP
90cd1de6a2 feat(xo6): show backup and v2v speed in tasks (#10798)
* feat(backups,xo6): show the reading speed of tasks

Each source (disk, XVA) is read once whatever the number of writers, in its
own `read` subtask reporting its current speed, in bytes per second, in the
`speed` property.

xo6 shows the current reading speed of a running task: its own one, or the
sum of the ones of its running subtasks.
2026-12-03 17:20:22 +01:00
Joris K
62dcf1c0ca feat(xo6/tasks): filter the task lists with the query builder (#10972) 2026-12-03 16:54:12 +01:00
Olivier Lambert
0e5353a4c8 feat(rest-api): add vms/:id/actions/convert_to_template route (#10661) 2026-12-03 15:21:31 +01:00
Joris K
157be98c91 fix(web-core): show the query builder filter menus above its modal (#10975) 2026-12-03 12:11:05 +01:00
Joris K
9f568d0893 feat(lite): add SSH enable and disable actions for XCP-ng 9 hosts (#10974) 2026-12-03 11:37:16 +01:00
Alina D
b890851a31 feat(lite): add VIF page and link to it from Network tab (#10686)
Co-authored-by: Joris-K <joris.kosacki@vates.tech>
Co-authored-by: Joris K <43381087+J0ris-K@users.noreply.github.com>
2026-12-03 09:36:13 +01:00
Sylvère
22bcc37439 feat(web-core): add an optional details log viewer to the error modal (#10536) 2026-12-03 08:28:39 +01:00
Joris K
5ca2958d2a fix(web-core): stop the page sliding sideways to closed side panels (#10973) 2026-12-02 17:55:29 +01:00
Killian
205ae67940 docs(backups): add a procedure to repair a broken incremental chain (#10966)
* docs(backups): add a procedure to repair a broken incremental chain

No page told users what to do when a delta backup chain is broken on the
backup repository (a disk file missing or unreadable).

The new page works from the web interface and the REST API only, so it
applies to an air-gapped XOA. It starts from the job log's Clean VM
directory warnings, then relies on what each run already does since
XO 5.100.0: delete the broken restore points and fall back to a full
when no valid base is left. The manual steps (reclaim-space through the
REST API or Delete backups in XO 5, then a forced full) cover what that
run doesn't: failing runs, and corrupted data the header check misses.

The two new screenshots were taken on a chain broken on purpose. The
troubleshooting page links the procedure from the unexpected full
export section.
2026-12-02 17:33:30 +01:00
Florent BEAUCHAMP
addfdd5475 fix(vmware-explorer): detect secure boot -improve snapshots for esxi6 (#10968)
* fix(vmware-explorer): detect secure boot for esxi6

* changelog

* fix: improve compatibility with automatic snapshot
2026-12-02 15:43:36 +01:00
spacotte-vates
5512fc65a6 feat(acl): resolve selectors on partial objects (#10731)
* feat(complex-matcher): throw when unknown state

* update changelog

* lil fixes

* fix review Killian

* move code from package/complex-matcher to xen-orchestra/acl

* fix review MathieuRA

* improve comment
2026-12-02 12:27:06 +01:00
Marie Garde
1f8f265afc fix(xo5): fix crash on metadata job with all objects (#10933)
* fix(xo5): fix crash on metadata job with all objects

* fix changelog

* rebase ok
2026-12-02 10:59:48 +01:00
Marie Garde
c0e7843274 feat(xo6): fix style backup job form (#10940)
* wip

* fix style on form

* fix checkbox and radio button in DS

* fix pipeline

* fix tests

* remove version DS

* edit style

* fix tests

* fix build

* fix changelog
2026-12-02 10:23:22 +01:00
Marie Garde
c893471c5e fix(xo6): Fix header menu pool (#10897)
* fix(xo6): Fix header menu pool

* rebase ok

* fix changelog
2026-12-02 09:31:17 +01:00
Sebastien Marie
6f91a90299 fix(xo-server-sdn-controller): set up the SDN controller on network rules too (#10917) 2026-12-01 18:14:57 +01:00
Florent BEAUCHAMP
41b290f166 fix(backups): correctly cleanup snapshot of diskless VM with a CDROM (#10789)
* fix(backups): correctly cleanup snapshot of diskless VM with a CDROM
* fix: correctly cleanup the snapshots even when switching from vm based to vdi based retention
2026-12-01 16:14:07 +01:00
Alina D
2475403b11 feat(lite): add possibility to delete a VIF (#10726) 2026-12-01 13:21:55 +01:00
MikitaKavaliouVates
0ae5d39aa5 feat(@vates/task, xapi, backups, xo-server, backup-reports): abort backup jobs running in the main thread (#10875)
BREAKING CHANGE: a subtask created under an aborted task no longer runs, unless it is created with
`cleanup: true`.

🔗 XO-3352

With backups.disableWorkers, a backup job could not be stopped. It can now be aborted from its task, the "run schedule" action or job.cancel: the transfers stop, the cleanup still runs and the run ends interrupted.

@vates/task: the new root option skipSubtasksAfterAbort skips the steps of an aborted task, except cleanup: true ones. Only backups use it.
Fixes the VM directory lock not being released after a failed transfer.
2026-12-01 11:52:21 +01:00
Sylvère
77b00ff871 feat(lite): 0.28.0 (#10951) 2026-12-01 08:22:41 +01:00
Sylvère
ed86fbec17 feat: release 6.11 (#10949) 2026-11-30 17:01:05 +01:00
Sylvère
1e6a049072 feat: technical release (#10946) 2026-11-30 14:26:35 +01:00
Mathieu
032159a609 feat(rest-api): CSRF middleware protection (#10945)
* feat: add CSRF protection middleware

* feat: scope urlencode middleware to signin routes

* feat: cookie sameSite default to lax

* changelog

---------

Co-authored-by: MathieuRA <contact@mathieu-raisin.fr>
2026-11-30 13:50:38 +01:00
Mathieu
a5295c6731 fix(auth-ldap): block LDAP unauthenticated bind via null password in session.signIn (#10944)
A JSON `null` password sent to `session.signIn` reached the LDAP provider,
which passed it to `client.bind()`. ldapts turns this into an LDAP
unauthenticated bind (DN + empty password), which some directories, such as
Active Directory by default, accept as a successful login. Anyone knowing a
username could sign in without its password.

- xo-server-auth-ldap: only bind with non-empty string username and password
- xo-server: reject empty or non-string passwords in `authenticateUser`,
  before any provider is called
- xo-server: add a `params` schema to `session.signIn` so non-string
  credentials are rejected at the API layer

Co-authored-by: Pierre Donias <pierre.donias@vates.tech>
2026-11-30 13:42:17 +01:00
Alex Castillo González
c8260fb259 fix(rest-api): keep colons in the password of Basic authentication (#10801) 2026-11-30 12:07:47 +01:00
Sylvère
756d7fa940 fix(xo6): my tasks optimization (#10935) 2026-11-30 11:11:04 +01:00
503 changed files with 14676 additions and 3080 deletions

View File

@@ -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

View File

@@ -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

View File

@@ -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

View File

@@ -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()

View File

@@ -1,7 +1,7 @@
{
"name": "@vates/types",
"private": false,
"version": "3.1.0",
"version": "3.2.0",
"main": "./dist/index.mjs",
"exports": {
".": {

View File

@@ -53,6 +53,7 @@ export interface BaseRouteDefinition<Middleware> {
endpoint: string
description?: string
tags?: string[]
deprecated?: boolean
params?: Record<string, ParamFieldDefinition>
query?: Record<string, QueryFieldDefinition>
body?: Record<string, FieldDefinition>

View File

@@ -481,6 +481,8 @@ export interface Xapi {
MAC?: string
}
): Promise<XenApiVif['$ref']>
/** ejects all removable media (e.g. CDs) then flags the VM as a template */
VM_convertToTemplate(vmRef: XenApiVm['$ref']): Promise<void>
VM_createCloudInitConfig(
vmRef: XenApiVm['$ref'],
cloudConfig: string,

View File

@@ -193,12 +193,21 @@ export type XoVmBackupArchive = {
id: Branded<'vm-backup-archive'>
type: 'xo-vm-backup'
backupRepository: XoBackupRepository['id']
disks: { id: string; name: string; uuid: XoVdiSnapshot['uuid'] }[]
disks: {
id: string
name: string
uuid: XoVdiSnapshot['uuid']
sizeOnDisk?: number
isDifferencing?: boolean
}[]
isImmutable?: boolean
jobId: XoVmBackupJob['id']
mode: XoVmBackupJob['mode']
scheduleId: XoSchedule['id']
/** Transferred size */
size: number
/** Space used on the backup repository, if known */
sizeOnDisk?: number
timestamp: number
vm: {
uuid: XoVm['uuid']
@@ -209,6 +218,7 @@ export type XoVmBackupArchive = {
differencingVhds?: number
dynamicVhds?: number
withMemory: boolean
tags: string[]
}
type XoMetadataBackupArchive = {

View File

@@ -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"

View File

@@ -1,5 +1,6 @@
export default {
clone: true,
'convert-to-template': true,
delete: true,
export: true,
'migrate-send': true,

View File

@@ -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)
)
}

View File

@@ -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 }))
}

View File

@@ -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', () => {

View File

@@ -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",

View File

@@ -13,6 +13,7 @@ import {
CleanResult,
DEFAULT_MERGE_CONCURRENCY,
DEFAULT_REMOVE_CONCURRENCY,
MergedDisk,
ResolvedBackupCleanOptions,
} from './VmBackup.types.mjs'
import { asyncEach } from '@vates/async-each'
@@ -425,16 +426,19 @@ export class RemoteDiskLineage {
this.#opts.logInfo('Disk chain needs merging', { count: toMerge.length })
}
// mergeTargetPath: final size of the disk everything was merged into
const mergedSizes = new Map<string, number>()
// mergeTargetPath: the disk everything was merged into
const mergedDisks = new Map<string, MergedDisk>()
if (merge) {
const limitedMergeChain = defaultMergeLimiter(this.#mergeChain.bind(this))
const doMerge = async () => {
await asyncEach(
toMerge,
async ({ chain, isResuming }) => {
const { finalDiskSize, mergeTargetPath } = await limitedMergeChain([...chain], isResuming)
mergedSizes.set(mergeTargetPath, (mergedSizes.get(mergeTargetPath) ?? 0) + finalDiskSize)
const { finalSizeOnDisk, mergeTargetPath, streamSize, isDifferencing } = await limitedMergeChain(
[...chain],
isResuming
)
mergedDisks.set(mergeTargetPath, { sizeOnDisk: finalSizeOnDisk, streamSize, isDifferencing })
// parentPath alias deleted by parentDisk.rename(mergeTargetPath)
// intermediates deleted by childDisk.unlink() when removeUnused=true
// Unregister so #cleanOrphanDataFiles does not read already-deleted aliases
@@ -453,19 +457,31 @@ export class RemoteDiskLineage {
await this.#cleanOrphanDataFiles(remove)
const sizeOnDisks = [...mergedDisks.values()].map(({ sizeOnDisk }) => sizeOnDisk)
return {
removedFiles: Array.from(toDelete),
merge: toMerge.length > 0,
size: [...mergedSizes.values()].reduce((total, subSize) => total + subSize, 0),
mergedSizes,
size: sizeOnDisks.reduce<number | undefined>(
(total, subSize) => (total !== undefined && subSize !== undefined ? total + subSize : undefined),
0
),
mergedDisks,
}
}
/**
* Merges ancestors into the active child at the end of the chain.
* Returns the final size of the merge target and its path.
* Returns the final size of the merge target and its path, undefined if unknown.
*/
async #mergeChain(chain: string[], isResuming: boolean): Promise<{ finalDiskSize: number; mergeTargetPath: string }> {
async #mergeChain(
chain: string[],
isResuming: boolean
): Promise<{
finalSizeOnDisk: number | undefined
mergeTargetPath: string
streamSize: number
isDifferencing: boolean
}> {
assert.ok(chain.length >= 2, `look to merge a chain shorter than 2 ${JSON.stringify(chain)}`)
const parentPath = chain[0]
this.#opts.logInfo('merging disk chain', { chain: [...chain] }) // need a copy here to log full chain
@@ -489,8 +505,8 @@ export class RemoteDiskLineage {
force: isResuming,
})
const { finalDiskSize } = (await merger.merge(parentDisk, childDisk!))!
return { finalDiskSize, mergeTargetPath }
const { finalSizeOnDisk, streamSize, isDifferencing } = (await merger.merge(parentDisk, childDisk!))!
return { finalSizeOnDisk, mergeTargetPath, streamSize, isDifferencing }
} finally {
await parentDisk?.close().catch(error => {
this.#opts.logWarn('Error closing parent Disk', error)

View File

@@ -6,7 +6,12 @@ export interface PartialBackupMetadata {
vhds?: Record<string, string>
vdis?: Record<string, unknown>
isVhdDifferencing?: Record<string, boolean>
// Transferred size. A merge only rewrites it, with the merged disks' stream size, when their size on disk is unknown.
size?: number
// Space used by each disk, keyed by vdiRef, updated by merges
vhdsSizeOnDisk?: Record<string, number>
// Space used by the XVA of a full backup, .checksum included
sizeOnDisk?: number
jobId: string
scheduleId: string
timestamp: number
@@ -38,7 +43,7 @@ export type ResolvedBackupCleanOptions = BackupCleanOptions & {
export interface ArchiveCleanOptions {
remove?: boolean
merge?: boolean
mergedSizes?: Map<string, number>
mergedDisks?: Map<string, MergedDisk>
}
export interface CheckResult {
@@ -55,11 +60,11 @@ export interface CheckResult {
export type CleanResult = {
removedFiles: string[]
// Files rewritten in place (e.g. metadata whose size was updated after a merge)
// Files rewritten in place (e.g. metadata recording the size on disk of the disks a merge rewrote)
changedFiles?: string[]
merge?: boolean
size?: number
mergedSizes?: Map<string, number>
mergedDisks?: Map<string, MergedDisk>
}
export interface VmBackupInterface {
@@ -74,3 +79,9 @@ export interface VmBackupInterface {
clean(opts?: ArchiveCleanOptions): Promise<CleanResult>
getAssociatedFiles(opts: object): Array<string>
}
export type MergedDisk = {
sizeOnDisk: number | undefined
streamSize: number
isDifferencing: boolean
}

View File

@@ -13,6 +13,7 @@ import {
PartialBackupMetadata,
ResolvedBackupCleanOptions,
DEFAULT_MERGE_CONCURRENCY,
MergedDisk,
} from './VmBackup.types.mjs'
import { cleanOrphanDiskDirs } from '@xen-orchestra/backup-archive/disks'
import { asyncEach } from '@vates/async-each'
@@ -138,19 +139,19 @@ export class VmBackupDirectory implements VmBackupInterface {
let someLineageMergedOrShouldBe = false
// Merge/delete orphan disks in VDI directories covered by archives; collect merged sizes per disk path
const allMergedSizes = new Map<string, number>()
const allMergedDisks = new Map<string, MergedDisk>()
await asyncEach(
Array.from(this.#uniqueLineages!.entries()),
async ([_vdiDir, lineage]) => {
const { mergedSizes, removedFiles, merge: hasPendingMerge } = await lineage.clean({ remove, merge })
const { mergedDisks, removedFiles, merge: hasPendingMerge } = await lineage.clean({ remove, merge })
if (removedFiles.length > 0) {
cacheNeedsRegen = true
}
if (hasPendingMerge) {
someLineageMergedOrShouldBe = true
}
for (const [diskPath, size] of mergedSizes || []) {
allMergedSizes.set(diskPath, (allMergedSizes.get(diskPath) ?? 0) + size)
for (const [diskPath, mergedDisk] of mergedDisks || []) {
allMergedDisks.set(diskPath, mergedDisk)
}
},
{ concurrency: DEFAULT_MERGE_CONCURRENCY }
@@ -174,7 +175,7 @@ export class VmBackupDirectory implements VmBackupInterface {
async ([metadataPath, archive]: [string, VmBackupInterface]) => {
const { removedFiles, changedFiles: archiveChangedFiles } = await archive.clean({
remove,
mergedSizes: allMergedSizes,
mergedDisks: allMergedDisks,
})
if (removedFiles.length > 0) {
cacheNeedsRegen = true
@@ -194,7 +195,7 @@ export class VmBackupDirectory implements VmBackupInterface {
this.backupArchives.delete(metadataPath)
}
if (this.#cacheExisted && (allMergedSizes.size > 0 || cacheNeedsRegen || this.#cacheOutOfSync)) {
if (this.#cacheExisted && (allMergedDisks.size > 0 || cacheNeedsRegen || this.#cacheOutOfSync)) {
await this.#regenerateCache()
}
@@ -216,7 +217,12 @@ export class VmBackupDirectory implements VmBackupInterface {
{ concurrency: 2 }
)
}
const size = [...allMergedSizes.values()].reduce((total, merged) => total + merged, 0)
const sizeOnDisks = [...allMergedDisks.values()].map(({ sizeOnDisk }) => sizeOnDisk)
const size = sizeOnDisks.reduce<number | undefined>(
(total, merged) => (total !== undefined && merged !== undefined ? total + merged : undefined),
0
)
// `removedFiles` lists the files this run removed, or would have removed if `remove` were set:
// root-level orphans plus the files each archive deemed removable (e.g. the metadata of an
// incomplete backup). Callers acting on it must therefore check `remove` themselves.

View File

@@ -14,11 +14,13 @@ import { RemoteVhdDisk } from '../dist/disks/RemoteVhdDisk.mjs'
import { MergeRemoteDisk } from '../dist/disks/MergeRemoteDisk.mjs'
/* eslint-enable n/no-missing-import */
import { VHDFOOTER, VHDHEADER } from './tests.fixtures.mjs'
import { VhdFile, Constants, VhdDirectory, VhdAbstract } from 'vhd-lib'
import { VhdFile, Constants, VhdDirectory, VhdAbstract, openVhd } from 'vhd-lib'
import Disposable from 'promise-toolbox/Disposable'
import { dirname, basename } from 'node:path'
import { promisify } from 'node:util'
import zlib from 'node:zlib'
import { rimraf } from 'rimraf'
import { isVhdAlias, resolveVhdAlias } from 'vhd-lib/aliases.js'
const { beforeEach, afterEach, describe } = test
@@ -51,6 +53,42 @@ afterEach(async () => {
const uniqueId = () => uuid.v1()
const uniqueIdBuffer = () => uuid.v1({}, Buffer.alloc(16))
// sum of the stored size of every file under `entry`, the reference `VhdDirectory#sizeOnDisk` is checked against
async function getFullSize(entry) {
let files
try {
files = await handler.list(entry, { prependDir: true })
} catch (error) {
if (error.code === 'ENOTDIR') {
return await handler.getSizeOnDisk(entry)
} else {
throw error
}
}
let size = 0
for (const file of files) {
size += await getFullSize(file)
}
return size
}
async function getDiskSizeOnDisk(diskPath) {
if (isVhdAlias(diskPath)) {
return (await getFullSize(await resolveVhdAlias(handler, diskPath))) + (await handler.getSizeOnDisk(diskPath))
}
return getFullSize(diskPath)
}
async function getDiskStreamSize(diskPath) {
return Disposable.use(openVhd(handler, diskPath), async vhd => {
await vhd.readBlockAllocationTable()
return vhd.streamSize()
})
}
async function generateVhd(path, opts = {}) {
let vhd
@@ -336,7 +374,7 @@ test('it merges delta of non destroyed chain', async () => {
`${rootPath}/metadata.json`,
JSON.stringify({
mode: 'delta',
size: 12000, // a size too small
size: 12000,
vhds: [
`${relativePath}/grandchild.vhd`, // grand child should not be merged
`${relativePath}/child.vhd`,
@@ -381,7 +419,152 @@ test('it merges delta of non destroyed chain', async () => {
assert.equal(remainingVhds.includes('grandchild.vhd'), true)
const metadata = JSON.parse(await handler.readFile(`${rootPath}/metadata.json`))
assert.equal(metadata.size, 4299776, 'metadata.size should be updated after merge')
assert.equal(metadata.size, 12000, 'metadata.size should not change')
assert.equal(
metadata.vhdsSizeOnDisk['1'],
await getDiskSizeOnDisk(`${basePath}/child.vhd`),
'vhdsSizeOnDisk should contain the size of the child'
)
assert.equal(
metadata.vhdsSizeOnDisk['0'],
undefined,
'vhdsSizeOnDisk should not contain the size of the grandchild as it was not measured'
)
})
// a backup of two disks: `a` has an orphan parent to merge, `b` has nothing to merge
//
// with `mode: 'directory'`, the disks of `a` are aliased VHD directories written without size.json:
// their size on disk is unknown
async function writeBackupWithOneDiskToMerge(metadata, { mode } = {}) {
const useAlias = mode === 'directory'
const suffix = useAlias ? '.alias.vhd' : ''
const orphan = await generateVhd(`${basePath}/orphan.vhd`, { mode, useAlias })
await generateVhd(`${basePath}/child.vhd`, {
mode,
useAlias,
header: {
parentUnicodeName: `orphan.vhd${suffix}`,
parentUuid: orphan.footer.uuid,
},
blocks: [0, 1],
})
await generateVhd(`${basePath2}/disk.vhd`)
await handler.writeFile(
`${rootPath}/metadata.json`,
JSON.stringify({
mode: 'delta',
size: 12000,
vhds: { a: `${relativePath}/child.vhd${suffix}`, b: `${relativePath2}/disk.vhd` },
...metadata,
})
)
await VmBackupDirectory.cleanVm(handler, rootPath, {
remove: true,
merge: true,
logInfo: () => {},
logWarn: () => {},
})
return JSON.parse(await handler.readFile(`${rootPath}/metadata.json`))
}
test('it only updates the size on disk of the merged disks', async () => {
// fake values, which cannot be mistaken for a real size
const metadata = await writeBackupWithOneDiskToMerge({ vhdsSizeOnDisk: { a: 1, b: 2 } })
assert.equal(metadata.size, 12000, 'metadata.size should not change')
assert.equal(metadata.vhdsSizeOnDisk.a, await getDiskSizeOnDisk(`${basePath}/child.vhd`))
assert.equal(metadata.vhdsSizeOnDisk.b, 2, 'the size on disk of a disk which has not been merged should not change')
})
test('it only marks the merged disks as not differencing', async () => {
const metadata = await writeBackupWithOneDiskToMerge({
isVhdDifferencing: { a: true, b: true },
vdis: { a: {}, b: {} },
})
assert.equal(metadata.isVhdDifferencing.a, false)
assert.equal(
metadata.isVhdDifferencing.b,
true,
'the isVhdDifferencing of a disk which has not been merged should not change'
)
})
test('it records the size on disk of the merged disks of a backup without any', async () => {
// a backup written before the size on disk was recorded
const metadata = await writeBackupWithOneDiskToMerge({})
assert.equal(metadata.size, 12000, 'metadata.size should not change')
assert.deepEqual(metadata.vhdsSizeOnDisk, { a: await getDiskSizeOnDisk(`${basePath}/child.vhd`) })
})
test('it forgets the size on disk of a merged disk whose size is unknown', async () => {
// fake values: the one of `a` would be stale after the merge, which adds the blocks of its parent
const metadata = await writeBackupWithOneDiskToMerge({ vhdsSizeOnDisk: { a: 1, b: 2 } }, { mode: 'directory' })
assert.deepEqual(
metadata.vhdsSizeOnDisk,
{ b: 2 },
'the size on disk of a merged disk should be removed when unknown, the others should not change'
)
})
test('it records the stream size of the merged disks in size when a size on disk is unknown', async () => {
// a chain started before the size on disk was recorded: the backup usage falls back to `size`
const metadata = await writeBackupWithOneDiskToMerge({}, { mode: 'directory' })
assert.equal(
metadata.size,
await getDiskStreamSize(`${basePath}/child.vhd.alias.vhd`),
'metadata.size should be the stream size of the merged disk, which now contains the blocks of its parent'
)
})
test('it keeps differencing a disk merged in the middle of a chain', async () => {
// ancestor -> orphan -> child: the ancestor is still used by an older backup, only the orphan is merged
const ancestor = await generateVhd(`${basePath}/ancestor.vhd`, { blocks: [0] })
const orphan = await generateVhd(`${basePath}/orphan.vhd`, {
header: { parentUnicodeName: 'ancestor.vhd', parentUuid: ancestor.footer.uuid },
blocks: [1],
})
await generateVhd(`${basePath}/child.vhd`, {
header: { parentUnicodeName: 'orphan.vhd', parentUuid: orphan.footer.uuid },
blocks: [2],
})
await handler.writeFile(
`${rootPath}/older.json`,
JSON.stringify({ mode: 'delta', size: 12000, vhds: { a: `${relativePath}/ancestor.vhd` } })
)
await handler.writeFile(
`${rootPath}/metadata.json`,
JSON.stringify({
mode: 'delta',
size: 12000,
vhds: { a: `${relativePath}/child.vhd` },
vdis: { a: {} },
isVhdDifferencing: { a: true },
})
)
await VmBackupDirectory.cleanVm(handler, rootPath, {
remove: true,
merge: true,
logInfo: () => {},
logWarn: () => {},
})
const remainingVhds = await handler.list(basePath)
assert.equal(remainingVhds.includes('orphan.vhd'), false, 'the orphan should have been merged')
assert.equal(remainingVhds.includes('ancestor.vhd'), true, 'the ancestor is still used and should not be merged')
const metadata = JSON.parse(await handler.readFile(`${rootPath}/metadata.json`))
assert.equal(metadata.isVhdDifferencing.a, true, 'the merged disk still has the ancestor as parent')
})
test('it merges a chain of multiple consecutive orphan ancestors in one pass', async () => {
@@ -727,8 +910,28 @@ describe('tests multiple combination ', { concurrency: 1 }, () => {
await VmBackupDirectory.cleanVm(handler, rootPath, { remove: true, merge: true, logWarn: () => {} })
const metadata = JSON.parse(await handler.readFile(`${rootPath}/metadata.json`))
// size should be the size of children + grand children + clean after the merge
assert.deepEqual(metadata.size, 6501888)
// merges record the size on disk of the disks they merged into, child and clean.
// Directory disks without `size.json` stay unknown, so size falls back to their stream size
assert.equal(
metadata.size,
vhdMode === 'directory'
? (await getDiskStreamSize(`${basePath}/child.vhd.alias.vhd`)) +
(await getDiskStreamSize(`${basePath}/clean.vhd.alias.vhd`))
: undefined
)
assert.equal(
metadata.vhdsSizeOnDisk['1'],
vhdMode === 'directory'
? undefined
: await getDiskSizeOnDisk(`${basePath}/child.vhd${useAlias ? '.alias.vhd' : ''}`)
)
assert.equal(
metadata.vhdsSizeOnDisk['2'],
vhdMode === 'directory'
? undefined
: await getDiskSizeOnDisk(`${basePath}/clean.vhd${useAlias ? '.alias.vhd' : ''}`)
)
assert.equal(metadata.vhdsSizeOnDisk['0'], undefined)
// no cache.json.gz existed before this run, so a merge must not create one
assert.ok(
!(await handler.list(rootPath)).includes('cache.json.gz'),
@@ -864,7 +1067,7 @@ test('it regenerates a pre-existing cache after a merge', async () => {
`${rootPath}/metadata.json`,
JSON.stringify({
mode: 'delta',
size: 12000, // a size too small, the merge will fix it
size: 12000,
vhds: [`${relativePath}/grandchild.vhd`, `${relativePath}/child.vhd`],
})
)
@@ -900,13 +1103,26 @@ test('it regenerates a pre-existing cache after a merge', async () => {
})
const metadata = JSON.parse(await handler.readFile(`${rootPath}/metadata.json`))
// size of child + grandchild after orphan has been merged into child
assert.equal(metadata.size, 4299776, 'metadata.size should be updated after merge')
assert.equal(metadata.size, 12000, 'metadata.size should not change')
assert.equal(
metadata.vhdsSizeOnDisk['1'],
await getDiskSizeOnDisk(`${basePath}/child.vhd`),
'vhdsSizeOnDisk should contain the size of the child'
)
assert.equal(
metadata.vhdsSizeOnDisk['0'],
undefined,
'vhdsSizeOnDisk should not contain the size of the grandchild as it was not measured'
)
assert.deepEqual(result.changedFiles, [`/${rootPath}metadata.json`], 'the rewritten metadata should be reported')
const cache = JSON.parse((await gunzip(await handler.readFile(`${rootPath}/cache.json.gz`))).toString())
assert.equal(Object.keys(cache).length, 1)
assert.equal(Object.values(cache)[0].size, metadata.size, 'cache entry should carry the post-merge size')
assert.deepEqual(
Object.values(cache)[0].vhdsSizeOnDisk,
metadata.vhdsSizeOnDisk,
'cache entry should carry the post-merge size on disk'
)
})
test('it regenerates a pre-existing cache when its entry count is out of sync, even with nothing to merge/remove', async () => {

View File

@@ -6,9 +6,10 @@ import {
VmBackupInterface,
PartialBackupMetadata,
DEFAULT_REMOVE_CONCURRENCY,
MergedDisk,
} from './VmBackup.types.mjs'
import { RemoteHandlerAbstract } from '@xen-orchestra/fs'
import { basename, dirname, normalize } from '@xen-orchestra/fs/path'
import { basename, dirname, normalize, resolveFromFile } from '@xen-orchestra/fs/path'
import { RemoteDiskLineage } from './RemoteDiskLineage.mjs'
import { asyncEach } from '@vates/async-each'
@@ -126,10 +127,13 @@ export class VmIncrementalBackupArchive implements VmBackupInterface {
/**
* Removes the metadata file if the backup is incomplete (missing disks).
* If mergedSizes is provided, updates metadata with the total merged size for this archive's disks.
* If mergedDisks is provided, records the size on disk of this archive's merged disks
* in vhdsSizeOnDisk (removed when unknown) and records whether they are still differencing.
* When the size on disk of a merged disk is unknown (chains started before it was recorded),
* size is set to the stream size of the merged disks, which the backup usage falls back to.
* Actual disk merge/deletion is handled by RemoteDiskLineage.
*/
async clean({ remove = this.opts.remove ?? false, mergedSizes }: ArchiveCleanOptions = {}): Promise<CleanResult> {
async clean({ remove = this.opts.remove ?? false, mergedDisks }: ArchiveCleanOptions = {}): Promise<CleanResult> {
if (!this.#isChecked) {
await this.check()
}
@@ -150,13 +154,18 @@ export class VmIncrementalBackupArchive implements VmBackupInterface {
}
const changedFiles: string[] = []
let mergedSize = 0
if (mergedSizes !== undefined) {
for (const diskPath of this.diskPaths) {
mergedSize += mergedSizes.get(diskPath) ?? 0
const updates: Record<string, MergedDisk> = {}
if (mergedDisks !== undefined) {
for (const [vdiRef, relPath] of Object.entries(this.metadata.vhds ?? {})) {
const vhdPath = normalize(resolveFromFile(this.metadataPath, relPath))
const mergedDisk = mergedDisks.get(vhdPath)
if (mergedDisk !== undefined) {
updates[vdiRef] = mergedDisk
}
}
if (mergedSize > 0) {
await this.updateMetadata(mergedSize)
if (Object.keys(updates).length > 0) {
await this.updateMetadata(updates)
changedFiles.push(this.metadataPath)
}
}
@@ -165,17 +174,30 @@ export class VmIncrementalBackupArchive implements VmBackupInterface {
}
/**
* Updates metadata.size after a merge and writes the updated metadata file to disk.
* Also resets isVhdDifferencing so all VDIs are marked as full (non-differencing).
* Updates the size on disk and the differencing status of the merged disks, then writes the metadata file.
* If the size on disk of a merged disk is unknown, size is set to the stream size of the merged disks.
*/
async updateMetadata(mergedSize: number): Promise<void> {
this.metadata.size = mergedSize
if (this.metadata.vdis !== undefined) {
this.metadata.isVhdDifferencing = {}
for (const id of Object.keys(this.metadata.vdis)) {
this.metadata.isVhdDifferencing[id] = false
async updateMetadata(updates: Record<string, MergedDisk>): Promise<void> {
const vhdsSizeOnDisk = { ...this.metadata.vhdsSizeOnDisk }
const totalStreamSize = Object.values(updates).reduce((total, { streamSize }) => {
return total + streamSize
}, 0)
for (const [vdiRef, { sizeOnDisk }] of Object.entries(updates)) {
if (sizeOnDisk === undefined) {
// Chains started before sizeOnDisk existed have no size on disk: size keeps the merged disks' stream size,
// which the backup usage falls back to
this.metadata.size = totalStreamSize
delete vhdsSizeOnDisk[vdiRef]
} else {
vhdsSizeOnDisk[vdiRef] = sizeOnDisk
}
}
this.metadata.vhdsSizeOnDisk = vhdsSizeOnDisk
this.metadata.isVhdDifferencing = this.metadata.isVhdDifferencing ?? {}
for (const [vdiRef, { isDifferencing }] of Object.entries(updates)) {
this.metadata.isVhdDifferencing[vdiRef] = isDifferencing
}
await this.handler.writeFile(this.metadataPath, JSON.stringify(this.metadata), { flags: 'w' })
}

View File

@@ -11,6 +11,7 @@ import { createLogger } from '@xen-orchestra/log'
import { basename, dirname } from 'path'
import { asyncEach } from '@vates/async-each'
import { relativeFromFile, normalize, resolveFromFile } from '@xen-orchestra/fs/path'
import { isVhdAlias } from 'vhd-lib/aliases.js'
// @ts-ignore
const { warn } = createLogger('remote-disk:merge')
@@ -23,7 +24,9 @@ const { warn } = createLogger('remote-disk:merge')
* @property {number} currentBlock
* @property {number} mergedDataSize
* @property {'mergeBlocks' | 'cleanup'} step
* @property {number} diskSize
* @property {number} [sizeOnDisk]
* @property {number} [streamSize]
* @property {boolean} [isDifferencing]
* @typedef {(message: string, data?: Record<string, unknown>) => void} Logger
*/
@@ -38,7 +41,6 @@ export class MergeRemoteDisk {
currentBlock: 0,
mergedDataSize: 0,
step: 'mergeBlocks',
diskSize: 0,
}
/**
@@ -220,10 +222,28 @@ export class MergeRemoteDisk {
await this.#writeState()
}
// Loads the stored size before the blocks are modified
if (!this.#isResuming) {
try {
await parentDisk.readSizeOnDisk()
} catch (err) {
warn(`Unable to read sizeOnDisk on ${parentDisk.getPath()}`, { error: err })
}
}
await this.#mergeBlocks(parentDisk, childDisk)
await parentDisk.flushMetadata(childDisk)
await parentDisk.mergeMetadata(childDisk)
this.#state.diskSize = parentDisk.getSizeOnDisk()
// A resumed merge has lost the size changes of the blocks moved before the interruption,
// its size is unknown.
if (!this.#isResuming) {
try {
await parentDisk.saveSizeOnDisk()
} catch (err) {
warn(`Unable to save sizeOnDisk on ${parentDisk.getPath()}`, { error: err })
}
}
}
/**
@@ -301,6 +321,36 @@ export class MergeRemoteDisk {
throw error
}
}
this.#state.sizeOnDisk = await this.#getFinalSizeOnDisk(parentDisk, mergeTargetPath)
this.#state.streamSize = parentDisk.getStreamSize()
// The merged disk keeps the ancestors of the parent: it is differencing if the parent was.
this.#state.isDifferencing = parentDisk.isDifferencing()
}
/**
* @param {RemoteDisk} parentDisk
* @param {string} mergeTargetPath
* @returns {Promise<number | undefined>}
*/
async #getFinalSizeOnDisk(parentDisk, mergeTargetPath) {
try {
let sizeOnDisk = await parentDisk.readSizeOnDisk()
if (sizeOnDisk === undefined) {
return undefined
}
if (isVhdAlias(mergeTargetPath)) {
sizeOnDisk += await this.#handler.getSizeOnDisk(mergeTargetPath)
}
return sizeOnDisk
} catch (err) {
warn(`Unable to get finalSizeOnDisk on ${parentDisk.getPath()}`, { error: err })
}
return undefined
}
/**
@@ -308,11 +358,13 @@ export class MergeRemoteDisk {
* @param {RemoteDisk} childDisk
* @param {boolean} cleanStateFile
*
* @returns {Promise<{mergedDataSize: number, finalDiskSize: number}>} result
* @returns {Promise<{mergedDataSize: number, finalSizeOnDisk: number | undefined, streamSize: number, isDifferencing: boolean}>} result
*/
async #cleanup(parentDisk, childDisk, cleanStateFile) {
const finalDiskSize = this.#state?.diskSize ?? 0
const finalSizeOnDisk = this.#state?.sizeOnDisk
const streamSize = this.#state?.streamSize ?? 0
const mergedDataSize = this.#state?.mergedDataSize ?? 0
const isDifferencing = this.#state?.isDifferencing ?? false
await parentDisk.close().catch(warn)
await childDisk.close().catch(warn)
@@ -320,7 +372,7 @@ export class MergeRemoteDisk {
await this.#handler.unlink(this.#statePath).catch(warn)
}
return { mergedDataSize, finalDiskSize }
return { mergedDataSize, finalSizeOnDisk, streamSize, isDifferencing }
}
/**

View File

@@ -36,8 +36,8 @@ export class RemoteDisk extends RandomAccessDisk {
* Abstract
* @returns {number} size
*/
getSizeOnDisk() {
throw new Error(`getSizeOnDisk must be implemented`)
getStreamSize() {
throw new Error(`getStreamSize must be implemented`)
}
/**
@@ -294,4 +294,22 @@ export class RemoteDisk extends RandomAccessDisk {
}
return parent
}
/**
* Write the disk size to its size.json metadata file, if it is known.
*
* @returns {Promise<void>}
*/
async saveSizeOnDisk() {
throw new Error(`saveSizeOnDisk must be implemented`)
}
/**
* Returns the space used by the data and undefined if unknown
*
* @returns {Promise<number|undefined>}
*/
async readSizeOnDisk() {
throw new Error(`readSizeOnDisk must be implemented`)
}
}

View File

@@ -13,12 +13,35 @@ import { RemoteVhdDiskChain } from './RemoteVhdDiskChain.mjs'
import { dirname, basename } from 'node:path'
import { rimraf } from 'rimraf'
import { MergeRemoteDisk } from './MergeRemoteDisk.mjs'
import { resolveVhdAlias } from 'vhd-lib/aliases.js'
import { normalize } from '@xen-orchestra/fs/path'
const { beforeEach, afterEach, describe } = test
let tempDir, handler, jobId, vdiId, basePath, relativePath
const rootPath = 'xo-vm-backups/VMUUID'
// sum of the stored size of every file under `entry`, the reference `VhdDirectory#sizeOnDisk` is checked against
async function getFullSize(handler, entry) {
let files
try {
files = await handler.list(entry, { prependDir: true })
} catch (error) {
if (error.code === 'ENOTDIR') {
return await handler.getSizeOnDisk(entry)
} else {
throw error
}
}
let size = 0
for (const file of files) {
size += await getFullSize(handler, file)
}
return size
}
beforeEach(async () => {
tempDir = await pFromCallback(cb => tmp.dir(cb))
handler = getHandler({ url: `file://${tempDir}` })
@@ -75,6 +98,9 @@ async function generateVhd(path, opts = {}) {
await vhd.writeBlockAllocationTable()
await vhd.writeHeader()
await vhd.writeFooter()
if (opts.mode === 'directory' && opts.writeSize !== false) {
await vhd.saveSize()
}
return vhd
}
@@ -350,9 +376,12 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
const result = await mergeRemoteDisk.merge(parent, child)
assert.ok(result.finalDiskSize > 0, 'merged disks should have non-zero size')
assert.equal(result.finalSizeOnDisk, await handler.getSizeOnDisk(`${basePath}/child.vhd`))
assert.ok(result.finalSizeOnDisk > 0, 'merged disks should have non-zero size')
assert.ok(result.mergedDataSize > 0, 'merged data size should be > 0')
assert.ok(progressCalls > 0, 'onProgress should have been called')
assert.equal(result.isDifferencing, false, 'the merged disk should not be differencing, like its parent')
// Check that ancestor was renamed to child
const remainingDisks = await handler.list(basePath)
@@ -362,6 +391,27 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
assert.deepEqual(parentIndexes, expectedIndexes, 'all child blocks should be merged into parent')
})
test('MergeRemoteDisk merges into a differencing parent a disk which stays differencing', async () => {
// the parent has its own parent: merging its child into it does not make it a full disk
await generateVhd(`${basePath}/ancestor.vhd`, {
header: { parentUnicodeName: 'grandAncestor.vhd', parentUuid: uniqueIdBuffer() },
blocks: [0, 1],
})
await generateVhd(`${basePath}/child.vhd`, { blocks: [2, 3] })
const parent = new RemoteVhdDisk({ handler, path: `${basePath}/ancestor.vhd` })
const child = new RemoteVhdDisk({ handler, path: `${basePath}/child.vhd` })
const mergeRemoteDisk = new MergeRemoteDisk(handler, { removeUnused: true })
await parent.init()
await child.init()
const result = await mergeRemoteDisk.merge(parent, child)
assert.equal(result.isDifferencing, true)
})
test('MergeRemoteDisk merges a simple ancestor VHD + child VHD chain', async () => {
let progressCalls = 0
const onProgress = () => {
@@ -412,7 +462,7 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
const result = await mergeRemoteDisk.merge(parent, childDiskChain)
assert.ok(result.finalDiskSize > 0, 'merged disks should have non-zero size')
assert.ok(result.finalSizeOnDisk > 0, 'merged disks should have non-zero size')
assert.ok(result.mergedDataSize > 0, 'merged data size should be > 0')
assert.ok(progressCalls > 0, 'onProgress should have been called')
@@ -450,7 +500,7 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
const result = await mergeRemoteDisk.merge(parent, child)
assert.ok(result.finalDiskSize > 0, 'merged disks should have non-zero size')
assert.ok(result.finalSizeOnDisk > 0, 'merged disks should have non-zero size')
assert.ok(result.mergedDataSize > 0, 'merged data size should be > 0')
assert.ok(progressCalls > 0, 'onProgress should have been called')
@@ -505,7 +555,7 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
const result = await mergeRemoteDisk.merge(parent, childDiskChain)
assert.ok(result.finalDiskSize > 0, 'merged disks should have non-zero size')
assert.ok(result.finalSizeOnDisk > 0, 'merged disks should have non-zero size')
assert.ok(result.mergedDataSize > 0, 'merged data size should be > 0')
assert.ok(progressCalls > 0, 'onProgress should have been called')
@@ -546,7 +596,7 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
const result = await mergeRemoteDisk.merge(parent, child)
assert.ok(result.finalDiskSize > 0, 'merged disks should have non-zero size')
assert.ok(result.finalSizeOnDisk > 0, 'merged disks should have non-zero size')
assert.ok(result.mergedDataSize > 0, 'merged data size should be > 0')
assert.ok(progressCalls > 0, 'onProgress should have been called')
@@ -587,7 +637,7 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
const result = await mergeRemoteDisk.merge(parent, child)
assert.ok(result.finalDiskSize > 0, 'merged disks should have non-zero size')
assert.ok(result.finalSizeOnDisk > 0, 'merged disks should have non-zero size')
assert.ok(result.mergedDataSize > 0, 'merged data size should be > 0')
assert.ok(progressCalls > 0, 'onProgress should have been called')
@@ -595,11 +645,33 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
const remainingDisks = await handler.list(basePath)
assert.deepEqual(remainingDisks, ['child.vhd.alias.vhd', 'data'])
// the ancestor is a plain file: it has been moved under `data` to be the target of the alias
const remainingDatas = await handler.list(basePath + '/data')
assert.deepEqual(remainingDatas, [])
assert.deepEqual(remainingDatas, ['ancestor.vhd'])
const aliasPath = `${basePath}/child.vhd.alias.vhd`
const dataPath = `${basePath}/data/ancestor.vhd`
assert.equal(normalize(await resolveVhdAlias(handler, aliasPath)), normalize(dataPath))
assert.equal(
result.finalSizeOnDisk,
(await handler.getSizeOnDisk(dataPath)) + (await handler.getSizeOnDisk(aliasPath))
)
const parentIndexes = parent.getBlockIndexes()
assert.deepEqual(parentIndexes, expectedIndexes, 'all child blocks should be merged into parent')
// the merged data are readable through the alias
const merged = new RemoteVhdDisk({ handler, path: aliasPath })
await merged.init()
try {
const { data } = await merged.readBlock(2)
assert.ok(
data.every(byte => byte === 2),
'block 2 should come from the child'
)
} finally {
await merged.close()
}
})
test('MergeRemoteDisk merges a alias ancestor VHD directory + alias child VHD directory', async () => {
@@ -628,7 +700,7 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
const result = await mergeRemoteDisk.merge(parent, child)
assert.ok(result.finalDiskSize > 0, 'merged disks should have non-zero size')
assert.ok(result.finalSizeOnDisk > 0, 'merged disks should have non-zero size')
assert.ok(result.mergedDataSize > 0, 'merged data size should be > 0')
assert.ok(progressCalls > 0, 'onProgress should have been called')
@@ -767,7 +839,7 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
const result = await mergeRemoteDisk.merge(parent2, child2)
// Verify merge completed
assert.ok(result.finalDiskSize > 0, 'final disk size should be > 0')
assert.ok(result.finalSizeOnDisk > 0, 'final disk size should be > 0')
assert.ok(result.mergedDataSize > 0, 'merged data size should be > 0')
// Verify state file removed after successful resume
@@ -863,7 +935,7 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
const result = await mergeRemoteDisk.merge(parent2, child2)
// Verify merge completed
assert.ok(result.finalDiskSize > 0, 'final disk size should be > 0')
assert.strictEqual(result.finalSizeOnDisk, undefined, 'the size of a resumed merge is unknown')
assert.ok(result.mergedDataSize > 0, 'merged data size should be > 0')
// Verify state file removed after successful resume
@@ -957,7 +1029,7 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
const result = await mergeRemoteDisk.merge(parent2, childDiskChain2)
assert.ok(result.finalDiskSize > 0, 'final disk size should be > 0')
assert.ok(result.finalSizeOnDisk > 0, 'final disk size should be > 0')
assert.equal(
(await handler.list(basePath)).includes(stateFileName),
@@ -1047,6 +1119,281 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
const parentIndexes = parent.getBlockIndexes()
assert.deepEqual(parentIndexes, expectedIndexes, 'all child blocks should be merged into parent')
})
test('mergeRemoteDisk merge on a parent with a size computes the correct size', async () => {
// Create ancestor and child VHDs
await generateVhd(`${basePath}/ancestor.vhd`, { blocks: [0, 1], mode: 'directory', useAlias: true })
await generateVhd(`${basePath}/child.vhd`, { blocks: [2, 3], mode: 'directory', useAlias: true })
const parent = new RemoteVhdDisk({ handler, path: `${basePath}/ancestor.vhd.alias.vhd` })
const child = new RemoteVhdDisk({ handler, path: `${basePath}/child.vhd.alias.vhd` })
const mergeRemoteDisk = new MergeRemoteDisk(handler, { removeUnused: true })
const isResumingMerge = await mergeRemoteDisk.isResuming(parent)
await parent.init({ force: isResumingMerge })
await child.init({ force: isResumingMerge })
assert.strictEqual(typeof (await parent.readSizeOnDisk()), 'number')
const result = await mergeRemoteDisk.merge(parent, child)
assert.equal(
result.finalSizeOnDisk,
(await getFullSize(handler, `${basePath}/data/ancestor.vhd`)) +
(await handler.getSizeOnDisk(`${basePath}/child.vhd.alias.vhd`))
)
const resultingDisk = new RemoteVhdDisk({ handler, path: `${basePath}/child.vhd.alias.vhd` })
await resultingDisk.init()
assert.strictEqual(
await resultingDisk.readSizeOnDisk(),
await getFullSize(handler, `${basePath}/data/ancestor.vhd`)
)
})
test('mergeRemoteDisk merge on a parent without a size has undefined size', async () => {
// Create ancestor and child VHDs
await generateVhd(`${basePath}/ancestor.vhd`, {
blocks: [0, 1],
mode: 'directory',
useAlias: true,
writeSize: false,
})
await generateVhd(`${basePath}/child.vhd`, { blocks: [2, 3], mode: 'directory', useAlias: true, writeSize: false })
const parent = new RemoteVhdDisk({ handler, path: `${basePath}/ancestor.vhd.alias.vhd` })
const child = new RemoteVhdDisk({ handler, path: `${basePath}/child.vhd.alias.vhd` })
const mergeRemoteDisk = new MergeRemoteDisk(handler, { removeUnused: true })
const isResumingMerge = await mergeRemoteDisk.isResuming(parent)
await parent.init({ force: isResumingMerge })
await child.init({ force: isResumingMerge })
assert.strictEqual(await parent.readSizeOnDisk(), undefined)
const result = await mergeRemoteDisk.merge(parent, child)
assert.equal(result.finalSizeOnDisk, undefined)
const resultingDisk = new RemoteVhdDisk({ handler, path: `${basePath}/child.vhd.alias.vhd` })
await resultingDisk.init()
assert.strictEqual(await resultingDisk.readSizeOnDisk(), undefined)
})
test('mergeRemoteDisk merge on a parent with a size does not recompute it', async t => {
await generateVhd(`${basePath}/ancestor.vhd`, { blocks: [0, 1], mode: 'directory', useAlias: true })
await generateVhd(`${basePath}/child.vhd`, { blocks: [1, 2], mode: 'directory', useAlias: true })
const parent = new RemoteVhdDisk({ handler, path: `${basePath}/ancestor.vhd.alias.vhd` })
const child = new RemoteVhdDisk({ handler, path: `${basePath}/child.vhd.alias.vhd` })
const mergeRemoteDisk = new MergeRemoteDisk(handler, { removeUnused: true })
const isResumingMerge = await mergeRemoteDisk.isResuming(parent)
await parent.init({ force: isResumingMerge })
await child.init({ force: isResumingMerge })
// listing and stating every block is what the stored size avoids
const list = t.mock.method(handler, 'list')
const result = await mergeRemoteDisk.merge(parent, child)
assert.equal(list.mock.callCount(), 0, 'the size should be updated, not recomputed')
assert.equal(
result.finalSizeOnDisk,
(await getFullSize(handler, `${basePath}/data/ancestor.vhd`)) +
(await handler.getSizeOnDisk(`${basePath}/child.vhd.alias.vhd`))
)
})
// the size on disk is only informative: failing to measure it must not fail the merge
for (const [failure, mockFailure] of [
[
'reading the size',
(t, parent) =>
t.mock.method(parent, 'readSizeOnDisk', async () => {
throw new Error('read failure')
}),
],
[
'saving the size',
(t, parent) =>
t.mock.method(parent, 'saveSizeOnDisk', async () => {
throw new Error('save failure')
}),
],
[
'measuring the alias',
t => {
const getSizeOnDisk = handler.getSizeOnDisk.bind(handler)
t.mock.method(handler, 'getSizeOnDisk', async path => {
if (path.endsWith('child.vhd.alias.vhd')) {
throw new Error('stat failure')
}
return getSizeOnDisk(path)
})
},
],
]) {
test(`mergeRemoteDisk merges and has undefined size when ${failure} fails`, async t => {
await generateVhd(`${basePath}/ancestor.vhd`, { blocks: [0, 1], mode: 'directory', useAlias: true })
await generateVhd(`${basePath}/child.vhd`, { blocks: [2, 3], mode: 'directory', useAlias: true })
const parent = new RemoteVhdDisk({ handler, path: `${basePath}/ancestor.vhd.alias.vhd` })
const child = new RemoteVhdDisk({ handler, path: `${basePath}/child.vhd.alias.vhd` })
const mergeRemoteDisk = new MergeRemoteDisk(handler, { removeUnused: true })
await parent.init()
await child.init()
mockFailure(t, parent)
const result = await mergeRemoteDisk.merge(parent, child)
if (failure === 'saving the size') {
// the size known in memory is still returned, but it is not stored
assert.equal(typeof result.finalSizeOnDisk, 'number')
} else {
assert.equal(result.finalSizeOnDisk, undefined)
}
t.mock.restoreAll()
const resultingDisk = new RemoteVhdDisk({ handler, path: `${basePath}/child.vhd.alias.vhd` })
await resultingDisk.init()
try {
for (const blockId of [0, 1, 2, 3]) {
assert.ok(resultingDisk.hasBlock(blockId), `block ${blockId} should be merged`)
}
if (failure !== 'measuring the alias') {
assert.equal(await resultingDisk.readSizeOnDisk(), undefined, 'no valid size.json should be stored')
}
} finally {
await resultingDisk.close()
}
})
}
test('mergeRemoteDisk merge on a parent with a stale size has undefined size', async () => {
await generateVhd(`${basePath}/ancestor.vhd`, { blocks: [0, 1], mode: 'directory', useAlias: true })
await generateVhd(`${basePath}/child.vhd`, { blocks: [2, 3], mode: 'directory', useAlias: true })
// like a merge done by a version which does not know size.json: a block is added and the footer takes the UUID
// of the merged child, but size.json is not updated
const { value: ancestor, dispose } = await VhdDirectory.open(handler, `${basePath}/data/ancestor.vhd`, {
flags: 'r+',
})
try {
await ancestor.readBlockAllocationTable()
await ancestor.writeEntireBlock({ id: 4, buffer: Buffer.alloc(2 * 1024 * 1024 + 512, 4) })
await ancestor.writeBlockAllocationTable()
ancestor.footer.uuid = uniqueIdBuffer()
await ancestor.writeFooter()
} finally {
await dispose()
}
const parent = new RemoteVhdDisk({ handler, path: `${basePath}/ancestor.vhd.alias.vhd` })
const child = new RemoteVhdDisk({ handler, path: `${basePath}/child.vhd.alias.vhd` })
const mergeRemoteDisk = new MergeRemoteDisk(handler, { removeUnused: true })
const isResumingMerge = await mergeRemoteDisk.isResuming(parent)
await parent.init({ force: isResumingMerge })
await child.init({ force: isResumingMerge })
assert.strictEqual(await parent.readSizeOnDisk(), undefined, 'a stale size must not be trusted')
const result = await mergeRemoteDisk.merge(parent, child)
assert.equal(result.finalSizeOnDisk, undefined)
const resultingDisk = new RemoteVhdDisk({ handler, path: `${basePath}/child.vhd.alias.vhd` })
await resultingDisk.init()
assert.strictEqual(await resultingDisk.readSizeOnDisk(), undefined)
})
test('mergeRemoteDisk resumes after interruption has undefined size', async () => {
// Create parent and child VHDs
await generateVhd(`${basePath}/ancestor.vhd`, { blocks: [0, 1], mode: 'directory', useAlias: true })
await generateVhd(`${basePath}/child.vhd`, {
blocks: [2, 3, 4, 5, 6, 7, 8, 9, 10],
mode: 'directory',
useAlias: true,
})
const parent = new RemoteVhdDisk({ handler, path: `${basePath}/ancestor.vhd.alias.vhd` })
const child = new RemoteVhdDisk({ handler, path: `${basePath}/child.vhd.alias.vhd` })
const mergeRemoteDisk = new MergeRemoteDisk(handler, { removeUnused: true, writeStateDelay: 0 })
let isResuming = await mergeRemoteDisk.isResuming(parent)
assert.ok(!isResuming, 'merge is not resuming')
await parent.init({ force: isResuming })
await child.init({ force: isResuming })
// Track merge progress
let blocksMerged = 0
const originalMergeBlock = parent.mergeBlock.bind(parent)
// Make mergeBlock fail on the second block
parent.mergeBlock = async (childDisk, index, isResumingMerge) => {
if (blocksMerged === 5) {
throw new Error('simulated interruption')
}
blocksMerged++
return originalMergeBlock(childDisk, index, isResumingMerge)
}
// First merge attempt should throw
let threw = false
try {
await mergeRemoteDisk.merge(parent, child)
} catch (err) {
threw = true
assert.equal(err.message, 'simulated interruption')
}
assert.equal(threw, true, 'merge should throw on simulated interruption')
// Verify that state file exists
assert.ok(
(await handler.list(dirname(parent.getPath()))).includes(`.${basename(parent.getPath())}.merge.json`),
'merge state file should exist after failure'
)
// Recreate new remoteDisks to simulate a new operation
const parent2 = new RemoteVhdDisk({ handler, path: `${basePath}/ancestor.vhd.alias.vhd` })
const child2 = new RemoteVhdDisk({ handler, path: `${basePath}/child.vhd.alias.vhd` })
isResuming = await mergeRemoteDisk.isResuming(parent)
assert.ok(isResuming, 'merge is resuming')
await parent2.init({ force: isResuming })
await child2.init({ force: isResuming })
// Resume merge
const result = await mergeRemoteDisk.merge(parent2, child2)
assert.equal(result.finalSizeOnDisk, undefined)
const resultingDisk = new RemoteVhdDisk({ handler, path: `${basePath}/child.vhd.alias.vhd` })
await resultingDisk.init()
assert.strictEqual(await resultingDisk.readSizeOnDisk(), undefined)
})
})
/**

View File

@@ -16,7 +16,7 @@ import { RemoteDisk } from './RemoteDisk.mjs'
import { DISK_TYPES } from 'vhd-lib/_constants.js'
import { isVhdAlias, resolveVhdAlias } from 'vhd-lib/aliases.js'
import { stringify } from 'uuid'
import { dirname, join } from 'node:path'
import { dirname, join, basename } from 'node:path'
import { RemoteVhdDiskChain } from './RemoteVhdDiskChain.mjs'
import { normalize } from '@xen-orchestra/fs/path'
@@ -138,9 +138,9 @@ export class RemoteVhdDisk extends RemoteDisk {
/**
* @returns {number} size
*/
getSizeOnDisk() {
getStreamSize() {
if (this.#vhd === undefined) {
throw new Error(`can't call getVirtualSize of a RemoteVhdDisk before init`)
throw new Error(`can't call getStreamSize of a RemoteVhdDisk before init`)
}
return this.#vhd.streamSize()
@@ -322,9 +322,7 @@ export class RemoteVhdDisk extends RemoteDisk {
(await childDisk.isDirectory())
) {
try {
await this.#handler.rename(childDisk.getBlockPath(index), this.getBlockPath(index))
this.setAllocatedBlocks([index])
await /** @type {VhdDirectory} */ (this.#vhd).moveBlockFrom(index, childDisk.getBlockPath(index))
} catch (error) {
// @ts-ignore
if (error.code === 'ENOENT' && isResumingMerge === true) {
@@ -333,9 +331,6 @@ export class RemoteVhdDisk extends RemoteDisk {
// it will throw an error if block is missing in parent
// won't detect if the block was already in parent and is broken/missing in child
// since we can't know the initial size, this will create a discrepancy
// on the size
const { data } = await this.readBlock(index)
if (data.length !== this.getBlockSize()) {
throw error
@@ -395,6 +390,39 @@ export class RemoteVhdDisk extends RemoteDisk {
await this.#vhd.ensureBatSize(blockCount)
}
/**
* Write the disk size to its size.json metadata file, if it is known.
* Does nothing to a VHD file
*
* @returns {Promise<void>}
*/
async saveSizeOnDisk() {
if (this.#vhd === undefined) {
throw new Error(`can't call saveSizeOnDisk of a RemoteVhdDisk before init`)
}
if (this.#vhd instanceof VhdDirectory) {
await this.#vhd.saveSize()
}
}
/**
* Returns the space used by the data and undefined if unknown
*
* @returns {Promise<number|undefined>}
*/
async readSizeOnDisk() {
if (this.#vhd === undefined) {
throw new Error(`can't call readSizeOnDisk of a RemoteVhdDisk before init`)
}
if (this.#vhd instanceof VhdDirectory) {
return this.#vhd.readSizeOnDisk()
} else {
return this.#handler.getSizeOnDisk(await resolveVhdAlias(this.#handler, this.#path))
}
}
/**
* Writes Block Allocation Table
* @param {RemoteDisk} childDisk
@@ -487,15 +515,29 @@ export class RemoteVhdDisk extends RemoteDisk {
/**
* Rename alias/disk
*
* A plain VHD file renamed to an alias is moved to the `data` directory next to the alias, which then points to it.
* @param {string} newPath
*/
async rename(newPath) {
if (isVhdAlias(newPath)) {
const dataPath = await resolveVhdAlias(this.#handler, this.#path)
if (isVhdAlias(this.#path)) {
const dataPath = await resolveVhdAlias(this.#handler, this.#path)
await this.#handler.unlink(newPath)
await VhdAbstract.createAlias(this.#handler, newPath, dataPath)
await this.#handler.unlink(this.#path)
await this.#handler.unlink(newPath)
await VhdAbstract.createAlias(this.#handler, newPath, dataPath)
await this.#handler.unlink(this.#path)
} else {
// the file is the data itself: keep it, under `data` to be claimed by the alias
//
// if interrupted before the alias is created, the data stays in `data` without any alias, like when
// interrupted after `newPath` has been removed in the other case
const dataPath = join(dirname(newPath), 'data', basename(this.#path))
await this.#handler.rename(this.#path, dataPath)
await this.#handler.unlink(newPath)
await VhdAbstract.createAlias(this.#handler, newPath, dataPath)
}
this.#path = newPath
} else {

View File

@@ -93,7 +93,7 @@ export class RemoteVhdDiskChain extends RemoteDisk {
/**
* @returns {number} size
*/
getSizeOnDisk() {
getStreamSize() {
const batEntrySize = 4
const sectorSize = 512
const batSize = Math.ceil((this.getMaxBlockCount() * batEntrySize) / sectorSize) * sectorSize
@@ -253,6 +253,24 @@ export class RemoteVhdDiskChain extends RemoteDisk {
throw new Error(`Can't flush metadata on a disk chain`)
}
/**
* Write the disk size to its size.json metadata file, if it is known.
*
* @returns {Promise<void>}
*/
async saveSizeOnDisk() {
throw new Error(`Can't save size on disk on a disk chain`)
}
/**
* Returns the space used by the data and undefined if unknown
*
* @returns {Promise<number|undefined>}
*/
async readSizeOnDisk() {
throw new Error(`Can't get size on disk on a disk chain`)
}
/**
* @param {RemoteDisk} childDisk
* @returns {Promise<void>}

View File

@@ -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.`,

View 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')
})
})

View File

@@ -3,7 +3,9 @@ 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 { meterDisk, SourceReadTask } from './_SourceReadTask.mjs'
import { decorateClass } from '@vates/decorate-with'
import { Task } from '@vates/task'
import { createLogger } from '@xen-orchestra/log'
@@ -424,7 +426,15 @@ export class ImportVmBackup {
throw new Error('live mounting a disk is only supported when restoring an incremental backup')
}
backup = await adapter.readFullVmBackup(metadata)
sizeContainer.readTask = new SourceReadTask('read')
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')
@@ -432,6 +442,9 @@ export class ImportVmBackup {
// releases them, a successful one hands their ids back to the caller
$defer.onFailure(() => this.#releaseLiveMounts())
backup = await this._decorateIncrementalVmMetadata()
for (const key in backup.disks) {
backup.disks[key] = meterDisk(backup.disks[key], backup.vdis[key])
}
}
return Task.run(
@@ -451,12 +464,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

View File

@@ -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])),
[]
)
})
})

View File

@@ -16,6 +16,7 @@ import { openVhd, VhdFile, VhdAbstract, Constants, VhdDirectory } from 'vhd-lib'
import computeGeometryForSize from 'vhd-lib/_computeGeometryForSize.js'
import { dirname, basename } from 'node:path'
import { rimraf } from 'rimraf'
import { resolveVhdAlias } from 'vhd-lib/aliases.js'
const { beforeEach, afterEach, describe } = test
@@ -23,6 +24,27 @@ let tempDir, handler, jobId, vdiId, basePath, relativePath
const vmUuid = 'a1b2c3d4-0000-0000-0000-000000000000'
const rootPath = `xo-vm-backups/${vmUuid}`
// sum of the stored size of every file under `entry`, the reference `VhdDirectory#sizeOnDisk` is checked against
async function getFullSize(handler, entry) {
let files
try {
files = await handler.list(entry, { prependDir: true })
} catch (error) {
if (error.code === 'ENOTDIR') {
return await handler.getSizeOnDisk(entry)
} else {
throw error
}
}
let size = 0
for (const file of files) {
size += await getFullSize(handler, file)
}
return size
}
beforeEach(async () => {
tempDir = await pFromCallback(cb => tmp.dir(cb))
jobId = uniqueId()
@@ -256,11 +278,20 @@ describe('RemoteAdapter#writeVhd validated by checkDisk', { concurrency: 1 }, ()
const adapter = await getAdapter({ useVhdDirectory })
const path = `${basePath}/${adapter.getVhdFileName('base')}`
const size = await adapter.writeVhd(path, new MockDisk(2, [0, 1], 0x42), {
const { size, sizeOnDisk } = await adapter.writeVhd(path, new MockDisk(2, [0, 1], 0x42), {
validator: tmpPath => checkDisk(handler, tmpPath),
uuid: uniqueIdBuffer(),
})
if (mode === 'directory') {
assert.equal(
sizeOnDisk,
(await getFullSize(handler, await resolveVhdAlias(handler, path))) + (await handler.getSizeOnDisk(path))
)
} else {
assert.equal(sizeOnDisk, await handler.getSizeOnDisk(path))
}
assert.ok(size > 0, 'reported size should be greater than 0')
assert.equal(basename(path).endsWith('.alias.vhd'), useVhdDirectory)
await Disposable.use(openVhd(handler, path), async vhd => {
@@ -317,6 +348,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 }), [])
})
}
})

View File

@@ -38,6 +38,7 @@ import { watchStreamSize } from './_watchStreamSize.mjs'
import { RemoteVhdDisk, openDiskChain, openDisposableDisk } from '@xen-orchestra/backup-archive/disks'
import { toVhdStream, writeToVhdDirectory } from 'vhd-lib/disk-consumer/index.mjs'
import { ReadAhead } from '@xen-orchestra/disk-transform'
import { getVmBackupSizeOnDisk } from './formatVmBackups.mjs'
export const DIR_XO_CONFIG_BACKUPS = 'xo-config-backups'
@@ -687,12 +688,18 @@ 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
*
* @returns {Promise<{size: number, sizeOnDisk: number}>}
*/
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 +712,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
@@ -713,7 +724,8 @@ export class RemoteAdapter {
checksum: false,
})
await validator(path)
return size
const sizeOnDisk = await this._handler.getSizeOnDisk(path)
return { size, sizeOnDisk }
}
}
@@ -883,9 +895,11 @@ export class RemoteAdapter {
return reduce(
backups,
(prev, backup) => {
const _backup = Array.isArray(backup) ? this.#computeTotalBackupSizeRecursively(backup) : backup
const size = Array.isArray(backup)
? this.#computeTotalBackupSizeRecursively(backup).onDisk
: (getVmBackupSizeOnDisk(backup) ?? backup.size)
return {
onDisk: prev.onDisk + (_backup.onDisk ?? _backup.size),
onDisk: prev.onDisk + size,
}
},
{ onDisk: 0 }

View File

@@ -0,0 +1,125 @@
import { Task } from '@vates/task'
import { MeteredDisk } from '@xen-orchestra/disk-transform'
const SPEED_INTERVAL = 5e3
/**
* Reports the reading of a source (a disk, a XVA) in its own task, child of the current task
*
* A source is read once, even when it is consumed by multiple writers, but from the async context of the writer
* pulling the next block: the task is held here instead of relying on the current task
*
* Its lifecycle follows the source: started on the first read, ended when the source is exhausted, fails or is closed
* early. A source never read (a step failing before the transfer, a disk without blocks) leaves no task
*
* The current reading speed, in bytes per second, is reported in the `speed` property every 5 seconds: it is 0 when
* the source is stalled. The total number of bytes read is reported in the `bytesRead` property at the end, to compute
* the average speed
*
* When the number of bytes to read is known, the `progress` property (a percentage) is reported with the speed
*
* Implements `ReadMeter` from `@xen-orchestra/disk-transform`
*/
export class SourceReadTask {
#bytesRead = 0
#bytesReadSinceLastSpeed = 0
#bytesToRead
#lastProgress
#lastSpeed
#speedInterval
#task
/**
* @param {string} name of the task
*/
constructor(name) {
// created here to be a child of the current task, only started on the first read
this.#task = new Task({ properties: { name } })
}
/**
* @param {number} length number of bytes the source will produce
*/
setBytesToRead(length) {
this.#bytesToRead = length
}
/**
* @param {number} length number of bytes read
*/
onRead(length) {
if (this.#speedInterval === undefined) {
this.#task.start()
this.#reportProgress()
// on a timer instead of on read: a stalled source must report a speed of 0, not its last one
this.#speedInterval = setInterval(() => this.#reportSpeed(), SPEED_INTERVAL)
// must not keep the process alive if the source is never ended
this.#speedInterval.unref()
}
// late reads, after the end, are never reported
this.#bytesRead += length
this.#bytesReadSinceLastSpeed += length
}
#reportSpeed() {
const speed = Math.round((this.#bytesReadSinceLastSpeed * 1e3) / SPEED_INTERVAL)
this.#bytesReadSinceLastSpeed = 0
// a source stalled for a long time must not emit an event every interval
if (speed !== this.#lastSpeed) {
this.#lastSpeed = speed
this.#task.set('speed', speed)
}
this.#reportProgress()
}
/**
* @param {number} [progress] defaults to the progress of the bytes read, never 100 before the end
*/
#reportProgress(progress) {
const bytesToRead = this.#bytesToRead
if (!(bytesToRead > 0)) {
return
}
progress ??= Math.min(99, Math.floor((this.#bytesRead * 100) / bytesToRead))
if (progress !== this.#lastProgress) {
this.#lastProgress = progress
this.#task.set('progress', progress)
}
}
/**
* A source closed early is not a failure: its consumers stopped, they report their own errors
*
* @param {unknown} [error]
*/
onEnd(error) {
const task = this.#task
// never started or already ended
if (this.#speedInterval === undefined || task.status !== 'pending') {
return
}
clearInterval(this.#speedInterval)
task.set('bytesRead', this.#bytesRead)
if (error === undefined) {
// the UI shows the progress of an ended task: a success is complete, even a source producing less than expected
this.#reportProgress(100)
task.success()
} else {
task.failure(error)
}
}
}
/**
* Reports the reading of a disk of an incremental export in its own task, child of the current task
*
* The returned `MeteredDisk` only exposes the generic `Disk` interface: source specific methods (`useNbd()` for
* example) must be called before
*
* @param {import('@xen-orchestra/disk-transform').Disk} disk
* @param {{ name_label: string }} vdi
*/
export function meterDisk(disk, vdi) {
return new MeteredDisk(disk, new SourceReadTask(`read disk ${vdi.name_label}`))
}

View File

@@ -0,0 +1,300 @@
import assert from 'node:assert/strict'
import { Readable, Writable } from 'node:stream'
import { pipeline } from 'node:stream/promises'
import { describe, it, mock } from 'node:test'
import { setTimeout as delay } from 'node:timers/promises'
import { Task } from '@vates/task'
import { MeteredDisk, RandomAccessDisk, SynchronizedDisk } from '@xen-orchestra/disk-transform'
import { forkStreamUnpipe } from './_runners/_forkStreamUnpipe.mjs'
import { meterDisk, SourceReadTask } from './_SourceReadTask.mjs'
import { watchStreamSize } from './_watchStreamSize.mjs'
const BLOCK_SIZE = 1024
const NB_BLOCKS = 20
class MemoryDisk extends RandomAccessDisk {
getVirtualSize() {
return NB_BLOCKS * BLOCK_SIZE
}
getBlockSize() {
return BLOCK_SIZE
}
async init() {}
async close() {}
isDifferencing() {
return false
}
getBlockIndexes() {
return Array.from({ length: NB_BLOCKS }, (_, index) => index)
}
hasBlock() {
return true
}
async readBlock(index) {
return { index, data: Buffer.alloc(BLOCK_SIZE) }
}
}
/**
* Runs `fn` in a root task, and returns the tasks created inside, by name
*/
async function collectTasks(fn) {
const tasksById = new Map()
const root = new Task({
properties: { name: 'root' },
onProgress(event) {
if (event.type === 'start') {
const { name, ...properties } = event.properties
tasksById.set(event.id, { id: event.id, name, parentId: event.parentId, properties, progresses: [], speeds: [] })
return
}
const task = tasksById.get(event.id)
if (task === undefined) {
return
}
if (event.type === 'property') {
task.properties[event.name] = event.value
if (event.name === 'speed') {
task.speeds.push(event.value)
} else if (event.name === 'progress') {
task.progresses.push(event.value)
}
} else if (event.type === 'end') {
task.status = event.status
task.result = event.result
}
},
})
await root.run(fn).catch(() => {})
const tasksByName = {}
for (const task of tasksById.values()) {
task.isRootChild = task.parentId === root.id
tasksByName[task.name] = task
}
return tasksByName
}
// each writer consumes its fork at its own pace, in its own task
function runWriters(consumers) {
return Promise.all(Object.entries(consumers).map(([name, consume]) => Task.run({ properties: { name } }, consume)))
}
function createMeteredDisk() {
return new MeteredDisk(new MemoryDisk(), new SourceReadTask('read disk'))
}
describe('SourceReadTask', () => {
it('reports the current speed every 5 seconds', async () => {
mock.timers.enable({ apis: ['setInterval'] })
try {
const tasks = await collectTasks(async () => {
const readTask = new SourceReadTask('read')
readTask.onRead(1e3)
mock.timers.tick(2e3)
readTask.onRead(4e3)
mock.timers.tick(3e3)
readTask.onRead(10e3)
mock.timers.tick(5e3)
readTask.onEnd()
})
assert.deepEqual(tasks.read.speeds, [1e3, 2e3])
assert.equal(tasks.read.properties.bytesRead, 15e3)
assert.equal(tasks.read.status, 'success')
// the number of bytes to read is unknown (a XVA exported by XAPI)
assert.deepEqual(tasks.read.progresses, [])
} finally {
mock.timers.reset()
}
})
it('reports a speed of 0 once, when the source is stalled', async () => {
mock.timers.enable({ apis: ['setInterval'] })
try {
const tasks = await collectTasks(async () => {
const readTask = new SourceReadTask('read')
readTask.onRead(5e3)
mock.timers.tick(5e3)
// nothing read during 3 intervals
mock.timers.tick(15e3)
readTask.onRead(5e3)
mock.timers.tick(5e3)
readTask.onEnd()
})
assert.deepEqual(tasks.read.speeds, [1e3, 0, 1e3])
} finally {
mock.timers.reset()
}
})
it('stops reporting the speed once ended', async () => {
mock.timers.enable({ apis: ['setInterval'] })
try {
const tasks = await collectTasks(async () => {
const readTask = new SourceReadTask('read')
readTask.onRead(5e3)
readTask.onEnd()
mock.timers.tick(10e3)
})
assert.deepEqual(tasks.read.speeds, [])
} finally {
mock.timers.reset()
}
})
it('reports the progress with the speed, and 100 only at the end', async () => {
mock.timers.enable({ apis: ['setInterval'] })
try {
const tasks = await collectTasks(async () => {
const readTask = new SourceReadTask('read')
readTask.setBytesToRead(20e3)
readTask.onRead(5e3)
mock.timers.tick(5e3)
readTask.onRead(15e3)
mock.timers.tick(5e3)
// nothing more read: the progress does not change
mock.timers.tick(5e3)
readTask.onEnd()
})
assert.deepEqual(tasks.read.progresses, [0, 25, 99, 100])
assert.equal(tasks.read.status, 'success')
} finally {
mock.timers.reset()
}
})
it('keeps the last progress when the source fails', async () => {
mock.timers.enable({ apis: ['setInterval'] })
try {
const tasks = await collectTasks(async () => {
const readTask = new SourceReadTask('read')
readTask.setBytesToRead(10e3)
readTask.onRead(5e3)
mock.timers.tick(5e3)
readTask.onEnd(new Error('read failed'))
})
assert.deepEqual(tasks.read.progresses, [0, 50])
assert.equal(tasks.read.status, 'failure')
} finally {
mock.timers.reset()
}
})
it('reports a disk read by multiple writers only in its own task', async () => {
const tasks = await collectTasks(async () => {
const synchronizedDisk = new SynchronizedDisk(createMeteredDisk())
const forks = { backup: synchronizedDisk.fork('backup'), replication: synchronizedDisk.fork('replication') }
await runWriters({
async backup() {
for await (const block of forks.backup.diskBlocks()) {
assert.equal(block.data.length, BLOCK_SIZE)
await delay(1)
}
},
async replication() {
for await (const block of forks.replication.diskBlocks()) {
assert.equal(block.data.length, BLOCK_SIZE)
await delay(Math.random() * 3)
}
},
})
})
const readTask = tasks['read disk']
assert.equal(readTask.isRootChild, true)
assert.equal(readTask.status, 'success')
assert.equal(readTask.properties.progress, 100)
assert.deepEqual(tasks.backup.properties, {})
assert.deepEqual(tasks.replication.properties, {})
})
it('reports a forked stream only in its own task', async () => {
const chunks = Array.from({ length: NB_BLOCKS }, () => Buffer.alloc(BLOCK_SIZE))
const tasks = await collectTasks(async () => {
const stream = Readable.from(chunks)
// set by the remote handler on the stream of a backup file
stream.length = NB_BLOCKS * BLOCK_SIZE
watchStreamSize(stream, { size: 0, readTask: new SourceReadTask('read') })
const forks = [forkStreamUnpipe(stream), forkStreamUnpipe(stream)]
const sink = () =>
new Writable({
write(_chunk, _encoding, callback) {
setTimeout(callback, 1)
},
})
await runWriters({
remote: () => pipeline(forks[0], sink()),
sr: () => pipeline(forks[1], sink()),
})
})
assert.equal(tasks.read.isRootChild, true)
assert.equal(tasks.read.status, 'success')
assert.equal(tasks.read.properties.progress, 100)
assert.deepEqual(tasks.remote.properties, {})
assert.deepEqual(tasks.sr.properties, {})
})
it('leaves no task when the source is never read', async () => {
const tasks = await collectTasks(async () => {
createMeteredDisk()
})
assert.deepEqual(Object.keys(tasks), ['root'])
})
it('succeeds when its consumers stop early', async () => {
const tasks = await collectTasks(async () => {
let nbRead = 0
for await (const block of createMeteredDisk().diskBlocks()) {
assert.equal(block.data.length, BLOCK_SIZE)
if (++nbRead === 5) {
break
}
}
})
assert.equal(tasks['read disk'].status, 'success')
})
it('fails when the source fails', async () => {
const tasks = await collectTasks(async () => {
const disk = new MemoryDisk()
disk.readBlock = async index => {
if (index === 2) {
throw new Error('NBD connection lost')
}
return { index, data: Buffer.alloc(BLOCK_SIZE) }
}
const meteredDisk = new MeteredDisk(disk, new SourceReadTask('read disk'))
await assert.rejects(async () => {
for await (const block of meteredDisk.diskBlocks()) {
assert.equal(block.data.length, BLOCK_SIZE)
}
})
})
assert.equal(tasks['read disk'].status, 'failure')
assert.equal(tasks['read disk'].properties.bytesRead, 2 * BLOCK_SIZE)
assert.equal(tasks['read disk'].result.message, 'NBD connection lost')
})
it('names the task of a disk after its VDI', async () => {
const tasks = await collectTasks(async () => {
const disk = meterDisk(new MemoryDisk(), { name_label: 'system' })
for await (const block of disk.diskBlocks()) {
assert.equal(block.data.length, BLOCK_SIZE)
}
})
assert.equal(tasks['read disk system'].isRootChild, true)
assert.equal(tasks['read disk system'].status, 'success')
})
})

View File

@@ -38,7 +38,7 @@ const BACKUP_JOURNAL_EVENTS = /** @type {const} */ (['add', 'change', 'del'])
* - `retention`: it was rotated out by a retention setting
* - `user`: a user explicitly deleted it
* - `clean-vm`: `cleanVm()` removed it, e.g. the metadata of an incomplete backup
* - `merge`: `cleanVm()` rewrote its size after merging its disks
* - `merge`: `cleanVm()` rewrote it after merging its disks, to record their new size on disk
*
* @typedef {'backup'|'retention'|'user'|'clean-vm'|'merge'} BackupJournalReason
*/

View File

@@ -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,

View File

@@ -8,7 +8,8 @@ import { getHandler } from '@xen-orchestra/fs'
import { pFromCallback } from 'promise-toolbox'
import { RemoteAdapter } from './RemoteAdapter.mjs'
import { VHDFOOTER, VHDHEADER } from './tests.fixtures.mjs'
import { VhdFile, Constants, VhdDirectory, VhdAbstract } from 'vhd-lib'
import { VhdFile, Constants, VhdDirectory, VhdAbstract, openVhd } from 'vhd-lib'
import Disposable from 'promise-toolbox/Disposable'
import { dirname, basename } from 'node:path'
import { rimraf } from 'rimraf'
@@ -34,6 +35,14 @@ afterEach(async () => {
await handler.forget()
})
// stream size of a disk, its block allocation table included
async function getDiskStreamSize(diskPath) {
return Disposable.use(openVhd(handler, diskPath), async vhd => {
await vhd.readBlockAllocationTable()
return vhd.streamSize()
})
}
const uniqueId = () => uuid.v1()
const uniqueIdBuffer = () => uuid.v1({}, Buffer.alloc(16))
@@ -198,7 +207,7 @@ test('it merges delta of non destroyed chain', async () => {
`${rootPath}/metadata.json`,
JSON.stringify({
mode: 'delta',
size: 12000, // a size too small
size: 12000,
vhds: [
`${relativePath}/grandchild.vhd`, // grand child should not be merged
`${relativePath}/child.vhd`,
@@ -239,7 +248,7 @@ test('it merges delta of non destroyed chain', async () => {
const metadata = JSON.parse(await handler.readFile(`${rootPath}/metadata.json`))
// size should be the size of children + grand children after the merge
assert.equal(metadata.size, 4299776)
assert.equal(metadata.size, 12000)
// merging is already tested in vhd-lib, don't retest it here (and theses vhd are as empty as my stomach at 12h12)
// only check deletion
@@ -453,8 +462,15 @@ describe('tests multiple combination ', { concurrency: 1 }, () => {
await adapter.cleanVm(rootPath, { remove: true, merge: true, logWarn: () => {}, lock: false })
const metadata = JSON.parse(await handler.readFile(`${rootPath}/metadata.json`))
// size is the sum of the merged chains' final on-disk sizes:
assert.deepEqual(metadata.size, 6501888)
// merges record the size on disk of the disks they merged into, child and clean.
// Directory disks without `size.json` stay unknown, so size falls back to their stream size
assert.equal(
metadata.size,
vhdMode === 'directory'
? (await getDiskStreamSize(`${basePath}/child.vhd.alias.vhd`)) +
(await getDiskStreamSize(`${basePath}/clean.vhd.alias.vhd`))
: undefined
)
// broken vhd, non referenced, abandoned should be deleted ( alias and data)
// ancestor and child should be merged

View 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)
}

View 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)
})
})

View File

@@ -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()
}

View File

@@ -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

View 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')
})
})

View File

@@ -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`, {

View 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')
})
})

View File

@@ -3,7 +3,9 @@ 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 { SourceReadTask } from '../../_SourceReadTask.mjs'
import { AggregatedFullRemoteWriter } from '../_writers/AggregatedFullRemoteWriter.mjs'
import { Task } from '@vates/task'
@@ -23,8 +25,10 @@ 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)
// the backup is read once, whatever the number of writers
const sizeContainer = watchStreamSize(stream, { size: 0, readTask: new SourceReadTask('read') })
let checksum
try {
// the unencrypted destinations store the same data as the source: no need to compute their checksum again
@@ -36,6 +40,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 +58,7 @@ export const FullRemote = class FullRemoteVmBackupRunner extends AbstractRemote
sizeContainer,
}),
'writer.run()'
)
).finally(stopDestroyOnAbort)
// for healthcheck
this._vm = metadata.vm
nbTransferredVms++

View 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)
})
})

View File

@@ -1,9 +1,11 @@
import { createLogger } from '@xen-orchestra/log'
import { Task } from '@vates/task'
import { forkStreamUnpipe } from '../_forkStreamUnpipe.mjs'
import { FullRemoteWriter } from '../_writers/FullRemoteWriter.mjs'
import { FullXapiWriter } from '../_writers/FullXapiWriter.mjs'
import { watchStreamSize } from '../../_watchStreamSize.mjs'
import { SourceReadTask } from '../../_SourceReadTask.mjs'
import { AbstractXapi } from './_AbstractXapi.mjs'
import { AggregatedFullRemoteWriter } from '../_writers/AggregatedFullRemoteWriter.mjs'
import { AggregatedFullXapiWriter } from '../_writers/AggregatedFullXapiWriter.mjs'
@@ -55,6 +57,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
@@ -78,7 +82,8 @@ export const FullXapi = class FullXapiVmBackupRunner extends AbstractXapi {
maxStreamLength += XVA_BLOCK_SIZE * nbBlocks + headersSize
}
const sizeContainer = watchStreamSize(stream)
// the export is read once, whatever the number of writers
const sizeContainer = watchStreamSize(stream, { size: 0, readTask: new SourceReadTask('read') })
const transferStart = Date.now()
await this._callWriters(

View 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')
})
})

View File

@@ -13,6 +13,7 @@ import { SynchronizedDisk, ThrottledDisk } from '@xen-orchestra/disk-transform'
import { AggregatedIncrementalRemoteWriter } from '../_writers/AggregatedIncrementalRemoteWriter.mjs'
import { Task } from '@vates/task'
import { TaskProgressHandler } from './_TaskProgressHandler.mjs'
import { meterDisk } from '../../_SourceReadTask.mjs'
const { warn } = createLogger('xo:backups:Incrementalremote')
class IncrementalRemoteVmBackupRunner extends AbstractRemote {
@@ -85,6 +86,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,
@@ -99,6 +102,8 @@ class IncrementalRemoteVmBackupRunner extends AbstractRemote {
let disk = incrementalExport.disks[key]
isVhdDifferencing[key] = disk.isDifferencing()
disk.addProgressHandler(new TaskProgressHandler())
// each disk is read once, whatever the number of writers
disk = meterDisk(disk, incrementalExport.vdis[key])
disk = new ThrottledDisk(disk, this._throttleGenerator)
incrementalExport.disks[key] = new SynchronizedDisk(disk)
}

View File

@@ -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)
})
})

View File

@@ -20,6 +20,7 @@ import { AggregatedIncrementalXapiWriter } from '../_writers/AggregatedIncrement
import { TaskProgressHandler } from './_TaskProgressHandler.mjs'
import { compileExpression, isExpression } from '../../_expressionPredicate.mjs'
import { buildVmContext } from '../../_buildContext.mjs'
import { meterDisk } from '../../_SourceReadTask.mjs'
const { debug } = createLogger('xo:backups:IncrementalXapiVmBackup')
@@ -55,6 +56,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 = {}
@@ -67,6 +70,8 @@ export const IncrementalXapi = class IncrementalXapiVmBackupRunner extends Abstr
Task.warning('Backup fell back to a full')
}
useNbd = useNbd || disk.useNbd()
// each disk is read once, whatever the number of writers
disk = meterDisk(disk, deltaExport.vdis[key])
disk = new ThrottledDisk(disk, this._throttleGenerator)
deltaExport.disks[key] = new SynchronizedDisk(disk)
}

View File

@@ -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)

View File

@@ -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')
})
})

View File

@@ -69,6 +69,7 @@ export class FullRemoteWriter extends MixinRemoteWriter(AbstractFullWriter) {
await deleteOldBackups()
}
let sizeOnDisk = 0
await Task.run({ properties: { name: 'transfer' } }, async () => {
await adapter.outputStream(dataFilename, stream, {
checksum,
@@ -76,9 +77,20 @@ export class FullRemoteWriter extends MixinRemoteWriter(AbstractFullWriter) {
streamLength,
validator: tmpPath => adapter.isValidXva(tmpPath),
})
sizeOnDisk = await adapter.handler.getSizeOnDisk(dataFilename)
try {
const size = await adapter.handler.getSizeOnDisk(`${dataFilename}.checksum`)
sizeOnDisk += size
} catch (error) {
if (error.code !== 'ENOENT') {
throw error
}
}
return { size: sizeContainer.size }
})
metadata.size = sizeContainer.size
metadata.sizeOnDisk = sizeOnDisk
metadata.tags = await this.getLongTermRetentionTags(metadata)
this._metadataFileName = await adapter.writeVmBackupMetadata(vm.uuid, metadata)

View File

@@ -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()
}
@@ -264,7 +280,10 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
vtpms: deltaExport.vtpms,
}
let size = 0
const vhdsSizeOnDisk = {}
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]) => {
@@ -281,10 +300,11 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
parentPath = relativeFromFile(path, parentDestPath)
}
const transferred = await adapter.writeVhd(path, disk, {
const { size: transferred, sizeOnDisk } = await adapter.writeVhd(path, disk, {
// 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),
@@ -292,6 +312,7 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
parentPath,
})
size += transferred
vhdsSizeOnDisk[diskRef] = sizeOnDisk
},
{
concurrency: settings.diskPerVmConcurrency,
@@ -300,8 +321,14 @@ 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
metadataContent.vhdsSizeOnDisk = vhdsSizeOnDisk
this._metadataFileName = await adapter.writeVmBackupMetadata(vm.uuid, metadataContent)
// TODO: run cleanup?

View File

@@ -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')
})
})

View File

@@ -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

View File

@@ -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')
})
})
}

View File

@@ -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 =

View File

@@ -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}`,

View File

@@ -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')
})
})

View File

@@ -1,17 +1,34 @@
import { TaskProgressHandler } from './_runners/_vmRunners/_TaskProgressHandler.mjs'
/**
* @param {import('node:stream').Readable} stream
* @param {{ size: number, progressHandler?: TaskProgressHandler, readTask?: import('./_SourceReadTask.mjs').SourceReadTask }} [container]
* `readTask`: reports the reading of the stream in its own task
*/
export function watchStreamSize(stream, container = { size: 0 }) {
const progressHandler = container.progressHandler ?? new TaskProgressHandler()
const { progressHandler = new TaskProgressHandler(), readTask } = container
stream.on('data', data => {
container.size += data.length
if (stream.length) {
// empty for xva exported by xapi
progressHandler.setProgress(container.size / stream.length)
}
readTask?.onRead(data.length)
})
stream.on('finish', () => {
progressHandler.setProgress(1)
})
if (readTask !== undefined) {
// unknown for a XVA exported by XAPI or read from an encrypted remote: no progress then
if (stream.length > 0) {
readTask.setBytesToRead(stream.length)
}
// no-op once the read task has ended
stream.on('error', error => readTask.onEnd(error))
stream.on('close', () => readTask.onEnd())
}
stream.pause()
return container
}

View File

@@ -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
```

View File

@@ -29,7 +29,17 @@ import { normalize } from '@xen-orchestra/fs/path'
*/
/**
* @returns {import('@vates/types').XoVmBackupArchive & { tags: string[] }}
* The fields of the metadata of a backup which tell the space it uses on the repository
*
* @typedef {object} BackupSizeMetadata
* @property {'full' | 'delta'} mode
* @property {number} [sizeOnDisk] full backup: size of the XVA, `.checksum` included
* @property {Record<string, string>} [vhds] delta backup: path of each disk, by VDI ref
* @property {Record<string, number>} [vhdsSizeOnDisk] delta backup: size of each disk, by VDI ref
*/
/**
* @returns {import('@vates/types').XoVmBackupArchive}
*/
export function formatVmBackup(backup) {
const { isVhdDifferencing, vmSnapshot } = backup
@@ -59,6 +69,8 @@ export function formatVmBackup(backup) {
id: `${dirname(backup._filename)}/${backup.vhds[vdiId]}`,
name: vdi.name_label,
uuid: vdi.uuid,
sizeOnDisk: backup.vhdsSizeOnDisk?.[vdiId],
isDifferencing: backup.isVhdDifferencing?.[vdiId],
}
}),
@@ -68,6 +80,7 @@ export function formatVmBackup(backup) {
mode: backup.mode,
scheduleId: backup.scheduleId,
size: backup.size,
sizeOnDisk: getVmBackupSizeOnDisk(backup),
timestamp: backup.timestamp,
vm: {
uuid: backup.vm.uuid,
@@ -131,3 +144,30 @@ export function formatJournalEvents(events, backupRepositoryId) {
return { event, vmUuid, filename, backup: formatVmBackupAt(metadata, filename, backupRepositoryId) }
})
}
/**
* Returns the space used on the repository or undefined if unknown or if a single disk is unknown
*
* @param {BackupSizeMetadata} metadata
* @returns {number | undefined}
*/
export function getVmBackupSizeOnDisk(metadata) {
if (metadata.mode === 'full') {
return metadata.sizeOnDisk
} else if (metadata.mode === 'delta' && metadata.vhds !== undefined) {
const vhdSizes = Object.keys(metadata.vhds).map(vdiRef => metadata.vhdsSizeOnDisk?.[vdiRef])
let sizeOnDisk = 0
for (const vhdSize of vhdSizes) {
if (vhdSize === undefined) {
return undefined
}
sizeOnDisk += vhdSize
}
return sizeOnDisk
}
return undefined
}

View File

@@ -54,7 +54,13 @@ describe('formatVmBackupAt()', () => {
for (const filename of [FILENAME, FILENAME.slice(1)]) {
assert.deepEqual(formatVmBackupAt(metadata, filename, REPOSITORY).disks, [
{ id: `/xo-vm-backups/${VM}/vdi.vhd`, name: 'a disk', uuid: 'a-vdi-uuid' },
{
id: `/xo-vm-backups/${VM}/vdi.vhd`,
isDifferencing: undefined,
name: 'a disk',
uuid: 'a-vdi-uuid',
sizeOnDisk: undefined,
},
])
}
})
@@ -99,6 +105,87 @@ describe('formatVmBackups()', () => {
})
})
describe('size on disk', () => {
const sizeOnDiskOf = metadata => {
const { disks, sizeOnDisk } = formatVmBackupAt(metadata, FILENAME, REPOSITORY)
return {
// keyed by uuid: the order of the disks follows the one of `vhds`
disks: Object.fromEntries(disks.map(disk => [disk.uuid, disk.sizeOnDisk])),
sizeOnDisk,
}
}
it('is the sum of the disks of a delta backup', () => {
const { disks, sizeOnDisk } = sizeOnDiskOf({
...metadata,
vhdsSizeOnDisk: { 'OpaqueRef:2f7a': 10, 'OpaqueRef:9c1b': 20 },
})
assert.deepEqual(disks, { 'snapshot-vdi-uuid-1': 10, 'snapshot-vdi-uuid-2': 20 })
assert.equal(sizeOnDisk, 30)
})
// a partial sum would look exact while missing disks
it('is unknown for a delta backup if the size of one of its disks is unknown', () => {
const { disks, sizeOnDisk } = sizeOnDiskOf({ ...metadata, vhdsSizeOnDisk: { 'OpaqueRef:2f7a': 10 } })
assert.deepEqual(disks, { 'snapshot-vdi-uuid-1': 10, 'snapshot-vdi-uuid-2': undefined })
assert.equal(sizeOnDisk, undefined)
})
it('is unknown for a delta backup written before it was recorded', () => {
const { disks, sizeOnDisk } = sizeOnDiskOf(metadata)
assert.deepEqual(disks, { 'snapshot-vdi-uuid-1': undefined, 'snapshot-vdi-uuid-2': undefined })
assert.equal(sizeOnDisk, undefined)
})
// a broken backup: its size is not known, and certainly not 0
it('is unknown for a delta backup without disks', () => {
assert.equal(sizeOnDiskOf({ ...metadata, vhds: undefined, vhdsSizeOnDisk: {} }).sizeOnDisk, undefined)
})
it('is the size of the XVA of a full backup', () => {
const { disks, sizeOnDisk } = sizeOnDiskOf(metadataOf({ sizeOnDisk: 42 }))
assert.deepEqual(disks, {})
assert.equal(sizeOnDisk, 42)
})
it('is unknown for a full backup written before it was recorded', () => {
assert.equal(sizeOnDiskOf(metadataOf()).sizeOnDisk, undefined)
})
it('is not the transferred size', () => {
const formatted = formatVmBackupAt(metadataOf({ size: 100, sizeOnDisk: 42 }), FILENAME, REPOSITORY)
assert.equal(formatted.size, 100)
assert.equal(formatted.sizeOnDisk, 42)
})
})
describe('is differencing', () => {
const isVhdDifferencingOf = metadata => {
const { disks } = formatVmBackupAt(metadata, FILENAME, REPOSITORY)
return Object.fromEntries(disks.map(disk => [disk.uuid, disk.isDifferencing]))
}
it('forwards isVhdDifferencing', () => {
const disks = isVhdDifferencingOf({
...metadata,
isVhdDifferencing: { 'OpaqueRef:2f7a': true, 'OpaqueRef:9c1b': false },
})
assert.deepEqual(disks, { 'snapshot-vdi-uuid-1': true, 'snapshot-vdi-uuid-2': false })
})
it('handles missing isVhdDifferencing', () => {
const disks = isVhdDifferencingOf(metadata)
assert.deepEqual(disks, { 'snapshot-vdi-uuid-1': undefined, 'snapshot-vdi-uuid-2': undefined })
})
})
describe('formatJournalEvents()', () => {
it('resolves the backup of the events which carry a metadata', () => {
const metadata = metadataOf()

View File

@@ -66,6 +66,11 @@ const main = Disposable.wrap(async function* main(args) {
await handler.unlink(previousTaskFile)
}
// the task has been removed since the queue was listed, nothing to do
if (error.code === 'ENOENT') {
return
}
throw error
}
@@ -80,7 +85,8 @@ const main = Disposable.wrap(async function* main(args) {
}
}
handler.unlink(taskFile).catch(error => warn('deleting task failure', { error }))
// wait for the deletion, otherwise the next listing may return a task which is about to be removed
await handler.unlink(taskFile).catch(error => warn('deleting task failure', { error }))
} catch (error) {
warn('failure handling task', { error })
if (error.code === 'ELOCKED') await new Promise(resolve => setTimeout(resolve, 5 * 60e3))

View File

@@ -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": {

View File

@@ -3,8 +3,8 @@ $ xo-disk-cli --help
Usage: xo-disk-cli <command> <handler-url> <path> [options]
Commands:
info Show disk info (virtual size, uid, parent uid, block size); --chain shows the full parent chain, --size adds the size on disk
list List all disks at a path and display their properties in a table; --size adds the size on disk
info Show disk info (virtual size, uid, parent uid, block size); --chain shows the full parent chain, --size adds the stream size
list List all disks at a path and display their properties in a table; --size adds the stream size
transform Convert a disk to another format and write to stdout (raw | vhd | qcow2)
```
@@ -30,8 +30,8 @@ Disk info: /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/snapshot.vhd
```
By default the disk is opened without reading its block allocation table, which
is cheap but does not allow computing the size on disk. Pass `--size` to read
the block allocation table and print the size on disk as an extra line:
is cheap but does not allow computing the stream size. Pass `--size` to read
the block allocation table and print the stream size as an extra line:
```
$ xo-disk-cli info file:///mnt/backups /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/snapshot.vhd --size
@@ -40,7 +40,7 @@ Disk info: /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/snapshot.vhd
Parent UID: <parent-uuid>
Virtual size: 8.00 GiB (8589934592 bytes)
Block size: 2.00 MiB (2097152 bytes)
Size on disk: 128.00 MiB (134217728 bytes)
Stream size: 128.00 MiB (134217728 bytes)
```
With `--chain`, the disk's full parent chain is opened and each disk is printed
@@ -73,7 +73,7 @@ xo-disk-cli list <handler-url> <dir-path> [--size]
```
By default disks are opened without reading their block allocation table (cheap),
so the "Size on disk" column is omitted:
so the "Stream size" column is omitted:
```
$ xo-disk-cli list file:///mnt/backups /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/
@@ -85,12 +85,12 @@ $ xo-disk-cli list file:///mnt/backups /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/
└──────────────┴──────────────────────────────────────┴──────────────┴─────────────┴──────────────────────────────────────┘
```
Pass `--size` to read each disk's block allocation table and add the "Size on disk" column:
Pass `--size` to read each disk's block allocation table and add the "Stream size" column:
```
$ xo-disk-cli list file:///mnt/backups /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/ --size
┌──────────────┬──────────────────────────────────────┬─────────────┬──────────────┬─────────────┬──────────────────────────────────────┐
│ File │ UID │ Size on disk│ Virtual size │ Differencing │ Parent UID │
│ File │ UID │ Stream size │ Virtual size │ Differencing │ Parent UID │
├──────────────┼──────────────────────────────────────┼─────────────┼──────────────┼─────────────┼──────────────────────────────────────┤
│ base.vhd │ xxxxxxxx-... │ 1.20 GiB │ 8.00 GiB │ no │ (none) │
│ snapshot.vhd │ yyyyyyyy-... │ 128.00 MiB │ 8.00 GiB │ yes │ ↑ │

View File

@@ -21,8 +21,8 @@ $ xo-disk-cli --help
Usage: xo-disk-cli <command> <handler-url> <path> [options]
Commands:
info Show disk info (virtual size, uid, parent uid, block size); --chain shows the full parent chain, --size adds the size on disk
list List all disks at a path and display their properties in a table; --size adds the size on disk
info Show disk info (virtual size, uid, parent uid, block size); --chain shows the full parent chain, --size adds the stream size
list List all disks at a path and display their properties in a table; --size adds the stream size
transform Convert a disk to another format and write to stdout (raw | vhd | qcow2)
```
@@ -48,8 +48,8 @@ Disk info: /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/snapshot.vhd
```
By default the disk is opened without reading its block allocation table, which
is cheap but does not allow computing the size on disk. Pass `--size` to read
the block allocation table and print the size on disk as an extra line:
is cheap but does not allow computing the stream size. Pass `--size` to read
the block allocation table and print the stream size as an extra line:
```
$ xo-disk-cli info file:///mnt/backups /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/snapshot.vhd --size
@@ -58,7 +58,7 @@ Disk info: /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/snapshot.vhd
Parent UID: <parent-uuid>
Virtual size: 8.00 GiB (8589934592 bytes)
Block size: 2.00 MiB (2097152 bytes)
Size on disk: 128.00 MiB (134217728 bytes)
Stream size: 128.00 MiB (134217728 bytes)
```
With `--chain`, the disk's full parent chain is opened and each disk is printed
@@ -91,7 +91,7 @@ xo-disk-cli list <handler-url> <dir-path> [--size]
```
By default disks are opened without reading their block allocation table (cheap),
so the "Size on disk" column is omitted:
so the "Stream size" column is omitted:
```
$ xo-disk-cli list file:///mnt/backups /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/
@@ -103,12 +103,12 @@ $ xo-disk-cli list file:///mnt/backups /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/
└──────────────┴──────────────────────────────────────┴──────────────┴─────────────┴──────────────────────────────────────┘
```
Pass `--size` to read each disk's block allocation table and add the "Size on disk" column:
Pass `--size` to read each disk's block allocation table and add the "Stream size" column:
```
$ xo-disk-cli list file:///mnt/backups /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/ --size
┌──────────────┬──────────────────────────────────────┬─────────────┬──────────────┬─────────────┬──────────────────────────────────────┐
│ File │ UID │ Size on disk│ Virtual size │ Differencing │ Parent UID │
│ File │ UID │ Stream size │ Virtual size │ Differencing │ Parent UID │
├──────────────┼──────────────────────────────────────┼─────────────┼──────────────┼─────────────┼──────────────────────────────────────┤
│ base.vhd │ xxxxxxxx-... │ 1.20 GiB │ 8.00 GiB │ no │ (none) │
│ snapshot.vhd │ yyyyyyyy-... │ 128.00 MiB │ 8.00 GiB │ yes │ ↑ │

View File

@@ -10,7 +10,7 @@ type DiskInfoLine = {
virtualSize: number
blockSize: number
// Only computed with --size; requires reading the block allocation table.
sizeOnDisk?: number
streamSize?: number
}
function readDiskInfo(disk: RemoteDisk, path: string, showSize: boolean): DiskInfoLine {
@@ -21,7 +21,7 @@ function readDiskInfo(disk: RemoteDisk, path: string, showSize: boolean): DiskIn
parentUid: isDifferencing ? disk.getParentUuid() : null,
virtualSize: disk.getVirtualSize(),
blockSize: disk.getBlockSize(),
sizeOnDisk: showSize ? disk.getSizeOnDisk() : undefined,
streamSize: showSize ? disk.getStreamSize() : undefined,
}
}
@@ -31,8 +31,8 @@ function printDiskInfo(info: DiskInfoLine): void {
console.log(` Parent UID: ${info.parentUid ?? '(none)'}`)
console.log(` Virtual size: ${formatBytes(info.virtualSize)} (${info.virtualSize} bytes)`)
console.log(` Block size: ${formatBytes(info.blockSize)} (${info.blockSize} bytes)`)
if (info.sizeOnDisk !== undefined) {
console.log(` Size on disk: ${formatBytes(info.sizeOnDisk)} (${info.sizeOnDisk} bytes)`)
if (info.streamSize !== undefined) {
console.log(` Stream size: ${formatBytes(info.streamSize)} (${info.streamSize} bytes)`)
}
}

View File

@@ -4,17 +4,17 @@ import { isDisk, openDisposableDisk, RemoteDisk } from '@xen-orchestra/backup-ar
import { formatBytes, renderTable } from '../utils.mjs'
import { asyncEach } from '@vates/async-each'
// The "Size on disk" column is only shown with --size: computing it requires
// The "Stream size" column is only shown with --size: computing it requires
// reading the block allocation table of every disk, which is costly.
function buildHeaders(showSize: boolean): string[] {
return ['File', 'UID', ...(showSize ? ['Size on disk'] : []), 'Virtual size', 'Differencing', 'Parent UID']
return ['File', 'UID', ...(showSize ? ['Stream size'] : []), 'Virtual size', 'Differencing', 'Parent UID']
}
export type OkDiskInfo = {
ok: true
filename: string
uid: string
sizeOnDisk?: string
streamSize?: string
virtualSize: string
differencing: boolean
parentUid: string | null
@@ -70,7 +70,7 @@ export function toTableRow(disk: DiskInfo, prevDisk: DiskInfo | undefined, showS
return [
disk.filename,
disk.uid,
...(showSize ? [disk.sizeOnDisk ?? '-'] : []),
...(showSize ? [disk.streamSize ?? '-'] : []),
disk.virtualSize,
disk.differencing ? 'yes' : 'no',
disk.differencing ? (parentIsAbove ? '↑' : (disk.parentUid ?? '')) : '(none)',
@@ -103,7 +103,7 @@ export async function listCommand(handlerUrl: string, dirPath: string, extraArgs
ok: true as const,
filename,
uid: disk.getUuid(),
sizeOnDisk: showSize ? formatBytes(disk.getSizeOnDisk()) : undefined,
streamSize: showSize ? formatBytes(disk.getStreamSize()) : undefined,
virtualSize: formatBytes(disk.getVirtualSize()),
differencing,
parentUid: differencing ? disk.getParentUuid() : null,

View File

@@ -51,7 +51,7 @@ declare module '@xen-orchestra/backup-archive/disks' {
import type { RandomAccessDisk } from '@xen-orchestra/disk-transform'
export interface RemoteDisk extends RandomAccessDisk {
getSizeOnDisk(): number
getStreamSize(): number
getPath(): string
getPaths(): string[]
getUuid(): string

View File

@@ -14,8 +14,8 @@ const COMMANDS: Record<string, CommandFn> = {
function showHelp(exitCode: number): never {
const commandDescriptions: Record<string, string> = {
info: 'Show disk info (virtual size, uid, parent uid, block size); --chain shows the full parent chain, --size adds the size on disk',
list: 'List all disks at a path and display their properties in a table; --size adds the size on disk',
info: 'Show disk info (virtual size, uid, parent uid, block size); --chain shows the full parent chain, --size adds the stream size',
list: 'List all disks at a path and display their properties in a table; --size adds the stream size',
transform: 'Convert a disk to another format and write to stdout (raw | vhd | qcow2)',
}

View File

@@ -5,7 +5,7 @@
* - Handler and disk are always disposed, even when disk methods throw.
* - Errors from broken disks are propagated (not swallowed).
* - By default disks are opened with ignoreBlockIndexes: true (cheap); --size
* opens with ignoreBlockIndexes: false and prints the size on disk.
* opens with ignoreBlockIndexes: false and prints the stream size.
* - --chain opens the whole lineage and prints each disk.
*
* Design: mock.module() is called once at the top level. The mocks read mutable
@@ -27,7 +27,7 @@ const baseDisk = {
isDifferencing: () => false,
getVirtualSize: () => 1024 * 1024 * 1024,
getBlockSize: () => 2 * 1024 * 1024,
getSizeOnDisk: () => 128 * 1024 * 1024,
getStreamSize: () => 128 * 1024 * 1024,
getUuid: () => 'aaaa-bbbb',
getParentUuid: () => 'pppp-qqqq',
}
@@ -128,17 +128,17 @@ describe('info command', () => {
await assert.rejects(() => infoCommand('file:///test', '/vdis/disk.vhd', []), /corrupt header/)
})
test('by default opens the disk with ignoreBlockIndexes: true and hides size on disk', async () => {
test('by default opens the disk with ignoreBlockIndexes: true and hides stream size', async () => {
const output = await captureLog(() => infoCommand('file:///test', '/vdis/disk.vhd', []))
assert.strictEqual(openDiskParams.length, 1)
assert.strictEqual(openDiskParams[0].ignoreBlockIndexes, true, 'block indexes must be skipped by default')
assert.ok(!output.includes('Size on disk'), 'size on disk must not be printed without --size')
assert.ok(!output.includes('Stream size'), 'stream size must not be printed without --size')
})
test('--size opens the disk with ignoreBlockIndexes: false and prints size on disk', async () => {
test('--size opens the disk with ignoreBlockIndexes: false and prints stream size', async () => {
const output = await captureLog(() => infoCommand('file:///test', '/vdis/disk.vhd', ['--size']))
assert.strictEqual(openDiskParams[0].ignoreBlockIndexes, false, 'block indexes must be read with --size')
assert.ok(output.includes('Size on disk'), 'size on disk must be printed with --size')
assert.ok(output.includes('Stream size'), 'stream size must be printed with --size')
})
test('without --chain, openDiskChain is never called', async () => {
@@ -164,15 +164,15 @@ describe('info command', () => {
)
})
test('--chain --size reads block indexes and prints size on disk for each disk', async () => {
test('--chain --size reads block indexes and prints stream size for each disk', async () => {
const output = await captureLog(() => infoCommand('file:///test', '/vdis/leaf.vhd', ['--chain', '--size']))
assert.strictEqual(openChainParams[0].ignoreBlockIndexes, false, 'chain walk must read block indexes with --size')
assert.ok(
openDiskParams.every(p => p.ignoreBlockIndexes === false),
'each chain disk must be opened with ignoreBlockIndexes: false'
)
const sizeLines = output.split('\n').filter(l => l.includes('Size on disk'))
assert.strictEqual(sizeLines.length, chainPaths.length, 'size on disk must be printed for each disk')
const sizeLines = output.split('\n').filter(l => l.includes('Stream size'))
assert.strictEqual(sizeLines.length, chainPaths.length, 'stream size must be printed for each disk')
})
test('--chain: chain is closed even when opening a disk in it throws', async () => {

View File

@@ -21,7 +21,7 @@ const diskDispose = mock.fn(() => Promise.resolve())
const baseDisk = {
isDifferencing: () => false,
getSizeOnDisk: () => 1024 * 1024 * 1024,
getStreamSize: () => 1024 * 1024 * 1024,
getVirtualSize: () => 8 * 1024 * 1024 * 1024,
getUuid: () => 'disk-uuid',
getParentUuid: () => null as unknown as string,
@@ -134,7 +134,7 @@ describe('list command', () => {
openDiskParams.every(p => p.ignoreBlockIndexes === true),
'disks must be opened with ignoreBlockIndexes: true by default'
)
assert.ok(!output.includes('Size on disk'), 'the size column must be hidden without --size')
assert.ok(!output.includes('Stream size'), 'the size column must be hidden without --size')
})
test('--size opens disks with ignoreBlockIndexes: false and shows the size column', async () => {
@@ -143,6 +143,6 @@ describe('list command', () => {
openDiskParams.every(p => p.ignoreBlockIndexes === false),
'disks must be opened with ignoreBlockIndexes: false with --size'
)
assert.ok(output.includes('Size on disk'), 'the size column must appear with --size')
assert.ok(output.includes('Stream size'), 'the size column must appear with --size')
})
})

View File

@@ -2,7 +2,7 @@ import { describe, test } from 'node:test'
import assert from 'node:assert/strict'
import { sortDisks, toTableRow, type DiskInfo } from '../commands/list.mjs'
// These tests assert on the full-width row (with the "Size on disk" column), so
// These tests assert on the full-width row (with the "Stream size" column), so
// they always exercise toTableRow with showSize = true.
const toTableRowWithSize = (disk: DiskInfo, prevDisk: DiskInfo | undefined) => toTableRow(disk, prevDisk, true)
@@ -15,7 +15,7 @@ function ok(uid: string, parentUid: string | null = null): DiskInfo & { ok: true
ok: true,
filename: `${uid}.vhd`,
uid,
sizeOnDisk: '1.00 GiB',
streamSize: '1.00 GiB',
virtualSize: '8.00 GiB',
differencing: parentUid !== null,
parentUid,

View File

@@ -0,0 +1,48 @@
import { Disk, DiskBlock } from './Disk.mjs'
import { DiskPassthrough } from './DiskPassthrough.mjs'
export type ReadMeter = {
/** called once, before the first read, with the number of bytes the source will produce */
setBytesToRead(length: number): void
/** called for each block read from the source */
onRead(length: number): void
/** called once, when the source is exhausted, closed early by its consumer or failed (`error`) */
onEnd(error?: unknown): void
}
/**
* Reports the bytes read from the source, and the end of its reading
*
* The meter is called from the async context of the consumer pulling the next block, which may be any of the
* forks of a SynchronizedDisk: it must not rely on this context
*/
export class MeteredDisk extends DiskPassthrough {
#meter: ReadMeter
constructor(source: Disk, meter: ReadMeter) {
super(source)
this.#meter = meter
}
async buildDiskBlockGenerator(): Promise<AsyncGenerator<DiskBlock>> {
const generator = await this.source.buildDiskBlockGenerator()
const meter = this.#meter
// known once the source is initialized, which building its generator requires: each block is full sized
meter.setBytesToRead(this.source.getBlockIndexesCount() * this.source.getBlockSize())
async function* meteredGenerator(): AsyncGenerator<DiskBlock> {
let error: unknown
try {
for await (const block of generator) {
meter.onRead(block.data.length)
yield block
}
} catch (err) {
error = err
throw err
} finally {
meter.onEnd(error)
}
}
return meteredGenerator()
}
}

View File

@@ -0,0 +1,123 @@
import { test } from 'node:test'
import assert from 'node:assert'
import { DebugDisk } from './utils/DebugDisk.mjs'
import { MeteredDisk, ReadMeter } from './MeteredDisk.mjs'
import { SynchronizedDisk } from './SynchronizedDisk.mjs'
import { DiskBlock } from './Disk.mjs'
const blockSize = 1024
const nbBlocks = 20
function createMeter() {
const meter = {
readSize: 0,
bytesToRead: [] as number[],
ends: [] as unknown[],
setBytesToRead(length: number) {
meter.bytesToRead.push(length)
},
onRead(length: number) {
meter.readSize += length
},
onEnd(error?: unknown) {
meter.ends.push(error)
},
} satisfies ReadMeter & Record<string, unknown>
return meter
}
async function createDisk() {
const disk = new DebugDisk({ nbBlocks, blockSize, fillRate: 100 })
await disk.init()
return disk
}
test('MeteredDisk', async t => {
await t.test('reports the bytes read and the end', async () => {
const disk = await createDisk()
const meter = createMeter()
const metered = new MeteredDisk(disk, meter)
for await (const block of metered.diskBlocks()) {
assert.strictEqual(block.data.length, blockSize)
}
assert.strictEqual(meter.readSize, nbBlocks * blockSize)
assert.deepStrictEqual(meter.bytesToRead, [nbBlocks * blockSize])
assert.deepStrictEqual(meter.ends, [undefined])
assert.strictEqual(disk.closeDone, true)
})
await t.test('reports an early stop of the consumer without error', async () => {
const meter = createMeter()
const metered = new MeteredDisk(await createDisk(), meter)
let nbRead = 0
for await (const block of metered.diskBlocks()) {
assert.strictEqual(block.data.length, blockSize)
if (++nbRead === 3) {
break
}
}
assert.strictEqual(meter.readSize, 3 * blockSize)
assert.deepStrictEqual(meter.ends, [undefined])
})
await t.test('reports the error of the source', async () => {
const disk = await createDisk()
const error = new Error('read failed')
disk.readBlock = async (index: number): Promise<DiskBlock> => {
if (index === 5) {
throw error
}
return { index, data: Buffer.alloc(blockSize) }
}
const meter = createMeter()
const metered = new MeteredDisk(disk, meter)
await assert.rejects(async () => {
for await (const block of metered.diskBlocks()) {
assert.strictEqual(block.data.length, blockSize)
}
}, error)
assert.strictEqual(meter.readSize, 5 * blockSize)
assert.deepStrictEqual(meter.ends, [error])
})
await t.test('counts a source read once by multiple forks', async () => {
const meter = createMeter()
const synchronized = new SynchronizedDisk(new MeteredDisk(await createDisk(), meter))
const forks = [synchronized.fork('first'), synchronized.fork('second')]
await Promise.all(
forks.map(async fork => {
for await (const block of fork.diskBlocks()) {
assert.strictEqual(block.data.length, blockSize)
await new Promise(resolve => setTimeout(resolve, Math.random() * 3))
}
})
)
assert.strictEqual(meter.readSize, nbBlocks * blockSize)
assert.deepStrictEqual(meter.bytesToRead, [nbBlocks * blockSize])
assert.deepStrictEqual(meter.ends, [undefined])
})
await t.test('reports the size of the blocks present in the source', async () => {
const disk = new DebugDisk({ nbBlocks, blockSize, fillRate: 50 })
await disk.init()
const meter = createMeter()
for await (const block of new MeteredDisk(disk, meter).diskBlocks()) {
assert.strictEqual(block.data.length, blockSize)
}
assert.strictEqual(meter.readSize, disk.getBlockIndexesCount() * blockSize)
// only the blocks present are to read, not the virtual size
assert.deepStrictEqual(meter.bytesToRead, [disk.getBlockIndexesCount() * blockSize])
})
await t.test('reads nothing from a source without blocks', async () => {
const disk = new DebugDisk({ nbBlocks, blockSize, fillRate: 0 })
await disk.init()
const meter = createMeter()
for await (const block of new MeteredDisk(disk, meter).diskBlocks()) {
assert.strictEqual(block.data.length, blockSize)
}
assert.strictEqual(meter.readSize, 0)
assert.deepStrictEqual(meter.bytesToRead, [0])
assert.deepStrictEqual(meter.ends, [undefined])
})
})

View File

@@ -9,5 +9,7 @@ export { RawDisk } from './RawDisk.mjs'
export { ReadAhead } from './ReadAhead.mjs'
export { SynchronizedDisk } from './SynchronizedDisk.mjs'
export { TimeoutDisk } from './Timeout.mjs'
export { MeteredDisk } from './MeteredDisk.mjs'
export type { ReadMeter } from './MeteredDisk.mjs'
export { ThrottledDisk } from './Throttled.mjs'
export { ProgressHandler } from './ProgressHandler.mjs'

View File

@@ -23,6 +23,14 @@ const computeRate = (hrtime, size) => {
return size / seconds
}
const getDataSize = data => {
if (Array.isArray(data)) {
return data.reduce((size, buffer) => size + Buffer.byteLength(buffer), 0)
}
return Buffer.byteLength(data)
}
const DEFAULT_TIMEOUT = 12e5 // 20 min
const DEFAULT_MAX_PARALLEL_OPERATIONS = 10
@@ -407,6 +415,7 @@ export default class RemoteHandlerAbstract {
encryptedData = Buffer.concat(encryptedData)
}
await this._outputFile(normalizePath(file), encryptedData, { dirMode, flags })
return getDataSize(encryptedData)
}
async read(file, buffer, position) {
@@ -596,6 +605,7 @@ export default class RemoteHandlerAbstract {
async __writeFile(file, data, { flags = 'wx' } = {}) {
const encryptedData = this.#encryptor.encryptData(data)
await this._writeFile(normalizePath(file), encryptedData, { flags })
return getDataSize(encryptedData)
}
// Methods that can be called by private methods to avoid parallel limit on public methods

View File

@@ -248,4 +248,21 @@ describe('encryption', () => {
code: 'MISSING_ENCRYPTION_KEY',
})
})
it('encrypted write returns the correct size', async () => {
const data = '0000000000'
await Disposable.use(
getSyncedHandler({ url: `file://${dir}?encryptionKey="73c1838d7d8a6088ca2317fb5f29cd91"` }),
async handler => {
const outputDataSize = await handler.outputFile('file', data)
const writeDataSize = await handler.writeFile('other', data)
assert.equal(outputDataSize, await handler.getSizeOnDisk(`file`))
assert(outputDataSize > Buffer.byteLength(data))
assert.equal(writeDataSize, await handler.getSizeOnDisk(`other`))
assert(writeDataSize > Buffer.byteLength(data))
}
)
})
})

View File

@@ -230,7 +230,7 @@ export default class AzureHandler extends RemoteHandlerAbstract {
*/
async _writeFile(file, data) {
const blobClient = this.#containerClient.getBlockBlobClient(this.#makeFullPath(file))
await blobClient.upload(data, data.length)
await blobClient.upload(data, Buffer.byteLength(data))
}
async _createReadStream(file) {

View File

@@ -190,6 +190,33 @@ handlers.forEach(url => {
await handler.sync()
await handler.outputFile(`xo-fs-tests-${Date.now()}/test`, '')
}, 40)
it('returns the correct file size', async () => {
const dataSize = await handler.outputFile('file', TEST_DATA)
assert.equal(dataSize, await handler.getSizeOnDisk('file'))
})
it('returns the correct file size with multi-byte character', async () => {
const dataSize = await handler.outputFile('file', 'é')
assert.equal(dataSize, await handler.getSizeOnDisk('file'))
})
it('returns the correct file size with buffer array', async () => {
const dataSize = await handler.outputFile('file', [TEST_DATA, TEST_DATA])
assert.equal(dataSize, await handler.getSizeOnDisk('file'))
})
})
describe('#writeFile()', () => {
it('returns the correct file size', async () => {
const dataSize = await handler.writeFile('file', TEST_DATA)
assert.equal(dataSize, await handler.getSizeOnDisk('file'))
})
it('returns the correct file size with multi-byte character', async () => {
const dataSize = await handler.writeFile('file', 'é')
assert.equal(dataSize, await handler.getSizeOnDisk('file'))
})
})
describe('#read()', () => {

View File

@@ -2,6 +2,19 @@
## **next**
- [VMs] The VMs tables work like in XO 6: side panel, per-VM actions menu, query builder search and bulk actions (PR [#10936](https://github.com/vatesfr/xen-orchestra/pull/10936))
## **0.28.1** (2026/12/04)
- [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))
- [VM/Network] Add a link to the pool network in the VIF side panel and table (PR [#10686](https://github.com/vatesfr/xen-orchestra/pull/10686))
- [VIF] Add a VIF page with general and network information, linked from the VM network table and the VIF side panel (PR [#10686](https://github.com/vatesfr/xen-orchestra/pull/10686))
- [Host] Add possibility to enable SSH on XCP-ng 9 hosts, and to disable it with auto-enable if XAPI goes down. The SSH status is shown in the host dashboard and System tab (PR [#10974](https://github.com/vatesfr/xen-orchestra/pull/10974))
- [Forms] The VM creation and XOA deployment forms show why a field is disabled (PR [#10963](https://github.com/vatesfr/xen-orchestra/pull/10963))
## **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))

View File

@@ -1,6 +1,6 @@
{
"name": "@xen-orchestra/lite",
"version": "0.27.0",
"version": "0.28.1",
"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",

View File

@@ -1,59 +0,0 @@
<template>
<UiFilterGroup>
<UiFilter
v-for="filter in activeFilters"
:key="filter"
@edit="openFilterModal(filter)"
@remove="emit('removeFilter', filter)"
>
{{ filter }}
</UiFilter>
<UiActionButton icon="fa:plus" class="add-filter" @click="openFilterModal()">
{{ t('action:add-filter') }}
</UiActionButton>
</UiFilterGroup>
</template>
<script lang="ts" setup>
import UiActionButton from '@/components/ui/UiActionButton.vue'
import UiFilter from '@/components/ui/UiFilter.vue'
import UiFilterGroup from '@/components/ui/UiFilterGroup.vue'
import type { Filters } from '@/types/filter.ts'
import { useOverlay } from '@core/packages/overlay/use-overlay.ts'
import { useI18n } from 'vue-i18n'
const { availableFilters } = defineProps<{
activeFilters: string[]
availableFilters: Filters
}>()
const emit = defineEmits<{
addFilter: [filter: string]
removeFilter: [filter: string]
}>()
const { t } = useI18n()
const { open } = useOverlay({
component: () => import('@/components/modals/CollectionFilterModal.vue'),
events: {
onCancel: true,
},
})
function openFilterModal(editedFilter?: string) {
return open({
props: { editedFilter, availableFilters },
events: {
onConfirm: newFilter => {
if (editedFilter !== undefined) {
emit('removeFilter', editedFilter)
}
emit('addFilter', newFilter)
},
},
})
}
</script>

View File

@@ -1,274 +0,0 @@
<template>
<div class="collection-filter-row">
<span class="or">{{ t('or') }}</span>
<div class="inputs">
<UiInput v-if="newFilter.isAdvanced" v-model="filterContent" accent="neutral" class="advanced-input" />
<template v-else>
<VtsSelect :id="builderPropertySelectId" accent="neutral" />
<VtsSelect v-if="hasComparisonSelect" :id="builderComparisonSelectId" accent="neutral" />
<VtsSelect v-if="currentFilter?.type === 'enum'" :id="builderValueSelectId" accent="neutral" />
<UiInput v-else-if="hasValueInput" v-model="newFilter.builder.value" accent="neutral" />
</template>
</div>
<div class="buttons">
<UiActionButton v-if="!newFilter.isAdvanced" icon="fa:pencil" @click="enableAdvancedMode" />
<UiActionButton icon="fa:remove" @click="emit('remove', newFilter.id)" />
</div>
</div>
</template>
<script lang="ts" setup>
import UiActionButton from '@/components/ui/UiActionButton.vue'
import { buildComplexMatcherNode } from '@/libs/complex-matcher.utils.ts'
import type { Filter, FilterComparisons, FilterComparisonType, Filters, FilterType, NewFilter } from '@/types/filter.ts'
import VtsSelect from '@core/components/select/VtsSelect.vue'
import UiInput from '@core/components/ui/input/UiInput.vue'
import { useFormSelect } from '@core/packages/form-select'
import { computed, watch } from 'vue'
import { useI18n } from 'vue-i18n'
const { availableFilters } = defineProps<{
availableFilters: Filters
}>()
const emit = defineEmits<{
remove: [filterId: number]
}>()
const newFilter = defineModel<NewFilter>({ required: true })
const filterContent = computed({
get: () => newFilter.value.content,
set: (content: string) => {
newFilter.value = {
...newFilter.value,
content,
}
},
})
const builderProperty = computed({
get: () => newFilter.value.builder.property,
set: (property: string) => {
newFilter.value = {
...newFilter.value,
builder: {
...newFilter.value.builder,
property,
comparison: getDefaultComparisonType(property),
value: '',
},
}
},
})
const builderComparison = computed({
get: () => newFilter.value.builder.comparison,
set: (comparison: FilterComparisonType) => {
newFilter.value = {
...newFilter.value,
builder: {
...newFilter.value.builder,
comparison,
},
}
},
})
const builderValue = computed({
get: () => newFilter.value.builder.value,
set: (value: string) => {
newFilter.value = {
...newFilter.value,
builder: {
...newFilter.value.builder,
value,
},
}
},
})
const { t } = useI18n()
function getDefaultComparisonType(property: string) {
const defaultTypes: { [key in FilterType]: FilterComparisonType } = {
string: 'stringContains',
boolean: 'booleanTrue',
number: 'numberEquals',
enum: 'enumIs',
}
return defaultTypes[availableFilters[property].type]
}
const currentFilter = computed<Filter | undefined>(() => availableFilters[builderProperty.value])
const hasValueInput = computed(() =>
currentFilter.value ? ['string', 'number'].includes(currentFilter.value?.type) : false
)
const hasComparisonSelect = computed(() => builderProperty.value !== '')
const enumChoices = computed(() => {
if (!builderProperty.value) {
return []
}
const availableFilter = availableFilters[builderProperty.value]
if (availableFilter.type !== 'enum') {
return []
}
return availableFilter.choices
})
const generatedFilter = computed(() => {
if (newFilter.value.isAdvanced) {
return newFilter.value.content
}
if (!builderComparison.value) {
return ''
}
try {
const node = buildComplexMatcherNode(builderComparison.value, builderProperty.value, builderValue.value)
if (node) {
return node.toString()
}
return ''
} catch (e) {
return ''
}
})
const enableAdvancedMode = () => {
newFilter.value = {
...newFilter.value,
isAdvanced: true,
content: generatedFilter.value,
}
}
watch(generatedFilter, value => {
newFilter.value = {
...newFilter.value,
content: value,
}
})
const comparisons = computed<FilterComparisons>(() => {
const comparisonsByType = {
string: {
stringContains: t('query-builder:operator:contains'),
stringEquals: t('query-builder:operator:equals'),
stringStartsWith: t('query-builder:operator:starts-with'),
stringEndsWith: t('query-builder:operator:ends-with'),
stringMatchesRegex: t('query-builder:operator:matches-regex'),
stringDoesNotContain: t('query-builder:operator:not-contain'),
stringDoesNotEqual: t('query-builder:operator:not-equal'),
stringDoesNotStartWith: t('query-builder:operator:not-start-with'),
stringDoesNotEndWith: t('query-builder:operator:not-end-with'),
stringDoesNotMatchRegex: t('query-builder:operator:not-match-regex'),
},
boolean: {
booleanTrue: t('query-builder:operator:is-true'),
booleanFalse: t('query-builder:operator:is-false'),
},
number: {
numberLessThan: '<',
numberLessThanOrEquals: '<=',
numberEquals: '=',
numberGreaterThanOrEquals: '>=',
numberGreaterThan: '>',
},
enum: {
enumIs: t('query-builder:operator:is'),
enumIsNot: t('query-builder:operator:is-not'),
},
}
return currentFilter.value?.type ? comparisonsByType[currentFilter.value.type] : {}
})
// BUILDER PROPERTY SELECT
const { id: builderPropertySelectId } = useFormSelect(Object.entries(availableFilters), {
model: builderProperty,
placeholder: `- ${t('property')} -`,
option: {
id: ([property]) => property,
label: ([property, filter]) => filter.label ?? property,
value: ([property]) => property,
},
})
// BUILDER COMPARISON SELECT
const { id: builderComparisonSelectId } = useFormSelect(
() => (hasComparisonSelect.value ? Object.entries(comparisons.value) : []),
{
model: builderComparison,
option: {
id: ([type]) => type,
label: ([, label]) => label,
value: ([type]) => type,
},
}
)
// BUILDER VALUE SELECT
const { id: builderValueSelectId } = useFormSelect(
() => (currentFilter.value?.type === 'enum' ? enumChoices.value : []),
{
model: builderValue,
}
)
</script>
<style lang="postcss" scoped>
.collection-filter-row {
display: flex;
align-items: center;
border-bottom: 1px solid var(--color-neutral-background-secondary);
gap: 1rem;
.or {
text-transform: uppercase;
}
&:only-child {
.or,
.remove {
display: none;
}
}
&:first-child .or {
visibility: hidden;
}
.inputs,
.buttons {
display: flex;
gap: 1rem;
@media (--small) {
flex-direction: column;
gap: 0.5rem;
}
}
.inputs {
flex: 1;
}
.buttons {
margin-left: auto;
}
}
</style>

View File

@@ -1,62 +0,0 @@
<template>
<UiFilterGroup class="collection-sorter">
<UiFilter
v-for="[property, isAscending] in activeSorts"
:key="property"
@edit="emit('toggleSortDirection', property)"
@remove="emit('removeSort', property)"
>
<span class="property">
<VtsIcon :name="isAscending ? 'fa:caret-up' : 'fa:caret-down'" size="medium" />
{{ property }}
</span>
</UiFilter>
<UiActionButton icon="fa:plus" class="add-sort" @click="openFormModal()">
{{ t('action:add-sort') }}
</UiActionButton>
</UiFilterGroup>
</template>
<script lang="ts" setup generic="TProperty extends PropertyKey">
import UiActionButton from '@/components/ui/UiActionButton.vue'
import UiFilter from '@/components/ui/UiFilter.vue'
import UiFilterGroup from '@/components/ui/UiFilterGroup.vue'
import type { ActiveSorts, Sorts } from '@/types/sort.ts'
import VtsIcon from '@core/components/icon/VtsIcon.vue'
import { useOverlay } from '@core/packages/overlay/use-overlay.ts'
import { useI18n } from 'vue-i18n'
const { availableSorts } = defineProps<{
availableSorts: Sorts
activeSorts: ActiveSorts<Record<TProperty, any>>
}>()
const emit = defineEmits<{
toggleSortDirection: [property: TProperty]
addSort: [property: TProperty, isAscending: boolean]
removeSort: [property: TProperty]
}>()
const { t } = useI18n()
const { open } = useOverlay({
component: () => import('@/components/modals/CollectionSorterModal.vue'),
events: {
onConfirm: ({ property, isAscending }) => emit('addSort', property as TProperty, isAscending),
onCancel: true,
},
})
function openFormModal() {
return open({ props: { availableSorts } })
}
</script>
<style lang="postcss" scoped>
.property {
display: inline-flex;
align-items: center;
gap: 0.7rem;
}
</style>

View File

@@ -19,7 +19,7 @@ const props = defineProps<{
id?: I
}>()
const route = useRoute<'/pool/[uuid]' | '/host/[uuid]' | '/vm/[uuid]'>()
const route = useRoute<'/pool/[uuid]' | '/host/[uuid]' | '/vm/[uuid]' | '/vif/[uuid]'>()
const id = computed(() => props.id ?? (route.params.uuid as I))

View File

@@ -8,6 +8,11 @@
</template>
</VtsKeyValueRow>
<VtsKeyValueRow :label="t('ip-address')" :value="host.address" copy />
<VtsKeyValueRow v-if="isSshManageable" :label="t('ssh')">
<template #value>
<VtsStatus :status="host.ssh_enabled ?? false" />
</template>
</VtsKeyValueRow>
<VtsKeyValueRow :label="t('started')" :value="isRunning ? relativeStartTime : undefined" />
<VtsKeyValueRow :label="t('master')">
<template #value>
@@ -49,7 +54,7 @@
<script lang="ts" setup>
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import { useHostUtils } from '@/modules/host/composables/host-utils.composable.ts'
import { getHostCoreSocketInfo, getHostManufacturerInfo } from '@/modules/host/utils/host.util.ts'
import { getHostCoreSocketInfo, getHostManufacturerInfo, isHostSshManageable } from '@/modules/host/utils/host.util.ts'
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
import { useHostStore } from '@/stores/xen-api/host.store.ts'
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
@@ -57,6 +62,7 @@ import VtsIcon from '@core/components/icon/VtsIcon.vue'
import VtsKeyValueList from '@core/components/key-value-list/VtsKeyValueList.vue'
import VtsKeyValueRow from '@core/components/key-value-row/VtsKeyValueRow.vue'
import VtsQuickInfoCard from '@core/components/quick-info-card/VtsQuickInfoCard.vue'
import VtsStatus from '@core/components/status/VtsStatus.vue'
import VtsTag from '@core/components/tag/VtsTag.vue'
import UiLink from '@core/components/ui/link/UiLink.vue'
import UiTagsList from '@core/components/ui/tag/UiTagsList.vue'
@@ -84,6 +90,8 @@ const manufacturerInfo = computed(() => getHostManufacturerInfo(host))
const coreSocketInfo = computed(() => getHostCoreSocketInfo(host))
const isSshManageable = computed(() => isHostSshManageable(host))
const ram = computed(() => {
const memory = getHostMemory(host)

View File

@@ -6,8 +6,8 @@
<slot name="title-actions" />
</template>
</UiTitle>
<UiQuerySearchBar v-bind="searchBindings" />
<div class="container">
<UiQuerySearchBar v-bind="searchBindings" />
<VtsTable :state :pagination-bindings sticky="right">
<thead>
<tr>

View File

@@ -5,6 +5,11 @@
</UiTitle>
<VtsTabularKeyValueList>
<VtsTabularKeyValueRow :label="t('ip-address')" :value="host.address" copy />
<VtsTabularKeyValueRow v-if="isSshManageable" :label="t('ssh')">
<template #value>
<VtsStatus :status="host.ssh_enabled ?? false" />
</template>
</VtsTabularKeyValueRow>
<VtsTabularKeyValueRow :label="t('remote-syslog')" :value="host.logging.syslog_destination" />
<VtsTabularKeyValueRow :label="t('iscsi-iqn')" :value="host.iscsi_iqn" copy />
<VtsTabularKeyValueRow :label="t('multi-pathing')">
@@ -18,16 +23,20 @@
<script setup lang="ts">
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import { isHostSshManageable } from '@/modules/host/utils/host.util.ts'
import VtsStatus from '@core/components/status/VtsStatus.vue'
import VtsTabularKeyValueList from '@core/components/tabular-key-value-list/VtsTabularKeyValueList.vue'
import VtsTabularKeyValueRow from '@core/components/tabular-key-value-row/VtsTabularKeyValueRow.vue'
import UiCard from '@core/components/ui/card/UiCard.vue'
import UiTitle from '@core/components/ui/title/UiTitle.vue'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
defineProps<{
const { host } = defineProps<{
host: XenApiHost
}>()
const { t } = useI18n()
const isSshManageable = computed(() => isHostSshManageable(host))
</script>

View File

@@ -1,151 +0,0 @@
<template>
<UiModal accent="info" @dismiss="emit('cancel')" @confirm="emit('confirm', generatedFilter)">
<template #content>
<div class="rows">
<CollectionFilterRow
v-for="(newFilter, index) in newFilters"
:key="newFilter.id"
v-model="newFilters[index]"
:available-filters="availableFilters"
@remove="removeNewFilter($event)"
/>
<div>
<VtsOverlayButton variant="tertiary" @click="addNewFilter()">
{{ t('add-or') }}
</VtsOverlayButton>
</div>
</div>
<div v-if="newFilters.some(filter => filter.isAdvanced)" class="available-properties">
{{ t('available-properties-for-advanced-filter:') }}
<div class="properties typo-body-regular">
<UiBadge v-for="(filter, property) in availableFilters" :key="property" :icon="getFilterIcon(filter)">
{{ property }}
</UiBadge>
</div>
</div>
</template>
<template #buttons>
<VtsOverlayCancelButton @click="emit('cancel')" />
<VtsOverlayConfirmButton :disabled="!isFilterValid">
{{ editedFilter ? t('action:update') : t('action:add') }}
</VtsOverlayConfirmButton>
</template>
</UiModal>
</template>
<script lang="ts" setup>
import CollectionFilterRow from '@/components/CollectionFilterRow.vue'
import UiBadge from '@/components/ui/UiBadge.vue'
import { getFilterIcon } from '@/libs/utils.ts'
import type { Filters, NewFilter } from '@/types/filter.ts'
import VtsOverlayButton from '@core/components/overlay/VtsOverlayButton.vue'
import VtsOverlayCancelButton from '@core/components/overlay/VtsOverlayCancelButton.vue'
import VtsOverlayConfirmButton from '@core/components/overlay/VtsOverlayConfirmButton.vue'
import UiModal from '@core/components/ui/modal/UiModal.vue'
import { Or, parse } from 'complex-matcher'
import { computed, onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
const { editedFilter } = defineProps<{
availableFilters: Filters
editedFilter?: string
}>()
const emit = defineEmits<{
confirm: [filter: string]
cancel: []
}>()
const { t } = useI18n()
const newFilters = ref<NewFilter[]>([])
let newFilterId = 0
const addNewFilter = () =>
newFilters.value.push({
id: newFilterId++,
content: '',
isAdvanced: false,
builder: { property: '', comparison: '', value: '', negate: false },
})
const removeNewFilter = (id: number) => {
const index = newFilters.value.findIndex(newFilter => newFilter.id === id)
if (index >= 0) {
newFilters.value.splice(index, 1)
}
}
const generatedFilter = computed(() => {
const filters = newFilters.value.filter(newFilter => newFilter.content !== '')
if (filters.length === 0) {
return ''
}
if (filters.length === 1) {
return filters[0].content
}
return `|(${filters.map(filter => filter.content).join(' ')})`
})
const isFilterValid = computed(() => generatedFilter.value !== '')
onMounted(() => {
if (editedFilter === undefined) {
addNewFilter()
return
}
const parsedFilter = parse(editedFilter)
const nodes = parsedFilter instanceof Or ? parsedFilter.children : [parsedFilter]
newFilters.value = nodes.map(node => ({
id: newFilterId++,
content: node.toString(),
isAdvanced: true,
builder: { property: '', comparison: '', value: '', negate: false },
}))
})
</script>
<style lang="postcss" scoped>
.properties {
margin-top: 1rem;
ul {
margin-left: 1rem;
}
li {
cursor: pointer;
&:hover {
opacity: 0.7;
}
}
}
.available-properties {
margin-top: 1rem;
}
.properties {
display: flex;
margin-top: 0.6rem;
gap: 0.5rem;
}
.rows {
display: flex;
flex-direction: column;
gap: 1rem;
max-width: 100%;
@media (--small) {
gap: 2.4rem;
}
}
</style>

View File

@@ -1,74 +0,0 @@
<template>
<UiModal accent="info" @dismiss="emit('cancel')" @confirm="handleSubmit()">
<template #content>
<div class="form-selects">
<VtsSelect :id="sortPropertySelectId" accent="neutral" />
<VtsSelect :id="isAscendingSelectId" accent="neutral" />
</div>
</template>
<template #buttons>
<VtsOverlayCancelButton @click="emit('cancel')" />
<VtsOverlayConfirmButton :disabled="!newSortProperty">{{ t('action:add') }}</VtsOverlayConfirmButton>
</template>
</UiModal>
</template>
<script lang="ts" setup>
import type { NewSort, Sorts } from '@/types/sort.ts'
import VtsOverlayCancelButton from '@core/components/overlay/VtsOverlayCancelButton.vue'
import VtsOverlayConfirmButton from '@core/components/overlay/VtsOverlayConfirmButton.vue'
import VtsSelect from '@core/components/select/VtsSelect.vue'
import UiModal from '@core/components/ui/modal/UiModal.vue'
import { useFormSelect } from '@core/packages/form-select'
import { ref } from 'vue'
import { useI18n } from 'vue-i18n'
const { availableSorts } = defineProps<{
availableSorts: Sorts
}>()
const emit = defineEmits<{
confirm: [sort: NewSort]
cancel: []
}>()
const { t } = useI18n()
const newSortProperty = ref()
const newSortIsAscending = ref<boolean>(true)
const handleSubmit = () =>
emit('confirm', {
property: newSortProperty.value,
isAscending: newSortIsAscending.value,
})
const { id: sortPropertySelectId } = useFormSelect(Object.entries(availableSorts), {
model: newSortProperty,
option: {
id: ([property]) => property,
label: ([property, sort]) => sort.label ?? property,
value: ([property]) => property,
},
})
const { id: isAscendingSelectId } = useFormSelect([true, false], {
model: newSortIsAscending,
option: {
id: value => value.toString(),
label: value => (value ? t('ascending') : t('descending')),
},
})
</script>
<style lang="postcss" scoped>
.form-selects {
display: flex;
gap: 1rem;
@media (--small) {
flex-direction: column;
}
}
</style>

View File

@@ -1,17 +1,15 @@
<template>
<tr class="pif-row" :class="{ compact }">
<td class="typo-body-regular-small host">
<UiLink
<HostLink
v-if="host"
:host
:to="{ name: '/host/[uuid]/network', params: { uuid: host.uuid }, query: { id: pif.uuid } }"
:icon="getHostIcon(host, getHostPowerState(host))"
:is-primary="isMasterHost(host.$ref)"
:primary-tooltip="t('master')"
size="small"
class="host-link"
>
<span v-tooltip class="text-ellipsis">{{ host.name_label }}</span>
</UiLink>
</HostLink>
<span v-else>{{ t('host:status:unknown') }}</span>
</td>
<td v-tooltip class="typo-body-regular-small text-ellipsis device">{{ pif.device }}</td>
@@ -23,13 +21,10 @@
<script setup lang="ts">
import type { XenApiPif } from '@/libs/xen-api/xen-api.types.ts'
import { getHostIcon } from '@/modules/host/utils/host.util.ts'
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
import HostLink from '@/modules/host/components/HostLink.vue'
import { useHostStore } from '@/stores/xen-api/host.store.ts'
import { usePifStore } from '@/stores/xen-api/pif.store.ts'
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
import VtsStatus from '@core/components/status/VtsStatus.vue'
import UiLink from '@core/components/ui/link/UiLink.vue'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
@@ -42,9 +37,7 @@ const { pif } = defineProps<{
const { t } = useI18n()
const { getByOpaqueRef } = useHostStore().subscribe()
const { getHostPowerState } = useHostMetricsStore().subscribe()
const { getPifStatus } = usePifStore().subscribe()
const { isMasterHost } = usePoolStore().subscribe()
const host = computed(() => getByOpaqueRef(pif.host))

View File

@@ -6,8 +6,8 @@
<slot name="title-actions" />
</template>
</UiTitle>
<UiQuerySearchBar v-bind="searchBindings" />
<div class="container">
<UiQuerySearchBar v-bind="searchBindings" />
<VtsTable :state :pagination-bindings sticky="right">
<thead>
<tr>

View File

@@ -85,6 +85,7 @@
<script setup lang="ts">
import PifRow from '@/components/pif/PifRow.vue'
import type { XenApiNetwork } from '@/libs/xen-api/xen-api.types.ts'
import { useNetworkUtils } from '@/modules/network/composables/network-utils.composable.ts'
import { useNetworkDelete } from '@/modules/network/composables/use-network-delete.composable.ts'
import { usePifStore } from '@/stores/xen-api/pif.store.ts'
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
@@ -108,6 +109,7 @@ const emit = defineEmits<{
}>()
const { getPifsByNetworkRef } = usePifStore().subscribe()
const { getNetworkVlan } = useNetworkUtils()
const { t } = useI18n()
@@ -115,13 +117,7 @@ const { deleteNetworks, isDeletingNetworks } = useNetworkDelete(() => (network !
const pifs = computed(() => (network !== undefined ? getPifsByNetworkRef(network.$ref) : []))
const networkVlan = computed(() => {
if (pifs.value.length === 0) {
return
}
return pifs.value[0].VLAN !== -1 ? pifs.value[0].VLAN.toString() : t('none')
})
const networkVlan = computed(() => (network !== undefined ? getNetworkVlan(network) : undefined))
const networkNbd = computed(() => (network?.purpose[0] ? t('on') : t('off')))

View File

@@ -6,8 +6,8 @@
<slot name="title-actions" />
</template>
</UiTitle>
<UiQuerySearchBar v-bind="searchBindings" />
<div class="container">
<UiQuerySearchBar v-bind="searchBindings" />
<VtsTable :state :pagination-bindings sticky="right">
<thead>
<tr>

View File

@@ -1,66 +0,0 @@
<template>
<button
:class="{
busy: busy,
disabled: isDisabled,
active,
'has-icon': icon !== undefined,
}"
:disabled="busy || isDisabled"
class="ui-action-button"
type="button"
>
<VtsIcon :busy :name="icon" size="medium" />
<slot />
</button>
</template>
<script lang="ts" setup>
import type { IconName } from '@core/icons'
import VtsIcon from '@core/components/icon/VtsIcon.vue'
import { useDisabled } from '@core/composables/disabled.composable.ts'
const props = defineProps<{
busy?: boolean
disabled?: boolean
icon?: IconName
active?: boolean
}>()
const isDisabled = useDisabled(() => props.disabled)
</script>
<style lang="postcss" scoped>
.ui-action-button {
font-size: 1.6rem;
font-weight: 400;
display: inline-flex;
align-items: center;
justify-content: center;
height: 4.4rem;
padding: 0 1.5rem;
border: none;
border-radius: 0.8rem;
gap: 1rem;
background-color: var(--color-neutral-background-primary);
&.disabled {
color: var(--color-neutral-border);
}
&:not(.disabled) {
color: var(--color-neutral-txt-secondary);
&:hover {
background-color: var(--color-neutral-background-secondary);
}
&:active,
&.active,
&.busy {
color: var(--color-brand-txt-base);
background-color: var(--color-brand-background-selected);
}
}
}
</style>

View File

@@ -1,15 +0,0 @@
<template>
<div class="ui-filter-group">
<slot />
</div>
</template>
<style lang="postcss" scoped>
.ui-filter-group {
display: flex;
align-items: center;
padding: 1rem;
background-color: var(--color-neutral-background-primary);
gap: 1rem;
}
</style>

View File

@@ -1,59 +1,36 @@
<template>
<MenuItem
v-tooltip="!areAllSelectedVmsHalted && t(isSingleAction ? 'vm-is-running' : 'selected-vms-in-execution')"
v-tooltip="isDisabled && copyVmErrorMessage"
accent="neutral"
:busy="areSomeSelectedVmsCloning"
:busy="isCopyingVm"
:disabled="isDisabled"
icon="action:duplicate"
@click="handleCopy"
@click="copyVm({ detached: true })"
>
{{ t('action:copy') }}
</MenuItem>
</template>
<script lang="ts" setup>
import { isVmOperationPending } from '@/libs/vm.ts'
import { VM_OPERATION, VM_POWER_STATE } from '@/libs/xen-api/xen-api.enums.ts'
import { useVmCopyJob } from '@/jobs/vm-copy.job.ts'
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
import { useXenApiStore } from '@/stores/xen-api.store.ts'
import MenuItem from '@core/components/menu/MenuItem.vue'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const props = defineProps<{
selectedRefs: XenApiVm['$ref'][]
isSingleAction?: boolean
const { vm } = defineProps<{
vm: XenApiVm
}>()
const { t } = useI18n()
const { getByOpaqueRef } = useVmStore().subscribe()
const {
run: copyVm,
canRun: canCopyVm,
isRunning: isCopyingVm,
errorMessage: copyVmErrorMessage,
} = useVmCopyJob(() => [vm])
const selectedVms = computed(() =>
props.selectedRefs.map(vmRef => getByOpaqueRef(vmRef)).filter((vm): vm is XenApiVm => vm !== undefined)
)
const areAllSelectedVmsHalted = computed(
() =>
selectedVms.value.length > 0 &&
selectedVms.value.every(selectedVm => selectedVm.power_state === VM_POWER_STATE.HALTED)
)
const areSomeSelectedVmsCloning = computed(() =>
selectedVms.value.some(vm => isVmOperationPending(vm, VM_OPERATION.CLONE))
)
const isDisabled = computed(() => {
return selectedVms.value.length === 0 || !areAllSelectedVmsHalted.value
})
const handleCopy = async () => {
const xapiStore = useXenApiStore()
const vmRefsToClone = Object.fromEntries(selectedVms.value.map(vm => [vm.$ref, `${vm.name_label} (COPY)`]))
await xapiStore.getXapi().vm.clone(vmRefsToClone)
}
const isDisabled = computed(() => !canCopyVm.value && !isCopyingVm.value)
</script>

View File

@@ -1,51 +1,31 @@
<template>
<MenuItem
v-tooltip="areSomeVmsInExecution && t('selected-vms-in-execution')"
<VtsActionButton
variant="tertiary"
accent="danger"
:busy="isDeletingVms"
:disabled="isDisabled"
icon="fa:trash"
@click="openDeleteModal()"
:hint="deleteVmsErrorMessage"
@click="deleteVms()"
>
{{ t('action:delete') }}
</MenuItem>
</VtsActionButton>
</template>
<script lang="ts" setup>
import { VM_POWER_STATE } from '@/libs/xen-api/xen-api.enums.ts'
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
import { useXenApiStore } from '@/stores/xen-api.store.ts'
import MenuItem from '@core/components/menu/MenuItem.vue'
import { useDeleteModal } from '@core/composables/modals/use-delete-modal.ts'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import { computed } from 'vue'
import { useVmDelete } from '@/modules/vm/composables/vm-delete.composable.ts'
import VtsActionButton from '@core/components/action-button/VtsActionButton.vue'
import { useDisabled } from '@core/composables/disabled.composable.ts'
import { useI18n } from 'vue-i18n'
const { vmRefs } = defineProps<{
vmRefs: XenApiVm['$ref'][]
const { vm } = defineProps<{
vm: XenApiVm
}>()
const { t } = useI18n()
const { getByOpaqueRef: getVm } = useVmStore().subscribe()
const { deleteVms, canDeleteVms, isDeletingVms, deleteVmsErrorMessage } = useVmDelete(() => [vm])
const vms = computed<XenApiVm[]>(() => vmRefs.map(getVm).filter((vm): vm is XenApiVm => vm !== undefined))
const areSomeVmsInExecution = computed(() => vms.value.some(vm => vm.power_state !== VM_POWER_STATE.HALTED))
const isDisabled = computed(() => vms.value.length === 0 || areSomeVmsInExecution.value)
const xenApi = useXenApiStore().getXapi()
const { open: openModal } = useDeleteModal()
function openDeleteModal() {
return openModal({
events: { onConfirm: () => xenApi.vm.delete(vmRefs) },
props: {
subject: t('n-vms', { n: vmRefs.length }),
confirmLabel: t('action:delete-n-vms', { n: vmRefs.length }),
},
})
}
const isDisabled = useDisabled(() => !canDeleteVms.value && !isDeletingVms.value)
</script>

Some files were not shown because too many files have changed in this diff Show More