Compare commits

..

8 Commits

Author SHA1 Message Date
Sebastien Rodot
488ddd5e74 docs: CHANGELOG.unreleased.md
Add user-facing bug fix entries for the xo-server-sdn-controller
private networks fixes (host joining a pool, host ejected from a pool)
and mark xo-server-sdn-controller for a patch release.
2026-11-26 11:23:14 +01:00
Sebastien Rodot
b1ddc3fa70 fix(xo-server-sdn-controller): rewire private networks when a host leaves the pool
When a host is ejected from a pool, the VXLAN legs created by the SDN
controller on the remaining hosts (in particular on the star center) are
never removed: XAPI only destroys the tunnel records of the ejected host
itself, so the center keeps an active tunnel port toward the host's underlay
IP until the plugin is reloaded.

On the removal of a non-center host, re-run the network registration of its
pool (resetForNetwork then addHost for each host), as done on plugin load,
to remove the stale ports and rewire the remaining hosts.
2026-11-25 13:43:54 +01:00
Sebastien Rodot
76ae982a48 fix(xo-server-sdn-controller): log "Host added" only when the port is (re)created
Since the tunnel index fix (_addHostToPrivateNetworks reading `tunnel`
instead of the nonexistent `SDN_tunnel`), the host wiring runs on every host
metrics event (the reconcile), and addHost unconditionally logged
"Host added" at info level, spamming the log once per host per private
network every ~10 s even when nothing changed.

addInterfaceAndPort now reports whether it created the port ({name, added})
instead of only the bridge name, and addHost logs only when the host or the
center side was actually (re)wired. The bridge name is still returned so
the tunnel status key is restored, and the OVSDB operations are unchanged.
2026-11-25 13:43:54 +01:00
Sebastien Rodot
ba73b578f2 test(xo-server-sdn-controller): cover wiring a host that joins with private networks
Add tests that a just-joined host gets its OVSDB client created once it
becomes enabled, and that _addHostToPrivateNetworks only processes the tunnels
whose access PIF belongs to that host.
2026-11-25 13:43:54 +01:00
Sebastien Rodot
5a5f780441 fix(xo-server-sdn-controller): read the tunnel index by its real class name
_addHostToPrivateNetworks iterated the host's tunnels from
`indexes.type.SDN_tunnel`, a class name that does not exist in the XAPI data
model (the IDL calls it `tunnel`). The lookup always returned nothing, so the
per-network host wiring was a silent no-op and tunnels were never activated on
a newly added host.

Read `indexes.type.tunnel` instead.
2026-11-25 13:43:54 +01:00
Sebastien Rodot
5a411d2448 fix(xo-server-sdn-controller): create the OVSDB client when a host becomes enabled
A host that joins a pool while the SDN controller is already running never
got its OVSDB client created: it is only attempted on the host `add` event,
which bails out while the host is not yet `enabled`, and the later `enabled`
update (_hostUpdated) never retried it. With no client, the VXLAN tunnel leg
is never programmed and a VM migrated to that host is isolated at L2 until a
plugin reload.

Create the client once the host passes the join guard (enabled and recorded
as new), just before the pool certificates are synced.
2026-11-25 13:43:54 +01:00
Sebastien Rodot
37cf301562 test(xo-server-sdn-controller): cover a missing OVSDB Controller row
Add a test that setBridgeControllerForNetwork returns without throwing (and
without sending a transaction) when the host's Controller row does not exist
yet.
2026-11-25 13:43:54 +01:00
Sebastien Rodot
a92d89890b fix(xo-server-sdn-controller): handle a missing OVSDB Controller row
setBridgeControllerForNetwork resolved the host's controller UUID by selecting
the OVSDB `Controller` row and dereferencing the result unconditionally. For a
host that just joined the pool that row does not exist yet (setBridgeController()
has not run), so the select came back empty and undefined._uuid threw a
TypeError, surfacing as an unhandled rejection (the call is fire-and-forget).

Return early when the row is not found: the join flow creates the controller
right after, and later PIF events pick it up.

While here, remove now dead code assert.
2026-11-25 13:43:54 +01:00
473 changed files with 2231 additions and 14171 deletions

View File

@@ -13,7 +13,7 @@
"url": "https://vates.fr"
},
"license": "ISC",
"version": "3.7.2",
"version": "3.7.1",
"engines": {
"node": ">=14.0"
},

View File

@@ -25,17 +25,6 @@ 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
@@ -49,12 +38,9 @@ task.id
// - failure
task.status
// Triggers the abort signal associated to the task, and the ones of its subtasks.
// Triggers the abort signal associated to the task.
//
// 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.
// This simply requests the task to abort, it will be up to the task to handle or not this signal.
task.abort(reason)
// if fn rejects, the task will be marked as failed

View File

@@ -41,17 +41,6 @@ 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
@@ -65,12 +54,9 @@ task.id
// - failure
task.status
// Triggers the abort signal associated to the task, and the ones of its subtasks.
// Triggers the abort signal associated to the task.
//
// 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.
// This simply requests the task to abort, it will be up to the task to handle or not this signal.
task.abort(reason)
// if fn rejects, the task will be marked as failed

View File

@@ -35,17 +35,6 @@ 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'
@@ -97,12 +86,11 @@ class Task {
}
}
// These properties should not be used outside the class
// These two 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,
@@ -122,26 +110,18 @@ class Task {
return this.#status
}
// `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 } = {}) {
constructor({ properties, onProgress } = {}) {
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) {
// `_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
}
const { signal } = parent._abortController
signal.addEventListener('abort', () => {
this._abortController.abort(signal.reason)
})
this._onProgress = parent._onProgress
this.#startData.parentId = parent.id
@@ -158,23 +138,10 @@ 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) {
@@ -225,14 +192,8 @@ 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,213 +175,6 @@ 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.2.0",
"version": "3.0.0",
"main": "./dist/index.mjs",
"exports": {
".": {

View File

@@ -822,16 +822,3 @@ export type RPU_RECOVERY_STEP_NAME = (typeof RPU_RECOVERY_STEP_NAMES)[number]
export const COMMON_TAG = {
NOBAK: 'xo:no-bak',
} as const
/**
* a package of the XO appliance with another version available
*
* Returned by `xoa-updater` as `upgradablePackages` at the end of an update check.
*/
export type XoaPackageUpdate = {
name: string
/** version which will be installed */
version: string
/** undefined: the package is not installed yet */
installedVersion?: string
}

View File

@@ -53,7 +53,6 @@ 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

@@ -462,7 +462,6 @@ export interface Xapi {
stream: Readable | Buffer,
opts: { signal?: AbortSignal; format: SUPPORTED_VDI_FORMAT }
): Promise<void>
VDI_resize(vdiRef: XenApiVdi['$ref'], size: number): Promise<void>
VIF_create(
options: {
currently_attached?: boolean
@@ -481,8 +480,6 @@ 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

@@ -472,7 +472,6 @@ export type XoApp = EventEmitter & {
getPlugin(id: XoPlugin['id']): Promise<XoPlugin>
getPlugins(): Promise<XoPlugin[]>
getProxy(id: XoProxy['id']): Promise<XoProxy>
getProxyApplianceUpdaterState(id: XoProxy['id']): Promise<{ level: string; message: string; state: string }>
getRemote(id: XoBackupRepository['id']): Promise<XoBackupRepository>
getAllRemotes(): Promise<XoBackupRepository[]>
removeRemote(id: XoBackupRepository['id']): Promise<void>

View File

@@ -193,21 +193,12 @@ export type XoVmBackupArchive = {
id: Branded<'vm-backup-archive'>
type: 'xo-vm-backup'
backupRepository: XoBackupRepository['id']
disks: {
id: string
name: string
uuid: XoVdiSnapshot['uuid']
sizeOnDisk?: number
isDifferencing?: boolean
}[]
disks: { id: string; name: string; uuid: XoVdiSnapshot['uuid'] }[]
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']
@@ -218,7 +209,6 @@ 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.2.0",
"@vates/types": "^3.0.0",
"rimraf": "^6.0.1",
"typescript": "~5.6",
"typescript-eslint": "^8.61.0"

View File

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

View File

@@ -8,28 +8,9 @@ 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']
@@ -47,14 +28,9 @@ 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() {
@@ -68,20 +44,11 @@ export class Privilege<T extends SupportedResource> {
return this.#action === '*' || this.#action === action || action.startsWith(`${this.#action}:`)
}
#matchSelector(object: object, knownFields?: string[]) {
#matchSelector(object: object) {
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)
}
@@ -93,12 +60,11 @@ export class Privilege<T extends SupportedResource> {
action: SupportedActions<Resource>
resource: Resource
object: object
knownFields?: string[]
}): boolean | typeof UNKNOWN {
}): boolean {
return (
this.#matchResource(constraint.resource) &&
this.#matchAction(constraint.action) &&
this.#matchSelector(constraint.object, constraint.knownFields)
this.#matchSelector(constraint.object)
)
}

View File

@@ -7,7 +7,6 @@ import {
SupportedActions,
SupportedActionsByResource,
SupportedResource,
UNKNOWN,
} from './class/privilege.mjs'
// Export all types constructed using SUPPORTED_ACTIONS_BY_RESOURCE
@@ -24,7 +23,6 @@ export type AnyPrivilegeOnParam = {
resource: Resource
action: SupportedActions<Resource>
objects: object | object[]
knownFields?: string[]
}
}[SupportedResource]
@@ -34,14 +32,12 @@ 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
@@ -67,7 +63,7 @@ export function hasPrivilegeOn<T extends SupportedResource>({
return true
}
const effectsByObject = new Map<object, { known: boolean; effect: Privilege<T>['effect'] }[]>()
const effectsByObject = new Map<object, Privilege<T>['effect'][]>()
if (Array.isArray(objects)) {
objects.forEach(obj => effectsByObject.set(obj, []))
} else {
@@ -78,49 +74,20 @@ export function hasPrivilegeOn<T extends SupportedResource>({
const privilege = new CPrivilege(userPrivilege as Privilege<typeof userPrivilege.resource>)
for (const [object, effects] of effectsByObject.entries()) {
const result = privilege.match({ action, resource, object, knownFields })
if (!result) {
if (!privilege.match({ action, resource, object })) {
continue
}
effects.push({ known: result !== UNKNOWN, effect: privilege.effect })
effects.push(privilege.effect)
}
}
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}`
if (
Array.from(effectsByObject.values()).some(
effects => effects.length === 0 || effects.some(effect => effect === 'deny')
)
error.code = 'RBAC_UNKNOWN_RESULT'
throw error
) {
return false
}
return true
}
@@ -134,7 +101,6 @@ 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 }) => {
@@ -176,7 +142,6 @@ 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, UNKNOWN } from '../class/privilege.mjs'
import { Privilege } from '../class/privilege.mjs'
import type { Privilege as TPrivilege } from '../index.mjs'
import {
filterObjectsWithPrivilege,
@@ -81,108 +81,6 @@ 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 () => {
@@ -499,205 +397,6 @@ 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.2.0"
"@vates/types": "^3.0.0"
},
"dependencies": {
"@xen-orchestra/log": "^1.0.0",

View File

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

View File

@@ -6,12 +6,7 @@ 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
@@ -43,7 +38,7 @@ export type ResolvedBackupCleanOptions = BackupCleanOptions & {
export interface ArchiveCleanOptions {
remove?: boolean
merge?: boolean
mergedDisks?: Map<string, MergedDisk>
mergedSizes?: Map<string, number>
}
export interface CheckResult {
@@ -60,11 +55,11 @@ export interface CheckResult {
export type CleanResult = {
removedFiles: string[]
// Files rewritten in place (e.g. metadata recording the size on disk of the disks a merge rewrote)
// Files rewritten in place (e.g. metadata whose size was updated after a merge)
changedFiles?: string[]
merge?: boolean
size?: number
mergedDisks?: Map<string, MergedDisk>
mergedSizes?: Map<string, number>
}
export interface VmBackupInterface {
@@ -79,9 +74,3 @@ 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,7 +13,6 @@ 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'
@@ -139,19 +138,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 allMergedDisks = new Map<string, MergedDisk>()
const allMergedSizes = new Map<string, number>()
await asyncEach(
Array.from(this.#uniqueLineages!.entries()),
async ([_vdiDir, lineage]) => {
const { mergedDisks, removedFiles, merge: hasPendingMerge } = await lineage.clean({ remove, merge })
const { mergedSizes, removedFiles, merge: hasPendingMerge } = await lineage.clean({ remove, merge })
if (removedFiles.length > 0) {
cacheNeedsRegen = true
}
if (hasPendingMerge) {
someLineageMergedOrShouldBe = true
}
for (const [diskPath, mergedDisk] of mergedDisks || []) {
allMergedDisks.set(diskPath, mergedDisk)
for (const [diskPath, size] of mergedSizes || []) {
allMergedSizes.set(diskPath, (allMergedSizes.get(diskPath) ?? 0) + size)
}
},
{ concurrency: DEFAULT_MERGE_CONCURRENCY }
@@ -175,7 +174,7 @@ export class VmBackupDirectory implements VmBackupInterface {
async ([metadataPath, archive]: [string, VmBackupInterface]) => {
const { removedFiles, changedFiles: archiveChangedFiles } = await archive.clean({
remove,
mergedDisks: allMergedDisks,
mergedSizes: allMergedSizes,
})
if (removedFiles.length > 0) {
cacheNeedsRegen = true
@@ -195,7 +194,7 @@ export class VmBackupDirectory implements VmBackupInterface {
this.backupArchives.delete(metadataPath)
}
if (this.#cacheExisted && (allMergedDisks.size > 0 || cacheNeedsRegen || this.#cacheOutOfSync)) {
if (this.#cacheExisted && (allMergedSizes.size > 0 || cacheNeedsRegen || this.#cacheOutOfSync)) {
await this.#regenerateCache()
}
@@ -217,12 +216,7 @@ export class VmBackupDirectory implements VmBackupInterface {
{ concurrency: 2 }
)
}
const sizeOnDisks = [...allMergedDisks.values()].map(({ sizeOnDisk }) => sizeOnDisk)
const size = sizeOnDisks.reduce<number | undefined>(
(total, merged) => (total !== undefined && merged !== undefined ? total + merged : undefined),
0
)
const size = [...allMergedSizes.values()].reduce((total, merged) => total + merged, 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,13 +14,11 @@ 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, openVhd } from 'vhd-lib'
import Disposable from 'promise-toolbox/Disposable'
import { VhdFile, Constants, VhdDirectory, VhdAbstract } from 'vhd-lib'
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
@@ -53,42 +51,6 @@ 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
@@ -374,7 +336,7 @@ test('it merges delta of non destroyed chain', async () => {
`${rootPath}/metadata.json`,
JSON.stringify({
mode: 'delta',
size: 12000,
size: 12000, // a size too small
vhds: [
`${relativePath}/grandchild.vhd`, // grand child should not be merged
`${relativePath}/child.vhd`,
@@ -419,152 +381,7 @@ 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, 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')
assert.equal(metadata.size, 4299776, 'metadata.size should be updated after merge')
})
test('it merges a chain of multiple consecutive orphan ancestors in one pass', async () => {
@@ -910,28 +727,8 @@ 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`))
// 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)
// size should be the size of children + grand children + clean after the merge
assert.deepEqual(metadata.size, 6501888)
// 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'),
@@ -1067,7 +864,7 @@ test('it regenerates a pre-existing cache after a merge', async () => {
`${rootPath}/metadata.json`,
JSON.stringify({
mode: 'delta',
size: 12000,
size: 12000, // a size too small, the merge will fix it
vhds: [`${relativePath}/grandchild.vhd`, `${relativePath}/child.vhd`],
})
)
@@ -1103,26 +900,13 @@ test('it regenerates a pre-existing cache after a merge', async () => {
})
const metadata = JSON.parse(await handler.readFile(`${rootPath}/metadata.json`))
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'
)
// size of child + grandchild after orphan has been merged into child
assert.equal(metadata.size, 4299776, 'metadata.size should be updated after merge')
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.deepEqual(
Object.values(cache)[0].vhdsSizeOnDisk,
metadata.vhdsSizeOnDisk,
'cache entry should carry the post-merge size on disk'
)
assert.equal(Object.values(cache)[0].size, metadata.size, 'cache entry should carry the post-merge size')
})
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,10 +6,9 @@ import {
VmBackupInterface,
PartialBackupMetadata,
DEFAULT_REMOVE_CONCURRENCY,
MergedDisk,
} from './VmBackup.types.mjs'
import { RemoteHandlerAbstract } from '@xen-orchestra/fs'
import { basename, dirname, normalize, resolveFromFile } from '@xen-orchestra/fs/path'
import { basename, dirname, normalize } from '@xen-orchestra/fs/path'
import { RemoteDiskLineage } from './RemoteDiskLineage.mjs'
import { asyncEach } from '@vates/async-each'
@@ -127,13 +126,10 @@ export class VmIncrementalBackupArchive implements VmBackupInterface {
/**
* Removes the metadata file if the backup is incomplete (missing 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.
* If mergedSizes is provided, updates metadata with the total merged size for this archive's disks.
* Actual disk merge/deletion is handled by RemoteDiskLineage.
*/
async clean({ remove = this.opts.remove ?? false, mergedDisks }: ArchiveCleanOptions = {}): Promise<CleanResult> {
async clean({ remove = this.opts.remove ?? false, mergedSizes }: ArchiveCleanOptions = {}): Promise<CleanResult> {
if (!this.#isChecked) {
await this.check()
}
@@ -154,18 +150,13 @@ export class VmIncrementalBackupArchive implements VmBackupInterface {
}
const changedFiles: string[] = []
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
}
let mergedSize = 0
if (mergedSizes !== undefined) {
for (const diskPath of this.diskPaths) {
mergedSize += mergedSizes.get(diskPath) ?? 0
}
if (Object.keys(updates).length > 0) {
await this.updateMetadata(updates)
if (mergedSize > 0) {
await this.updateMetadata(mergedSize)
changedFiles.push(this.metadataPath)
}
}
@@ -174,30 +165,17 @@ export class VmIncrementalBackupArchive implements VmBackupInterface {
}
/**
* 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.
* 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).
*/
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
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
}
}
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,7 +11,6 @@ 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')
@@ -24,9 +23,7 @@ const { warn } = createLogger('remote-disk:merge')
* @property {number} currentBlock
* @property {number} mergedDataSize
* @property {'mergeBlocks' | 'cleanup'} step
* @property {number} [sizeOnDisk]
* @property {number} [streamSize]
* @property {boolean} [isDifferencing]
* @property {number} diskSize
* @typedef {(message: string, data?: Record<string, unknown>) => void} Logger
*/
@@ -41,6 +38,7 @@ export class MergeRemoteDisk {
currentBlock: 0,
mergedDataSize: 0,
step: 'mergeBlocks',
diskSize: 0,
}
/**
@@ -222,28 +220,10 @@ 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)
// 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 })
}
}
this.#state.diskSize = parentDisk.getSizeOnDisk()
}
/**
@@ -321,36 +301,6 @@ 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
}
/**
@@ -358,13 +308,11 @@ export class MergeRemoteDisk {
* @param {RemoteDisk} childDisk
* @param {boolean} cleanStateFile
*
* @returns {Promise<{mergedDataSize: number, finalSizeOnDisk: number | undefined, streamSize: number, isDifferencing: boolean}>} result
* @returns {Promise<{mergedDataSize: number, finalDiskSize: number}>} result
*/
async #cleanup(parentDisk, childDisk, cleanStateFile) {
const finalSizeOnDisk = this.#state?.sizeOnDisk
const streamSize = this.#state?.streamSize ?? 0
const finalDiskSize = this.#state?.diskSize ?? 0
const mergedDataSize = this.#state?.mergedDataSize ?? 0
const isDifferencing = this.#state?.isDifferencing ?? false
await parentDisk.close().catch(warn)
await childDisk.close().catch(warn)
@@ -372,7 +320,7 @@ export class MergeRemoteDisk {
await this.#handler.unlink(this.#statePath).catch(warn)
}
return { mergedDataSize, finalSizeOnDisk, streamSize, isDifferencing }
return { mergedDataSize, finalDiskSize }
}
/**

View File

@@ -36,8 +36,8 @@ export class RemoteDisk extends RandomAccessDisk {
* Abstract
* @returns {number} size
*/
getStreamSize() {
throw new Error(`getStreamSize must be implemented`)
getSizeOnDisk() {
throw new Error(`getSizeOnDisk must be implemented`)
}
/**
@@ -294,22 +294,4 @@ 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,35 +13,12 @@ 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}` })
@@ -98,9 +75,6 @@ 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
}
@@ -376,12 +350,9 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
const result = await mergeRemoteDisk.merge(parent, child)
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.finalDiskSize > 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)
@@ -391,27 +362,6 @@ 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 = () => {
@@ -462,7 +412,7 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
const result = await mergeRemoteDisk.merge(parent, childDiskChain)
assert.ok(result.finalSizeOnDisk > 0, 'merged disks should have non-zero size')
assert.ok(result.finalDiskSize > 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')
@@ -500,7 +450,7 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
const result = await mergeRemoteDisk.merge(parent, child)
assert.ok(result.finalSizeOnDisk > 0, 'merged disks should have non-zero size')
assert.ok(result.finalDiskSize > 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')
@@ -555,7 +505,7 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
const result = await mergeRemoteDisk.merge(parent, childDiskChain)
assert.ok(result.finalSizeOnDisk > 0, 'merged disks should have non-zero size')
assert.ok(result.finalDiskSize > 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')
@@ -596,7 +546,7 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
const result = await mergeRemoteDisk.merge(parent, child)
assert.ok(result.finalSizeOnDisk > 0, 'merged disks should have non-zero size')
assert.ok(result.finalDiskSize > 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')
@@ -637,7 +587,7 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
const result = await mergeRemoteDisk.merge(parent, child)
assert.ok(result.finalSizeOnDisk > 0, 'merged disks should have non-zero size')
assert.ok(result.finalDiskSize > 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')
@@ -645,33 +595,11 @@ 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, ['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))
)
assert.deepEqual(remainingDatas, [])
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 () => {
@@ -700,7 +628,7 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
const result = await mergeRemoteDisk.merge(parent, child)
assert.ok(result.finalSizeOnDisk > 0, 'merged disks should have non-zero size')
assert.ok(result.finalDiskSize > 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')
@@ -839,7 +767,7 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
const result = await mergeRemoteDisk.merge(parent2, child2)
// Verify merge completed
assert.ok(result.finalSizeOnDisk > 0, 'final disk size should be > 0')
assert.ok(result.finalDiskSize > 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
@@ -935,7 +863,7 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
const result = await mergeRemoteDisk.merge(parent2, child2)
// Verify merge completed
assert.strictEqual(result.finalSizeOnDisk, undefined, 'the size of a resumed merge is unknown')
assert.ok(result.finalDiskSize > 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
@@ -1029,7 +957,7 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
const result = await mergeRemoteDisk.merge(parent2, childDiskChain2)
assert.ok(result.finalSizeOnDisk > 0, 'final disk size should be > 0')
assert.ok(result.finalDiskSize > 0, 'final disk size should be > 0')
assert.equal(
(await handler.list(basePath)).includes(stateFileName),
@@ -1119,281 +1047,6 @@ 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, basename } from 'node:path'
import { dirname, join } 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
*/
getStreamSize() {
getSizeOnDisk() {
if (this.#vhd === undefined) {
throw new Error(`can't call getStreamSize of a RemoteVhdDisk before init`)
throw new Error(`can't call getVirtualSize of a RemoteVhdDisk before init`)
}
return this.#vhd.streamSize()
@@ -322,7 +322,9 @@ export class RemoteVhdDisk extends RemoteDisk {
(await childDisk.isDirectory())
) {
try {
await /** @type {VhdDirectory} */ (this.#vhd).moveBlockFrom(index, childDisk.getBlockPath(index))
await this.#handler.rename(childDisk.getBlockPath(index), this.getBlockPath(index))
this.setAllocatedBlocks([index])
} catch (error) {
// @ts-ignore
if (error.code === 'ENOENT' && isResumingMerge === true) {
@@ -331,6 +333,9 @@ 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
@@ -390,39 +395,6 @@ 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
@@ -515,29 +487,15 @@ 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)) {
if (isVhdAlias(this.#path)) {
const dataPath = await resolveVhdAlias(this.#handler, 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)
} 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)
}
await this.#handler.unlink(newPath)
await VhdAbstract.createAlias(this.#handler, newPath, dataPath)
await this.#handler.unlink(this.#path)
this.#path = newPath
} else {

View File

@@ -93,7 +93,7 @@ export class RemoteVhdDiskChain extends RemoteDisk {
/**
* @returns {number} size
*/
getStreamSize() {
getSizeOnDisk() {
const batEntrySize = 4
const sectorSize = 512
const batSize = Math.ceil((this.getMaxBlockCount() * batEntrySize) / sectorSize) * sectorSize
@@ -253,24 +253,6 @@ 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

@@ -8,7 +8,7 @@
"dependencies": {
"@vates/async-each": "^1.0.3",
"@xen-orchestra/async-map": "^0.1.5",
"@xen-orchestra/backups": "^1.0.1",
"@xen-orchestra/backups": "^1.0.0",
"@xen-orchestra/fs": "^4.11.0",
"filenamify": "^6.0.0",
"getopts": "^2.2.5",

View File

@@ -21,9 +21,6 @@ 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')
@@ -36,7 +33,6 @@ export class HealthCheckVmBackup {
// start Vm
await xapi.callAsync(
signal,
'VM.start',
restoredVm.$ref,
false, // Start paused?
@@ -55,7 +51,6 @@ 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`,
@@ -66,7 +61,6 @@ 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.`,
@@ -83,7 +77,6 @@ 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

@@ -1,52 +0,0 @@
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,9 +3,7 @@ import assert from 'node:assert'
import { formatFilenameDate } from './_filenameDate.mjs'
import { importIncrementalVm } from './_incrementalVm.mjs'
import { liveMountXapiLabels } from './liveMountXapiLabels.mjs'
import { destroyOnAbort } from './_destroyOnAbort.mjs'
import { watchStreamSize } from './_watchStreamSize.mjs'
import { meterDisk, SourceReadTask } from './_SourceReadTask.mjs'
import { decorateClass } from '@vates/decorate-with'
import { Task } from '@vates/task'
import { createLogger } from '@xen-orchestra/log'
@@ -426,15 +424,7 @@ 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')
@@ -442,9 +432,6 @@ 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(
@@ -464,21 +451,12 @@ export class ImportVmBackup {
additionalVmTag !== undefined && vm.add_tags(additionalVmTag),
])
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
}
const vmRef = isFull
? await xapi.VM_import(backup, srRef, onVmCreation)
: await importIncrementalVm(backup, await xapi.getRecord('SR', srRef), {
newMacAddresses,
vmNamePrefix,
})
let size = 0
if (isFull) {
size = sizeContainer.size

View File

@@ -304,109 +304,3 @@ 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,7 +16,6 @@ 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
@@ -24,27 +23,6 @@ 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()
@@ -278,20 +256,11 @@ describe('RemoteAdapter#writeVhd validated by checkDisk', { concurrency: 1 }, ()
const adapter = await getAdapter({ useVhdDirectory })
const path = `${basePath}/${adapter.getVhdFileName('base')}`
const { size, sizeOnDisk } = await adapter.writeVhd(path, new MockDisk(2, [0, 1], 0x42), {
const size = 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 => {
@@ -348,34 +317,6 @@ 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,7 +38,6 @@ 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'
@@ -688,18 +687,12 @@ export class RemoteAdapter {
return path
}
/**
* `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 } = {}) {
async writeVhd(path, disk, { validator = noop, writeBlockConcurrency, uuid, parentUuid, parentPath } = {}) {
const handler = this._handler
if (this.useVhdDirectory()) {
return await writeToVhdDirectory({
disk,
signal,
target: {
handler,
path,
@@ -712,11 +705,7 @@ export class RemoteAdapter {
},
})
} else {
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 stream = await toVhdStream(disk, { uuid, parentUuid, parentPath })
const size = await this.outputStream(path, stream, {
validator,
// no checksum for VHDs, because they will be invalidated by
@@ -724,8 +713,7 @@ export class RemoteAdapter {
checksum: false,
})
await validator(path)
const sizeOnDisk = await this._handler.getSizeOnDisk(path)
return { size, sizeOnDisk }
return size
}
}
@@ -895,11 +883,9 @@ export class RemoteAdapter {
return reduce(
backups,
(prev, backup) => {
const size = Array.isArray(backup)
? this.#computeTotalBackupSizeRecursively(backup).onDisk
: (getVmBackupSizeOnDisk(backup) ?? backup.size)
const _backup = Array.isArray(backup) ? this.#computeTotalBackupSizeRecursively(backup) : backup
return {
onDisk: prev.onDisk + size,
onDisk: prev.onDisk + (_backup.onDisk ?? _backup.size),
}
},
{ onDisk: 0 }

View File

@@ -1,125 +0,0 @@
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

@@ -1,300 +0,0 @@
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 it after merging its disks, to record their new size on disk
* - `merge`: `cleanVm()` rewrote its size after merging its disks
*
* @typedef {'backup'|'retention'|'user'|'clean-vm'|'merge'} BackupJournalReason
*/

View File

@@ -178,8 +178,6 @@ 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,8 +8,7 @@ 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, openVhd } from 'vhd-lib'
import Disposable from 'promise-toolbox/Disposable'
import { VhdFile, Constants, VhdDirectory, VhdAbstract } from 'vhd-lib'
import { dirname, basename } from 'node:path'
import { rimraf } from 'rimraf'
@@ -35,14 +34,6 @@ 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))
@@ -207,7 +198,7 @@ test('it merges delta of non destroyed chain', async () => {
`${rootPath}/metadata.json`,
JSON.stringify({
mode: 'delta',
size: 12000,
size: 12000, // a size too small
vhds: [
`${relativePath}/grandchild.vhd`, // grand child should not be merged
`${relativePath}/child.vhd`,
@@ -248,7 +239,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, 12000)
assert.equal(metadata.size, 4299776)
// 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
@@ -462,15 +453,8 @@ 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`))
// 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
)
// size is the sum of the merged chains' final on-disk sizes:
assert.deepEqual(metadata.size, 6501888)
// broken vhd, non referenced, abandoned should be deleted ( alias and data)
// ancestor and child should be merged

View File

@@ -1,28 +0,0 @@
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

@@ -1,50 +0,0 @@
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,9 +32,7 @@ export async function exportIncrementalVm(vm, baseVdis = {}, { signal, nbdConcur
const disks = {}
const vdis = {}
const vbds = {}
// 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) => {
await abortableMap(signal, vm.$VBDs, async (signal, vbd) => {
let vdi
if (vbd.type !== 'Disk' || !(vdi = vbd.$VDI)) {
// Ignore this VBD.
@@ -70,7 +68,6 @@ export async function exportIncrementalVm(vm, baseVdis = {}, { signal, nbdConcur
baseRef: baseVdi?.$ref,
nbdConcurrency,
preferNbd,
signal,
})
await disks[vdiRef].init()
})
@@ -87,7 +84,6 @@ export async function exportIncrementalVm(vm, baseVdis = {}, { signal, nbdConcur
xapi: vm.$xapi,
nbdConcurrency,
preferNbd,
signal,
})
await disks[vdiRef].init()
}

View File

@@ -40,9 +40,6 @@ 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
@@ -84,10 +81,6 @@ export const VmsRemote = class RemoteVmsBackupRunner extends Abstract {
const nTriesByVmId = {}
const handleVm = async vmUuid => {
if (signal?.aborted) {
return
}
if (nTriesByVmId[vmUuid] === undefined) {
nTriesByVmId[vmUuid] = 0
}
@@ -150,10 +143,9 @@ export const VmsRemote = class RemoteVmsBackupRunner extends Abstract {
nbVmsDone++
return task.success(result)
}
// once aborted, the VM backup is not retried: it failed because of the abort, whatever its error
if (isLastRun || signal?.aborted) {
if (isLastRun) {
nbVmsDone++
return task.failure(signal?.aborted ? signal.reason : taskError)
return task.failure(taskError)
}
Task.set('progress', Math.round((nbVmsDone * 100) / nbVms))
// don't end the task

View File

@@ -1,73 +0,0 @@
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,9 +63,6 @@ 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
@@ -146,10 +143,6 @@ 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] }
@@ -212,14 +205,9 @@ export const VmsXapi = class VmsXapiBackupRunner extends Abstract {
const queue = new Set(snapshotedVmIds)
const handleVm = vmUuid => {
if (signal?.aborted) {
return
}
const vmBackupFailed = async (error, task) => {
// 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)
if (isLastRun) {
return task.failure(error)
} else {
// don't end the task
task.warning(`Retry the VM backup due to an error`, {

View File

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

View File

@@ -1,119 +0,0 @@
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,11 +1,9 @@
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'
@@ -57,8 +55,6 @@ 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
@@ -82,8 +78,7 @@ export const FullXapi = class FullXapiVmBackupRunner extends AbstractXapi {
maxStreamLength += XVA_BLOCK_SIZE * nbBlocks + headersSize
}
// the export is read once, whatever the number of writers
const sizeContainer = watchStreamSize(stream, { size: 0, readTask: new SourceReadTask('read') })
const sizeContainer = watchStreamSize(stream)
const transferStart = Date.now()
await this._callWriters(

View File

@@ -1,68 +0,0 @@
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,7 +13,6 @@ 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 {
@@ -86,8 +85,6 @@ 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,
@@ -102,8 +99,6 @@ 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,6 +1,5 @@
import assert from 'node:assert/strict'
import { describe, it } from 'node:test'
import { Task } from '@vates/task'
import { IncrementalRemote } from './IncrementalRemote.mjs'
@@ -44,42 +43,3 @@ 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,7 +20,6 @@ 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')
@@ -56,8 +55,6 @@ 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 = {}
@@ -70,8 +67,6 @@ 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,7 +233,6 @@ 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()
@@ -382,9 +381,7 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
const xapi = this._xapi
const vdiCandidates = {}
// 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)
const vdiUuids = this._vm.$VBDs.map(({ VDI }) => VDI)
Object.values(xapi.objects.indexes.type.VDI)
.filter(_ => !!_) // filter nullish
.filter(({ other_config, snapshot_of }) => {
@@ -403,20 +400,21 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
this._jobSnapshotVdis = Object.values(vdiCandidates)
// 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)
)
// 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 = []
}
}
async _removeUnusedSnapshots() {
@@ -452,13 +450,7 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
.pop()
// remove older snapshot schedule per schedule
// 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])
const snapshotsPerSchedule = groupBy(this._jobSnapshotVdis, _ => _.other_config[SCHEDULE_ID])
await asyncMap(Object.entries(snapshotsPerSchedule), async ([scheduleId, snapshots]) => {
const snapshotPerDatetime = groupBy(snapshots, _ => _.other_config[DATETIME])
@@ -481,18 +473,7 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
) {
return
}
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)
const vdis = snapshotPerDatetime[datetime]
let vm
// if there is an attached VM => destroy the VM (Non CBT backups)
for (const vdi of vdis) {
@@ -546,6 +527,34 @@ 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,10 +2,9 @@ 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, VM_UUID } from '../../_otherConfig.mjs'
import { DATETIME, EXPORTED_SUCCESSFULLY, JOB_ID, SCHEDULE_ID } from '../../_otherConfig.mjs'
// Build an AbstractXapi instance without running its heavy constructor, then
// assign only the fields the method under test reads.
@@ -658,197 +657,3 @@ 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,7 +69,6 @@ export class FullRemoteWriter extends MixinRemoteWriter(AbstractFullWriter) {
await deleteOldBackups()
}
let sizeOnDisk = 0
await Task.run({ properties: { name: 'transfer' } }, async () => {
await adapter.outputStream(dataFilename, stream, {
checksum,
@@ -77,20 +76,9 @@ 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,24 +161,8 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
this._prepare = task.wrapInside(this._prepare)
this.transfer = task.wrapInside(this.transfer)
this.healthCheck = task.wrapInside(this.healthCheck)
// `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)
}
this.cleanup = task.wrapInside(this.cleanup)
this.afterBackup = task.wrap(this.afterBackup)
return this._prepare()
}
@@ -280,10 +264,7 @@ 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]) => {
@@ -300,11 +281,10 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
parentPath = relativeFromFile(path, parentDestPath)
}
const { size: transferred, sizeOnDisk } = await adapter.writeVhd(path, disk, {
const transferred = 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),
@@ -312,7 +292,6 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
parentPath,
})
size += transferred
vhdsSizeOnDisk[diskRef] = sizeOnDisk
},
{
concurrency: settings.diskPerVmConcurrency,
@@ -321,14 +300,8 @@ 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

@@ -1,266 +0,0 @@
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,20 +327,11 @@ 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) {
cleanupInTask = task.wrapInside(this.cleanup)
this.cleanup = task.wrapInside(this.cleanup)
this.healthCheck = task.wrap(this.healthCheck)
} else {
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))
this.cleanup = task.wrap(this.cleanup)
}
return this._prepare(isFull)
@@ -513,8 +504,6 @@ 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

@@ -1,83 +0,0 @@
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,12 +26,9 @@ export const MixinRemoteWriter = (BaseClass = Object) =>
this._vmBackupDir = getVmBackupDir(rest.vmUuid)
}
// `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 }) {
async _cleanVm(options) {
try {
return await Task.run({ properties: { name: 'clean-vm' }, cleanup }, () => {
return await Task.run({ properties: { name: 'clean-vm' } }, () => {
return this._adapter.cleanVm(this._vmBackupDir, {
...options,
logInfo: info,
@@ -75,13 +72,8 @@ export const MixinRemoteWriter = (BaseClass = Object) =>
const { handler } = this._adapter
const synchronousMerge = this._settings.mergeBackupsSynchronously
const willMergeInWorker = !synchronousMerge && !disableMergeWorker && typeof handler.getRealPath === 'function'
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()
}
const { merge } = await this._cleanVm({ remove: true, merge: !willMergeInWorker })
await this.#lock.dispose()
if (merge && willMergeInWorker) {
const taskFile =

View File

@@ -48,20 +48,13 @@ export const MixinXapiWriter = (BaseClass = Object) =>
if (await this.#isAlreadyOnHealthCheckSr(baseVm)) {
healthCheckVmRef = await Task.run(
{ properties: { name: 'cloning-vm' } },
async () =>
await xapi.callAsync(
Task.abortSignal,
'VM.clone',
this._targetVmRef,
`Health Check - ${baseVm.name_label}`
)
async () => await xapi.callAsync('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

@@ -1,43 +0,0 @@
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,34 +1,17 @@
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 = new TaskProgressHandler(), readTask } = container
const progressHandler = container.progressHandler ?? new TaskProgressHandler()
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,7 +13,6 @@
- [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)
@@ -241,41 +240,6 @@ 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,17 +29,7 @@ import { normalize } from '@xen-orchestra/fs/path'
*/
/**
* 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}
* @returns {import('@vates/types').XoVmBackupArchive & { tags: string[] }}
*/
export function formatVmBackup(backup) {
const { isVhdDifferencing, vmSnapshot } = backup
@@ -69,8 +59,6 @@ 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],
}
}),
@@ -80,7 +68,6 @@ export function formatVmBackup(backup) {
mode: backup.mode,
scheduleId: backup.scheduleId,
size: backup.size,
sizeOnDisk: getVmBackupSizeOnDisk(backup),
timestamp: backup.timestamp,
vm: {
uuid: backup.vm.uuid,
@@ -144,30 +131,3 @@ 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,13 +54,7 @@ describe('formatVmBackupAt()', () => {
for (const filename of [FILENAME, FILENAME.slice(1)]) {
assert.deepEqual(formatVmBackupAt(metadata, filename, REPOSITORY).disks, [
{
id: `/xo-vm-backups/${VM}/vdi.vhd`,
isDifferencing: undefined,
name: 'a disk',
uuid: 'a-vdi-uuid',
sizeOnDisk: undefined,
},
{ id: `/xo-vm-backups/${VM}/vdi.vhd`, name: 'a disk', uuid: 'a-vdi-uuid' },
])
}
})
@@ -105,87 +99,6 @@ 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

@@ -8,7 +8,7 @@
"type": "git",
"url": "https://github.com/vatesfr/xen-orchestra.git"
},
"version": "1.0.1",
"version": "1.0.0",
"engines": {
"node": ">=22.19"
},
@@ -27,10 +27,10 @@
"@vates/disposable": "^0.1.7",
"@vates/fuse-vhd": "^2.1.4",
"@vates/generator-toolbox": "^1.1.3",
"@vates/nbd-client": "^3.7.2",
"@vates/nbd-client": "^3.7.1",
"@vates/parse-duration": "^0.1.1",
"@vates/task": "^0.7.0",
"@vates/types": "^3.2.0",
"@vates/types": "^3.0.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.1.0"
"@xen-orchestra/xapi": "^10.0.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 stream size
list List all disks at a path and display their properties in a table; --size adds the stream size
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
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 stream size. Pass `--size` to read
the block allocation table and print the stream size as an extra line:
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:
```
$ 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)
Stream size: 128.00 MiB (134217728 bytes)
Size on disk: 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 "Stream size" column is omitted:
so the "Size on disk" 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 "Stream size" column:
Pass `--size` to read each disk's block allocation table and add the "Size on disk" column:
```
$ xo-disk-cli list file:///mnt/backups /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/ --size
┌──────────────┬──────────────────────────────────────┬─────────────┬──────────────┬─────────────┬──────────────────────────────────────┐
│ File │ UID │ Stream size │ Virtual size │ Differencing │ Parent UID │
│ File │ UID │ Size on disk│ 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 stream size
list List all disks at a path and display their properties in a table; --size adds the stream size
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
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 stream size. Pass `--size` to read
the block allocation table and print the stream size as an extra line:
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:
```
$ 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)
Stream size: 128.00 MiB (134217728 bytes)
Size on disk: 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 "Stream size" column is omitted:
so the "Size on disk" 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 "Stream size" column:
Pass `--size` to read each disk's block allocation table and add the "Size on disk" column:
```
$ xo-disk-cli list file:///mnt/backups /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/ --size
┌──────────────┬──────────────────────────────────────┬─────────────┬──────────────┬─────────────┬──────────────────────────────────────┐
│ File │ UID │ Stream size │ Virtual size │ Differencing │ Parent UID │
│ File │ UID │ Size on disk│ 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

@@ -20,7 +20,7 @@
},
"dependencies": {
"@vates/async-each": "^1.0.3",
"@xen-orchestra/backups": "^1.0.1",
"@xen-orchestra/backups": "^1.0.0",
"@xen-orchestra/backup-archive": "^1.2.1",
"@xen-orchestra/disk-transform": "^1.3.4",
"@xen-orchestra/fs": "^4.11.0",

View File

@@ -10,7 +10,7 @@ type DiskInfoLine = {
virtualSize: number
blockSize: number
// Only computed with --size; requires reading the block allocation table.
streamSize?: number
sizeOnDisk?: 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(),
streamSize: showSize ? disk.getStreamSize() : undefined,
sizeOnDisk: showSize ? disk.getSizeOnDisk() : 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.streamSize !== undefined) {
console.log(` Stream size: ${formatBytes(info.streamSize)} (${info.streamSize} bytes)`)
if (info.sizeOnDisk !== undefined) {
console.log(` Size on disk: ${formatBytes(info.sizeOnDisk)} (${info.sizeOnDisk} 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 "Stream size" column is only shown with --size: computing it requires
// The "Size on disk" 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 ? ['Stream size'] : []), 'Virtual size', 'Differencing', 'Parent UID']
return ['File', 'UID', ...(showSize ? ['Size on disk'] : []), 'Virtual size', 'Differencing', 'Parent UID']
}
export type OkDiskInfo = {
ok: true
filename: string
uid: string
streamSize?: string
sizeOnDisk?: 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.streamSize ?? '-'] : []),
...(showSize ? [disk.sizeOnDisk ?? '-'] : []),
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(),
streamSize: showSize ? formatBytes(disk.getStreamSize()) : undefined,
sizeOnDisk: showSize ? formatBytes(disk.getSizeOnDisk()) : 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 {
getStreamSize(): number
getSizeOnDisk(): 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 stream size',
list: 'List all disks at a path and display their properties in a table; --size adds the stream size',
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',
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 stream size.
* opens with ignoreBlockIndexes: false and prints the size on disk.
* - --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,
getStreamSize: () => 128 * 1024 * 1024,
getSizeOnDisk: () => 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 stream size', async () => {
test('by default opens the disk with ignoreBlockIndexes: true and hides size on disk', 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('Stream size'), 'stream size must not be printed without --size')
assert.ok(!output.includes('Size on disk'), 'size on disk must not be printed without --size')
})
test('--size opens the disk with ignoreBlockIndexes: false and prints stream size', async () => {
test('--size opens the disk with ignoreBlockIndexes: false and prints size on disk', 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('Stream size'), 'stream size must be printed with --size')
assert.ok(output.includes('Size on disk'), 'size on disk 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 stream size for each disk', async () => {
test('--chain --size reads block indexes and prints size on disk 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('Stream size'))
assert.strictEqual(sizeLines.length, chainPaths.length, 'stream size must be printed for each disk')
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')
})
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,
getStreamSize: () => 1024 * 1024 * 1024,
getSizeOnDisk: () => 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('Stream size'), 'the size column must be hidden without --size')
assert.ok(!output.includes('Size on disk'), '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('Stream size'), 'the size column must appear with --size')
assert.ok(output.includes('Size on disk'), '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 "Stream size" column), so
// These tests assert on the full-width row (with the "Size on disk" 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,
streamSize: '1.00 GiB',
sizeOnDisk: '1.00 GiB',
virtualSize: '8.00 GiB',
differencing: parentUid !== null,
parentUid,

View File

@@ -1,48 +0,0 @@
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

@@ -1,123 +0,0 @@
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,7 +9,5 @@ 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,14 +23,6 @@ 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
@@ -415,7 +407,6 @@ export default class RemoteHandlerAbstract {
encryptedData = Buffer.concat(encryptedData)
}
await this._outputFile(normalizePath(file), encryptedData, { dirMode, flags })
return getDataSize(encryptedData)
}
async read(file, buffer, position) {
@@ -605,7 +596,6 @@ 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,21 +248,4 @@ 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, Buffer.byteLength(data))
await blobClient.upload(data, data.length)
}
async _createReadStream(file) {

View File

@@ -190,33 +190,6 @@ 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

@@ -22,7 +22,7 @@
},
"dependencies": {
"@vates/async-each": "^1.0.3",
"@xen-orchestra/backups": "^1.0.1",
"@xen-orchestra/backups": "^1.0.0",
"@xen-orchestra/log": "^1.0.0",
"app-conf": "^3.0.0",
"execa": "^5.0.0",

View File

@@ -1,17 +1,7 @@
# ChangeLog
## **0.28.1** (2026/12/04)
## **next**
- [VM/Network] Add possibility to delete a VIF (PR [#10726](https://github.com/vatesfr/xen-orchestra/pull/10726))
- [Web-Core/VtsErrorModal] Add an optional details log viewer, unified icon (PR [#10536](https://github.com/vatesfr/xen-orchestra/pull/10536))
- [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))
- [Pages] The page header and tabs now stay in place on every page: dashboards, System tabs, consoles, tasks, settings and creation forms scroll under them instead of scrolling with them (PR [#10822](https://github.com/vatesfr/xen-orchestra/pull/10822))
@@ -26,8 +16,6 @@
- [Side panels] Fix the double scrollbar when the side panel content is taller than the screen: the page header now stays in place, and the list and the side panel each scroll on their own. All scrollbars are now thin, like the side panel one (PR [#10807](https://github.com/vatesfr/xen-orchestra/pull/10807))
- [Mobile] Searchable dropdown lists no longer overflow the screen (PR [#10854](https://github.com/vatesfr/xen-orchestra/pull/10854))
- [New/VM] Fix the storage table overflowing horizontally, which hid part of the delete button (PR [#10851](https://github.com/vatesfr/xen-orchestra/pull/10851))
- [New/VM] Fix template disk settings being applied to every disk of the new VM: each disk now keeps its own name, description and SR (PR [#10898](https://github.com/vatesfr/xen-orchestra/pull/10898))
- [VM/System] Display the default 4 MiB video RAM for HVM VMs that don't define it, as XO 6 does (PR [#10901](https://github.com/vatesfr/xen-orchestra/pull/10901))
## **0.27.0** (2026-10-29)

View File

@@ -1,6 +1,6 @@
{
"name": "@xen-orchestra/lite",
"version": "0.28.1",
"version": "0.27.0",
"type": "module",
"scripts": {
"dev": "GIT_HEAD=$(git rev-parse HEAD) vite",
@@ -27,13 +27,13 @@
"@types/file-saver": "^2.0.7",
"@types/lodash-es": "^4.17.12",
"@types/node": "^18.19.80",
"@vates/types": "^3.2.0",
"@vates/types": "^3.0.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.67.0",
"@xen-orchestra/web-core": "^0.66.0",
"complex-matcher": "^1.1.1",
"d3-time-format": "^4.1.0",
"decorator-synchronized": "^0.6.0",

View File

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

View File

@@ -42,7 +42,7 @@ const progress = computed(() => {
.progress-circle-fill {
animation: progress 1s ease-out forwards;
fill: none;
stroke: var(--color-success-data);
stroke: var(--color-success-item-base);
stroke-width: 1.2;
stroke-linecap: round;
stroke-dasharray: v-bind(progress), 100;

View File

@@ -8,11 +8,6 @@
</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>
@@ -54,7 +49,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, isHostSshManageable } from '@/modules/host/utils/host.util.ts'
import { getHostCoreSocketInfo, getHostManufacturerInfo } 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'
@@ -62,7 +57,6 @@ 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'
@@ -90,8 +84,6 @@ const manufacturerInfo = computed(() => getHostManufacturerInfo(host))
const coreSocketInfo = computed(() => getHostCoreSocketInfo(host))
const isSshManageable = computed(() => isHostSshManageable(host))
const ram = computed(() => {
const memory = getHostMemory(host)

View File

@@ -5,11 +5,6 @@
</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')">
@@ -23,20 +18,16 @@
<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'
const { host } = defineProps<{
defineProps<{
host: XenApiHost
}>()
const { t } = useI18n()
const isSshManageable = computed(() => isHostSshManageable(host))
</script>

View File

@@ -68,11 +68,11 @@ const hasError = computed(() => hostStoreHasError.value || vmStoreHasError.value
<style lang="postcss" scoped>
.progress-item {
--progress-bar-height: 1.2rem;
--progress-bar-color: var(--color-brand-data);
--progress-bar-color: var(--color-brand-item-base);
--progress-bar-background-color: var(--color-neutral-background-disabled);
&.warning {
--progress-bar-color: var(--color-warning-data);
--progress-bar-color: var(--color-warning-item-base);
--footer-value-color: var(--color-warning-item-base);
}

View File

@@ -56,7 +56,7 @@ const inactive = computed(() => props.total - props.active)
width: 1.3rem;
height: 1.3rem;
border-radius: 0.65rem;
background-color: var(--color-success-data);
background-color: var(--color-success-item-base);
&.inactive {
background-color: var(--color-neutral-background-disabled);

View File

@@ -85,7 +85,6 @@
<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'
@@ -109,7 +108,6 @@ const emit = defineEmits<{
}>()
const { getPifsByNetworkRef } = usePifStore().subscribe()
const { getNetworkVlan } = useNetworkUtils()
const { t } = useI18n()
@@ -117,7 +115,13 @@ const { deleteNetworks, isDeletingNetworks } = useNetworkDelete(() => (network !
const pifs = computed(() => (network !== undefined ? getPifsByNetworkRef(network.$ref) : []))
const networkVlan = computed(() => (network !== undefined ? getNetworkVlan(network) : undefined))
const networkVlan = computed(() => {
if (pifs.value.length === 0) {
return
}
return pifs.value[0].VLAN !== -1 ? pifs.value[0].VLAN.toString() : t('none')
})
const networkNbd = computed(() => (network?.purpose[0] ? t('on') : t('off')))

View File

@@ -57,7 +57,6 @@
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import { getHostIcon } from '@/modules/host/utils/host.util.ts'
import { useVmUtils } from '@/modules/vm/composables/vm-utils.composable.ts'
import { getVmDomainType } from '@/modules/vm/utils/vm.util.ts'
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
import { useVmGuestMetricsStore } from '@/stores/xen-api/vm-guest-metrics.store.ts'
@@ -134,7 +133,16 @@ const ram = computed(() => formatSizeRaw(vm.memory_dynamic_max, 0))
const osVersion = computed(() => guestMetrics.value?.os_version.name)
const domainType = computed(() => getVmDomainType(vm))
const domainType = computed(() => {
if (
vm.domain_type !== undefined && // XS < 7.5
vm.domain_type !== 'unspecified' // detection failed
) {
return vm.domain_type
}
return vm.HVM_boot_policy === '' ? 'pv' : 'hvm'
})
const virtualizationType = computed(() =>
domainType.value === 'hvm' && guestMetrics.value?.PV_drivers_detected ? 'pvhvm' : domainType.value

View File

@@ -10,8 +10,8 @@
</template>
</VtsTabularKeyValueRow>
<VtsTabularKeyValueRow :label="t('video-ram')">
<template v-if="videoRam" #value>
{{ `${videoRam} ${t('bytes:mi')}` }}
<template v-if="vm.platform.videoram" #value>
{{ `${vm.platform.videoram} ${t('bytes:mi')}` }}
</template>
</VtsTabularKeyValueRow>
</VtsTabularKeyValueList>
@@ -20,18 +20,14 @@
<script setup lang="ts">
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import { getVmDomainType } from '@/modules/vm/utils/vm.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'
const { vm } = defineProps<{ vm: XenApiVm }>()
defineProps<{ vm: XenApiVm }>()
const { t } = useI18n()
const videoRam = computed(() => (getVmDomainType(vm) === 'hvm' ? Number(vm.platform.videoram ?? 4) : undefined))
</script>

View File

@@ -35,7 +35,6 @@
<script setup lang="ts">
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import { getVmDomainType } from '@/modules/vm/utils/vm.util.ts'
import { useHostStore } from '@/stores/xen-api/host.store.ts'
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
import { useVtpmStore } from '@/stores/xen-api/vtpm.store.ts'
@@ -56,7 +55,16 @@ const { pool } = usePoolStore().subscribe()
const { getByOpaqueRef: getHostOpaqueRef } = useHostStore().subscribe()
const { getByOpaqueRef: getVtpmOpaqueRef } = useVtpmStore().subscribe()
const virtualizationMode = computed(() => getVmDomainType(vm))
/**
* @see `packages/xo-server/src/xapi/utils.mjs`:57
**/
const virtualizationMode = computed(() =>
vm.domain_type !== undefined && vm.domain_type !== 'unspecified'
? vm.domain_type
: vm.HVM_boot_policy === ''
? 'pv'
: 'hvm'
)
const isNestedVirtualizationEnabled = computed(() => {
const poolMaster = pool.value !== undefined ? getHostOpaqueRef(pool.value.master) : undefined

View File

@@ -20,10 +20,6 @@ export function createHostOperations(xenApi: XenApi) {
const restartAgent = (hostRef: HostRef) => xenApi.call('host.restart_agent', [hostRef])
const enableSsh = (hostRef: HostRef) => xenApi.call('host.enable_ssh', [hostRef])
const setSshAutoMode = (hostRef: HostRef, value: boolean) => xenApi.call('host.set_ssh_auto_mode', [hostRef, value])
const clearHost = async (hostRef: HostRef, force: boolean) => {
await disable(hostRef)
@@ -45,8 +41,6 @@ export function createHostOperations(xenApi: XenApi) {
powerOn,
destroy,
restartAgent,
enableSsh,
setSshAutoMode,
cleanReboot: async (hostRef: HostRef, forceReboot: boolean) => {
await clearHost(hostRef, forceReboot)

View File

@@ -164,7 +164,6 @@ export interface XenApiHost extends XenApiRecord<'host'> {
multipathing: boolean
enabled: boolean
PGPUs: XenApiPgpu['$ref'][]
ssh_enabled?: boolean
}
export interface XenApiSr extends XenApiRecord<'sr'> {

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