Compare commits

..

4 Commits

Author SHA1 Message Date
Thomas Moraine
f49398d5de docs(sdn-controller): use the Vates VMS subscription wording
XOA Premium is a legacy XOA tier. Use the same wording as the other
technical pages: on XOA, the plugin requires a Vates VMS subscription that
includes it.
2026-11-19 09:02:35 +01:00
Thomas Moraine
507b4477b5 docs(sdn-controller): replace the Networking category with SDN controller
Networking only contained the SDN controller pages, which put them one
level deeper than any other page of the docs. The SDN controller category
now sits directly under Management, and /category/networking redirects to
it.
2026-11-19 08:57:33 +01:00
Thomas Moraine
fc16175dbb Merge remote-tracking branch 'origin/master' into docs/sdn-controller-restructure
# Conflicts:
#	docs/docs/manage-your-infrastructure/networking/sdn_controller.md
2026-11-19 08:51:28 +01:00
Thomas Moraine
f3d12a9171 docs(sdn-controller): split the page into how it works, setup, traffic rules and advanced
- How it works: brings in the content of the two SDN devblogs, with their
  diagrams redrawn in the current Schema style. Describes the actual
  topology (a single star center, also across pools) and the preferred
  center option.
- Setup: requirements first (connectivity, VxLAN, encryption, MTU), then
  the plugin configuration, then the network creation.
- Traffic rules: only the default OpenFlow mode, available out of the box.
- Advanced: XAPI plugin mode (beta), xo-cli, migration script and OpenSSL 3
  certificate regeneration.

The old URL redirects to the setup page, and internal links are updated.
2026-11-19 08:47:01 +01:00
1333 changed files with 16590 additions and 61718 deletions

View File

@@ -59,33 +59,6 @@ module.exports = {
'n/no-unpublished-import': 'off',
},
},
// The XO 6 test files share their modules (no isolation): mocking or resetting a module from one file would leak
// into the others. See @xen-orchestra/web/docs/tests/mocking.md
{
files: ['@xen-orchestra/web/src/**/*.unit.test.ts'],
rules: {
'no-restricted-syntax': [
'error',
{
selector: "CallExpression[callee.object.name='vi'][callee.property.name=/^(mock|doMock|unmock|doUnmock)$/]",
message: 'Mock a module with `mockModule` from `@/test/spy-on-module.ts`, never `vi.mock`.',
},
{
selector: "CallExpression[callee.object.name='vi'][callee.property.name='resetModules']",
message: 'The test files share their modules: never reset them.',
},
{
selector: "CallExpression[callee.object.name='vi'][callee.property.name='hoisted']",
message: '`mockModule` is not hoisted: declare the stubs as plain constants.',
},
{
selector: "CallExpression[callee.object.name='vi'][callee.property.name='resetAllMocks']",
message:
'Reset the stubs with `resetStubs` from `@/test/reset-stubs.ts`: `vi.resetAllMocks()` also resets the module mocks.',
},
],
},
},
{
files: ['@xen-orchestra/{web-core,lite,web}/**/*.{vue,ts}'],
parser: 'vue-eslint-parser',

View File

@@ -14,7 +14,7 @@
"url": "https://vates.fr"
},
"license": "ISC",
"version": "0.1.7",
"version": "0.1.6",
"engines": {
"node": ">=8.10"
},
@@ -25,7 +25,7 @@
"dependencies": {
"@vates/multi-key-map": "^0.2.0",
"@xen-orchestra/async-map": "^0.1.5",
"@xen-orchestra/log": "^1.0.0",
"@xen-orchestra/log": "^0.7.2",
"ensure-array": "^1.0.0"
},
"devDependencies": {

View File

@@ -1,6 +1,6 @@
{
"name": "@vates/fuse-vhd",
"version": "2.1.4",
"version": "2.1.3",
"license": "ISC",
"private": false,
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/@vates/fuse-vhd",
@@ -19,12 +19,12 @@
},
"main": "./index.mjs",
"dependencies": {
"@xen-orchestra/fs": "^4.11.0",
"@xen-orchestra/log": "^1.0.0",
"@xen-orchestra/fs": "^4.10.0",
"@xen-orchestra/log": "^0.7.2",
"fuse-native": "^2.2.6",
"lru-cache": "^7.14.0",
"promise-toolbox": "^0.21.0",
"vhd-lib": "^4.17.1"
"vhd-lib": "^4.17.0"
},
"bin": {
"xo-fuse-vhd": "./cli.mjs"

View File

@@ -1,6 +1,6 @@
{
"name": "@vates/iscsi",
"version": "0.4.1",
"version": "0.4.0",
"main": "dist/index.mjs",
"types": "dist/index.d.mts",
"bin": {
@@ -24,7 +24,7 @@
"@vates/async-each": "^1.0.3",
"@vates/read-chunk": "^1.2.1",
"@xen-orchestra/disk-transform": "^1.3.4",
"@xen-orchestra/log": "^1.0.0",
"@xen-orchestra/log": "^0.7.2",
"promise-toolbox": "^0.21.0"
},
"devDependencies": {

View File

@@ -1,6 +1,6 @@
import assert from 'node:assert'
import { spawn } from 'node:child_process'
import { pFromCallback, pTimeout } from 'promise-toolbox'
import { pFromCallback } from 'promise-toolbox'
import { createLogger } from '@xen-orchestra/log'
import AbstractNbdClient from './AbstractNbdClient.mjs'
@@ -9,9 +9,6 @@ const { warn } = createLogger('vates:nbd-client:stdio')
// only the tail is kept: it's the part describing why the server died
const STDERR_MAX_LENGTH = 4096
// how long a failed connection waits for the server to exit and its stderr to end
const CLOSE_TIMEOUT = 1e3
/**
* NBD client talking to a server through its standard streams, like
* `nbdkit -s` or `qemu-nbd` in `--fd` mode: the queries are written to the
@@ -31,7 +28,7 @@ export default class NbdStdioClient extends AbstractNbdClient {
#cwd
#env
/** @type {{ child: import('node:child_process').ChildProcess, closing: boolean, stderr: string, closed: Promise<unknown> }|undefined} */
/** @type {{ child: import('node:child_process').ChildProcess, closing: boolean, stderr: string }|undefined} */
#state
/**
@@ -71,36 +68,6 @@ export default class NbdStdioClient extends AbstractNbdClient {
return this.#state?.child.pid
}
/**
* A server dying before the handshake makes it fail with "stream has ended
* without data", and the exit handler, racing with the teardown, often
* reports nothing: what the server wrote on stderr is the only reason given,
* so it becomes the error.
*/
async connect() {
try {
return await super.connect()
} catch (error) {
const state = this.#state
const closed =
state !== undefined &&
(await pTimeout.call(state.closed, CLOSE_TIMEOUT).then(
() => true,
() => false
))
// exitCode is null when the process was killed, by us when it did not die by itself
if (closed && state.child.exitCode !== null && state.stderr !== '') {
const serverError = new Error(state.stderr.trim(), { cause: error })
serverError.code = 'NBD_SERVER_EXITED'
serverError.exitCode = state.child.exitCode
serverError.command = this.#command
serverError.stderr = state.stderr
throw serverError
}
throw error
}
}
async _openTransport() {
const child = spawn(this.#command, this.#args, {
cwd: this.#cwd,
@@ -108,13 +75,7 @@ export default class NbdStdioClient extends AbstractNbdClient {
// the protocol goes through stdin/stdout, stderr is only used for diagnostics
stdio: ['pipe', 'pipe', 'pipe'],
})
const state = {
child,
closing: false,
stderr: '',
// 'close' comes after the exit and the end of the standard streams: stderr is complete
closed: new Promise(resolve => child.once('close', resolve)),
}
const state = { child, closing: false, stderr: '' }
this.#state = state
child.stderr.setEncoding('utf8')

View File

@@ -1,19 +0,0 @@
import assert from 'node:assert/strict'
import { describe, it } from 'node:test'
import NbdStdioClient from './NbdStdioClient.mjs'
describe('NbdStdioClient', () => {
it('reports what the server wrote on stderr when it dies before the handshake', async () => {
// the end of stdout and the exit of the process come in either order: repeat
for (let i = 0; i < 20; i++) {
const client = new NbdStdioClient({ command: 'sh', args: ['-c', 'echo "the actual reason" >&2; exit 1'] })
await assert.rejects(client.connect(), {
code: 'NBD_SERVER_EXITED',
exitCode: 1,
message: 'the actual reason',
stderr: 'the actual reason\n',
})
}
})
})

View File

@@ -13,7 +13,7 @@
"url": "https://vates.fr"
},
"license": "ISC",
"version": "3.7.2",
"version": "3.7.0",
"engines": {
"node": ">=14.0"
},
@@ -23,9 +23,9 @@
"@vates/read-chunk": "^1.2.1",
"@xen-orchestra/async-map": "^0.1.5",
"@xen-orchestra/disk-transform": "^1.3.4",
"@xen-orchestra/log": "^1.0.0",
"@xen-orchestra/log": "^0.7.2",
"promise-toolbox": "^0.21.0",
"xen-api": "^6.0.0"
"xen-api": "^5.1.0"
},
"devDependencies": {
"tap": "^18.7.0",

View File

@@ -1,6 +1,6 @@
{
"name": "@vates/node-vsphere-soap",
"version": "2.2.1",
"version": "2.2.0",
"description": "interface to vSphere SOAP/WSDL from node for interfacing with vCenter or ESXi, forked from node-vsphere-soap",
"main": "lib/client.mjs",
"author": "reedog117",
@@ -11,7 +11,7 @@
},
"bugs": "https://github.com/vatesfr/xen-orchestra/issues",
"dependencies": {
"@xen-orchestra/log": "^1.0.0",
"@xen-orchestra/log": "^0.7.2",
"axios": "^1.15.0",
"soap": "^1.0.0",
"soap-cookie": "^0.10.1"

View File

@@ -13,7 +13,7 @@
"url": "https://vates.fr"
},
"license": "ISC",
"version": "0.2.0",
"version": "0.1.0",
"engines": {
"node": ">=8.10"
},

View File

@@ -19,7 +19,7 @@
"url": "https://vates.fr"
},
"license": "ISC",
"version": "0.2.0",
"version": "0.1.0",
"engines": {
"node": ">=18"
},

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": "2.5.0",
"main": "./dist/index.mjs",
"exports": {
".": {

View File

@@ -22,11 +22,6 @@ export const BACKUP_EXPRESSION_CONTEXT = {
tags: { type: 'string[]' },
power_state: { type: 'string' },
},
pool: {
name_label: { type: 'string' },
description: { type: 'string' },
tags: { type: 'string[]' },
},
chainLength: { type: 'number' },
} as const
@@ -38,8 +33,6 @@ export const BACKUP_SETTING_CONTEXT = {
vmFilter: ['vm', 'run'],
srs: ['sr', 'run'],
remotes: ['backupRepository', 'run'],
vms: ['vm', 'run'],
pools: ['pool', 'run'],
} as const
export type BACKUP_SETTING_CONTEXT = (typeof BACKUP_SETTING_CONTEXT)[keyof typeof BACKUP_SETTING_CONTEXT]

View File

@@ -759,10 +759,6 @@ export type TrafficRuleProtocol = (typeof TRAFFIC_RULE_PROTOCOLS)[number]
export const SDN_CONTROLLER_OF_RULES_KEY = 'xo:sdn-controller:of-rules'
export const SDN_CONTROLLER_OF_METHOD_KEY = 'xo:sdn-controller:of-method'
export const SDN_CONTROLLER_OF_FORMAT_KEY = 'xo:sdn-controller:of-format'
export const SDN_CONTROLLER_PRIVATE_NETWORK_UUID_KEY = 'xo:sdn-controller:private-network-uuid'
export const SDN_CONTROLLER_ENCRYPTED_KEY = 'xo:sdn-controller:encrypted'
export const SDN_CONTROLLER_ENCAPSULATION_KEY = 'xo:sdn-controller:encapsulation'
export const SDN_CONTROLLER_PREFERRED_CENTER_KEY = 'xo:sdn-controller:preferred-center'
export const TRAFFIC_RULE_PROTOCOLS = ['ARP', 'ICMP', 'IP', 'TCP', 'UDP'] as const
export const TRAFFIC_RULE_PROTOCOLS_WITH_PORT: readonly TrafficRuleProtocol[] = ['TCP', 'UDP']
@@ -822,16 +818,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

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

View File

@@ -155,80 +155,26 @@ export type PoolRollingUpdateRecoveryError = {
}
export type PoolRollingUpdateRecoveryHost = {
/** `interrupted`: left in progress by a run that is over */
status: 'pending' | 'running' | 'interrupted' | 'succeeded' | 'failed' | 'not-needed'
status: 'pending' | 'running' | 'succeeded' | 'failed' | 'not-needed'
steps: Record<RPU_RECOVERY_STEP_NAME, PoolRollingUpdateRecoveryStep>
lastError: PoolRollingUpdateRecoveryError | null
}
/** a VM the last migrate back of the run could not bring to its original host */
export type PoolRollingUpdateRecoveryVmConflict = {
vmId: string
/** unknown for a VM deleted before the run could read it */
vmName?: string
/** UUID of the host the VM was running on before the run */
hostId: string
/** `stopped` and `deleted`: left to the operator; `migration-failed`: retried by a resume */
reason: 'stopped' | 'deleted' | 'migration-failed'
/** XAPI error of the last migration, `migration-failed` only */
message?: string
}
/** what an operator changed, since the run, on a setting the run left changed or on an object of the run */
export type PoolRollingUpdateRecoveryOperatorChange = {
/** `haHeartbeatSr`: a heartbeat SR needed to enable HA again no longer exists */
type: 'ha' | 'autoPowerOn' | 'wlb' | 'schedule' | 'haHeartbeatSr' | 'host' | 'vm'
/** pool, schedule, SR, host or VM UUID */
id: string
/** schedules enabled again only */
name?: string
/** `disabled` as the run left it, `present` for a heartbeat SR, a host or a VM */
expected: 'disabled' | 'present'
/** `missing` for a deleted schedule, heartbeat SR, host or VM */
observed: 'enabled' | 'missing'
}
/** hosts resumes added to the plan of the run: patches released since it started, or hosts new to the pool */
export type PoolRollingUpdateRecoveryPlanChange = {
/** the last resume which added hosts */
attempt: number
/** UUIDs of hosts the run did not plan to update, or had finished, added by any resume */
addedHostIds: string[]
}
export type PoolRollingUpdateRecoveryRun = {
runId: string
poolId: string
/** `awaiting-acceptance`: a resume found operator changes and waits for them to be accepted */
status:
| 'preparing'
| 'running'
| 'interrupted'
| 'resuming'
| 'failed'
| 'cleaning'
| 'succeeded'
| 'awaiting-acceptance'
status: 'preparing' | 'running' | 'interrupted' | 'resuming' | 'failed' | 'cleaning' | 'succeeded'
startedAt: string
updatedAt: string
finishedAt?: string
interruptedAt?: string
taskId?: string
variant?: 'xcp' | 'xs-cdn'
/** 1 for the first attempt, incremented by each resume of the run */
attempt?: number
/** whether a resume would be accepted: run failed, interrupted or awaiting the acceptance of operator changes */
resumable?: boolean
hostOrder?: string[]
hosts: Record<string, PoolRollingUpdateRecoveryHost>
lastError: PoolRollingUpdateRecoveryError | null
/** VM UUID -> UUID of the host it must be started on */
haltedPinnedVms: Record<string, string>
vmConflicts: PoolRollingUpdateRecoveryVmConflict[]
/** found by the last resume, the run stays `awaiting-acceptance` until they are accepted */
operatorChanges: PoolRollingUpdateRecoveryOperatorChange[]
/** absent when no resume changed the plan */
planChange?: PoolRollingUpdateRecoveryPlanChange
}
/** record unreadable or of an unknown schema version: recovery needs a human */
@@ -357,8 +303,6 @@ export type XoApp = EventEmitter & {
checkFeatureAuthorization(featureCode: FeatureCode): Promise<void>
/* whether this machine can run the tools of an import from VMware */
checkEsxiDependencies(): Promise<XoV2vStatus>
/* Throw if the proxy cannot be reached */
checkProxyHealth(id: XoProxy['id']): Promise<void>
/* validate, apply and persist the configuration of a plugin */
configurePlugin(id: string, configuration: unknown, mergeWithExisting?: boolean): Promise<void>
/* connect a server (XCP-ng/XenServer) */
@@ -472,7 +416,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>
@@ -674,10 +617,6 @@ export type XoApp = EventEmitter & {
): Promise<void>
getRollingUpdateRecovery(poolId: XoPool['id']): Promise<PoolRollingUpdateRecovery | undefined>
finalizeRollingUpdate(pool: XoPool, opts?: { force?: boolean; parentTask?: VatesTask }): Promise<void>
resumeRollingPoolUpdate(
pool: XoPool,
opts?: { acceptOperatorChanges?: boolean; bypassBackupCheck?: boolean; parentTask?: VatesTask }
): Promise<void>
setVmResourceSet(vmId: XoVm['id'], resourceSetId: string | null, force?: boolean): Promise<void>
shareVmResourceSet(vmId: XoVm['id']): Promise<void>
removeUserFromGroup(userId: XoUser['id'], id: XoGroup['id']): Promise<void>

View File

@@ -579,9 +579,6 @@ export type XoBrowserMediaSession = {
export type XoProxy = {
id: Branded<'proxy'>
/**
* @deprecated no replacement for this field
*/
url: string
version?: string
name: string
@@ -646,7 +643,7 @@ export type XoVmBackupJob = BaseXoJob & {
proxy?: XoProxy['id']
mode: 'full' | 'delta'
remotes?: CMType.IdOr<XoBackupRepository['id']> | string
vms: CMType.IdOr<XoVm['id']> | Record<string, unknown> | string
vms: CMType.IdOr<XoVm['id']> | Record<string, unknown>
srs?: CMType.IdOr<XoSr['id']> | string
type: 'backup'
settings: {
@@ -663,7 +660,7 @@ export type XoMetadataBackupJobScheduleSettings = {
}
export type XoMetadataBackupJob = BaseXoJob & {
type: 'metadataBackup'
pools?: CMType.IdOr<XoPool['id']> | string
pools?: CMType.IdOr<XoPool['id']>
remotes: CMType.IdOr<XoBackupRepository['id']>
settings: {
''?: XoMetadataBackupJobGeneralSettings
@@ -696,7 +693,6 @@ export type XoMirrorBackupJob = BaseXoJob & {
sourceRemote: XoBackupRepository['id']
remotes: CMType.IdOr<XoBackupRepository['id']>
proxy?: XoProxy['id']
filter?: { vm: { uuid: { __or: XoVm['id'][] } } } | null
settings: {
'': XoMirrorBackupGeneralSettings
[scheduleId: XoSchedule['id']]: XoMirrorBackupScheduleSettings | undefined

View File

@@ -6,7 +6,7 @@
"main": "dist/index.mjs",
"name": "@xen-orchestra/acl",
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/@xen-orchestra/acl",
"version": "1.9.0",
"version": "1.8.0",
"license": "AGPL-3.0-or-later",
"private": false,
"type": "module",
@@ -30,7 +30,7 @@
},
"devDependencies": {
"@eslint/js": "^9.19.0",
"@vates/types": "^3.2.0",
"@vates/types": "^2.5.0",
"rimraf": "^6.0.1",
"typescript": "~5.6",
"typescript-eslint": "^8.61.0"

View File

@@ -3,16 +3,7 @@ export default {
delete: true,
forget: true,
import: {
vdi: {
upload: true,
/**
* Warning: lets the holder make XO send a GET request to any HTTP(S) URL, including internal addresses
* reachable from the XO server (localhost, management network, etc.).
*
* Covered by `import:vdi`, `import` and `*`: only grant these to trusted users.
*/
url: true,
},
vdi: true,
vm: true,
},
'migrate-receive': true,

View File

@@ -38,10 +38,33 @@ export class Privilege<T extends SupportedResource> {
}
#matchAction<Resource extends SupportedResource = T>(action: SupportedActions<Resource>) {
// A privilege allows its own action and every action below it in the tree:
// e.g. `*`, `import`, `import:vdi` and `import:vdi:url` all allow `import:vdi:url`,
// but `import:vdi:upload` does not (it is a sibling, not a parent)
return this.#action === '*' || this.#action === action || action.startsWith(`${this.#action}:`)
// read:name_label - read:name_label
if (this.#action === action) {
return true
}
const [namespaceToMatch, actionToMatch] = action.split(':')
const [thisNamespace, thisAction] = this.#action.split(':')
if (thisNamespace === '*') {
return true
}
// update:vm - read:name_label
if (thisNamespace !== namespaceToMatch) {
return false
}
// read - read:name_label
if (thisAction === undefined) {
return true
}
// read:name_decription - read:name_label
if (thisAction !== actionToMatch) {
return false
}
throw new Error(`Unable to verify if ${this.#action} match ${action} `)
}
#matchSelector(object: object) {

View File

@@ -27,12 +27,6 @@ suite('Privilege.checkActionIsValid behavior', () => {
test('should work', () => {
assert.doesNotThrow(() => Privilege.checkActionIsValid('vm', 'read'))
})
test('should work with 3-level actions', () => {
assert.doesNotThrow(() => Privilege.checkActionIsValid('sr', 'import:vdi:url'))
// @ts-expect-error test invalid action
assert.throws(() => Privilege.checkActionIsValid('sr', 'import:vdi:foo'))
})
})
suite('Privilege.match behavior', () => {
@@ -65,22 +59,6 @@ suite('Privilege.match behavior', () => {
const cleanShutdownPrivilege = new Privilege({ action: 'shutdown:clean', resource: 'vm', effect: 'allow' })
assert.strictEqual(cleanShutdownPrivilege.match({ resource: 'vm', action: 'shutdown', object }), false)
})
test('Should match 3-level actions with any parent action', () => {
for (const action of ['*', 'import', 'import:vdi', 'import:vdi:url'] as const) {
const srPrivilege = new Privilege({ action, resource: 'sr', effect: 'allow' })
assert.strictEqual(srPrivilege.match({ resource: 'sr', action: 'import:vdi:url', object }), true, action)
}
})
test('Should not match 3-level actions with a sibling or a child action', () => {
const uploadPrivilege = new Privilege({ action: 'import:vdi:upload', resource: 'sr', effect: 'allow' })
assert.strictEqual(uploadPrivilege.match({ resource: 'sr', action: 'import:vdi:url', object }), false)
assert.strictEqual(uploadPrivilege.match({ resource: 'sr', action: 'import:vdi', object }), false)
const vmImportPrivilege = new Privilege({ action: 'import:vm', resource: 'sr', effect: 'allow' })
assert.strictEqual(vmImportPrivilege.match({ resource: 'sr', action: 'import:vdi:url', object }), false)
})
})
suite('ACL V2 behavior', async () => {
@@ -280,23 +258,6 @@ suite('ACL V2 behavior', async () => {
false
)
})
test('Should allow VDI upload but not URL import with import:vdi allowed and import:vdi:url denied', () => {
const sr = { id: 'sr-id' }
const userPrivileges = [
{ id: privilegeId, action: 'import:vdi', resource: 'sr', effect: 'allow', roleId },
{ id: privilegeId, action: 'import:vdi:url', resource: 'sr', effect: 'deny', roleId },
] satisfies TPrivilege<'sr'>[]
assert.strictEqual(
hasPrivilegeOn({ user, action: 'import:vdi:upload', resource: 'sr', objects: sr, userPrivileges }),
true
)
assert.strictEqual(
hasPrivilegeOn({ user, action: 'import:vdi:url', resource: 'sr', objects: sr, userPrivileges }),
false
)
})
})
suite('getMissingPrivileges behavior', () => {
@@ -414,12 +375,4 @@ suite('getActionStrings', () => {
assert.ok(actions.includes('shutdown:clean'))
assert.ok(actions.includes('shutdown:hard'))
})
test('3-level actions are included alongside their parents', () => {
const actions = getActionStrings('sr')
assert.ok(actions.includes('import'))
assert.ok(actions.includes('import:vdi'))
assert.ok(actions.includes('import:vdi:upload'))
assert.ok(actions.includes('import:vdi:url'))
})
})

View File

@@ -7,7 +7,7 @@
"type": "git",
"url": "https://github.com/vatesfr/xen-orchestra.git"
},
"version": "0.4.1",
"version": "0.4.0",
"engines": {
"node": ">=14"
},
@@ -17,7 +17,7 @@
},
"dependencies": {
"@vates/decorate-with": "^2.1.0",
"@xen-orchestra/log": "^1.0.0",
"@xen-orchestra/log": "^0.7.2",
"golike-defer": "^0.5.1",
"object-hash": "^2.0.1"
},

View File

@@ -1,7 +1,7 @@
{
"private": true,
"name": "@xen-orchestra/autopilot-docking",
"version": "0.1.0",
"version": "0.0.0",
"description": "Live ISO that prepares a VM imported from another hypervisor to boot on XCP-ng",
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/@xen-orchestra/autopilot-docking",
"bugs": "https://github.com/vatesfr/xen-orchestra/issues",

View File

@@ -1,6 +1,6 @@
{
"name": "@xen-orchestra/backup-archive",
"version": "1.2.1",
"version": "1.2.0",
"description": "Helper to handle generic backup archives",
"license": "ISC",
"author": "",
@@ -21,18 +21,18 @@
"tar-stream": "^3.1.8",
"@types/tar-stream": "^3.1.4",
"tmp": "^0.2.1",
"@vates/types": "^3.2.0"
"@vates/types": "^2.5.0"
},
"dependencies": {
"@xen-orchestra/log": "^1.0.0",
"@xen-orchestra/fs": "^4.11.0",
"@xen-orchestra/log": "^0.7.1",
"@xen-orchestra/fs": "^4.10.0",
"@xen-orchestra/disk-transform": "^1.3.4",
"@vates/task": "0.7.0",
"golike-defer": "0.5.1",
"uuid": "^9.0.0",
"promise-toolbox": "^0.21.0",
"@vates/async-each": "^1.0.1",
"vhd-lib": "^4.17.1"
"vhd-lib": "^4.17.0"
},
"scripts": {
"build": "yarn run clean && tsc",

View File

@@ -8,8 +8,8 @@
"dependencies": {
"@vates/async-each": "^1.0.3",
"@xen-orchestra/async-map": "^0.1.5",
"@xen-orchestra/backups": "^1.0.1",
"@xen-orchestra/fs": "^4.11.0",
"@xen-orchestra/backups": "^0.78.0",
"@xen-orchestra/fs": "^4.10.0",
"filenamify": "^6.0.0",
"getopts": "^2.2.5",
"lodash": "^4.18.0",
@@ -28,7 +28,7 @@
"scripts": {
"postversion": "npm publish --access public"
},
"version": "1.1.19",
"version": "1.1.18",
"license": "AGPL-3.0-or-later",
"author": {
"name": "Vates SAS",

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,7 +3,6 @@ import assert from 'node:assert'
import { formatFilenameDate } from './_filenameDate.mjs'
import { importIncrementalVm } from './_incrementalVm.mjs'
import { liveMountXapiLabels } from './liveMountXapiLabels.mjs'
import { destroyOnAbort } from './_destroyOnAbort.mjs'
import { watchStreamSize } from './_watchStreamSize.mjs'
import { decorateClass } from '@vates/decorate-with'
import { Task } from '@vates/task'
@@ -426,13 +425,6 @@ export class ImportVmBackup {
}
backup = await adapter.readFullVmBackup(metadata)
watchStreamSize(backup, sizeContainer)
// the restore stops once aborted (e.g. the health check of an aborted backup): a full backup is a stream that
// `VM_import()` sends as is, destroying it fails the import, and XAPI drops the partial VM
//
// set up as soon as the stream exists, so that an abort landing before the import starts, or leaving the transfer
// subtask unable to run, still closes it (a file handle or an S3 request)
$defer(destroyOnAbort(backup, Task.abortSignal))
} else {
assert.strictEqual(metadata.mode, 'delta')
@@ -459,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

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

@@ -687,14 +687,12 @@ export class RemoteAdapter {
return path
}
// `signal` stops the write once aborted: the partial disk is then removed
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,
@@ -707,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

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

@@ -9,7 +9,6 @@ const { warn } = createLogger('xo:backups:buildContext')
/**
* @typedef {import('@vates/types/xen-api').XenApiVm} XenApiVm
* @typedef {import('@vates/types/xo').XoSr} XoSr
* @typedef {import('@vates/types/xo').XoPool} XoPool
* @typedef {import('@vates/types/xo').XoBackupRepository} XoBackupRepository
*
* @typedef {object} RunContext
@@ -31,10 +30,6 @@ const { warn } = createLogger('xo:backups:buildContext')
* @typedef {object} BackupRepositoryContext
* @property {{name: string, type: string | undefined, tags: string[]}} backupRepository
* @property {RunContext} run
*
* @typedef {object} PoolContext
* @property {{name_label: string, description: string, tags: string[]}} pool
* @property {RunContext} run
*/
/**
@@ -114,19 +109,3 @@ export function buildBackupRepositoryContext(backupRepository, run) {
run,
}
}
/**
* @param {XoPool} pool
* @param {RunContext} run
* @returns {PoolContext}
*/
export function buildPoolContext(pool, run) {
return {
pool: {
name_label: pool.name_label,
description: pool.name_description,
tags: Array.isArray(pool.tags) ? pool.tags : [],
},
run,
}
}

View File

@@ -1,13 +1,7 @@
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import {
buildRunContext,
buildVmContext,
buildSrContext,
buildBackupRepositoryContext,
buildPoolContext,
} from './_buildContext.mjs'
import { buildRunContext, buildVmContext, buildSrContext, buildBackupRepositoryContext } from './_buildContext.mjs'
import { BACKUP_EXPRESSION_CONTEXT } from '@vates/types/backup-expression-context'
describe('buildContext', () => {
@@ -150,39 +144,4 @@ describe('buildContext', () => {
Object.keys(BACKUP_EXPRESSION_CONTEXT.backupRepository).sort()
)
})
it('buildPoolContext', () => {
const pool1 = {
name_label: 'name_label',
name_description: 'description',
ignored: 'ignored',
}
const poolContext1 = buildPoolContext(pool1, runContext)
assert.deepEqual(poolContext1, {
pool: {
name_label: 'name_label',
description: 'description',
tags: [],
},
run: expectedRunContext,
})
assert.deepEqual(Object.keys(poolContext1.pool).sort(), Object.keys(BACKUP_EXPRESSION_CONTEXT.pool).sort())
const pool2 = {
name_label: 'name_label',
name_description: 'description',
tags: ['tag'],
ignored: 'ignored',
}
const poolContext2 = buildPoolContext(pool2, runContext)
assert.deepEqual(poolContext2, {
pool: {
name_label: 'name_label',
description: 'description',
tags: ['tag'],
},
run: expectedRunContext,
})
assert.deepEqual(Object.keys(poolContext2.pool).sort(), Object.keys(BACKUP_EXPRESSION_CONTEXT.pool).sort())
})
})

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,7 +3,6 @@ import { createLogger } from '@xen-orchestra/log'
import { AbstractRemote } from './_AbstractRemote.mjs'
import { FullRemoteWriter } from '../_writers/FullRemoteWriter.mjs'
import { forkStreamUnpipe } from '../_forkStreamUnpipe.mjs'
import { destroyOnAbort } from '../../_destroyOnAbort.mjs'
import { watchStreamSize } from '../../_watchStreamSize.mjs'
import { AggregatedFullRemoteWriter } from '../_writers/AggregatedFullRemoteWriter.mjs'
import { Task } from '@vates/task'
@@ -24,7 +23,6 @@ export const FullRemote = class FullRemoteVmBackupRunner extends AbstractRemote
const nbTransferrableVms = transferList.length
let nbTransferredVms = 0
for (const metadata of transferList) {
Task.abortSignal?.throwIfAborted()
const stream = this._throttleStream(await this._sourceRemoteAdapter.readFullVmBackup(metadata))
const sizeContainer = watchStreamSize(stream)
let checksum
@@ -38,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 =>
@@ -56,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,5 +1,4 @@
import { createLogger } from '@xen-orchestra/log'
import { Task } from '@vates/task'
import { forkStreamUnpipe } from '../_forkStreamUnpipe.mjs'
import { FullRemoteWriter } from '../_writers/FullRemoteWriter.mjs'
@@ -56,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

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

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

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

@@ -55,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 = {}

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

View File

@@ -2,7 +2,6 @@ import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { formatDateTime } from '@xen-orchestra/xapi'
import { Task } from '@vates/task'
import { AbstractXapi } from './_AbstractXapi.mjs'
import { DATETIME, EXPORTED_SUCCESSFULLY, JOB_ID, SCHEDULE_ID } from '../../_otherConfig.mjs'
@@ -658,80 +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',
])
})
})

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()
}
@@ -281,8 +265,6 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
}
let size = 0
await Task.run({ properties: { name: 'transfer' } }, async () => {
// stops the writes once the backup is aborted
const signal = Task.abortSignal
await asyncEach(
Object.entries(deltaExport.disks),
async ([diskRef, disk]) => {
@@ -303,7 +285,6 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
// no checksum for VHDs, because they will be invalidated by
// merges and chains
checksum: false,
signal,
validator: tmpPath => checkDisk(handler, tmpPath),
writeBlockConcurrency: this._config.writeBlockConcurrency,
uuid: packUuid(vdi.uuid),
@@ -319,11 +300,6 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
return { size }
})
// the metadata makes the backup restorable: it is not written for an aborted backup, whose disks are removed by
// the clean-vm of `afterBackup()`
Task.abortSignal?.throwIfAborted()
metadataContent.tags = await this.getLongTermRetentionTags(metadataContent)
metadataContent.size = size // @todo return exactly the size written by this writer
this._metadataFileName = await adapter.writeVmBackupMetadata(vm.uuid, metadataContent)

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

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

@@ -83,7 +83,6 @@ const main = Disposable.wrap(async function* main(args) {
handler.unlink(taskFile).catch(error => warn('deleting task failure', { error }))
} catch (error) {
warn('failure handling task', { error })
if (error.code === 'ELOCKED') await new Promise(resolve => setTimeout(resolve, 5 * 60e3))
}
},
{ concurrency }

View File

@@ -8,7 +8,7 @@
"type": "git",
"url": "https://github.com/vatesfr/xen-orchestra.git"
},
"version": "1.0.1",
"version": "0.78.0",
"engines": {
"node": ">=22.19"
},
@@ -24,20 +24,20 @@
"@vates/cached-dns.lookup": "^1.0.0",
"@vates/compose": "^2.1.0",
"@vates/decorate-with": "^2.1.0",
"@vates/disposable": "^0.1.7",
"@vates/fuse-vhd": "^2.1.4",
"@vates/disposable": "^0.1.6",
"@vates/fuse-vhd": "^2.1.3",
"@vates/generator-toolbox": "^1.1.3",
"@vates/nbd-client": "^3.7.2",
"@vates/nbd-client": "^3.7.0",
"@vates/parse-duration": "^0.1.1",
"@vates/task": "^0.7.0",
"@vates/types": "^3.2.0",
"@vates/types": "^2.5.0",
"@xen-orchestra/async-map": "^0.1.5",
"@xen-orchestra/disk-transform": "^1.3.4",
"@xen-orchestra/fs": "^4.11.0",
"@xen-orchestra/log": "^1.0.0",
"@xen-orchestra/fs": "^4.10.0",
"@xen-orchestra/log": "^0.7.2",
"@xen-orchestra/qcow2": "^1.4.1",
"@xen-orchestra/template": "^0.1.1",
"@xen-orchestra/backup-archive": "^1.2.1",
"@xen-orchestra/backup-archive": "^1.2.0",
"app-conf": "^3.0.0",
"compare-versions": "^6.0.0",
"complex-matcher": "^1.1.1",
@@ -56,8 +56,8 @@
"tar": "^7.5.19",
"uuid": "^9.0.0",
"value-matcher": "^0.2.0",
"vhd-lib": "^4.17.1",
"xen-api": "^6.0.0",
"vhd-lib": "^4.17.0",
"xen-api": "^5.1.0",
"xo-common": "^0.11.0",
"xo-remote-parser": "^2.0.0",
"yazl": "^2.5.1"
@@ -70,7 +70,7 @@
"typescript": "^5.9.3"
},
"peerDependencies": {
"@xen-orchestra/xapi": "^10.1.0"
"@xen-orchestra/xapi": "^9.1.0"
},
"license": "AGPL-3.0-or-later",
"author": {

View File

@@ -1,7 +1,7 @@
{
"private": false,
"name": "@xen-orchestra/cr-seed-cli",
"version": "1.0.4",
"version": "1.0.3",
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/@xen-orchestra/cr-seed-cli",
"bugs": "https://github.com/vatesfr/xen-orchestra/issues",
"repository": {
@@ -18,7 +18,7 @@
"preferGlobal": true,
"dependencies": {
"golike-defer": "^0.5.1",
"xen-api": "^6.0.0"
"xen-api": "^5.1.0"
},
"scripts": {
"postversion": "npm publish"

View File

@@ -1,7 +1,7 @@
{
"private": false,
"name": "@xen-orchestra/disk-cli",
"version": "2.2.6",
"version": "2.2.5",
"description": "CLI tool to inspect and manage disks in backup repositories",
"type": "module",
"bin": {
@@ -20,13 +20,13 @@
},
"dependencies": {
"@vates/async-each": "^1.0.3",
"@xen-orchestra/backups": "^1.0.1",
"@xen-orchestra/backup-archive": "^1.2.1",
"@xen-orchestra/backups": "^0.78.0",
"@xen-orchestra/backup-archive": "^1.2.0",
"@xen-orchestra/disk-transform": "^1.3.4",
"@xen-orchestra/fs": "^4.11.0",
"@xen-orchestra/fs": "^4.10.0",
"@xen-orchestra/qcow2": "^1.4.1",
"promise-toolbox": "^0.21.0",
"vhd-lib": "^4.17.1"
"vhd-lib": "^4.17.0"
},
"devDependencies": {
"@types/node": "^22.3.0",

View File

@@ -1,7 +1,7 @@
{
"private": false,
"name": "@xen-orchestra/fs",
"version": "4.11.0",
"version": "4.10.0",
"license": "AGPL-3.0-or-later",
"description": "The File System for Xen Orchestra backups.",
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/@xen-orchestra/fs",
@@ -30,7 +30,7 @@
"@vates/coalesce-calls": "^0.1.0",
"@vates/decorate-with": "^2.1.0",
"@vates/read-chunk": "^1.2.1",
"@xen-orchestra/log": "^1.0.0",
"@xen-orchestra/log": "^0.7.2",
"bind-property-descriptor": "^2.0.0",
"decorator-synchronized": "^0.6.0",
"execa": "^5.0.0",

View File

@@ -16,14 +16,14 @@
"xo-immutable-remote": "./dist/protectRemotes.mjs"
},
"license": "AGPL-3.0-or-later",
"version": "3.0.10",
"version": "3.0.9",
"engines": {
"node": ">=20.0.0"
},
"dependencies": {
"@vates/async-each": "^1.0.3",
"@xen-orchestra/backups": "^1.0.1",
"@xen-orchestra/log": "^1.0.0",
"@xen-orchestra/backups": "^0.78.0",
"@xen-orchestra/log": "^0.7.2",
"app-conf": "^3.0.0",
"execa": "^5.0.0",
"ms": "^2.1.3"

View File

@@ -2,14 +2,6 @@
## **next**
- [VM/Network] Add possibility to delete a VIF (PR [#10726](https://github.com/vatesfr/xen-orchestra/pull/10726))
- [Host/VM/Pool] Add a Stats tab showing the CPU, RAM, network and load (or disk for VMs) charts over the last 10 minutes, 2 hours, week or year, with one line per CPU, interface, disk or host and an option to show the totals (PR [#10956](https://github.com/vatesfr/xen-orchestra/pull/10956))
## **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))
- [VM/Host] Main actions (shutdown, reboot, start, resume, migrate, snapshot) are shown as buttons in the VM and host headers and move one by one into "More actions" when space runs out; "More actions" groups them under "Change state" and "Actions" sections, and VMs without guest tools get force shutdown and force reboot instead (PR [#10815](https://github.com/vatesfr/xen-orchestra/pull/10815))
- [Web-Core/UiButtonIcon] Update icon buttons design, with a counter replacing the notification dot (PR [#10799](https://github.com/vatesfr/xen-orchestra/pull/10799))
@@ -20,10 +12,6 @@
- [Web-Core/UiDropdownButton] Update dropdown buttons design (PR [#9850](https://github.com/vatesfr/xen-orchestra/pull/9850))
- [Tables] Tables are filtered as you type, half a second after the last keystroke, or right away with Enter; the "Search" button is removed (PR [#10797](https://github.com/vatesfr/xen-orchestra/pull/10797))
- [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.0",
"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": "^2.5.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.65.0",
"complex-matcher": "^1.1.1",
"d3-time-format": "^4.1.0",
"decorator-synchronized": "^0.6.0",

View File

@@ -2,12 +2,12 @@
<div class="collection-filter-row">
<span class="or">{{ t('or') }}</span>
<div class="inputs">
<UiInput v-if="newFilter.isAdvanced" v-model="filterContent" accent="neutral" class="advanced-input" />
<UiInput v-if="newFilter.isAdvanced" v-model="filterContent" accent="brand" class="advanced-input" />
<template v-else>
<VtsSelect :id="builderPropertySelectId" accent="neutral" />
<VtsSelect v-if="hasComparisonSelect" :id="builderComparisonSelectId" accent="neutral" />
<VtsSelect v-if="currentFilter?.type === 'enum'" :id="builderValueSelectId" accent="neutral" />
<UiInput v-else-if="hasValueInput" v-model="newFilter.builder.value" accent="neutral" />
<VtsSelect :id="builderPropertySelectId" accent="brand" />
<VtsSelect v-if="hasComparisonSelect" :id="builderComparisonSelectId" accent="brand" />
<VtsSelect v-if="currentFilter?.type === 'enum'" :id="builderValueSelectId" accent="brand" />
<UiInput v-else-if="hasValueInput" v-model="newFilter.builder.value" accent="brand" />
</template>
</div>
<div class="buttons">

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

@@ -1,5 +1,5 @@
<template>
<VtsSelect v-if="isSelectWidget(widget)" :id="selectId" accent="neutral" />
<VtsSelect v-if="isSelectWidget(widget)" :id="selectId" accent="brand" />
<UiRadioButtonGroup v-else-if="isRadioWidget(widget)" accent="brand" gap="wide">
<UiRadioButton
v-for="choice in widget.choices"

View File

@@ -1,7 +1,7 @@
<template>
<VtsInputGroup>
<UiInput v-model.number="sizeInput" accent="neutral" type="number" :max-decimals="3" />
<VtsSelect :id="prefixSelectId" accent="neutral" />
<UiInput v-model.number="sizeInput" accent="brand" type="number" :max-decimals="3" />
<VtsSelect :id="prefixSelectId" accent="brand" />
</VtsInputGroup>
</template>

View File

@@ -1,25 +0,0 @@
<template>
<VtsStatsCharts :charts :granularity :loading="hostStats === undefined" :error="hasError || !!lastError" />
</template>
<script lang="ts" setup>
import { useObjectStats } from '@/composables/object-stats.composable.ts'
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import { useHostStore } from '@/stores/xen-api/host.store.ts'
import VtsStatsCharts from '@core/components/stats-charts/VtsStatsCharts.vue'
import { useHostStatsCharts } from '@core/composables/stats-charts/host-stats-charts.composable.ts'
import type { XapiStatsGranularity } from '@vates/types/common'
// The parent re-mounts this component (`key`) when the host or the granularity changes
const { host, granularity, showTotals } = defineProps<{
host: XenApiHost
granularity: XapiStatsGranularity
showTotals: boolean
}>()
const { getStats, lastError } = useHostStore().subscribe()
const { stats: hostStats, hasError } = useObjectStats<XenApiHost>(getStats, host, granularity)
const charts = useHostStatsCharts(hostStats, () => showTotals)
</script>

View File

@@ -6,9 +6,6 @@
<RouterTab :to="{ name: '/host/[uuid]/console', params: { uuid } }">
{{ t('console') }}
</RouterTab>
<RouterTab :to="{ name: '/host/[uuid]/stats', params: { uuid } }">
{{ t('stats') }}
</RouterTab>
<RouterTab :to="{ name: '/host/[uuid]/system', params: { uuid } }">
{{ t('system') }}
</RouterTab>

View File

@@ -2,8 +2,8 @@
<UiModal accent="info" @dismiss="emit('cancel')" @confirm="handleSubmit()">
<template #content>
<div class="form-selects">
<VtsSelect :id="sortPropertySelectId" accent="neutral" />
<VtsSelect :id="isAscendingSelectId" accent="neutral" />
<VtsSelect :id="sortPropertySelectId" accent="brand" />
<VtsSelect :id="isAscendingSelectId" accent="brand" />
</div>
</template>

View File

@@ -7,7 +7,7 @@
@dismiss="emit('cancel')"
>
<template #content>
<UiTextarea v-model="editedJson" accent="neutral" class="modal-textarea" />
<UiTextarea v-model="editedJson" accent="brand" class="modal-textarea" />
<VtsOverlayButton variant="tertiary" @click="formatJson()">
{{ t('action:reformat') }}
</VtsOverlayButton>

View File

@@ -8,7 +8,7 @@
:label="t('select-compression')"
learn-more-url="https://xcp-ng.org/blog/2018/12/19/zstd-compression-for-xcp-ng/"
>
<VtsSelect :id="compressionSelectId" accent="neutral" />
<VtsSelect :id="compressionSelectId" accent="brand" />
</VtsInputWrapper>
</template>
<template #buttons>

View File

@@ -7,7 +7,7 @@
<template #content>
<div>
<VtsInputWrapper :label="t('select-destination-host')">
<VtsSelect :id="hostSelectId" accent="neutral" />
<VtsSelect :id="hostSelectId" accent="brand" />
</VtsInputWrapper>
</div>
</template>

View File

@@ -45,7 +45,6 @@ const emit = defineEmits<{
const { t } = useI18n()
const { HeadCells, BodyCells, colspan } = useNewVmNetworkColumns({
exclude: ['rank'],
body: ({ networkInterface, onRemove }: { networkInterface: NetworkInterface; onRemove: () => void }) => {
const { id: interfaceSelectId } = useFormSelect(networks, {
model: toRef(networkInterface, 'interface'),

View File

@@ -1,5 +1,5 @@
<template>
<VtsTable class="new-vm-sr-table" fixed>
<VtsTable>
<thead>
<tr>
<HeadCells />
@@ -49,7 +49,6 @@ const emit = defineEmits<{
const { t } = useI18n()
const { HeadCells, BodyCells, colspan } = useNewVmSrColumns({
exclude: ['rank'],
body: ({ vdi, onRemove }: { vdi: Vdi; onRemove?: () => void }) => {
const { id: srSelectId } = useFormSelect(() => srs, {
model: toRef(vdi, 'SR'),
@@ -77,9 +76,3 @@ const { HeadCells, BodyCells, colspan } = useNewVmSrColumns({
},
})
</script>
<style lang="postcss" scoped>
.new-vm-sr-table {
--vts-table-min-width: 80rem;
}
</style>

View File

@@ -1,50 +0,0 @@
<template>
<VtsStatsCharts :charts :granularity :loading :error="hasError || !!lastError" />
</template>
<script lang="ts" setup>
import useFetchStats from '@/composables/fetch-stats.composable.ts'
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
import { useHostStore } from '@/stores/xen-api/host.store.ts'
import VtsStatsCharts from '@core/components/stats-charts/VtsStatsCharts.vue'
import { type PoolHostStats, usePoolStatsCharts } from '@core/composables/stats-charts/pool-stats-charts.composable.ts'
import type { XapiStatsGranularity } from '@vates/types/common'
import { differenceBy } from 'lodash-es'
import { computed, watch } from 'vue'
// The parent re-mounts this component (`key`) when the granularity changes
const { granularity, showTotals } = defineProps<{
granularity: XapiStatsGranularity
showTotals: boolean
}>()
const { getStats, runningHosts, lastError } = useHostStore().subscribe()
// The running hosts are only known once their metrics are loaded
const { isReady: areHostMetricsReady } = useHostMetricsStore().subscribe()
const { stats, register, unregister } = useFetchStats<XenApiHost>(getStats, granularity)
watch(
runningHosts,
(hosts, previousHosts = []) => {
differenceBy(hosts, previousHosts, 'uuid').forEach(host => register(host))
differenceBy(previousHosts, hosts, 'uuid').forEach(host => unregister(host))
},
{ immediate: true }
)
// A host whose stats can't be fetched doesn't hold the others back
const loading = computed(
() => !areHostMetricsReady.value || stats.value.some(stat => stat.stats === undefined && !stat.hasError)
)
const hasError = computed(() => stats.value.length > 0 && stats.value.every(stat => stat.hasError))
const hostsStats = computed<PoolHostStats[]>(() =>
stats.value.flatMap(({ name, response }) => (response === undefined ? [] : [{ name, stats: response }]))
)
const charts = usePoolStatsCharts(hostsStats, () => showTotals)
</script>

View File

@@ -6,7 +6,7 @@
<RouterTab :to="{ name: '/pool/[uuid]/alarms', params: { uuid: pool?.uuid ?? '-' } }" disabled>
{{ t('alarms') }}
</RouterTab>
<RouterTab :to="{ name: '/pool/[uuid]/stats', params: { uuid: pool?.uuid ?? '-' } }">
<RouterTab :to="{ name: '/pool/[uuid]/stats', params: { uuid: pool?.uuid ?? '-' } }" disabled>
{{ t('stats') }}
</RouterTab>
<RouterTab :to="{ name: '/pool/[uuid]/system', params: { uuid: pool?.uuid ?? '-' } }">

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

@@ -59,7 +59,7 @@ const useTaskColumns = defineColumns(() => {
const { t } = useI18n()
return {
name: useTextColumn({ headerLabel: t('name'), flexible: true }),
name: useTextColumn({ headerLabel: t('name') }),
host: useLinkColumn({ headerLabel: t('host') }),
progress: useProgressBarColumn({ headerLabel: t('progress') }),
started: useDateColumn({ headerLabel: t('started') }),

View File

@@ -1,25 +0,0 @@
<template>
<VtsStatsCharts :charts :granularity :loading="vmStats === undefined" :error="hasError || !!lastError" />
</template>
<script lang="ts" setup>
import { useObjectStats } from '@/composables/object-stats.composable.ts'
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
import VtsStatsCharts from '@core/components/stats-charts/VtsStatsCharts.vue'
import { useVmStatsCharts } from '@core/composables/stats-charts/vm-stats-charts.composable.ts'
import type { XapiStatsGranularity } from '@vates/types/common'
// The parent re-mounts this component (`key`) when the VM or the granularity changes
const { vm, granularity, showTotals } = defineProps<{
vm: XenApiVm
granularity: XapiStatsGranularity
showTotals: boolean
}>()
const { getStats, lastError } = useVmStore().subscribe()
const { stats: vmStats, hasError } = useObjectStats<XenApiVm>(getStats, vm, granularity)
const charts = useVmStatsCharts(vmStats, () => showTotals)
</script>

View File

@@ -9,7 +9,7 @@
<RouterTab :to="{ name: '/vm/[uuid]/alarms', params: { uuid } }" disabled>
{{ t('alarms') }}
</RouterTab>
<RouterTab :to="{ name: '/vm/[uuid]/stats', params: { uuid } }">
<RouterTab :to="{ name: '/vm/[uuid]/stats', params: { uuid } }" disabled>
{{ t('stats') }}
</RouterTab>
<RouterTab :to="{ name: '/vm/[uuid]/system', params: { uuid } }">

View File

@@ -143,7 +143,7 @@ const state = useTableState({
})
const { HeadCells, BodyCells } = useVmColumns({
exclude: ['actions', 'checkbox', 'lastBackupDate'],
exclude: ['actions', 'checkbox'],
body: (vm: XenApiVm) => {
const guestMetrics = computed(() => getGuestMetrics(vm.guest_metrics))
const vmMetrics = computed(() => getVmMetrics(vm.metrics))

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

@@ -1,17 +1,13 @@
import { RRD_STEP_FROM_STRING, type XapiStatsResponse } from '@/libs/xapi-stats.ts'
import { type GRANULARITY, RRD_STEP_FROM_STRING, type XapiStatsResponse } from '@/libs/xapi-stats.ts'
import type { XenApiHost, XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import type { XapiHostStatsRaw, XapiStatsGranularity, XapiVmStatsRaw } from '@vates/types/common'
import type { XapiHostStatsRaw, XapiVmStatsRaw } from '@vates/types/common'
import { type Pausable, promiseTimeout, useTimeoutPoll } from '@vueuse/core'
import { computed, type ComputedRef, markRaw, onUnmounted, ref, type Ref } from 'vue'
import { computed, type ComputedRef, onUnmounted, ref, type Ref } from 'vue'
export type Stat<T> = {
canBeExpired: boolean
// The last fetch failed: `stats` holds the previous ones, if any
hasError: boolean
id: string
name: string
// Shaped like the XO REST API stats, which the web-core stats charts expect
response: XapiStatsResponse<T> | undefined
stats: T | undefined
pausable: Pausable
}
@@ -21,7 +17,7 @@ export type GetStats<
S extends XapiHostStatsRaw | XapiVmStatsRaw = T extends XenApiHost ? XapiHostStatsRaw : XapiVmStatsRaw,
> = (
uuid: T['uuid'],
granularity: XapiStatsGranularity,
granularity: GRANULARITY,
ignoreExpired: boolean,
opts: { abortSignal?: AbortSignal }
) => Promise<XapiStatsResponse<S> | undefined> | undefined
@@ -37,13 +33,10 @@ export type FetchedStats<
timestampEnd: ComputedRef<number>
}
// In seconds
const RETRY_DELAY = 10
export default function useFetchStats<
T extends XenApiHost | XenApiVm,
S extends XapiHostStatsRaw | XapiVmStatsRaw = T extends XenApiHost ? XapiHostStatsRaw : XapiVmStatsRaw,
>(getStats: GetStats<T, S>, granularity: XapiStatsGranularity): FetchedStats<T, S> {
>(getStats: GetStats<T, S>, granularity: GRANULARITY): FetchedStats<T, S> {
const stats = ref(new Map()) as Ref<Map<string, Stat<S>>>
const timestamp = ref<number[]>([0, 0])
const abortController = new AbortController()
@@ -55,36 +48,15 @@ export default function useFetchStats<
return
}
let isFirstCall = true
const ignoreExpired = computed(() => !stats.value.has(mapKey))
const pausable = useTimeoutPoll(
async () => {
let newStats: XapiStatsResponse<S> | undefined
let hasError = false
// The first call accepts expired cached stats (e.g. when coming back to a page) to show something right away
const ignoreExpired = isFirstCall
isFirstCall = false
const newStats = (await getStats(object.uuid, granularity, ignoreExpired.value, {
abortSignal: abortController.signal,
})) as XapiStatsResponse<S>
try {
newStats = await getStats(object.uuid, granularity, ignoreExpired, {
abortSignal: abortController.signal,
})
} catch {
hasError = true
}
// The object may have been unregistered while its stats were being fetched
const stat = stats.value.get(mapKey)
if (stat === undefined) {
return
}
stat.hasError = hasError
// Without new stats (failure, disconnected XAPI…), retries soon, but not in a tight loop
if (newStats === undefined) {
await promiseTimeout(Math.min(RRD_STEP_FROM_STRING[granularity], RETRY_DELAY) * 1000)
return
}
@@ -94,16 +66,9 @@ export default function useFetchStats<
newStats.endTimestamp,
]
// Raw: replacing the stats is enough to update the charts, which then read their samples without proxies.
// Unchanged stats (e.g. the cache read again right after the first call) don't redraw the charts
if (stat.response?.endTimestamp !== newStats.endTimestamp) {
stat.stats = markRaw(newStats.stats)
stat.response = markRaw(newStats)
}
stat.canBeExpired = newStats.canBeExpired
// Cached stats (`canBeExpired`), possibly old (e.g. when coming back to a page), are checked again right away:
// the next call skips the cache if it's expired, instead of a full interval later, which can be a day
await promiseTimeout(newStats.canBeExpired ? 0 : newStats.interval * 1000)
stats.value.get(mapKey)!.stats = newStats.stats
stats.value.get(mapKey)!.canBeExpired = newStats.canBeExpired
await promiseTimeout(newStats.interval * 1000)
},
0,
{ immediate: true }
@@ -111,10 +76,8 @@ export default function useFetchStats<
stats.value.set(mapKey, {
canBeExpired: false,
hasError: false,
id: object.uuid,
name: object.name_label,
response: undefined,
stats: undefined,
pausable,
})

View File

@@ -1,20 +0,0 @@
import useFetchStats, { type GetStats } from '@/composables/fetch-stats.composable.ts'
import type { XenApiHost, XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import type { XapiHostStatsRaw, XapiStatsGranularity, XapiVmStatsRaw } from '@vates/types/common'
import { computed } from 'vue'
// Polls the stats of a single host or VM. The object and the granularity are fixed: the caller must be re-mounted to
// change them
export function useObjectStats<
T extends XenApiHost | XenApiVm,
S extends XapiHostStatsRaw | XapiVmStatsRaw = T extends XenApiHost ? XapiHostStatsRaw : XapiVmStatsRaw,
>(getStats: GetStats<T, S>, object: T, granularity: XapiStatsGranularity) {
const { stats, register } = useFetchStats<T, S>(getStats, granularity)
register(object)
return {
stats: computed(() => stats.value[0]?.response),
hasError: computed(() => stats.value[0]?.hasError === true),
}
}

View File

@@ -1,7 +1,6 @@
import type XenApi from '@/libs/xen-api/xen-api.ts'
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import type { XapiHostStatsRaw, XapiVmStatsRaw } from '@vates/types'
import type { XapiStatsGranularity } from '@vates/types/common'
import { synchronized } from 'decorator-synchronized'
// eslint-disable-next-line import/default -- https://github.com/json5/json5/issues/287
import JSON5 from 'json5'
@@ -33,7 +32,7 @@ export enum GRANULARITY {
Days = 'days',
}
export const RRD_STEP_FROM_STRING: Record<XapiStatsGranularity, RRD_STEP> = {
export const RRD_STEP_FROM_STRING: { [key in GRANULARITY]: RRD_STEP } = {
[GRANULARITY.Seconds]: RRD_STEP.Seconds,
[GRANULARITY.Minutes]: RRD_STEP.Minutes,
[GRANULARITY.Hours]: RRD_STEP.Hours,
@@ -417,7 +416,7 @@ export default class XapiStats {
host: XenApiHost
ignoreExpired?: boolean
uuid: any
granularity: XapiStatsGranularity
granularity: GRANULARITY
}) {
const step = granularity === undefined ? RRD_STEP.Seconds : RRD_STEP_FROM_STRING[granularity]
if (step === undefined) {

View File

@@ -1,6 +1,6 @@
<template>
<VtsInputWrapper :label :message="error">
<VtsSelect :id accent="neutral" />
<VtsSelect :id accent="brand" />
</VtsInputWrapper>
</template>

View File

@@ -1,6 +1,6 @@
<template>
<VtsInputWrapper :label :message="error">
<UiInput v-model.trim="model" accent="neutral" :required :disabled />
<UiInput v-model.trim="model" accent="brand" :required :disabled />
</VtsInputWrapper>
</template>

View File

@@ -1,5 +1,5 @@
<template>
<UiTextarea v-model.trim="model" accent="neutral">
<UiTextarea v-model.trim="model" accent="brand">
{{ t('description') }}
</UiTextarea>
</template>

View File

@@ -24,7 +24,6 @@
<script lang="ts" setup>
import type { XenApiVbd, XenApiVdi } from '@/libs/xen-api/xen-api.types.ts'
import { getVdiFormat, getVdiIcon } from '@/modules/vdi/utils/vdi.util.ts'
import { useVdiStore } from '@/stores/xen-api/vdi.store.ts'
import VtsRow from '@core/components/table/VtsRow.vue'
import VtsTable from '@core/components/table/VtsTable.vue'
import UiQuerySearchBar from '@core/components/ui/query-search-bar/UiQuerySearchBar.vue'
@@ -44,7 +43,6 @@ const { vdis, vbds, busy, error } = defineProps<{
error?: boolean
}>()
const { t } = useI18n()
const { getChainPhysicalUsage } = useVdiStore().subscribe()
const selectedVdiId = useRouteQuery('id')
const { items: filteredVdis, searchBindings } = useSearchFilter(() => vdis)
const state = useTableState({
@@ -58,7 +56,6 @@ const { HeadCells, BodyCells } = useVdiColumns({
exclude: ['actions'],
body: (vdi: XenApiVdi) => {
const vdiVbds = computed(() => vbds.filter(vbd => vbd.VDI === vdi.$ref))
const usedSpace = computed(() => formatSizeRaw(getChainPhysicalUsage(vdi), 2))
const size = computed(() => formatSizeRaw(vdi.virtual_size, 2))
const format = computed(() => getVdiFormat(vdi.sm_config['image-format']))
return {
@@ -68,7 +65,7 @@ const { HeadCells, BodyCells } = useVdiColumns({
icon: getVdiIcon(vdiVbds.value),
}),
description: r => r(vdi.name_description),
usedSpace: r => r(usedSpace.value.value, usedSpace.value.prefix),
usedSpace: r => r(vdi.physical_utilisation, vdi.virtual_size),
size: r => r(size.value.value, size.value.prefix),
format: r => r(format.value),
selectItem: r => r(() => (selectedVdiId.value = vdi.uuid)),

View File

@@ -1,48 +1,12 @@
<template>
<UiPanelCard>
<UiPanelCardTitle size="medium" :label="t('space')" />
<VtsCardRowList>
<VtsCardRowKeyValue>
<template #key>{{ t('used-space') }}</template>
<template #value>{{ usedSpace }}</template>
<template v-if="chainPhysicalUsage > 0" #addons>
<VtsCopyButton :value="usedSpace" />
</template>
</VtsCardRowKeyValue>
<VtsCardRowKeyValue>
<template #key>{{ t('size') }}</template>
<template #value>{{ size }}</template>
<template v-if="vdi.virtual_size > 0" #addons>
<VtsCopyButton :value="size" />
</template>
</VtsCardRowKeyValue>
</VtsCardRowList>
</UiPanelCard>
<VtsSpaceCard :used="vdi.physical_utilisation" :total="vdi.virtual_size" :label="vdi.name_label" />
</template>
<script setup lang="ts">
import type { XenApiVdi } from '@/libs/xen-api/xen-api.types.ts'
import { useVdiStore } from '@/stores/xen-api/vdi.store.ts'
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
import VtsCardRowList from '@core/components/card/VtsCardRowList.vue'
import VtsCopyButton from '@core/components/copy-button/VtsCopyButton.vue'
import UiPanelCard from '@core/components/ui/panel-card/UiPanelCard.vue'
import UiPanelCardTitle from '@core/components/ui/panel-card-title/UiPanelCardTitle.vue'
import { formatSize } from '@core/utils/size.util.ts'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import VtsSpaceCard from '@core/components/space-card/VtsSpaceCard.vue'
const { vdi } = defineProps<{
defineProps<{
vdi: XenApiVdi
}>()
const { t } = useI18n()
const { getChainPhysicalUsage } = useVdiStore().subscribe()
const chainPhysicalUsage = computed(() => getChainPhysicalUsage(vdi))
const usedSpace = computed(() => formatSize(chainPhysicalUsage.value, 2))
const size = computed(() => formatSize(vdi.virtual_size, 2))
</script>

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