Compare commits

..

12 Commits

Author SHA1 Message Date
MelissaFrncJrg
23a121e285 correct changelog 2026-11-25 11:47:58 +01:00
MelissaFrncJrg
2a678eb6d6 changelog entry 2026-11-25 11:47:58 +01:00
MelissaFrncJrg
b237144bb5 feat(rest-api): expose proxy upgrade action 2026-11-25 11:47:58 +01:00
MelissaFrncJrg
ed8cc840f8 feat(rest-api): expose proxy upgrade action 2026-11-25 11:47:22 +01:00
MelissaFrncJrg
33b20e6876 rebase 2026-11-25 11:05:26 +01:00
MelissaFrncJrg
918ef1198a rename proxy updater state route and test it 2026-11-25 10:58:51 +01:00
MelissaFrncJrg
acefda0a7b changelog 2026-11-25 10:58:45 +01:00
MelissaFrncJrg
a890cdf73d feat(rest-api): expose proxy updater state endpoint 2026-11-25 10:57:35 +01:00
ayoub-el-kajji-v
9c68705932 fix(backups/merge): adding delay in background merge when ELOCKED (#10866)
* fix(backups/merge): adding delay in background merge when ELOCKED

* add changelog

* changing logs display and unblocking non-locked tasks

* reducing changes to not make code complicated
2026-11-25 10:40:40 +01:00
Mathieu
14ed5fd5b9 fix(nbd-client): report the stderr of a stdio server dying before the handshake (#10842)
* fix(nbd-client): report the stderr of a stdio server dying before the handshake

When vectura exits before the NBD greeting (unreachable host, disk the
host refuses...), the V2V import failed with only:

    stream has ended without data, was looking for 8 bytes

The end of its stdout makes the handshake read fail first, then
`_destroyTransport` marks the exit as expected and the exit handler
reports nothing. When the exit comes first, stderr may not be read yet.

`connect()` now waits for the `close` event of the server, which comes
after its standard streams end, and throws `NBD_SERVER_EXITED` with its
stderr as the message and the handshake error as `cause`. `reconnect()`
goes through `connect()`, so the retries of `readBlock()` get it too.

Introduced by #10381

* fix(nbd-client): attach stderr to the pre-handshake NBD_SERVER_EXITED error

Same shape as the error built by the exit handler.
2026-11-25 10:13:27 +01:00
OlivierFL
f7e476cd81 docs(v2v): document the XO 6 migration wizard (#10833)
* docs(v2v): document the XO 6 migration wizard

* docs(v2v): add the XO 6 prerequisite check screenshot

* docs(v2v): add a screenshot of each XO 6 migration wizard step

* docs(v2v): flag the guide as new and the XO 5 section as legacy
2026-11-25 09:52:27 +01:00
spacotte-vates
2a4491aeda fix(backup-jobs): fix issues on backup job creation from the REST API (#10779)
* fix(rest-api): backup-job schedule settings lost on creation
* fix(backup-jobs): fix mirror and metadata job failing due to targeting backup repo with expression
* feat(backup-jobs): add expression support for vms and pools
* fix(rest-api): add filter support to backup-jobs
2026-11-25 09:44:12 +01:00
36 changed files with 722 additions and 168 deletions

View File

@@ -1,6 +1,6 @@
import assert from 'node:assert'
import { spawn } from 'node:child_process'
import { pFromCallback } from 'promise-toolbox'
import { pFromCallback, pTimeout } from 'promise-toolbox'
import { createLogger } from '@xen-orchestra/log'
import AbstractNbdClient from './AbstractNbdClient.mjs'
@@ -9,6 +9,9 @@ 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
@@ -28,7 +31,7 @@ export default class NbdStdioClient extends AbstractNbdClient {
#cwd
#env
/** @type {{ child: import('node:child_process').ChildProcess, closing: boolean, stderr: string }|undefined} */
/** @type {{ child: import('node:child_process').ChildProcess, closing: boolean, stderr: string, closed: Promise<unknown> }|undefined} */
#state
/**
@@ -68,6 +71,36 @@ 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,
@@ -75,7 +108,13 @@ 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: '' }
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)),
}
this.#state = state
child.stderr.setEncoding('utf8')

View File

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

@@ -22,6 +22,11 @@ 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
@@ -33,6 +38,8 @@ 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

@@ -466,14 +466,13 @@ export type XoApp = EventEmitter & {
opts?: { bypassAuthorization?: boolean; fromGroup?: boolean; fromUser?: boolean }
): Promise<XoAclRole[]>
getAllGroups(): Promise<XoGroup[]>
/** Also destroys the VM of the proxy, if any */
destroyProxy(id: XoProxy['id']): Promise<void>
getAllProxies(): Promise<XoProxy[]>
getAllJobs<T extends AnyXoJob['type']>(type: T): Promise<Extract<AnyXoJob, { type: T }>[]>
getAllJobs(type?: string): Promise<AnyXoJob[]>
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>
@@ -505,7 +504,10 @@ export type XoApp = EventEmitter & {
* `assertBrowserMediaInsertable` reports the predictable failures synchronously, e.g. before
* starting a task.
*/
insertBrowserMedia(params: { id: XoBrowserMediaSession['id']; vmId: XoVm['id'] }): Promise<{ vdiId: XoVdi['id'] }>
insertBrowserMedia(params: {
id: XoBrowserMediaSession['id']
vmId: XoVm['id']
}): Promise<{ vdiId: XoVdi['id'] }>
assertBrowserMediaInsertable(params: { id: XoBrowserMediaSession['id']; vmId: XoVm['id'] }): void
/** Eject the ISO of a browser media session, release its storage, and disconnect the browser */
ejectBrowserMedia(id: XoBrowserMediaSession['id']): Promise<void>
@@ -758,6 +760,8 @@ export type XoApp = EventEmitter & {
url?: string
}
): Promise<XoBackupRepository>
/** Throw if backup jobs are running on the proxy, unless ignored; `force` reboots the proxy VM */
upgradeProxyAppliance(id: XoProxy['id'], opts: { force?: boolean; ignoreRunningJobs?: boolean }): Promise<void>
getAllXapis(): Record<string, Xapi>
getObjects(opts?: { filter?: Record<string, unknown>; limit?: number }): Record<string, XapiXoRecord>
getLicenses(params?: { productType?: LicenseProductType }): Promise<License[]>

View File

@@ -646,7 +646,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>
vms: CMType.IdOr<XoVm['id']> | Record<string, unknown> | string
srs?: CMType.IdOr<XoSr['id']> | string
type: 'backup'
settings: {
@@ -663,7 +663,7 @@ export type XoMetadataBackupJobScheduleSettings = {
}
export type XoMetadataBackupJob = BaseXoJob & {
type: 'metadataBackup'
pools?: CMType.IdOr<XoPool['id']>
pools?: CMType.IdOr<XoPool['id']> | string
remotes: CMType.IdOr<XoBackupRepository['id']>
settings: {
''?: XoMetadataBackupJobGeneralSettings
@@ -696,6 +696,7 @@ 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

@@ -1,4 +1,4 @@
export default {
read: true,
delete: true,
upgrade: true,
}

View File

@@ -9,6 +9,7 @@ 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
@@ -30,6 +31,10 @@ 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
*/
/**
@@ -109,3 +114,19 @@ 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,7 +1,13 @@
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { buildRunContext, buildVmContext, buildSrContext, buildBackupRepositoryContext } from './_buildContext.mjs'
import {
buildRunContext,
buildVmContext,
buildSrContext,
buildBackupRepositoryContext,
buildPoolContext,
} from './_buildContext.mjs'
import { BACKUP_EXPRESSION_CONTEXT } from '@vates/types/backup-expression-context'
describe('buildContext', () => {
@@ -144,4 +150,39 @@ 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

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

@@ -15,6 +15,8 @@ import type {
import type { RestApi } from '../rest-api/rest-api.mjs'
import { assertValidCron, vmContainsNoBakTag } from '../helpers/utils.helper.mjs'
import type { CreateBackupJobBody, CreateBackupJobSchedule, UpdateBackupJobBody } from './backup-job.type.mjs'
import { compileExpression, isExpression } from '@xen-orchestra/backups/_expressionPredicate.mjs'
import { buildRunContext, buildVmContext } from '@xen-orchestra/backups/_buildContext.mjs'
export class BackupJobService {
#backupJobTypes = ['backup', 'metadataBackup', 'mirrorBackup']
@@ -69,12 +71,24 @@ export class BackupJobService {
*/
assertJobHasValidExpressions(type: AnyXoBackupJob['type'], job: UpdateBackupJobBody): void {
if (type === 'backup') {
const { srs, remotes, settings } = job as Extract<UpdateBackupJobBody, { srs?: unknown }>
const { srs, remotes, vms, settings } = job as Extract<UpdateBackupJobBody, { srs?: unknown }>
assertValidExpression('srs', srs)
assertValidExpression('remotes', remotes)
assertValidExpression('vms', vms)
assertValidSettingsExpression(settings, ['healthCheckVmsWithTags', 'fullInterval'])
} else if (type === 'mirrorBackup') {
assertValidSettingsExpression(job.settings, ['healthCheckVmsWithTags', 'vmFilter'])
const { filter, remotes, settings } = job as Extract<UpdateBackupJobBody, { sourceRemote?: unknown }>
assertValidSettingsExpression(settings, ['healthCheckVmsWithTags', 'vmFilter'])
assertValidExpression('remotes', remotes)
if (filter != null && filter.vm.uuid.__or.length === 0) {
throw invalidParameters('filter must contain at least one VM', [
{ instancePath: '/filter/vm/uuid/__or', message: 'must NOT have fewer than 1 items' },
])
}
} else if (type === 'metadataBackup') {
const { remotes, pools } = job as Extract<UpdateBackupJobBody, { pools?: unknown }>
assertValidExpression('remotes', remotes)
assertValidExpression('pools', pools)
}
}
@@ -90,16 +104,47 @@ export class BackupJobService {
return false
}
const isVmInJob = await this.getBackupJobVmMatcher(backupJob)
return isVmInJob(vm)
}
/**
* Returns a function telling whether a VM is selected by the `vms` of the job,
* whether it is a list of IDs, an object pattern or an expression
*/
async getBackupJobVmMatcher(backupJob: XoVmBackupJob): Promise<(vm: XoVm) => boolean> {
try {
const vmIds: XoVm['id'][] = extractIdsFromSimplePattern(backupJob.vms)
return vmIds.some(id => id === vm.id)
const vmIds = new Set<XoVm['id']>(extractIdsFromSimplePattern(backupJob.vms))
return vm => vmIds.has(vm.id)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (_) {
const predicate = createPredicate(backupJob.vms)
return predicate(vm)
if (!isExpression(backupJob.vms)) {
return createPredicate(backupJob.vms)
}
// `run:` clauses depend on the timezone, which is resolved per schedule like the executor does,
// so the VM is in the job if it matches for at least one of its schedules
const predicate = compileExpression(backupJob.vms)
const now = new Date()
const runContexts = (await this.#getScheduleTimezones(backupJob)).map(timezone => buildRunContext(now, timezone))
return vm => runContexts.some(runContext => predicate(buildVmContext(vm, runContext)))
}
}
async #getScheduleTimezones(backupJob: XoVmBackupJob): Promise<(string | undefined)[]> {
const schedules = (await this.#restApi.xoApp.getAllSchedules()).filter(schedule => schedule.jobId === backupJob.id)
if (schedules.length === 0) {
return [backupJob.settings['']?.timezone]
}
return schedules.map(schedule => {
const scheduleTimezone = backupJob.settings[schedule.id]?.timezone
return typeof scheduleTimezone === 'string'
? scheduleTimezone
: (backupJob.settings['']?.timezone ?? schedule.timezone)
})
}
async backupJobHasAtLeastOneScheduleEnabled(id: XoVmBackupJob['id']): Promise<boolean> {
const backupJob = await this.#restApi.xoApp.getJob<XoVmBackupJob>(id)

View File

@@ -6,15 +6,19 @@ import type {
XoMetadataBackupJobGeneralSettings,
XoMetadataBackupJobScheduleSettings,
XoMirrorBackupGeneralSettings,
XoVm,
} from '@vates/types'
import { Unbrand } from '../open-api/common/response.common.mjs'
import type * as CMType from '@vates/types/lib/complex-matcher'
// Manual copy because with Unbrand<>, tsoa emits an empty schema. If XoVmBackupJobScheduleSettings changes
// in @vates/types, you have to update this copy too.
type UnbrandedXoVmBackupJobScheduleSettings = {
/**
* Copy of XoVmBackupJobScheduleSettings without the brand:
* tsoa empties any mapped type (Unbrand, Pick, Omit…) nested under Unbrand<UnbrandedXoVmBackupJob>,
* which dropped every schedule setting from the request bodies
*/
type VmBackupJobScheduleSettings = {
exportRetention?: number
healthCheckVmsWithTags?: string[] | string
healthCheckVmsWithTags?: XoVm['tags'] | string
fullInterval?: number | string
copyRetention?: number
snapshotRetention?: number
@@ -25,17 +29,17 @@ type UnbrandedXoVmBackupJobScheduleSettings = {
type UnbrandedXoVmBackupJob = Omit<XoVmBackupJob, 'settings' | 'remotes' | 'vms' | 'srs'> & {
remotes?: CMType.IdOr<string> | string
vms: CMType.IdOr<string> | Record<string, unknown>
vms: CMType.IdOr<string> | Record<string, unknown> | string
srs?: CMType.IdOr<string> | string
settings: {
'': XoVmBackupJobGeneralSettings
[scheduleId: string]: UnbrandedXoVmBackupJobScheduleSettings | undefined
[scheduleId: string]: VmBackupJobScheduleSettings | undefined
}
}
export type UnbrandXoVmBackupJob = Unbrand<UnbrandedXoVmBackupJob>
type UnbrandedXoMetadataBackupJob = Omit<XoMetadataBackupJob, 'settings' | 'pools' | 'remotes'> & {
pools?: CMType.IdOr<string>
pools?: CMType.IdOr<string> | string
remotes: CMType.IdOr<string>
settings: {
''?: XoMetadataBackupJobGeneralSettings
@@ -44,21 +48,23 @@ type UnbrandedXoMetadataBackupJob = Omit<XoMetadataBackupJob, 'settings' | 'pool
}
export type UnbrandXoMetadataBackupJob = Unbrand<UnbrandedXoMetadataBackupJob>
// Manual copy because with Unbrand<>, tsoa emits an empty schema. If XoMirrorBackupScheduleSettings changes
// in @vates/types, you have to update this copy too.
type UnbrandedXoMirrorBackupScheduleSettings = {
/**
* Same as VmBackupJobScheduleSettings
*/
type MirrorBackupJobScheduleSettings = {
exportRetention?: number
healthCheckVmsWithTags?: string[] | string
healthCheckVmsWithTags?: XoVm['tags'] | string
vmFilter?: string
healthCheckSr?: string
[key: string]: unknown
}
type UnbrandedXoMirrorBackupJob = Omit<XoMirrorBackupJob, 'settings' | 'remotes'> & {
type UnbrandedXoMirrorBackupJob = Omit<XoMirrorBackupJob, 'settings' | 'remotes' | 'filter'> & {
remotes: CMType.IdOr<string>
filter?: { vm: { uuid: { __or: string[] } } } | null
settings: {
'': XoMirrorBackupGeneralSettings
[scheduleId: string]: UnbrandedXoMirrorBackupScheduleSettings | undefined
[scheduleId: string]: MirrorBackupJobScheduleSettings | undefined
}
}
export type UnbrandXoMirrorBackupJob = Unbrand<UnbrandedXoMirrorBackupJob>

View File

@@ -27,3 +27,9 @@ export const proxy = {
}
export const proxyHealth = { success: true }
export const proxyApplianceUpdaterState = {
level: 'info',
message: 'All up to date',
state: 'xoa-up-to-date',
}

View File

@@ -1,10 +1,11 @@
import {
Delete,
Body,
Example,
Extension,
Get,
Middlewares,
Path,
Post,
Query,
Request,
Response,
@@ -14,15 +15,18 @@ import {
Tags,
} from 'tsoa'
import { inject } from 'inversify'
import { json } from 'express'
import { provide } from 'inversify-binding-decorators'
import type { Request as ExRequest } from 'express'
import type { XoProxy } from '@vates/types'
import type { XoApp, XoProxy } from '@vates/types'
import { acl } from '../middlewares/acl.middleware.mjs'
import { ApiError } from '../helpers/error.helper.mjs'
import {
asynchronousActionResp,
badRequestResp,
forbiddenOperationResp,
incorrectStateResp,
internalServerErrorResp,
noContentResp,
notFoundResp,
@@ -30,7 +34,15 @@ import {
unauthorizedResp,
type Unbrand,
} from '../open-api/common/response.common.mjs'
import { partialProxies, proxy, proxyHealth, proxyIds } from '../open-api/oa-examples/proxy.oa-example.mjs'
import type { CreateActionReturnType } from '../abstract-classes/base-controller.mjs'
import { taskLocation } from '../open-api/oa-examples/task.oa-example.mjs'
import {
partialProxies,
proxy,
proxyHealth,
proxyIds,
proxyApplianceUpdaterState,
} from '../open-api/oa-examples/proxy.oa-example.mjs'
import type { SendObjects } from '../helpers/helper.type.mjs'
import { XoController } from '../abstract-classes/xo-controller.mjs'
import { RestApi } from '../rest-api/rest-api.mjs'
@@ -150,32 +162,97 @@ export class ProxyController extends XoController<XoProxy> {
}
/**
* Deletes a proxy
* Returns the state of the proxy appliance updater (e.g. `xoa-up-to-date`, or a state ending with `-upgrade-needed`)
*
* Destroys the VM of the proxy, if it has one, with its disks and snapshots, then removes the proxy from Xen Orchestra.
* Before reading the state, sets the updater channel to the one expected by Xen Orchestra.
* A successful result is cached for 60 seconds per proxy, errors are not cached.
*
* Required privilege:
* - resource: proxy, action: delete
*
* This privilege is enough to destroy the VM of the proxy: no privilege on that VM is checked.
* - resource: proxy, action: read
*
* @example id "e625ea0c-a876-405a-b838-109d762efe88"
*/
@Extension('x-mcp-exposure', 'confirm')
@Delete('{id}')
@Example(proxyApplianceUpdaterState)
@Extension('x-mcp-exposure', 'allow')
@Get('{id}/appliance_updater_state')
@Middlewares(
acl({
resource: 'proxy',
action: 'delete',
action: 'read',
objectId: 'params.id',
getObject: ({ restApi }) => restApi.xoApp.getProxy,
})
)
@SuccessResponse(noContentResp.status, noContentResp.description)
@SuccessResponse(200, 'OK')
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
@Response(notFoundResp.status, notFoundResp.description)
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
async deleteProxy(@Path() id: string): Promise<void> {
await this.restApi.xoApp.destroyProxy(id as XoProxy['id'])
@Response(proxyUnreachableResp.status, proxyUnreachableResp.description)
getProxyApplianceUpdaterState(@Path() id: string): ReturnType<XoApp['getProxyApplianceUpdaterState']> {
return callProxy(this.restApi.xoApp.getProxyApplianceUpdaterState(id as XoProxy['id']))
}
/**
* Upgrades the proxy appliance
*
* By default, the upgrade is refused with an `incorrect state` error if backup jobs are running on the proxy.
*
* Set `force` to `true` to upgrade by rebooting the proxy VM, which also ignores running jobs. Only available if the
* proxy VM is known. No privilege on the VM is checked: the `upgrade` action is enough to reboot it.
*
* Required privilege:
* - resource: proxy, action: upgrade
*
* @example id "e625ea0c-a876-405a-b838-109d762efe88"
* @example body { "force": false, "ignoreRunningJobs": false }
*/
@Example(taskLocation)
@Extension('x-mcp-exposure', 'confirm')
@Post('{id}/actions/upgrade')
@Middlewares([
json(),
acl({
resource: 'proxy',
action: 'upgrade',
objectId: 'params.id',
getObject: ({ restApi }) => restApi.xoApp.getProxy,
}),
])
@SuccessResponse(asynchronousActionResp.status, asynchronousActionResp.description)
@Response(noContentResp.status, noContentResp.description)
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
@Response(notFoundResp.status, notFoundResp.description)
@Response(incorrectStateResp.status, incorrectStateResp.description)
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
@Response(proxyUnreachableResp.status, proxyUnreachableResp.description)
upgradeProxy(
@Path() id: string,
@Body()
body?: {
force?: boolean
ignoreRunningJobs?: boolean
},
@Query() sync?: boolean
): CreateActionReturnType<void> {
const proxyId = id as XoProxy['id']
const force = body?.force ?? false
const opts = {
force,
ignoreRunningJobs: body?.ignoreRunningJobs ?? force,
}
const action = async () => {
await callProxy(this.restApi.xoApp.upgradeProxyAppliance(proxyId, opts))
}
return this.createAction<void>(action, {
sync,
statusCode: noContentResp.status,
taskProperties: {
name: 'upgrade proxy appliance',
objectId: proxyId,
params: body,
},
})
}
}

View File

@@ -5,65 +5,129 @@ import { ApiError } from '../helpers/error.helper.mjs'
import { ProxyController } from './proxy.controller.mjs'
import type { RestApi } from '../rest-api/rest-api.mjs'
function createController(checkProxyHealth: (id: string) => Promise<void>) {
const proxyId = 'e625ea0c-a876-405a-b838-109d762efe88'
const updaterState = { level: 'info', message: 'xoa is up to date', state: 'xoa-up-to-date' }
const unreachableErrors = [
Object.assign(new TypeError('fetch failed'), { code: 'PROXY_UNREACHABLE' }),
Object.assign(new Error('cannot get the proxy address'), { code: 'PROXY_UNREACHABLE' }),
]
function createController(result: () => Promise<unknown>) {
const calls: unknown[] = []
const tasks: unknown[] = []
const record =
(method: string) =>
async (...args: unknown[]) => {
calls.push([method, ...args])
return result()
}
const restApi = {
xoApp: {
checkProxyHealth: async (id: string) => {
calls.push(['checkProxyHealth', id])
return checkProxyHealth(id)
tasks: {
create: (properties: unknown) => {
tasks.push(properties)
return { id: 'task-1', properties, run: (fn: () => unknown) => fn() }
},
},
xoApp: {
checkProxyHealth: record('checkProxyHealth'),
getProxyApplianceUpdaterState: record('getProxyApplianceUpdaterState'),
upgradeProxyAppliance: record('upgradeProxyAppliance'),
},
} as unknown as RestApi
const controller = new ProxyController(restApi)
return { calls, controller }
return { calls, controller, tasks }
}
const proxyId = 'e625ea0c-a876-405a-b838-109d762efe88'
for (const [method, xoAppMethod, xoAppResult, expected] of [
['getProxyHealth', 'checkProxyHealth', undefined, { success: true }],
['getProxyApplianceUpdaterState', 'getProxyApplianceUpdaterState', updaterState, updaterState],
] as const) {
describe(`ProxyController.${method}`, () => {
it(`forwards the id to ${xoAppMethod} and returns the result`, async () => {
const { calls, controller } = createController(async () => xoAppResult)
describe('ProxyController.getProxyHealth', () => {
it('forwards the id and returns success when the proxy is reachable', async () => {
const { calls, controller } = createController(async () => {})
assert.deepEqual(await controller.getProxyHealth(proxyId), { success: true })
assert.deepEqual(calls, [['checkProxyHealth', proxyId]])
})
it('throws a 502 ApiError when the proxy is unreachable', async () => {
const { controller } = createController(async () => {
throw Object.assign(new TypeError('fetch failed'), { code: 'PROXY_UNREACHABLE' })
assert.deepEqual(await controller[method](proxyId), expected)
assert.deepEqual(calls, [[xoAppMethod, proxyId]])
})
await assert.rejects(
controller.getProxyHealth(proxyId),
error => error instanceof ApiError && error.status === 502 && error.message === 'Proxy unreachable'
)
})
for (const unreachableError of unreachableErrors) {
it(`throws a 502 ApiError on "${unreachableError.message}"`, async () => {
const { controller } = createController(async () => {
throw unreachableError
})
it('rethrows unrelated errors unchanged', async () => {
const unrelatedError = new Error('500 Internal Server Error')
const { controller } = createController(async () => {
throw unrelatedError
await assert.rejects(
controller[method](proxyId),
error => error instanceof ApiError && error.status === 502 && error.message === 'Proxy unreachable'
)
})
}
it('rethrows unrelated errors unchanged', async () => {
const unrelatedError = new Error('401 Unauthorized')
const { controller } = createController(async () => {
throw unrelatedError
})
await assert.rejects(controller[method](proxyId), error => error === unrelatedError)
})
await assert.rejects(controller.getProxyHealth(proxyId), error => error === unrelatedError)
})
})
}
describe('ProxyController.deleteProxy', () => {
it('forwards the id to destroyProxy', async () => {
const calls: unknown[] = []
const restApi = {
xoApp: {
destroyProxy: async (id: string) => {
calls.push(['destroyProxy', id])
},
describe('ProxyController.upgradeProxy', () => {
it('upgrades in a task without force by default', async () => {
const { calls, controller, tasks } = createController(async () => undefined)
await controller.upgradeProxy(proxyId, undefined, true)
assert.deepEqual(calls, [['upgradeProxyAppliance', proxyId, { force: false, ignoreRunningJobs: false }]])
assert.deepEqual(tasks, [
{
name: 'REST API: upgrade proxy appliance',
objectId: proxyId,
objectType: 'proxy',
params: undefined,
type: 'xo:rest-api:action',
},
} as unknown as RestApi
const controller = new ProxyController(restApi)
await controller.deleteProxy(proxyId)
assert.deepEqual(calls, [['destroyProxy', proxyId]])
])
assert.equal(controller.getStatus(), 204)
})
it('ignores running jobs by default when forced', async () => {
const { calls, controller } = createController(async () => undefined)
await controller.upgradeProxy(proxyId, { force: true }, true)
assert.deepEqual(calls, [['upgradeProxyAppliance', proxyId, { force: true, ignoreRunningJobs: true }]])
})
it('forwards an explicit ignoreRunningJobs', async () => {
const { calls, controller } = createController(async () => undefined)
await controller.upgradeProxy(proxyId, { force: true, ignoreRunningJobs: false }, true)
assert.deepEqual(calls, [['upgradeProxyAppliance', proxyId, { force: true, ignoreRunningJobs: false }]])
})
it('returns the task id when not synchronous', async () => {
const { controller } = createController(async () => undefined)
assert.deepEqual(await controller.upgradeProxy(proxyId), { taskId: 'task-1' })
assert.equal(controller.getStatus(), 202)
})
for (const unreachableError of unreachableErrors) {
it(`throws a 502 ApiError on "${unreachableError.message}"`, async () => {
const { controller } = createController(async () => {
throw unreachableError
})
await assert.rejects(
controller.upgradeProxy(proxyId, undefined, true),
error => error instanceof ApiError && error.status === 502 && error.message === 'Proxy unreachable'
)
})
}
})

View File

@@ -14,7 +14,6 @@ import {
XoBackupLog,
} from '@vates/types'
import { createLogger } from '@xen-orchestra/log'
import { createPredicate } from 'value-matcher'
import { extractIdsFromSimplePattern } from '@xen-orchestra/backups/extractIdsFromSimplePattern.mjs'
import { noSuchObject } from 'xo-common/api-errors.js'
import { parse } from 'xo-remote-parser'
@@ -361,23 +360,22 @@ export class XoaService {
const nonReplicaVms = Object.values(this.#restApi.getObjectsByType<XoVm>('VM', { filter: vm => !isReplicaVm(vm) }))
const restApi = this.#restApi
const xoApp = restApi.xoApp
function _extractVmIdsFromBackupJob(job: XoVmBackupJob) {
let vmIds: XoVm['id'][]
const backupJobService = this.#backupJobService
async function _extractVmIdsFromBackupJob(job: XoVmBackupJob): Promise<XoVm['id'][]> {
try {
vmIds = extractIdsFromSimplePattern(job.vms)
return extractIdsFromSimplePattern(job.vms)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (_) {
const predicate = createPredicate(job.vms)
vmIds = nonReplicaVms.filter(predicate).map(vm => vm.id)
const isVmInJob = await backupJobService.getBackupJobVmMatcher(job)
return nonReplicaVms.filter(isVmInJob).map(vm => vm.id)
}
return vmIds
}
function _processVmsProtection(job: XoVmBackupJob, isProtected: boolean) {
async function _processVmsProtection(job: XoVmBackupJob, isProtected: boolean) {
if (job.type !== BACKUP_TYPE.backup) {
return
}
_extractVmIdsFromBackupJob(job).forEach(vmId => {
;(await _extractVmIdsFromBackupJob(job)).forEach(vmId => {
_updateVmProtection(vmId, isProtected)
})
}
@@ -434,7 +432,7 @@ export class XoaService {
for (const job of jobs) {
if (!(await this.#backupJobService.backupJobHasAtLeastOneScheduleEnabled(job.id))) {
_processVmsProtection(job, false)
await _processVmsProtection(job, false)
disabledJobs++
continue
}
@@ -486,7 +484,7 @@ export class XoaService {
}
if (last3BackupLogs.length === 0) {
_processVmsProtection(job, false)
await _processVmsProtection(job, false)
continue
}
@@ -500,11 +498,11 @@ export class XoaService {
backupLogStatusesByVm[id].push(isSuccess)
}
last3BackupLogs.forEach(jobLob => {
const { tasks, status } = jobLob
let jobVmIds: XoVm['id'][] | undefined
for (const { tasks, status } of last3BackupLogs) {
if (tasks === undefined) {
const vmIds = _extractVmIdsFromBackupJob(job)
vmIds.forEach(vmId => updateVmBackupLogStatuses(vmId, status === 'success'))
jobVmIds ??= await _extractVmIdsFromBackupJob(job)
jobVmIds.forEach(vmId => updateVmBackupLogStatuses(vmId, status === 'success'))
} else {
tasks.forEach(task => {
if (task.data === undefined) {
@@ -513,7 +511,7 @@ export class XoaService {
updateVmBackupLogStatuses(task.data.id as XoVm['id'], task.status === 'success')
})
}
})
}
for (const [vmId, statuses] of Object.entries(backupLogStatusesByVm)) {
_updateVmProtection(

View File

@@ -9,12 +9,16 @@
> Users must be able to say: "Nice enhancement, I'm eager to test it"
- [REST API] Delete a proxy: `DELETE /rest/v0/proxies/:id` (PR [#10900](https://github.com/vatesfr/xen-orchestra/pull/10900))
- [REST API] Get the state of a proxy appliance updater: `GET /rest/v0/proxies/:id/appliance_updater_state` (PR [#10773](https://github.com/vatesfr/xen-orchestra/pull/10773))
- [REST API] Upgrade a proxy appliance: `POST /rest/v0/proxies/:id/actions/upgrade` (PR [#10872](https://github.com/vatesfr/xen-orchestra/pull/10872))
### Bug fixes
> Users must be able to say: "I had this issue, happy to know it's fixed"
- [Backups/Merge] The background merge no longer crashes with `ENAMETOOLONG` when a VM's backups are locked by another job: it waits 5 minutes before trying again instead of retrying in a loop (PR [#10866](https://github.com/vatesfr/xen-orchestra/pull/10866))
- [V2V] When the import of a disk fails before its transfer starts, the task shows the reason given by the migration engine (e.g. `could not connect: timed out`) instead of `stream has ended without data, was looking for 8 bytes` (PR [#10842](https://github.com/vatesfr/xen-orchestra/pull/10842))
### Packages to release
> When modifying a package, add it here with its release type.
@@ -31,7 +35,10 @@
<!--packages-start-->
- @vates/nbd-client patch
- @vates/types minor
- @xen-orchestra/acl minor
- @xen-orchestra/backups patch
- @xen-orchestra/rest-api minor
<!--packages-end-->

View File

@@ -569,7 +569,7 @@ XCP-ng is a type 1 hypervisor, similar to VMware ESXi.
You can migrate your VM from VMware vSphere to a Vates environment (Xen Orchestra and XCP-ng), directly from Xen Orchestra. For this, we use V2V ("VMware to Vates").
To know more on using V2V in Xen Orchestra to migrate your environment from VMware, refer to the [XO V2V section in the XCP-ng documentation](https://docs.xcp-ng.org/installation/migrate-to-xcp-ng/#xo-v2v).
Since XO 6.11, the migration is driven from XO 6, in **Administration → V2V → Migrate VMs**. To know more on using V2V in Xen Orchestra to migrate your environment from VMware, refer to the [VMware migration (V2V) guide](../migrate-from-vmware/v2v-migration-guide.md).
## Hosts management

View File

@@ -3,13 +3,13 @@ sidebar_label: VMware migration (V2V)
sidebar_position: 1
---
# VMware migration (V2V)
# VMware migration (V2V) — NEW
## Introduction {#-introduction}
Xen Orchestra 5.110 introduced a new migration backend for moving virtual machines from VMware to XCP-ng (V2V). It replaces the old NFS-based method with `vectura`, a standalone reader of VMware's NFC protocol, delivering better performance and reliability without any VMware-provided library.
The whole process is driven from Xen Orchestra, in **Import → VM → From VMware**. XO connects to your vCenter or ESXi host, reads the VM disks directly, and imports them into an XCP-ng storage repository:
The whole process is driven from Xen Orchestra, in **Administration → V2V → Migrate VMs**. XO connects to your vCenter or ESXi host, reads the VM disks directly, and imports them into an XCP-ng storage repository:
<Schema label="XO reads the VM disks from ESXi through vectura, and imports them into an XCP-ng pool. The source VM keeps running during most of the transfer" legend={[["#5ac8c8", "VMware"], ["#8e83fe", "XCP-ng"], ["#6aabf0", "XO"]]} maxWidth="640px">
<svg viewBox="0 0 640 240" role="img" aria-label="A VM running on an ESXi host inside a VMware infrastructure is exported by Xen Orchestra using vectura, then imported into an XCP-ng host in the destination pool, where the migrated VM is ready to boot; the source VM keeps running during the warm phase of the transfer">
@@ -46,6 +46,7 @@ This guide walks you through the entire migration process:
- Preparing your Xen Orchestra environment
- Preparing your VMware environment
- Running the migration wizard
- Running a test migration
- Executing the final cutover
- Preparing the guest to boot on XCP-ng with the [Autopilot docking](#-autopilot-docking)
@@ -53,7 +54,7 @@ This guide walks you through the entire migration process:
You will also find troubleshooting advice and best practices to maximize speed and minimize downtime.
:::note
The V2V import is currently available in the XO 5 interface. The new XO 6 web UI does not expose it yet: even if you use XO 6 daily, switch to the XO 5 interface for the migration itself.
Since XO 6.11, the V2V import is available in the XO 6 interface, in **Administration → V2V → Migrate VMs**. This guide describes the XO 6 interface. The XO 5 import form remains available: see [Using XO 5 (legacy)](#-using-xo-5).
:::
## Benefits {#-benefits}
@@ -80,6 +81,8 @@ Additionally, UEFI VMs are no longer forced into Secure Boot mode, which resolve
Recent releases keep improving the workflow: since XO 6.6, a CD-ROM drive present on the source is recreated on the destination VM, and a two-step transfer (a first warm pass followed by a final run) tells you upfront whether the next run will be a full or a delta transfer.
Since XO 6.11, the XO 6 interface brings a migration wizard: you can migrate several VMs at once, choose a storage repository for each disk and a network for each network adapter, and resume a partial import from its last sync. Migration lists are saved in your browser, one per source and destination pool.
#### Performance gains
Performance gains can be significant, though results depend on the environment:
@@ -94,7 +97,9 @@ Performance gains can be significant, though results depend on the environment:
Make sure your Xen Orchestra instance is up to date. The import page includes an automatic check that verifies that `vectura`, shipped with your Xen Orchestra, runs on this system. Errors must be resolved before the migration can start.
<UiDetail src="/img/xo5/v2v-prerequisite-check.png" alt="The prerequisite check on the import page, showing the status of vectura" width={232} />
<UiDetail src="/img/xo6/v2v-prerequisite-check.png" alt="The prerequisite check on the Source step of the migration wizard, showing the status of vectura" width={340} />
<UiDetail src="/img/xo5/v2v-prerequisite-check.png" alt="The prerequisite check on the XO 5 import page, showing the status of vectura" width={232} />
### Dependencies
@@ -103,15 +108,7 @@ is shipped with Xen Orchestra and runs from there: there is nothing to install,
from VMware or Broadcom, and nothing to compile. It needs a Linux x86-64 system with glibc 2.31 or
later, such as Debian 11 or Ubuntu 20.04.
Go to the **Import → VM → From VMware** section. Once the check passes, a **transfer form** appears:
<UiDetail src="/img/xo5/v2v-transfer-form.png" alt="The transfer form used to connect to VMware and import a VM into Xen Orchestra" width={620} />
:::warning
Filling in this form and clicking the **Connect** button will start the VM import. Make sure your VMware environment is ready first!
Read [Preparing the VMware environment](#-preparing-the-vmware-environment) to know more.
:::
Go to **Administration → V2V → Migrate VMs**. The prerequisite check is shown at the top of the **Connect a new VMware source** card. Until it passes, VMs cannot be migrated.
## Preparing the VMware environment {#-preparing-the-vmware-environment}
@@ -148,7 +145,7 @@ A snapshot taken before CBT was enabled cannot be used to compute a delta. Remov
Keep the VMware Tools (or open-vm-tools) installed and running on the source VMs. XO uses them to:
- shut the guest down cleanly when the `Stop source` option is enabled, instead of powering it off;
- shut the guest down cleanly when the **Stop the source VM** option is enabled, instead of powering it off;
- read the IP addresses of each network card, which the [Autopilot docking](#-autopilot-docking) needs for Windows VMs with several network cards in static addressing.
With the Autopilot docking, there is no need to remove the VMware Tools before the migration: the docking disables them on the migrated VM.
@@ -188,7 +185,7 @@ Here is the "surefire method" to prepare your VMware environment.
It involves a lot of manual steps, but it lets you detect and fix issues without impacting production.
:::tip
There is also a "fire-and-forget" approach: launch the migration with the `Stop source` option enabled, then start the VM once the migration is complete.
There is also a "fire-and-forget" approach: launch the migration with the **Stop the source VM** option enabled, then start the VM once the migration is complete.
This method is only recommended for non-critical VMs, and only after the first few migrations have gone smoothly.
:::
@@ -215,6 +212,115 @@ Without the Autopilot docking, take another snapshot named `vm without tools`.
This snapshot captures the state of the VM without VMware-specific components, and will be used for the initial migration.
## Running the migration wizard {#-running-the-migration-wizard}
The wizard has five steps: **Source**, **Destination**, **VMs**, **Mapping** and **Review**. Only administrators can migrate VMs.
### Source
Fill in the **Connect a new VMware source** form with the address of your vCenter or ESXi host (**Host** and **Port**, 443 by default), your VMware **Username** and **Password**, then click **Connect**.
<UiShot light="/img/xo6/v2v-source-light.png" dark="/img/xo6/v2v-source-dark.png" alt="The Source step of the migration wizard, with the remembered connections and the connection form" url="https://your-xo/v6/#/admin/v2v/migrate" />
- **Skip SSL check (self-signed certificate)** is enabled by default: the server certificate is not verified.
- **Remember connection in this browser** keeps the connection, password included, in this browser only. Xen Orchestra never stores your VMware credentials. Make sure this complies with your security guidelines.
Remembered connections are listed in the **Remembered connections** card, with the number of VMs and their migration status. Click **Connect** to reuse one. The connection remembered by the XO 5 import form is added to this list.
### Destination
Choose the **Destination pool**, then the global defaults applied to every VM:
- **Default storage repository**: prefilled with the pool default SR.
- **Default network**: prefilled with the management network of the pool master.
- **Default template**.
<UiShot light="/img/xo6/v2v-destination-light.png" dark="/img/xo6/v2v-destination-dark.png" alt="The Destination step of the migration wizard, with the destination pool and the global defaults" url="https://your-xo/v6/#/admin/v2v/migrate?step=destination" />
Each VM can override these defaults in the **Mapping** step.
Each source and destination pool pair has its own migration list, saved in your browser. If a list already exists for this pair, click **Continue with existing list** to reopen it, with the current migration state of every VM.
### VMs
The table lists the VMs of the source, with their power state, datastores, size, migration status and last sync. Filter them with the presets (**All**, **Not migrated**, **Not ready**, **In progress**, **Warm synced**, **Cutover done**), with the query builder, or by clicking a datastore.
<UiShot light="/img/xo6/v2v-vms-light.png" dark="/img/xo6/v2v-vms-dark.png" alt="The VMs step of the migration wizard, with the VMs of the source and the Selected VMs side panel" url="https://your-xo/v6/#/admin/v2v/migrate?step=vms" />
Select the VMs to migrate, then click **Add to migration list**. VMs with an [unsupported disk](#-unsupported) cannot be selected.
The **Selected VMs** side panel shows the migration list. Removing a VM from the list does not delete anything, neither on the source nor in XO.
### Mapping
The table shows every VM of the migration list, with its type:
- **New**: the VM is imported for the first time.
- **Resume**: a partial import of the VM exists on the destination pool. The import resumes from the last sync, with the mapping of the first run.
<UiShot light="/img/xo6/v2v-mapping-light.png" dark="/img/xo6/v2v-mapping-dark.png" alt="The Mapping step of the migration wizard, with the details of a VM in the side panel" url="https://your-xo/v6/#/admin/v2v/migrate?step=mapping" />
Click a VM to open its details in the side panel, then click **Edit settings** to choose:
- a **Target SR** for each disk,
- a **Target network** for each network adapter,
- the **Template**.
Each value shows whether it comes from the **Global default** or is **Overridden**. Click **Reset to default** to go back to the global default.
The mapping of a resumed VM is locked. To start over with a new mapping, click **Delete** in its side panel: the partial import is deleted, and the VM is imported as a new VM.
The **Checks** column tells whether each VM is ready. A VM with one of these checks is not migrated:
- **Not found in the source**
- An [unsupported disk](#-unsupported)
- **Import in progress**
- **Partial import on pool \{pool\}**: the partial import of the VM exists on another pool.
- **Mapping incomplete**: a chosen SR, network or template is no longer available on the pool.
A VM with the **Already migrated, confirmation at launch** check is only migrated again after your confirmation, in the **Review** step.
### Review
Set the **Default options** of the launch:
- **Stop the source VM**: enabled by default. The source VM is stopped before the last delta transfer. This is needed to fully transfer a running VM.
- **Stop on error**: enabled by default. The migration stops on the first error when importing VMs.
- **Concurrent VMs**: the number of VMs imported at the same time, 2 by default (from 1 to 8).
<UiShot light="/img/xo6/v2v-review-light.png" dark="/img/xo6/v2v-review-dark.png" alt="The Review step of the migration wizard, with the default options and the per-VM options" url="https://your-xo/v6/#/admin/v2v/migrate?step=review" />
In the **Per-VM options** table, you can override the **Stop source** option for each VM.
Before the launch, VMs are grouped as follows:
- **Excluded**: VMs with a blocking check. They are not migrated.
- **Already fully migrated**: tick **Create a second copy of \{name\}** to migrate the VM again. A second VM is created on the destination pool.
- **Resumed**: VMs resumed from their last sync.
- **New**: VMs imported for the first time.
Click **Launch \{n\} VMs** to start the migration. The migration runs in a task: click **See the task** to follow its progress.
### Limitations {#-limitations}
- The **Tags** and **Keep MAC addresses** options of the **Mapping** step are not applied yet.
- The **Start the VM on XCP-ng** and **Automatically clean up the VM** options are not supported yet.
- Do not launch the migration of the same VM twice at the same time: both imports would use the same partial import.
### Using XO 5 (legacy) {#-using-xo-5}
Go to the **Import → VM → From VMware** section. Once the check passes, a **transfer form** appears:
<UiDetail src="/img/xo5/v2v-transfer-form.png" alt="The transfer form used to connect to VMware and import a VM into Xen Orchestra" width={620} />
:::warning
Filling in this form and clicking the **Connect** button will start the VM import. Make sure your VMware environment is ready first!
Read [Preparing the VMware environment](#-preparing-the-vmware-environment) to know more.
:::
In XO 5, the `Stop source` option matches the **Stop the source VM** option of the XO 6 wizard.
## Initial test migration {#-initial-test-migration}
Before making the final switch, **run a test migration first**. This lets you catch any issues before moving to production.
@@ -224,23 +330,23 @@ Before making the final switch, **run a test migration first**. This lets you ca
Understanding the warm migration mechanism helps you follow the progress:
1. If the source VM is running and has no snapshot, XO automatically takes one, named `[V2V] migration to XCP-ng`.
2. XO creates the destination VM (its name ends with `importing...` while the transfer runs) and imports the read-only snapshot chain while the source VM keeps running in production.
2. XO creates the destination VM (its name starts with `[Importing...]` while the transfer runs) and imports the read-only snapshot chain while the source VM keeps running in production.
3. A snapshot of the destination VM is taken after this first pass, so the process can be resumed safely without creating duplicate VMs.
4. If the `Stop source` option is enabled, XO then shuts the source VM down through its VMware Tools, transfers only the final delta (the blocks written since the snapshot), and takes a final `complete import from V2V` snapshot. When the VMware Tools do not run, or the guest does not shut down within 10 minutes, the VM is powered off instead, and the task reports it.
4. If the **Stop the source VM** option is enabled, XO then shuts the source VM down through its VMware Tools, transfers only the final delta (the blocks written since the snapshot), and takes a final `complete import from V2V` snapshot. When the VMware Tools do not run, or the guest does not shut down within 10 minutes, the VM is powered off instead, and the task reports it.
5. If the [Autopilot docking](#-autopilot-docking) is enabled and the import is complete, XO boots the destination VM on the docking ISO, which prepares the guest to run on XCP-ng.
As long as the import is partial (the source VM is still live), XO blocks the destination VM from starting normally, to prevent both copies from running at once.
### Perform the first migration attempt
1. **Start the V2V migration** in Xen Orchestra, without enabling the `Stop source` option.\
1. **Start the V2V migration** in Xen Orchestra, with the **Stop the source VM** option disabled (it is enabled by default).\
This will transfer the VM data up to the snapshot named `vm without tools`.
:::tip
You can safely close your browser while the migration runs.
:::
2. **Monitor the migration progress** using one of these methods:
- Check the VM status in Xen Orchestra (its name should show `importing...`).
- Follow the disk transfer progress indicators.
- Check the VM status in Xen Orchestra (its name should show `[Importing...]`).
- Follow the migration task: click **See the task** once the migration is launched.
### Testing the migrated VM
@@ -271,7 +377,7 @@ Once you have finished your checks and taken notes, delete the test VM. This wil
When you're ready for the final migration:
- Shut down the source VM completely.
- Start the V2V migration in Xen Orchestra with the `Stop source` option enabled.\
- Start the V2V migration in Xen Orchestra with the **Stop the source VM** option enabled.\
This ensures the final sync happens while the VM is powered off, and prevents any inconsistencies.
### Post-migration tasks
@@ -385,6 +491,9 @@ If you encounter problems during migration, try these steps to diagnose and reso
- **Test network connectivity**\
Ensure stable network connectivity between the VMware environment, Xen Orchestra, and XCP-ng hosts.
- **Check the launch errors**\
When the migration cannot be started, the **Review** step lists the problem of each VM. VMs with a blocking check are listed in the **Excluded** group, with the reason.
- **Retry with cold migration**\
If warm migration fails, power off the VM, remove all snapshots, and try again.

View File

@@ -190,7 +190,7 @@ This action makes the XO server send a GET request to the given URL, so the hold
| | `reclaim-space`, |
| `schedule` | `read`, `run` |
| `restore-log` | `read` |
| `proxy` | `read`, `delete` |
| `proxy` | `read`, `upgrade` |
| `server` | `read`, `create`, `delete`, `connect`, `disconnect` |
| `task` | `read`, `abort`, `delete` |
| `alarm` | `read` |

View File

@@ -38,6 +38,7 @@ XO 6 is under active development, so this table evolves with every release. As a
| Storage | Inspect SRs and VDIs; connect, disconnect and delete SRs; create, attach, export, delete VDIs and migrate them between SRs | SR creation, advanced disk operations |
| Performance stats | Usage charts on every dashboard (last week) | Full stats views with granularity control, via the marked Stats link |
| Backups | Job list with run history, per-job pages (runs, configuration, backed up VMs, targets), per-VM protection status, dashboard health panels | Job creation and editing, restore, remotes, mirrors, sequences, health checks |
| VMware migration (V2V) | Migration wizard: several VMs at once, a storage repository per disk and a network per network adapter, resume from the last sync | VMware import form |
| Tasks | Full task history at every level, last-24-hours quick view | Task list |
| Users and access | Users list with details, groups and authentication tokens | User creation and editing, groups, roles, LDAP and other auth providers, ACLs |
| Settings | Color mode, five themes, 21 languages | Servers, plugins, proxies, licenses, everything under Settings |

Binary file not shown.

After

Width:  |  Height:  |  Size: 134 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 132 KiB

BIN
docs/static/img/xo6/v2v-mapping-dark.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 181 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 178 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 8.4 KiB

BIN
docs/static/img/xo6/v2v-review-dark.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 149 KiB

BIN
docs/static/img/xo6/v2v-review-light.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 147 KiB

BIN
docs/static/img/xo6/v2v-source-dark.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 136 KiB

BIN
docs/static/img/xo6/v2v-source-light.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 134 KiB

BIN
docs/static/img/xo6/v2v-vms-dark.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 194 KiB

BIN
docs/static/img/xo6/v2v-vms-light.png vendored Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 192 KiB

View File

@@ -1,5 +1,9 @@
import { isSrWritable } from '../../utils.mjs'
import { buildSrContext, buildBackupRepositoryContext } from '@xen-orchestra/backups/_buildContext.mjs'
import {
buildSrContext,
buildBackupRepositoryContext,
buildPoolContext,
} from '@xen-orchestra/backups/_buildContext.mjs'
import { compileExpression } from '@xen-orchestra/backups/_expressionPredicate.mjs'
export function resolveBackupSrs(job, srs, runContext) {
@@ -40,3 +44,16 @@ export function resolveBackupRepositories(job, backupRepositories, runContext) {
return { backupRepositoryIds, proxySkippedIds, invalidUrlIds }
}
export function resolveBackupPools(job, pools, runContext) {
const predicate = compileExpression(job.pools)
const poolUuids = []
pools.forEach(pool => {
if (predicate(buildPoolContext(pool, runContext))) {
poolUuids.push(pool.uuid)
}
})
return poolUuids
}

View File

@@ -2,7 +2,7 @@ import assert from 'node:assert/strict'
import { describe, it } from 'node:test'
import { buildRunContext } from '@xen-orchestra/backups/_buildContext.mjs'
import { resolveBackupRepositories, resolveBackupSrs } from './_resolveBackupTargets.mjs'
import { resolveBackupRepositories, resolveBackupSrs, resolveBackupPools } from './_resolveBackupTargets.mjs'
// a Monday, at 22:00 UTC
const RUN_CONTEXT = buildRunContext(new Date('2026-11-02T22:00:00Z'), 'UTC')
@@ -25,6 +25,13 @@ const backupRepository = ({ id, name = id, url = 'nfs://nas:/backups', enabled =
proxy,
})
const pool = ({ uuid, name_label = uuid, tags = [] }) => ({
uuid,
name_label,
name_description: '',
tags,
})
describe('resolveBackupSrs()', () => {
it('returns the SRs matching the expression', () => {
const srs = [sr({ uuid: 'nfs-sr' }), sr({ uuid: 'local-sr', SR_type: 'ext' })]
@@ -148,3 +155,24 @@ describe('resolveBackupRepositories()', () => {
)
})
})
describe('resolveBackupPools()', () => {
it('returns the pools matching the expression', () => {
const pools = [pool({ uuid: 'pool1' }), pool({ uuid: 'pool2' })]
assert.deepEqual(resolveBackupPools({ pools: 'pool:name_label:pool1' }, pools, RUN_CONTEXT), ['pool1'])
})
it('evaluates the run context', () => {
const pools = [pool({ uuid: 'pool1' })]
assert.deepEqual(resolveBackupPools({ pools: 'run:hour:22' }, pools, RUN_CONTEXT), ['pool1'])
assert.deepEqual(resolveBackupPools({ pools: 'run:hour:23' }, pools, RUN_CONTEXT), [])
})
it('returns an empty array when nothing matches', () => {
const pools = [pool({ uuid: 'pool1' })]
assert.deepEqual(resolveBackupPools({ pools: 'pool:name_label:missing' }, pools, RUN_CONTEXT), [])
})
})

View File

@@ -22,8 +22,8 @@ import { serializeError, unboxIdsFromPattern } from '../../utils.mjs'
import { journalPurgeHorizon, serveVmBackups, VmBackupsCache } from './_vmBackupsCache.mjs'
import { VmBackupsSource } from './_vmBackupsSource.mjs'
import { waitAll } from '../../_waitAll.mjs'
import { isExpression } from '@xen-orchestra/backups/_expressionPredicate.mjs'
import { buildRunContext } from '@xen-orchestra/backups/_buildContext.mjs'
import { compileExpression, isExpression } from '@xen-orchestra/backups/_expressionPredicate.mjs'
import { buildRunContext, buildVmContext } from '@xen-orchestra/backups/_buildContext.mjs'
import { resolveBackupSrs, resolveBackupRepositories } from './_resolveBackupTargets.mjs'
const logger = createLogger('xo:xo-mixins:backups-ng')
@@ -214,9 +214,41 @@ export default class BackupNg {
job = { ...job, runContext }
const remotesExpression = isExpression(job.remotes) ? job.remotes : undefined
if (remotesExpression !== undefined) {
const {
backupRepositoryIds: remoteIds,
proxySkippedIds,
invalidUrlIds,
} = resolveBackupRepositories(job, await app.getAllRemotes(), runContext)
if (proxySkippedIds.length > 0) {
jobsLogger.warning(
'some backup repositories matched the expression but are not linked to the proxy of this job, they are skipped',
{
event: 'task.warning',
taskId: runJobId,
data: { backupRepositories: proxySkippedIds, proxy: job.proxy },
}
)
}
if (invalidUrlIds.length > 0) {
jobsLogger.warning(
'some backup repositories matched the expression but have an invalid URL, they are skipped',
{
event: 'task.warning',
taskId: runJobId,
data: { backupRepositories: invalidUrlIds },
}
)
}
job.remotes = { id: { __or: remoteIds } }
}
if (job.type === 'backup') {
const srsExpression = isExpression(job.srs) ? job.srs : undefined
const remotesExpression = isExpression(job.remotes) ? job.remotes : undefined
if (isExpression(job.srs)) {
const srUuids = resolveBackupSrs(job, Object.values(app.getObjectsByType('SR')), runContext)
@@ -224,38 +256,6 @@ export default class BackupNg {
job.srs = { id: { __or: srUuids } }
}
if (isExpression(job.remotes)) {
const {
backupRepositoryIds: remoteIds,
proxySkippedIds,
invalidUrlIds,
} = resolveBackupRepositories(job, await app.getAllRemotes(), runContext)
if (proxySkippedIds.length > 0) {
jobsLogger.warning(
'some backup repositories matched the expression but are not linked to the proxy of this job, they are skipped',
{
event: 'task.warning',
taskId: runJobId,
data: { backupRepositories: proxySkippedIds, proxy: job.proxy },
}
)
}
if (invalidUrlIds.length > 0) {
jobsLogger.warning(
'some backup repositories matched the expression but have an invalid URL, they are skipped',
{
event: 'task.warning',
taskId: runJobId,
data: { backupRepositories: invalidUrlIds },
}
)
}
job.remotes = { id: { __or: remoteIds } }
}
if (
(srsExpression !== undefined || remotesExpression !== undefined) &&
unboxIdsFromPattern(job.srs).length === 0 &&
@@ -313,10 +313,16 @@ export default class BackupNg {
vmIds = Object.keys(
app.getObjects({
filter: (() => {
const isMatchingVm = createPredicate({
type: 'VM',
...vmsPattern,
})
let isMatchingVm
if (isExpression(vmsPattern)) {
const predicate = compileExpression(vmsPattern)
isMatchingVm = obj => obj.type === 'VM' && predicate(buildVmContext(obj, runContext))
} else {
isMatchingVm = createPredicate({
type: 'VM',
...vmsPattern,
})
}
return obj =>
isMatchingVm(obj) &&

View File

@@ -5,6 +5,9 @@ import { createLogger } from '@xen-orchestra/log'
import { createRunner } from '@xen-orchestra/backups/Backup.mjs'
import { parseMetadataBackupId } from '@xen-orchestra/backups/parseMetadataBackupId.mjs'
import { RestoreMetadataBackup } from '@xen-orchestra/backups/RestoreMetadataBackup.mjs'
import { isExpression } from '@xen-orchestra/backups/_expressionPredicate.mjs'
import { resolveBackupPools, resolveBackupRepositories } from './backups-ng/_resolveBackupTargets.mjs'
import { buildRunContext } from '@xen-orchestra/backups/_buildContext.mjs'
import { Task } from '@vates/task'
import { debounceWithKey, REMOVE_CACHE_ENTRY } from '../_pDebounceWithKey.mjs'
@@ -48,12 +51,62 @@ export default class metadataBackup {
}
const app = this._app
const runContext = buildRunContext(
new Date(),
job.settings[schedule.id]?.timezone ?? job.settings['']?.timezone ?? schedule.timezone
)
if (job.xoMetadata) {
const config = await app.exportConfig()
job.xoMetadata = typeof config === 'string' ? config : { encoding: 'base64', data: config.toString('base64') }
}
if (isExpression(job.remotes)) {
const {
backupRepositoryIds: remoteIds,
proxySkippedIds,
invalidUrlIds,
} = resolveBackupRepositories(job, await app.getAllRemotes(), runContext)
if (proxySkippedIds.length > 0) {
jobsLogger.warning(
'some backup repositories matched the expression but are not linked to the proxy of this job, they are skipped',
{
event: 'task.warning',
taskId: runJobId,
data: { backupRepositories: proxySkippedIds, proxy: job.proxy },
}
)
}
if (invalidUrlIds.length > 0) {
jobsLogger.warning(
'some backup repositories matched the expression but have an invalid URL, they are skipped',
{
event: 'task.warning',
taskId: runJobId,
data: { backupRepositories: invalidUrlIds },
}
)
}
job.remotes = { id: { __or: remoteIds } }
}
if (isExpression(job.pools)) {
const poolIds = resolveBackupPools(job, Object.values(app.getObjectsByType('pool')), runContext)
if (poolIds.length === 0) {
jobsLogger.warning('no matching pool found', {
event: 'task.warning',
taskId: runJobId,
data: { pools: job.pools },
})
}
job.pools = { id: { __or: poolIds } }
}
const remoteIds = unboxIdsFromPattern(job.remotes)
const proxyId = job.proxy
try {

View File

@@ -289,6 +289,10 @@ export default class Proxy {
// ensure the updater is using the expected channel otherwise the state will not be correct
await this.callProxyMethod(id, 'appliance.updater.configure', { channel: await this._getChannel() })
} catch (error) {
// getState would fail the same way, after waiting for another timeout
if (error.code === PROXY_UNREACHABLE) {
throw error
}
log.warn('failed to set proxy updater channel', { error })
}