Compare commits

..

2 Commits

Author SHA1 Message Date
MelissaFrncJrg
007b601876 changelog 2026-11-24 10:55:27 +01:00
MelissaFrncJrg
6be40ce218 feat(rest-api): expose proxy update endpoint 2026-11-24 10:54:32 +01:00
575 changed files with 5059 additions and 23842 deletions

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

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

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

View File

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

@@ -472,7 +472,10 @@ 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 }>
updateProxy(
id: XoProxy['id'],
updates: { address?: string | null; authenticationToken?: string; name?: string; vmUuid?: XoVm['id'] | null }
): Promise<XoProxy>
getRemote(id: XoBackupRepository['id']): Promise<XoBackupRepository>
getAllRemotes(): Promise<XoBackupRepository[]>
removeRemote(id: XoBackupRepository['id']): Promise<void>
@@ -504,10 +507,7 @@ 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>

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> | string
vms: CMType.IdOr<XoVm['id']> | Record<string, unknown>
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']> | string
pools?: CMType.IdOr<XoPool['id']>
remotes: CMType.IdOr<XoBackupRepository['id']>
settings: {
''?: XoMetadataBackupJobGeneralSettings
@@ -696,7 +696,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

@@ -1,3 +1,6 @@
export default {
read: true,
update: {
name: true,
},
}

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

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

@@ -3,7 +3,6 @@ import ignoreErrors from 'promise-toolbox/ignoreErrors'
import { asyncMap } from '@xen-orchestra/async-map'
import { compareVersions } from 'compare-versions'
import { defer } from 'golike-defer'
import { limitConcurrency } from 'limit-concurrency-decorator'
import { Task } from '@vates/task'
import { abortableMap } from './_abortableMap.mjs'
@@ -30,7 +29,6 @@ export async function updateMemoryFields(xapi, targetVm, vmRecord) {
export async function exportIncrementalVm(vm, baseVdis = {}, { signal, nbdConcurrency = 1, preferNbd } = {}) {
// refs of VM's VDIs → base's VDIs.
// the disks are not opened here but just before their transfer
const disks = {}
const vdis = {}
const vbds = {}
@@ -71,6 +69,7 @@ export async function exportIncrementalVm(vm, baseVdis = {}, { signal, nbdConcur
nbdConcurrency,
preferNbd,
})
await disks[vdiRef].init()
})
const suspendVdi = vm.$suspend_VDI
@@ -86,6 +85,7 @@ export async function exportIncrementalVm(vm, baseVdis = {}, { signal, nbdConcur
nbdConcurrency,
preferNbd,
})
await disks[vdiRef].init()
}
const vifs = {}
@@ -130,16 +130,7 @@ export const importIncrementalVm = defer(async function importIncrementalVm(
$defer,
incrementalVm,
sr,
{
signal,
// 0 means no limit
diskConcurrency = 0,
// the disks of an export from XAPI are opened just before their transfer
initDisks = false,
newMacAddresses = false,
targetRef = undefined,
vmNamePrefix = '[Importing…] ',
} = {}
{ signal, newMacAddresses = false, targetRef = undefined, vmNamePrefix = '[Importing…] ' } = {}
) {
const { version } = incrementalVm
if (compareVersions(version, '1.0.0') < 0) {
@@ -338,45 +329,30 @@ export const importIncrementalVm = defer(async function importIncrementalVm(
})
const { disks } = incrementalVm
const importDiskContent = limitConcurrency(diskConcurrency)(async (signal, id) => {
// another disk may have failed while this one was waiting for its turn
if (signal.aborted) {
// release the forks
await Promise.all(ensureArray(disks[id]).map(disk => disk?.close()))
signal.throwIfAborted()
}
const vdi = newVdis[id]
for (const disk of ensureArray(disks[id])) {
if (disk === null) {
// we restore a backup and reuse completely a local snapshot
continue
}
await xapi.setField('VDI', vdi.$ref, 'name_label', `[Importing] ${vdiRecords[id].name_label}`)
if (initDisks) {
await disk.init()
}
let stream, format
if (vdi.virtual_size > VHD_MAX_SIZE) {
stream = await toQcow2Stream(disk)
format = 'qcow2'
} else {
stream = await toVhdStream(disk)
format = 'vhd'
}
await vdi.$importContent(stream, { signal, format })
await xapi.setField('VDI', vdi.$ref, 'name_label', vdiRecords[id].name_label)
}
})
await Promise.all([
// Import VDI contents.
//
// in the same order as the other writers sharing the same disks: they all wait for each other at each block
abortableMap(signal, Object.keys(vdiRecords), importDiskContent),
abortableMap(signal, Object.entries(newVdis), async (signal, [id, vdi]) => {
for (const disk of ensureArray(disks[id])) {
if (disk === null) {
// we restore a backup and reuse completely a local snapshot
continue
}
await xapi.setField('VDI', vdi.$ref, 'name_label', `[Importing] ${vdiRecords[id].name_label}`)
let stream, format
if (vdi.virtual_size > VHD_MAX_SIZE) {
stream = await toQcow2Stream(disk)
format = 'qcow2'
} else {
stream = await toVhdStream(disk)
format = 'vhd'
}
await vdi.$importContent(stream, { signal, format })
await xapi.setField('VDI', vdi.$ref, 'name_label', vdiRecords[id].name_label)
}
}),
// Create VIFs.
asyncMap(Object.values(incrementalVm.vifs), vif => {

View File

@@ -121,6 +121,7 @@ class IncrementalRemoteVmBackupRunner extends AbstractRemote {
writer.transfer({
deltaExport: forkDeltaExport(incrementalExport, writer.constructor.name),
includeNonNbdQcow2Fix: metadata.includeNonNbdQcow2Fix,
isVhdDifferencing,
timestamp: metadata.timestamp,
vm: metadata.vm,
vmSnapshot: metadata.vmSnapshot,

View File

@@ -57,48 +57,40 @@ export const IncrementalXapi = class IncrementalXapiVmBackupRunner extends Abstr
preferNbd: this._settings.preferNbd,
})
// the disks are opened by the writers, just before their transfer
const sourceDisks = { ...deltaExport.disks }
const isVhdDifferencing = {}
let useNbd = false
for (const key in deltaExport.disks) {
let disk = deltaExport.disks[key]
disk.addProgressHandler(new TaskProgressHandler())
isVhdDifferencing[key] = disk.isDifferencing()
if (!isFull && !isVhdDifferencing[key] && key !== exportedVm.$suspend_VDI?.$ref) {
Task.warning('Backup fell back to a full')
}
useNbd = useNbd || disk.useNbd()
disk = new ThrottledDisk(disk, this._throttleGenerator)
deltaExport.disks[key] = new SynchronizedDisk(disk)
}
if (useNbd) {
Task.info('Transfer data using NBD')
}
// @todo : reimplement throttle
try {
await this._callWriters(
writer =>
writer.transfer({
deltaExport: forkDeltaExport(deltaExport, writer.constructor.name),
// freshly exported from XAPI by code that has the fix and the force-full gate
// (writer.checkBaseVdis ran before this transfer), so the chain is verified/forced
// clean; the tip's flag lets the next run skip re-probing
includeNonNbdQcow2Fix: true,
timestamp: this.timestamp,
vm,
vmSnapshot: exportedVm,
}),
'writer.transfer()'
)
} finally {
let useNbd = false
for (const [key, disk] of Object.entries(sourceDisks)) {
if (!disk.isInitialized()) {
// not reached before the transfer failed
continue
}
if (!isFull && !disk.isDifferencing() && key !== exportedVm.$suspend_VDI?.$ref) {
Task.warning('Backup fell back to a full')
}
useNbd = useNbd || disk.useNbd()
}
if (useNbd) {
Task.info('Transfer data using NBD')
}
}
await this._callWriters(
writer =>
writer.transfer({
deltaExport: forkDeltaExport(deltaExport, writer.constructor.name),
// freshly exported from XAPI by code that has the fix and the force-full gate
// (writer.checkBaseVdis ran before this transfer), so the chain is verified/forced
// clean; the tip's flag lets the next run skip re-probing
includeNonNbdQcow2Fix: true,
isVhdDifferencing,
timestamp: this.timestamp,
vm,
vmSnapshot: exportedVm,
}),
'writer.transfer()'
)
if (isFull) {
await setVmDeltaChainLength(this._xapi, exportedVm.$ref, 0)

View File

@@ -215,7 +215,7 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
}
}
async _transfer($defer, { includeNonNbdQcow2Fix, timestamp, deltaExport, vm, vmSnapshot }) {
async _transfer($defer, { includeNonNbdQcow2Fix, isVhdDifferencing, timestamp, deltaExport, vm, vmSnapshot }) {
const adapter = this._adapter
const job = this._job
const scheduleId = this._schedule.id
@@ -243,8 +243,6 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
return { size: 0 }
}
// filled as the disks are opened, before the metadata are written
const isVhdDifferencing = {}
metadataContent = {
// marks whether the disk data is known-good w.r.t. the non-NBD qcow2 corruption bug.
// A fresh XAPI export by fixed code passes `true`; the mirror runner propagates the
@@ -273,10 +271,6 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
const path = `${this._vmBackupDir}/${vhds[diskRef]}`
const vdi = deltaExport.vdis[diskRef]
// opened just before its transfer to limit the number of exports running at the same time on the host
await disk.init()
isVhdDifferencing[diskRef] = disk.isDifferencing()
let parentUuid, parentPath
if (isVhdDifferencing[diskRef]) {
const parentDestPath = this.#parentVdiPaths[dirname(path)]

View File

@@ -504,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, {
diskConcurrency: this._settings.diskPerVmConcurrency,
initDisks: true,
targetRef: this._targetVmRef,
})
// this also ensure the data are up to date on the snapshot

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

@@ -3,7 +3,6 @@ import { Synchronized } from '@vates/generator-toolbox'
import { Disk, DiskBlock } from './Disk.mjs'
class ForkedDisk extends DiskPassthrough {
#closed = false
#generator: AsyncGenerator<DiskBlock, any, any>
#generatedDiskBlocks = 0
constructor(source: Disk, generator: AsyncGenerator<DiskBlock, any, any>) {
@@ -14,15 +13,10 @@ class ForkedDisk extends DiskPassthrough {
throw new ErrorEvent(' No need to open forked disk ')
}
async init(): Promise<void> {
// the source is shared by all the forks: it must handle being initialized by each of them
await this.source.init()
/* source has already been open , */
}
async *diskBlocks(): AsyncGenerator<DiskBlock> {
try {
if (this.#closed) {
// it has been closed while the source was being opened, it would look like an empty disk
throw new Error(`Can't read the blocks of a closed forked disk`)
}
for await (const block of this.#generator) {
this.#generatedDiskBlocks++
yield block
@@ -35,19 +29,6 @@ class ForkedDisk extends DiskPassthrough {
getNbGeneratedBlock(): number {
return this.#generatedDiskBlocks
}
async close(): Promise<void> {
const alreadyClosed = this.#closed
this.#closed = true
try {
// closing the source first makes a pending read fail instead of ending like a complete disk
await super.close()
} finally {
if (!alreadyClosed) {
// the other forks are waiting for this one at each block, even if it has not been consumed at all
await this.#generator.return(undefined)
}
}
}
}
export class SynchronizedDisk {

View File

@@ -1,6 +1,5 @@
import { test } from 'node:test'
import assert from 'node:assert'
import { setTimeout } from 'node:timers/promises'
import { DebugDisk } from './utils/DebugDisk.mjs'
import { SynchronizedDisk } from './SynchronizedDisk.mjs'
@@ -30,46 +29,4 @@ test('Disk class', async t => {
assert.strictEqual(source.getNbGeneratedBlock(), nbBlocks)
})
console.log({ testRes })
await t.test('initializing a fork initializes the source', async () => {
const source = new DebugDisk({ nbBlocks: 20, blockSize: 1024, fillRate: 100 })
const disk = new SynchronizedDisk(source)
const forks = [disk.fork('generator_0'), disk.fork('generator_1')]
assert.strictEqual(source.initDone, false, 'source is not opened before a fork is initialized')
await forks[0].init()
assert.strictEqual(source.initDone, true)
assert.strictEqual(forks[0].getBlockSize(), 1024)
await Promise.all(forks.map(fork => consumeGenerator(fork.diskBlocks())))
assert.strictEqual(source.getNbGeneratedBlock(), 20)
})
await t.test('closing a fork that has never been consumed does not block the other ones', async () => {
const source = new DebugDisk({ nbBlocks: 20, blockSize: 1024, fillRate: 100 })
const disk = new SynchronizedDisk(source)
const forks = [disk.fork('generator_0'), disk.fork('generator_1')]
await forks[0].init()
await forks[1].close()
assert.strictEqual(await consumeGenerator(forks[0].diskBlocks()), 'finished')
assert.strictEqual(source.getNbGeneratedBlock(), 20)
})
await t.test('a fork closed while its source was being opened cannot be read', async () => {
class SlowToOpenDisk extends DebugDisk {
async init(): Promise<void> {
await setTimeout(10)
await super.init()
}
}
const source = new SlowToOpenDisk({ nbBlocks: 20, blockSize: 1024, fillRate: 100 })
const disk = new SynchronizedDisk(source)
const [fork] = [disk.fork('generator_0')]
const opening = fork.init()
await fork.close()
assert.strictEqual(source.initDone, false, 'the source is still being opened when the fork is closed')
await opening
await assert.rejects(consumeGenerator(fork.diskBlocks()), /closed forked disk/)
assert.strictEqual(source.getNbGeneratedBlock(), 0)
// closing a source opened after its close is the responsibility of the source (see XapiDiskSource)
assert.strictEqual(source.closeDone, true, 'the close is forwarded to the source')
})
})

View File

@@ -8,10 +8,6 @@ export class ThrottledDisk extends DiskPassthrough {
super(source)
this.#throttle = throttle
}
async init(): Promise<void> {
// nothing to open here, but the source may not be opened yet
await this.source.init()
}
async buildDiskBlockGenerator(): Promise<AsyncGenerator<DiskBlock>> {
const generator = await this.source.buildDiskBlockGenerator()
//throttle want to be able to know the length of the data

View File

@@ -30,10 +30,3 @@ test('ThrottledDisk keeps the other properties of the blocks', async () => {
}
assert.strictEqual(nbBlocksRead, nbBlocks)
})
test('ThrottledDisk initializes its source', async () => {
const source = new DebugDisk({ nbBlocks: 5, blockSize: 1024, fillRate: 100 })
const disk = new ThrottledDisk(source, new Throttle(0))
await disk.init()
assert.strictEqual(source.initDone, true)
})

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,9 +2,6 @@
## **next**
## **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))
@@ -19,8 +16,6 @@
- [Side panels] Fix the double scrollbar when the side panel content is taller than the screen: the page header now stays in place, and the list and the side panel each scroll on their own. All scrollbars are now thin, like the side panel one (PR [#10807](https://github.com/vatesfr/xen-orchestra/pull/10807))
- [Mobile] Searchable dropdown lists no longer overflow the screen (PR [#10854](https://github.com/vatesfr/xen-orchestra/pull/10854))
- [New/VM] Fix the storage table overflowing horizontally, which hid part of the delete button (PR [#10851](https://github.com/vatesfr/xen-orchestra/pull/10851))
- [New/VM] Fix template disk settings being applied to every disk of the new VM: each disk now keeps its own name, description and SR (PR [#10898](https://github.com/vatesfr/xen-orchestra/pull/10898))
- [VM/System] Display the default 4 MiB video RAM for HVM VMs that don't define it, as XO 6 does (PR [#10901](https://github.com/vatesfr/xen-orchestra/pull/10901))
## **0.27.0** (2026-10-29)

View File

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

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

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

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

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

View File

@@ -43,20 +43,6 @@ export function areVmToolsDetected(guestMetrics: XenApiVmGuestMetrics | undefine
return managementAgentDetected && pvDriversDetected
}
/**
* @see `packages/xo-server/src/xapi/utils.mjs`:57
**/
export function getVmDomainType(vm: XenApiVm) {
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'
}
export type VmPowerStateAction =
| 'start'
| 'pause'

View File

@@ -512,7 +512,6 @@ const getExistingVdis = (template: XenApiVm) => {
acc.push({
id: vdi.$ref,
userdevice: vbd.userdevice,
name_label: vdi.name_label,
name_description: vdi.name_description,
size: bytesToGiB(vdi.virtual_size),
@@ -699,7 +698,6 @@ const _createVm = defer(async ($defer: Defer) => {
const vdiRef = await xapi.getField<XenApiVdi['$ref']>('VBD', vbdRef, 'VDI')
const type = await xapi.getField<VBD_TYPE>('VBD', vbdRef, 'type')
const bootable = await xapi.getField<boolean>('VBD', vbdRef, 'bootable')
const userdevice = await xapi.getField<XenApiVbd['userdevice']>('VBD', vbdRef, 'userdevice')
if (!hasBootableDisk) {
hasBootableDisk = bootable
@@ -709,49 +707,45 @@ const _createVm = defer(async ($defer: Defer) => {
continue
}
const vdi = existingVdis.find(vdi => vdi.userdevice === userdevice)
for (const vdi of existingVdis) {
const srRef = await xapi.getField<XenApiSr['$ref']>('VDI', vdiRef, 'SR')
const vbdRefs = await xapi.getField<XenApiVbd['$ref'][]>('VDI', vdiRef, 'VBDs')
if (vdi === undefined) {
continue
}
await xapi.vdi.setNameLabel(vdiRef, vdi.name_label)
await xapi.vdi.setNameDescription(vdiRef, vdi.name_description)
const srRef = await xapi.getField<XenApiSr['$ref']>('VDI', vdiRef, 'SR')
const vbdRefs = await xapi.getField<XenApiVbd['$ref'][]>('VDI', vdiRef, 'VBDs')
await xapi.vdi.setNameLabel(vdiRef, vdi.name_label)
await xapi.vdi.setNameDescription(vdiRef, vdi.name_description)
// EDIT SR: Migrate VDI or create new one
if (vdi.SR !== srRef) {
try {
await xapi.vdi.poolMigrate(vdiRef, vdi.SR)
} catch (error) {
if (!(error instanceof Error)) {
throw error
}
const { message } = error
if (
message !== 'NO_HOSTS_AVAILABLE' &&
message !== 'LICENCE_RESTRICTION' &&
message !== 'VDI_NEEDS_VM_FOR_MIGRATE'
) {
throw error
}
const newVdiRef = await xapi.vdi.copy(vdiRef, vdi.SR)
if (vbdRefs) {
for (const vbdRef of vbdRefs) {
const vbd = await xapi.getField<XenApiVbd>('VBD', vbdRef, 'record')
await xapi.vbd.delete(vbdRef)
await xapi.vbd.create({ ...vbd, vmRefs, vdiRef: newVdiRef[0] })
// EDIT SR: Migrate VDI or create new one
if (vdi.SR !== srRef) {
try {
await xapi.vdi.poolMigrate(vdiRef, vdi.SR)
} catch (error) {
if (!(error instanceof Error)) {
throw error
}
}
await xapi.vdi.delete(vdiRef)
const { message } = error
if (
message !== 'NO_HOSTS_AVAILABLE' &&
message !== 'LICENCE_RESTRICTION' &&
message !== 'VDI_NEEDS_VM_FOR_MIGRATE'
) {
throw error
}
const newVdiRef = await xapi.vdi.copy(vdiRef, vdi.SR)
if (vbdRefs) {
for (const vbdRef of vbdRefs) {
const vbd = await xapi.getField<XenApiVbd>('VBD', vbdRef, 'record')
await xapi.vbd.delete(vbdRef)
await xapi.vbd.create({ ...vbd, vmRefs, vdiRef: newVdiRef[0] })
}
}
await xapi.vdi.delete(vdiRef)
}
}
}
}

View File

@@ -653,13 +653,6 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/task/vts-task-list': RouteRecordInfo<
'/story/web-core/task/vts-task-list',
'/story/web-core/task/vts-task-list',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/tree/vts-tree-item': RouteRecordInfo<
'/story/web-core/tree/vts-tree-item',
'/story/web-core/tree/vts-tree-item',
@@ -891,13 +884,6 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/ui/group-subcategory/ui-group-subcategory': RouteRecordInfo<
'/story/web-core/ui/group-subcategory/ui-group-subcategory',
'/story/web-core/ui/group-subcategory/ui-group-subcategory',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/ui/head-bar/ui-head-bar': RouteRecordInfo<
'/story/web-core/ui/head-bar/ui-head-bar',
'/story/web-core/ui/head-bar/ui-head-bar',
@@ -905,13 +891,6 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/ui/image-radio-button/ui-image-radio-button': RouteRecordInfo<
'/story/web-core/ui/image-radio-button/ui-image-radio-button',
'/story/web-core/ui/image-radio-button/ui-image-radio-button',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/ui/info/ui-info': RouteRecordInfo<
'/story/web-core/ui/info/ui-info',
'/story/web-core/ui/info/ui-info',
@@ -1066,20 +1045,6 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/ui/rich-checkbox/ui-rich-checkbox': RouteRecordInfo<
'/story/web-core/ui/rich-checkbox/ui-rich-checkbox',
'/story/web-core/ui/rich-checkbox/ui-rich-checkbox',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/ui/rich-checkbox-group/ui-rich-checkbox-group': RouteRecordInfo<
'/story/web-core/ui/rich-checkbox-group/ui-rich-checkbox-group',
'/story/web-core/ui/rich-checkbox-group/ui-rich-checkbox-group',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/ui/rich-radio-button/ui-rich-radio-button': RouteRecordInfo<
'/story/web-core/ui/rich-radio-button/ui-rich-radio-button',
'/story/web-core/ui/rich-radio-button/ui-rich-radio-button',
@@ -1087,13 +1052,6 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/ui/rich-radio-button-group/ui-rich-radio-button-group': RouteRecordInfo<
'/story/web-core/ui/rich-radio-button-group/ui-rich-radio-button-group',
'/story/web-core/ui/rich-radio-button-group/ui-rich-radio-button-group',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/ui/stacked-bar/ui-stacked-bar': RouteRecordInfo<
'/story/web-core/ui/stacked-bar/ui-stacked-bar',
'/story/web-core/ui/stacked-bar/ui-stacked-bar',
@@ -1150,13 +1108,6 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/ui/tag/ui-label-value-tag': RouteRecordInfo<
'/story/web-core/ui/tag/ui-label-value-tag',
'/story/web-core/ui/tag/ui-label-value-tag',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/ui/tag/ui-tag': RouteRecordInfo<
'/story/web-core/ui/tag/ui-tag',
'/story/web-core/ui/tag/ui-tag',
@@ -1171,6 +1122,13 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/ui/tag/ui-tertiary-tag': RouteRecordInfo<
'/story/web-core/ui/tag/ui-tertiary-tag',
'/story/web-core/ui/tag/ui-tertiary-tag',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/ui/task-item/ui-task-item': RouteRecordInfo<
'/story/web-core/ui/task-item/ui-task-item',
'/story/web-core/ui/task-item/ui-task-item',
@@ -1178,6 +1136,13 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/ui/task-list/ui-task-list': RouteRecordInfo<
'/story/web-core/ui/task-list/ui-task-list',
'/story/web-core/ui/task-list/ui-task-list',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/ui/title/ui-title': RouteRecordInfo<
'/story/web-core/ui/title/ui-title',
'/story/web-core/ui/title/ui-title',
@@ -1869,12 +1834,6 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/stories/web-core/task/vts-task-list.story.vue': {
routes:
| '/story/web-core/task/vts-task-list'
views:
| never
}
'src/stories/web-core/tree/vts-tree-item.story.vue': {
routes:
| '/story/web-core/tree/vts-tree-item'
@@ -2073,24 +2032,12 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/stories/web-core/ui/group-subcategory/ui-group-subcategory.story.vue': {
routes:
| '/story/web-core/ui/group-subcategory/ui-group-subcategory'
views:
| never
}
'src/stories/web-core/ui/head-bar/ui-head-bar.story.vue': {
routes:
| '/story/web-core/ui/head-bar/ui-head-bar'
views:
| never
}
'src/stories/web-core/ui/image-radio-button/ui-image-radio-button.story.vue': {
routes:
| '/story/web-core/ui/image-radio-button/ui-image-radio-button'
views:
| never
}
'src/stories/web-core/ui/info/ui-info.story.vue': {
routes:
| '/story/web-core/ui/info/ui-info'
@@ -2223,30 +2170,12 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/stories/web-core/ui/rich-checkbox/ui-rich-checkbox.story.vue': {
routes:
| '/story/web-core/ui/rich-checkbox/ui-rich-checkbox'
views:
| never
}
'src/stories/web-core/ui/rich-checkbox-group/ui-rich-checkbox-group.story.vue': {
routes:
| '/story/web-core/ui/rich-checkbox-group/ui-rich-checkbox-group'
views:
| never
}
'src/stories/web-core/ui/rich-radio-button/ui-rich-radio-button.story.vue': {
routes:
| '/story/web-core/ui/rich-radio-button/ui-rich-radio-button'
views:
| never
}
'src/stories/web-core/ui/rich-radio-button-group/ui-rich-radio-button-group.story.vue': {
routes:
| '/story/web-core/ui/rich-radio-button-group/ui-rich-radio-button-group'
views:
| never
}
'src/stories/web-core/ui/stacked-bar/ui-stacked-bar.story.vue': {
routes:
| '/story/web-core/ui/stacked-bar/ui-stacked-bar'
@@ -2295,12 +2224,6 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/stories/web-core/ui/tag/ui-label-value-tag.story.vue': {
routes:
| '/story/web-core/ui/tag/ui-label-value-tag'
views:
| never
}
'src/stories/web-core/ui/tag/ui-tag.story.vue': {
routes:
| '/story/web-core/ui/tag/ui-tag'
@@ -2313,12 +2236,24 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/stories/web-core/ui/tag/ui-tertiary-tag.story.vue': {
routes:
| '/story/web-core/ui/tag/ui-tertiary-tag'
views:
| never
}
'src/stories/web-core/ui/task-item/ui-task-item.story.vue': {
routes:
| '/story/web-core/ui/task-item/ui-task-item'
views:
| never
}
'src/stories/web-core/ui/task-list/ui-task-list.story.vue': {
routes:
| '/story/web-core/ui/task-list/ui-task-list'
views:
| never
}
'src/stories/web-core/ui/title/ui-title.story.vue': {
routes:
| '/story/web-core/ui/title/ui-title'

View File

@@ -1,37 +1,9 @@
import type { XenApiVdi } from '@/libs/xen-api/xen-api.types.ts'
import { createXapiStoreConfig } from '@/stores/xen-api/create-xapi-store-config.ts'
import { createSubscribableStoreContext } from '@core/utils/create-subscribable-store-context.util.ts'
import { defineStore } from 'pinia'
export const useVdiStore = defineStore('xen-api-vdi', () => {
const { context: baseContext, ...configRest } = createXapiStoreConfig('vdi')
const config = createXapiStoreConfig('vdi')
const getChainPhysicalUsage = (vdi: XenApiVdi) => {
if (vdi.is_a_snapshot || !vdi.managed) {
return vdi.physical_utilisation
}
let total = vdi.physical_utilisation
let parentUuid = vdi.sm_config['vhd-parent'] as XenApiVdi['uuid'] | undefined
while (parentUuid !== undefined) {
const parent = baseContext.getByUuid(parentUuid)
if (parent === undefined) {
break
}
total += parent.physical_utilisation
parentUuid = parent.sm_config['vhd-parent'] as XenApiVdi['uuid'] | undefined
}
return total
}
const context = {
...baseContext,
getChainPhysicalUsage,
}
return createSubscribableStoreContext({ context, ...configRest }, {})
return createSubscribableStoreContext(config, {})
})

View File

@@ -2,32 +2,36 @@
<ComponentStory
v-slot="{ properties }"
:params="[
prop('accent').required().enum('neutral', 'success', 'warning', 'danger').preset('neutral').widget(),
prop('id').required().obj('FormSelectId').preset(id),
prop('accent').required().enum('neutral', 'warning', 'danger').preset('neutral').widget(),
prop('options').required().arr('FormOption<TEntry, TValue>').widget().preset(options),
prop('selectedLabel').str(),
prop('required').bool().widget(),
prop('placeholder').str().widget().preset('Choose colors'),
prop('searchPlaceholder').str().widget().preset('Search colors'),
prop('loading').bool().widget(),
model('search'),
slot(),
]"
>
<VtsSelect v-bind="properties" />
<VtsSelect v-bind="properties" v-model:search="searchTerm" :selected-label />
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { prop, slot } from '@/libs/story/story-param.ts'
import { model, prop, slot } from '@/libs/story/story-param.ts'
import VtsSelect from '@core/components/select/VtsSelect.vue'
import { useFormSelect } from '@core/packages/form-select'
import { upperFirst } from 'lodash-es'
const colors = ['blue', 'yellow', 'red', 'green', 'orange', 'purple', 'white', 'grey', 'black']
const { id } = useFormSelect(colors, {
option: {
label: color => `${upperFirst(color)} color`,
disabled: color => color === 'blue' || color === 'orange' || color === 'black',
},
const { options, searchTerm, selectedLabel } = useFormSelect(colors, {
properties: color => ({
value: color,
label: `${upperFirst(color)} color`,
disabled: color === 'blue' || color === 'orange' || color === 'black',
}),
multiple: true,
searchable: true,
placeholder: 'Choose colors',
searchPlaceholder: 'Search colors',
})
</script>

View File

@@ -1,33 +0,0 @@
<template>
<ComponentStory
v-slot="{ properties }"
:params="[
prop('tasks').type('Task[]').required().preset(allTasks),
prop('selectedTaskId').str().widget(),
prop('showEyeIcon').bool().widget(),
prop('autoCollapseCompleted').bool().widget(),
prop('expandAll')
.bool()
.widget()
.help('Shows every task expanded; turning it off restores the tasks expanded before'),
prop('unreadTaskIds').type('ReadonlySet<string>').help('Shows an unread dot column, with a dot for these tasks'),
event('select').args({ id: 'string' }),
]"
:presets="{
'Unread tasks': {
props: {
unreadTaskIds: new Set(['1', '1-2', '4', '9', '9-2', '9-2-1']),
},
},
}"
>
<VtsTaskList v-bind="properties" />
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { event, prop } from '@/libs/story/story-param.ts'
import { allTasks } from '@/stories/web-core/ui/task-item/mock-tasks.ts'
import VtsTaskList from '@core/components/task/VtsTaskList.vue'
</script>

View File

@@ -3,7 +3,6 @@
v-slot="{ properties, settings }"
:params="[
prop('accent').type('CheckboxAccent').required().enum('brand', 'warning', 'danger').preset('brand').widget(),
prop('value').str().help('Used when the model is an array'),
prop('disabled').bool().widget(),
slot(),
slot('info'),
@@ -11,7 +10,7 @@
setting('defaultSlot').widget(text()).preset('Label'),
setting('info').widget(text()).preset('Lorem ipsum dolor sit amet, consectetur adipiscing elit.'),
setting('message').widget(text()).preset('Lorem ipsum dolor sit amet, consectetur adipiscing elit.'),
model().type('boolean | undefined | string[]').preset(undefined).help('undefined means partly checked'),
model().type('boolean').preset(undefined),
]"
>
<UiCheckbox v-bind="properties">

View File

@@ -1,23 +0,0 @@
<template>
<ComponentStory
v-slot="{ settings }"
:params="[
slot().help('Meant to receive the subcategory title'),
slot('info').help('Meant to receive a short text displayed on the right'),
setting('defaultSlot').widget(text()).preset('Into a pool'),
setting('info').widget(text()).preset('Writes to a pool'),
]"
>
<UiGroupSubcategory>
{{ settings.defaultSlot }}
<template v-if="settings.info" #info>{{ settings.info }}</template>
</UiGroupSubcategory>
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { setting, slot } from '@/libs/story/story-param.ts'
import { text } from '@/libs/story/story-widget.ts'
import UiGroupSubcategory from '@core/components/ui/group-subcategory/UiGroupSubcategory.vue'
</script>

View File

@@ -1,39 +0,0 @@
<template>
<ComponentStory
v-slot="{ properties, settings }"
:params="[
prop('accent').required().enum('brand', 'warning', 'danger').preset('brand').widget(),
prop('size').required().enum('small', 'medium').preset('medium').widget(),
prop('disabled').bool().widget(),
prop('src').required().str().help('Image URL for rich mode'),
prop('alt').required().str().help('Alt text for image'),
model().type('string').preset(''),
setting('defaultSlot').widget(text()).preset('Label'),
]"
>
<div class="radio">
<UiImageRadioButton v-model="selectedRadio" value="1" v-bind="properties" :src="imageUrl" :alt="properties.alt">
{{ settings.defaultSlot }}
</UiImageRadioButton>
</div>
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { model, prop, setting } from '@/libs/story/story-param.ts'
import { text } from '@/libs/story/story-widget.ts'
import UiImageRadioButton from '@core/components/ui/image-radio-button/UiImageRadioButton.vue'
import { ref } from 'vue'
import imageUrl from '../../../../assets/color-mode-dark.svg'
const selectedRadio = ref('')
</script>
<style lang="postcss" scoped>
.radio {
display: flex;
gap: 1.6rem;
flex-wrap: wrap;
}
</style>

View File

@@ -10,16 +10,16 @@
slot().help('Meant to receive a list of radio button components'),
slot('label').help('Meant to receive a label UiLabel component or another component'),
slot('info').help('Meant to receive a message info or UiInfo component or another component'),
setting('imageRadioButton').widget(boolean()),
setting('richRadioButton').widget(boolean()),
]"
>
<UiRadioButtonGroup v-bind="properties">
<component
:is="settings.imageRadioButton === true ? UiImageRadioButton : UiRadioButton"
:is="settings.richRadioButton === true ? UiRichRadioButton : UiRadioButton"
v-for="(label, index) in labels"
:key="index"
v-model="selectedRadio"
v-bind="imageButtonProps(properties, settings.imageRadioButton)"
v-bind="richButtonProps(properties, settings.richRadioButton)"
:value="`radio-${index}`"
>
{{ label }}
@@ -32,9 +32,9 @@
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { prop, setting, slot } from '@/libs/story/story-param.ts'
import { boolean } from '@/libs/story/story-widget.ts'
import UiImageRadioButton from '@core/components/ui/image-radio-button/UiImageRadioButton.vue'
import UiRadioButton from '@core/components/ui/radio-button/UiRadioButton.vue'
import UiRadioButtonGroup from '@core/components/ui/radio-button-group/UiRadioButtonGroup.vue'
import UiRichRadioButton from '@core/components/ui/rich-radio-button/UiRichRadioButton.vue'
import { ref } from 'vue'
import imageUrl from '../../../../assets/color-mode-dark.svg'
@@ -42,8 +42,8 @@ const selectedRadio = ref('')
const labels = ref(['Label 1', 'Label 2', 'Label 3'])
const imageButtonProps = (properties: any, imageRadioButton: boolean) => {
if (imageRadioButton) {
const richButtonProps = (properties: any, richRadioButton: boolean) => {
if (richRadioButton) {
return {
...properties,
src: imageUrl,

View File

@@ -1,75 +0,0 @@
<template>
<ComponentStory
v-slot="{ properties }"
:params="[
prop('accent').type('RichCheckboxAccent').required().enum('brand', 'warning', 'danger').preset('brand').widget(),
prop('label').str().widget().preset('Backup repositories'),
prop('info').str().widget(),
prop('message').str().widget().help('Only displayed when the accent is not brand'),
prop('vertical').bool().widget().preset(true),
slot().help('Meant to receive UiRichCheckbox components, and UiGroupSubcategory components in vertical mode'),
slot('label').help('Meant to receive a UiLabel component or another component'),
slot('info').help('Meant to receive a UiInfo component or another component'),
slot('message').help('Meant to receive a UiInfo component or another component'),
]"
>
<UiRichCheckboxGroup v-bind="properties">
<template v-for="category of properties.vertical ? categories : horizontalCategories" :key="category.title">
<UiGroupSubcategory v-if="properties.vertical">
{{ category.title }}
<template v-if="category.info" #info>{{ category.info }}</template>
</UiGroupSubcategory>
<UiRichCheckbox
v-for="option of category.options"
:key="option.value"
v-model="selectedRepositories"
:accent="properties.accent"
:value="option.value"
:tag="option.tag"
:description="option.description"
:disabled="option.disabled"
icon="fa:server"
>
{{ option.label }}
</UiRichCheckbox>
</template>
</UiRichCheckboxGroup>
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { prop, slot } from '@/libs/story/story-param.ts'
import UiGroupSubcategory from '@core/components/ui/group-subcategory/UiGroupSubcategory.vue'
import UiRichCheckbox from '@core/components/ui/rich-checkbox/UiRichCheckbox.vue'
import UiRichCheckboxGroup from '@core/components/ui/rich-checkbox-group/UiRichCheckboxGroup.vue'
import { ref } from 'vue'
type StoryOption = {
value: string
label: string
description: string
tag?: string
disabled?: boolean
}
const selectedRepositories = ref(['nfs-backups', 'smb-archive'])
const categories: { title: string; info?: string; options: StoryOption[] }[] = [
{
title: 'Category 1',
options: [
{ value: 'rd-s3', label: 'RD - S3', description: '3.1 TiB free', tag: 'Source' },
{ value: 'nfs-backups', label: 'NFS backups', description: '4.2 TiB free' },
{ value: 'local-backups', label: 'Local backups', description: '120 GiB free', disabled: true },
],
},
{
title: 'Category 2',
info: 'Info',
options: [{ value: 'smb-archive', label: 'SMB archive', description: '900 GiB free' }],
},
]
const horizontalCategories = categories.slice(0, 1)
</script>

View File

@@ -1,41 +0,0 @@
<template>
<ComponentStory
v-slot="{ properties, settings }"
:params="[
prop('accent').type('RichCheckboxAccent').required().enum('brand', 'warning', 'danger').preset('brand').widget(),
prop('value').str().help('Used when the model is an array'),
iconProp(),
prop('tag').str().widget().preset('Label'),
prop('description').str().widget().preset('Description'),
prop('info').str().widget(),
prop('message').str().widget().help('Only displayed when the accent is not brand'),
prop('disabled').bool().widget(),
model().type('boolean | undefined | string[]').preset(undefined).help('undefined means partly checked'),
slot().help('Meant to receive the label'),
slot('tag').help('Meant to receive a UiTag component, to use another accent than the default info one'),
slot('description'),
slot('info'),
slot('message'),
setting('defaultSlot').widget(text()).preset('Label'),
]"
>
<div class="checkbox">
<UiRichCheckbox v-bind="properties">
{{ settings.defaultSlot }}
</UiRichCheckbox>
</div>
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { iconProp, model, prop, setting, slot } from '@/libs/story/story-param.ts'
import { text } from '@/libs/story/story-widget.ts'
import UiRichCheckbox from '@core/components/ui/rich-checkbox/UiRichCheckbox.vue'
</script>
<style lang="postcss" scoped>
.checkbox {
max-width: 40rem;
}
</style>

View File

@@ -1,125 +0,0 @@
<template>
<ComponentStory
v-slot="{ properties }"
:params="[
prop('accent')
.type('RichRadioButtonAccent')
.required()
.enum('brand', 'warning', 'danger')
.preset('brand')
.widget(),
prop('label').str().widget().preset('Restore type'),
prop('info').str().widget(),
prop('message').str().widget().help('Only displayed when the accent is not brand'),
prop('vertical').bool().widget().preset(true),
slot().help('Meant to receive UiRichRadioButton components, and UiGroupSubcategory components in vertical mode'),
slot('label').help('Meant to receive a UiLabel component or another component'),
slot('info').help('Meant to receive a UiInfo component or another component'),
slot('message').help('Meant to receive a UiInfo component or another component'),
]"
>
<UiRichRadioButtonGroup v-bind="properties">
<template v-for="category of properties.vertical ? categories : horizontalCategories" :key="category.title">
<UiGroupSubcategory v-if="properties.vertical">
{{ category.title }}
<template #info>{{ category.info }}</template>
</UiGroupSubcategory>
<UiRichRadioButton
v-for="option of category.options"
:key="option.value"
v-model="selectedRadio"
:accent="properties.accent"
:value="option.value"
:icon="option.icon"
:description="option.description"
:disabled="option.disabled"
>
{{ option.label }}
<template v-if="option.tag" #tag>
<UiTag :accent="option.tag.accent" variant="secondary">{{ option.tag.label }}</UiTag>
</template>
</UiRichRadioButton>
</template>
</UiRichRadioButtonGroup>
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { prop, slot } from '@/libs/story/story-param.ts'
import type { IconName } from '@core/icons'
import UiGroupSubcategory from '@core/components/ui/group-subcategory/UiGroupSubcategory.vue'
import UiRichRadioButton from '@core/components/ui/rich-radio-button/UiRichRadioButton.vue'
import UiRichRadioButtonGroup from '@core/components/ui/rich-radio-button-group/UiRichRadioButtonGroup.vue'
import UiTag, { type TagAccent } from '@core/components/ui/tag/UiTag.vue'
import { ref } from 'vue'
type StoryOption = {
value: string
label: string
description: string
icon: IconName
tag?: { label: string; accent: TagAccent }
disabled?: boolean
}
const selectedRadio = ref('copy-then-start')
const categories: { title: string; info: string; options: StoryOption[] }[] = [
{
title: 'Into a pool',
info: 'Writes to a pool',
options: [
{
value: 'copy-then-start',
label: 'Copy, then start',
description:
'Copy the disks to a storage of the pool, then start the VM. When a snapshot of the VM is still in the pool, only the blocks that differ are transferred, if possible.',
icon: 'action:copy',
tag: { label: 'Default', accent: 'info' },
},
{
value: 'start-now',
label: 'Start now',
description: 'Start the VM right away from the backup. What it writes goes to a cache storage.',
icon: 'status:running',
tag: { label: 'Live restore', accent: 'neutral' },
},
{
value: 'attach-disk',
label: 'Attach a disk to a running VM',
description: 'Serve a disk of the backup, read-only, to an existing VM. Nothing is copied.',
icon: 'action:attach',
},
],
},
{
title: 'Out of the backup',
info: 'Nothing written to a pool',
options: [
{
value: 'download-files',
label: 'Download files',
description:
'Browse a partition of a disk and download individual files or folders. Best for a small amount of data.',
icon: 'action:download',
},
{
value: 'export-disk',
label: 'Export a disk',
description: 'Convert one disk to qcow2, vmdk, vhd or raw, then download it.',
icon: 'action:download',
},
{
value: 'export-vm',
label: 'Export the VM',
description: 'Build an XVA from the backup, to import into XCP-ng or XenServer.',
icon: 'action:download',
disabled: true,
},
],
},
]
const horizontalCategories = categories.slice(0, 1)
</script>

View File

@@ -2,30 +2,17 @@
<ComponentStory
v-slot="{ properties, settings }"
:params="[
prop('accent')
.type('RichRadioButtonAccent')
.required()
.enum('brand', 'warning', 'danger')
.preset('brand')
.widget(),
iconProp(),
prop('tag').str().widget().preset('Label'),
prop('description').str().widget().preset('Description'),
prop('info').str().widget(),
prop('accent').required().enum('brand', 'warning', 'danger').preset('brand').widget(),
prop('size').required().enum('small', 'medium').preset('medium').widget(),
prop('disabled').bool().widget(),
model().type('string'),
slot().help('Meant to receive the label'),
slot('tag').help('Meant to receive a UiTag component, to use another accent than the default info one'),
slot('description'),
slot('info'),
prop('src').required().str().help('Image URL for rich mode'),
prop('alt').required().str().help('Alt text for image'),
model().type('string').preset(''),
setting('defaultSlot').widget(text()).preset('Label'),
]"
>
<div class="radios">
<UiRichRadioButton v-model="selectedRadio" v-bind="properties" value="1">
{{ settings.defaultSlot }}
</UiRichRadioButton>
<UiRichRadioButton v-model="selectedRadio" v-bind="properties" value="2">
<div class="radio">
<UiRichRadioButton v-model="selectedRadio" value="1" v-bind="properties" :src="imageUrl" :alt="properties.alt">
{{ settings.defaultSlot }}
</UiRichRadioButton>
</div>
@@ -34,19 +21,19 @@
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { iconProp, model, prop, setting, slot } from '@/libs/story/story-param.ts'
import { model, prop, setting } from '@/libs/story/story-param.ts'
import { text } from '@/libs/story/story-widget.ts'
import UiRichRadioButton from '@core/components/ui/rich-radio-button/UiRichRadioButton.vue'
import { ref } from 'vue'
import imageUrl from '../../../../assets/color-mode-dark.svg'
const selectedRadio = ref('')
</script>
<style lang="postcss" scoped>
.radios {
.radio {
display: flex;
flex-direction: column;
gap: 0.8rem;
max-width: 40rem;
gap: 1.6rem;
flex-wrap: wrap;
}
</style>

View File

@@ -9,7 +9,6 @@
.enum('brand', 'info', 'neutral', 'success', 'warning', 'danger', 'muted')
.widget(),
prop('variant').type('TagVariant').required().preset('primary').enum('primary', 'secondary').widget(),
iconProp(),
slot(),
setting('slot').preset('Label').widget(),
]"
@@ -22,6 +21,6 @@
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { iconProp, prop, setting, slot } from '@/libs/story/story-param.ts'
import { prop, setting, slot } from '@/libs/story/story-param.ts'
import UiTag from '@core/components/ui/tag/UiTag.vue'
</script>

View File

@@ -8,18 +8,18 @@
<UiTag accent="success" variant="primary">{{ settings.slot }}</UiTag>
<UiTag accent="warning" variant="secondary">{{ settings.slot }}</UiTag>
<UiTag accent="danger" variant="secondary">{{ settings.slot }}</UiTag>
<UiLabelValueTag accent="info">
<UiTertiaryTag accent="info">
{{ settings.slot }}
<template #term>
{{ settings.slot }}
</template>
</UiLabelValueTag>
<UiLabelValueTag accent="success">
</UiTertiaryTag>
<UiTertiaryTag accent="success">
{{ settings.slot }}
<template #term>
{{ settings.slot }}
</template>
</UiLabelValueTag>
</UiTertiaryTag>
</UiTagsList>
</ComponentStory>
</template>
@@ -27,7 +27,7 @@
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { setting, slot } from '@/libs/story/story-param.ts'
import UiLabelValueTag from '@core/components/ui/tag/UiLabelValueTag.vue'
import UiTag from '@core/components/ui/tag/UiTag.vue'
import UiTagsList from '@core/components/ui/tag/UiTagsList.vue'
import UiTertiaryTag from '@core/components/ui/tag/UiTertiaryTag.vue'
</script>

View File

@@ -20,15 +20,12 @@
setting('maxWidth').widget(number()).help('Maximum width, in rem'),
]"
>
<UiLabelValueTag
v-bind="properties"
:style="{ maxWidth: settings.maxWidth ? `${settings.maxWidth}rem` : undefined }"
>
<UiTertiaryTag v-bind="properties" :style="{ maxWidth: settings.maxWidth ? `${settings.maxWidth}rem` : undefined }">
{{ settings.slot }}
<template #term>
{{ settings.term }}
</template>
</UiLabelValueTag>
</UiTertiaryTag>
</ComponentStory>
</template>
@@ -36,5 +33,5 @@
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { prop, setting, slot } from '@/libs/story/story-param.ts'
import { number } from '@/libs/story/story-widget.ts'
import UiLabelValueTag from '@core/components/ui/tag/UiLabelValueTag.vue'
import UiTertiaryTag from '@core/components/ui/tag/UiTertiaryTag.vue'
</script>

View File

@@ -67,107 +67,10 @@ export const deepNestedTask: Task = {
],
}
export const pendingWithoutProgressTask: Task = {
id: '6',
name: 'Queued replication',
status: 'pending',
start: Date.now() - 2 * 60_000,
}
export const pendingFullProgressTask: Task = {
id: '7',
name: 'Finalize export',
status: 'pending',
progress: 100,
start: Date.now() - 60_000,
infos: [{ message: 'Waiting for cleanup', data: null }],
}
export const infosAndWarningsTask: Task = {
id: '8',
name: 'Rolling pool update',
status: 'pending',
progress: 50,
start: Date.now() - 3 * 60 * 60_000,
infos: [{ message: 'Hosts updated', data: { hosts: 4, done: 2 } }],
warnings: [{ message: 'Reboot required after update', data: { host: 'host-3' } }],
subtasks: [
{ id: '8-1', name: 'host-1', status: 'success', progress: 100, end: Date.now() - 2 * 60 * 60_000 },
{ id: '8-2', name: 'host-2', status: 'success', progress: 100, end: Date.now() - 60 * 60_000 },
{ id: '8-3', name: 'host-3', status: 'pending', progress: 30, start: Date.now() - 15 * 60_000 },
],
}
export const failedNestedTask: Task = {
id: '9',
name: 'Disaster recovery drill',
status: 'failure',
progress: 100,
start: Date.now() - 8 * 60 * 60_000,
end: Date.now() - 7 * 60 * 60_000,
subtasks: [
{ id: '9-1', name: 'Provision VM', status: 'success', progress: 100, end: Date.now() - 7.5 * 60 * 60_000 },
{
id: '9-2',
name: 'Restore data',
status: 'failure',
progress: 100,
end: Date.now() - 7 * 60 * 60_000,
warnings: [{ message: 'Missing backup files', data: { missing: 3 } }],
subtasks: [
{ id: '9-2-1', name: 'Mount SR', status: 'failure', progress: 100, end: Date.now() - 7.1 * 60 * 60_000 },
],
},
],
}
export const interruptedTask: Task = {
id: '10',
name: 'Storage migration',
status: 'interrupted',
progress: 10,
start: Date.now() - 2 * 60 * 60_000,
infos: [
{ message: 'Rows migrated before interruption', data: { rows: 1200 } },
{ message: 'Task manually aborted', data: null },
],
}
export const longNameTask: Task = {
id: '11',
name: 'Very long task name that should wrap gracefully in the task list UI when space is limited',
status: 'pending',
progress: 8,
start: Date.now() - 2 * 60 * 60_000,
}
export const longNameWithEverythingTask: Task = {
id: '12',
name: 'Very long task name for a full backup job that also has subtasks, infos, warnings and an end time to display',
to: '#',
status: 'failure',
progress: 100,
start: Date.now() - 5 * 60 * 60_000,
end: Date.now() - 4 * 60 * 60_000,
infos: [{ message: 'Transferred 120 GiB', data: { size: 120 } }],
warnings: [{ message: 'Some VDIs were skipped', data: { skipped: 2 } }],
subtasks: [
{ id: '12-1', name: 'Snapshot', status: 'success', progress: 100, end: Date.now() - 4.5 * 60 * 60_000 },
{ id: '12-2', name: 'Transfer', status: 'failure', progress: 100, end: Date.now() - 4 * 60 * 60_000 },
],
}
export const allTasks: Task[] = [
pendingBackupTask,
completedWithRootLinkTask,
failedWithWarningsTask,
migrationNamePartsTask,
deepNestedTask,
pendingWithoutProgressTask,
pendingFullProgressTask,
infosAndWarningsTask,
failedNestedTask,
interruptedTask,
longNameTask,
longNameWithEverythingTask,
]

View File

@@ -4,22 +4,27 @@
:presets
:params="[
prop('task').type('object').required().widget().preset(pendingBackupTask),
prop('depth').type('number').required().preset(1),
model('expanded').prop(p => p.type('boolean').widget(boolean()).preset(false)),
prop('selected').type('boolean').widget(boolean()).preset(false),
prop('showEyeIcon').type('boolean').widget(boolean()).preset(true),
prop('showUnread').bool().widget().help('Reserves the unread dot column'),
prop('unread').bool().widget(),
event('expand'),
event('select').args({ id: 'string' }),
]"
>
<UiTaskItem v-bind="properties" />
<ul>
<UiTaskItem v-bind="properties" @expand="properties['onUpdate:expanded']?.(!properties.expanded)" />
</ul>
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { event, prop } from '@/libs/story/story-param.ts'
import { event, model, prop } from '@/libs/story/story-param.ts'
import { boolean } from '@/libs/story/story-widget.ts'
import {
completedWithRootLinkTask,
deepNestedTask,
failedWithWarningsTask,
migrationNamePartsTask,
pendingBackupTask,
@@ -35,24 +40,45 @@ const presets: Record<
'Pending backup': {
props: {
task: pendingBackupTask,
depth: 1,
expanded: false,
selected: false,
showEyeIcon: true,
},
},
'Completed + root link': {
props: {
task: completedWithRootLinkTask,
depth: 1,
expanded: false,
selected: false,
showEyeIcon: true,
},
},
'Failed + warnings': {
props: {
task: failedWithWarningsTask,
depth: 1,
expanded: false,
selected: false,
showEyeIcon: true,
},
},
'Migration (nameParts)': {
props: {
task: migrationNamePartsTask,
depth: 1,
expanded: false,
selected: false,
showEyeIcon: true,
},
},
'Deep nested': {
props: {
task: deepNestedTask,
depth: 1,
expanded: true,
selected: false,
showEyeIcon: true,
},
},

View File

@@ -0,0 +1,15 @@
<template>
<ComponentStory
v-slot="{ properties }"
:params="[prop('tasks').type('Task[]').required().preset(allTasks), event('select')]"
>
<UiTaskList v-bind="properties" />
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { event, prop } from '@/libs/story/story-param.ts'
import { allTasks } from '@/stories/web-core/ui/task-item/mock-tasks.ts'
import UiTaskList from '@core/components/ui/task-list/UiTaskList.vue'
</script>

View File

@@ -1,16 +1,8 @@
import type {
XenApiHost,
XenApiNetwork,
XenApiSr,
XenApiVbd,
XenApiVdi,
XenApiVm,
} from '@/libs/xen-api/xen-api.types.ts'
import type { XenApiHost, XenApiNetwork, XenApiSr, XenApiVdi, XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import { type OPAQUE_REF_NULL, type VDI_TYPE } from '@vates/types/common'
export interface Vdi {
id?: XenApiVdi['$ref'] | undefined
userdevice?: XenApiVbd['userdevice']
name_label: string
name_description: string
size: number

View File

@@ -1,7 +1,7 @@
{
"private": false,
"name": "@xen-orchestra/log",
"version": "1.0.0",
"version": "0.7.2",
"license": "ISC",
"description": "Logging system with decoupled producers/consumer",
"keywords": [

View File

@@ -1,7 +1,7 @@
{
"private": false,
"name": "@xen-orchestra/mcp",
"version": "1.4.4",
"version": "1.4.3",
"description": "MCP server for Xen Orchestra — allows AI assistants to query and manage XO infrastructure",
"type": "module",
"main": "./dist/index.mjs",
@@ -34,7 +34,7 @@
"devDependencies": {
"@eslint/js": "^9.19.0",
"@types/node": "^22.3.0",
"@vates/types": "^3.2.0",
"@vates/types": "^2.5.0",
"rimraf": "^6.0.0",
"typescript": "~5.6.3",
"typescript-eslint": "^8.61.0"

View File

@@ -14,18 +14,18 @@
"url": "https://vates.fr"
},
"license": "AGPL-3.0-or-later",
"version": "0.24.0",
"version": "0.23.0",
"engines": {
"node": ">=15.6"
},
"dependencies": {
"@vates/async-each": "^1.0.3",
"@vates/event-listeners-manager": "^1.0.1",
"@vates/iscsi": "^0.4.1",
"@vates/iscsi": "^0.4.0",
"@vates/parse-duration": "^0.1.1",
"@vates/task": "^0.7.0",
"@xen-orchestra/backup-archive": "^1.2.1",
"@xen-orchestra/log": "^1.0.0",
"@xen-orchestra/backup-archive": "^1.2.0",
"@xen-orchestra/log": "^0.7.2",
"acme-client": "^5.0.0",
"app-conf": "^3.0.0",
"fast-xml-parser": "^4.0.0",
@@ -36,7 +36,7 @@
"xo-common": "^0.11.0"
},
"devDependencies": {
"@vates/types": "^3.2.0"
"@vates/types": "^2.5.0"
},
"scripts": {
"postversion": "npm publish --access public",

View File

@@ -1,7 +1,7 @@
{
"private": true,
"name": "@xen-orchestra/proxy",
"version": "0.35.2",
"version": "0.34.0",
"license": "AGPL-3.0-or-later",
"description": "XO Proxy used to remotely execute backup jobs",
"keywords": [
@@ -31,16 +31,16 @@
"@vates/cached-dns.lookup": "^1.0.0",
"@vates/compose": "^2.1.0",
"@vates/decorate-with": "^2.1.0",
"@vates/disposable": "^0.1.7",
"@vates/disposable": "^0.1.6",
"@vates/task": "^0.7.0",
"@xen-orchestra/async-map": "^0.1.5",
"@xen-orchestra/backups": "^1.0.1",
"@xen-orchestra/fs": "^4.11.0",
"@xen-orchestra/log": "^1.0.0",
"@xen-orchestra/backups": "^0.78.0",
"@xen-orchestra/fs": "^4.10.0",
"@xen-orchestra/log": "^0.7.2",
"@xen-orchestra/mixin": "^0.2.1",
"@xen-orchestra/mixins": "^0.24.0",
"@xen-orchestra/mixins": "^0.23.0",
"@xen-orchestra/self-signed": "^0.2.1",
"@xen-orchestra/xapi": "^10.1.0",
"@xen-orchestra/xapi": "^9.1.0",
"ajv": "^8.0.3",
"app-conf": "^3.0.0",
"async-iterator-to-stream": "^1.1.0",
@@ -62,7 +62,7 @@
"source-map-support": "^0.5.16",
"stoppable": "^1.0.6",
"xdg-basedir": "^5.1.0",
"xen-api": "^6.0.0",
"xen-api": "^5.1.0",
"xo-common": "^0.11.0"
},
"devDependencies": {

View File

@@ -2,7 +2,7 @@
"name": "@xen-orchestra/qa-test",
"private": true,
"type": "module",
"version": "1.5.0",
"version": "1.4.0",
"description": "XenOrchestra QA Test Suite",
"author": {
"name": "Vates SAS",
@@ -22,10 +22,10 @@
"dependencies": {
"@vates/async-each": "^1.0.3",
"@vates/read-chunk": "^1.2.1",
"@xen-orchestra/backups": "^1.0.1",
"@xen-orchestra/fs": "^4.11.0",
"@xen-orchestra/log": "^1.0.0",
"@xen-orchestra/vmware-explorer": "^1.4.0",
"@xen-orchestra/backups": "^0.78.0",
"@xen-orchestra/fs": "^4.10.0",
"@xen-orchestra/log": "^0.7.2",
"@xen-orchestra/vmware-explorer": "^1.2.0",
"nodemailer": "^7.0.13",
"xo-lib": "^0.11.2"
},

View File

@@ -37,38 +37,12 @@ function getBranchName() {
}
}
function getCommitHash() {
try {
return execSync('git rev-parse --short HEAD', { encoding: 'utf8', cwd: ROOT }).trim()
} catch {
return 'unknown'
}
}
function formatDatetime(date) {
// "19/11/2026 13:43 (Paris)"
return `${date.toLocaleString('fr-FR', {
timeZone: 'Europe/Paris',
dateStyle: 'short',
timeStyle: 'short',
})} (Paris)`
}
function formatDuration(ms) {
const hours = Math.floor(ms / 3600000)
const minutes = Math.floor((ms / 60000) % 60)
.toString()
.padStart(2, '0')
return `${hours}h${minutes}`
}
function getCount(output, label) {
const match = output.match(new RegExp(`ℹ ${label} (\\d+)`))
if (match === null) {
return '?'
} else {
return match[1]
}
// "2026-05-20 08:42 UTC"
return date
.toISOString()
.replace('T', ' ')
.replace(/:\d{2}\.\d+Z$/, ' UTC')
}
// ---------------------------------------------------------------------------
@@ -149,27 +123,14 @@ if (process.argv.includes('--smtp-test')) {
// ---------------------------------------------------------------------------
const branch = getBranchName()
const commitHash = getCommitHash()
const startedAt = new Date()
process.stderr.write(`[run-and-report] branch=${branch}\n`)
const { success, output, logFilePath } = await runTests()
const runtimeInMs = Date.now() - startedAt.getTime()
const emoji = success ? '✅' : '❌'
const status = success ? 'success' : 'failure'
const successTests = getCount(output, 'pass')
const totalTests = getCount(output, 'tests')
const failedTests = getCount(output, 'fail')
const cancelledTests = getCount(output, 'cancelled')
const skippedTests = getCount(output, 'skipped')
const subject = `${emoji} ${status} ${successTests}/${totalTests} passed ${formatDatetime(startedAt)} on ${branch}@${commitHash}`
const summary = `Result: ${emoji} ${status}
Commit: ${branch}@${commitHash}
Tests: ${successTests}/${totalTests} passed, ${failedTests} failed, ${cancelledTests} cancelled, ${skippedTests} skipped
Duration: ${formatDuration(runtimeInMs)}`
const subject = `test run ${formatDatetime(startedAt)} ${branch} ${status}`
// Attach the full structured debug log if we found its path
const attachments = []
@@ -188,9 +149,7 @@ await transport.sendMail({
from: process.env.SMTP_FROM ?? process.env.SMTP_USER,
to: process.env.SMTP_TO,
subject,
text: `${summary}
----------------------------------------
${output}`,
text: output,
attachments,
})

View File

@@ -6,7 +6,7 @@
"main": "./dist/index.mjs",
"name": "@xen-orchestra/rest-api",
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/@xen-orchestra/rest-api",
"version": "0.43.1",
"version": "0.41.1",
"description": "REST API to manage your XOA",
"license": "AGPL-3.0-or-later",
"private": false,
@@ -36,16 +36,16 @@
},
"dependencies": {
"@vates/async-each": "^1.0.3",
"@vates/obfuscate": "^0.2.0",
"@vates/obfuscate": "^0.1.0",
"@vates/task": "^0.7.0",
"@vates/types": "^3.2.0",
"@xen-orchestra/acl": "^1.9.0",
"@xen-orchestra/backups": "^1.0.1",
"@vates/types": "^2.5.0",
"@xen-orchestra/acl": "^1.8.0",
"@xen-orchestra/backups": "^0.78.0",
"@xen-orchestra/cron": "^1.0.7",
"@xen-orchestra/log": "^1.0.0",
"@xen-orchestra/log": "^0.7.2",
"@xen-orchestra/qcow2": "^1.4.1",
"@xen-orchestra/vmdk": "^1.0.0",
"@xen-orchestra/xapi": "^10.1.0",
"@xen-orchestra/xapi": "^9.1.0",
"complex-matcher": "^1.1.1",
"fast-xml-parser": "^5.10.1",
"golike-defer": "^0.5.1",
@@ -57,7 +57,7 @@
"swagger-ui-express": "^5.0.1",
"tsoa": "^6.6.0",
"value-matcher": "^0.2.0",
"vhd-lib": "^4.17.1",
"vhd-lib": "^4.17.0",
"xo-common": "^0.11.0",
"xo-remote-parser": "^2.0.0",
"zod": "^4.3.6",

View File

@@ -15,8 +15,6 @@ 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']
@@ -71,24 +69,12 @@ export class BackupJobService {
*/
assertJobHasValidExpressions(type: AnyXoBackupJob['type'], job: UpdateBackupJobBody): void {
if (type === 'backup') {
const { srs, remotes, vms, settings } = job as Extract<UpdateBackupJobBody, { srs?: unknown }>
const { srs, remotes, settings } = job as Extract<UpdateBackupJobBody, { srs?: unknown }>
assertValidExpression('srs', srs)
assertValidExpression('remotes', remotes)
assertValidExpression('vms', vms)
assertValidSettingsExpression(settings, ['healthCheckVmsWithTags', 'fullInterval'])
} else if (type === 'mirrorBackup') {
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)
assertValidSettingsExpression(job.settings, ['healthCheckVmsWithTags', 'vmFilter'])
}
}
@@ -104,47 +90,16 @@ 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 = new Set<XoVm['id']>(extractIdsFromSimplePattern(backupJob.vms))
return vm => vmIds.has(vm.id)
const vmIds: XoVm['id'][] = extractIdsFromSimplePattern(backupJob.vms)
return vmIds.some(id => id === vm.id)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (_) {
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)))
const predicate = createPredicate(backupJob.vms)
return predicate(vm)
}
}
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,19 +6,15 @@ 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'
/**
* 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 = {
// 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 = {
exportRetention?: number
healthCheckVmsWithTags?: XoVm['tags'] | string
healthCheckVmsWithTags?: string[] | string
fullInterval?: number | string
copyRetention?: number
snapshotRetention?: number
@@ -29,17 +25,17 @@ type VmBackupJobScheduleSettings = {
type UnbrandedXoVmBackupJob = Omit<XoVmBackupJob, 'settings' | 'remotes' | 'vms' | 'srs'> & {
remotes?: CMType.IdOr<string> | string
vms: CMType.IdOr<string> | Record<string, unknown> | string
vms: CMType.IdOr<string> | Record<string, unknown>
srs?: CMType.IdOr<string> | string
settings: {
'': XoVmBackupJobGeneralSettings
[scheduleId: string]: VmBackupJobScheduleSettings | undefined
[scheduleId: string]: UnbrandedXoVmBackupJobScheduleSettings | undefined
}
}
export type UnbrandXoVmBackupJob = Unbrand<UnbrandedXoVmBackupJob>
type UnbrandedXoMetadataBackupJob = Omit<XoMetadataBackupJob, 'settings' | 'pools' | 'remotes'> & {
pools?: CMType.IdOr<string> | string
pools?: CMType.IdOr<string>
remotes: CMType.IdOr<string>
settings: {
''?: XoMetadataBackupJobGeneralSettings
@@ -48,23 +44,21 @@ type UnbrandedXoMetadataBackupJob = Omit<XoMetadataBackupJob, 'settings' | 'pool
}
export type UnbrandXoMetadataBackupJob = Unbrand<UnbrandedXoMetadataBackupJob>
/**
* Same as VmBackupJobScheduleSettings
*/
type MirrorBackupJobScheduleSettings = {
// 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 = {
exportRetention?: number
healthCheckVmsWithTags?: XoVm['tags'] | string
healthCheckVmsWithTags?: string[] | string
vmFilter?: string
healthCheckSr?: string
[key: string]: unknown
}
type UnbrandedXoMirrorBackupJob = Omit<XoMirrorBackupJob, 'settings' | 'remotes' | 'filter'> & {
type UnbrandedXoMirrorBackupJob = Omit<XoMirrorBackupJob, 'settings' | 'remotes'> & {
remotes: CMType.IdOr<string>
filter?: { vm: { uuid: { __or: string[] } } } | null
settings: {
'': XoMirrorBackupGeneralSettings
[scheduleId: string]: MirrorBackupJobScheduleSettings | undefined
[scheduleId: string]: UnbrandedXoMirrorBackupScheduleSettings | undefined
}
}
export type UnbrandXoMirrorBackupJob = Unbrand<UnbrandedXoMirrorBackupJob>

View File

@@ -13,7 +13,6 @@ import { mcpGateMiddleware } from './middlewares/mcp-gate.middleware.mjs'
import { type OpenAPIV3 } from 'openapi-types'
import { createExternalRouter, sendObjects } from './router/external-router.mjs'
import { BASE_URL } from './helpers/utils.helper.mjs'
import { rejectCrossSiteMutation } from './middlewares/csrf.middleware.mjs'
export { sendObjects }
@@ -56,7 +55,6 @@ export default function setupRestApi(express: Express, xoApp: XoApp) {
express.use(BASE_URL, setupApiContext(xoApp))
express.use(BASE_URL, logMiddleware)
express.use(BASE_URL, mcpGateMiddleware)
express.use(BASE_URL, rejectCrossSiteMutation)
RegisterRoutes(express)

View File

@@ -9,7 +9,6 @@ import type { AuthenticatedRequest } from '../helpers/helper.type.mjs'
import { iocContainer } from '../ioc/ioc.mjs'
import { RestApi } from '../rest-api/rest-api.mjs'
import { ACL_MIDDLEWARE_NAME } from './acl.middleware.mjs'
import { parseBasicCredentials } from './basic-auth.helper.mjs'
import type { SecurityName } from '@vates/types'
const log = createLogger('xo:rest-api:authentication')
@@ -74,7 +73,7 @@ export function setupApiContext(xoApp: XoApp) {
return next(new ApiError('Malformed Authorization header', 400))
}
const { username, password } = parseBasicCredentials(encoded)
const [username, password] = Buffer.from(encoded, 'base64').toString().split(':')
Object.assign(credentials, { username, password, otp: query.otp })
res.locals.authType = 'basic'
}

View File

@@ -1,14 +0,0 @@
/**
* Extracts the credentials from the base64 payload of a `Authorization: Basic` header.
*
* Per RFC 7617 §2, the user-id cannot contain a colon but the password can: split on the
* first colon only and keep the remainder as the password.
*/
export function parseBasicCredentials(encoded: string): { username: string; password: string | undefined } {
const decoded = Buffer.from(encoded, 'base64').toString()
const index = decoded.indexOf(':')
if (index === -1) {
return { username: decoded, password: undefined }
}
return { username: decoded.slice(0, index), password: decoded.slice(index + 1) }
}

View File

@@ -1,25 +0,0 @@
import assert from 'node:assert/strict'
import { describe, it } from 'node:test'
import { parseBasicCredentials } from './basic-auth.helper.mjs'
const encode = (value: string) => Buffer.from(value).toString('base64')
describe('parseBasicCredentials()', () => {
it('splits username and password', () => {
assert.deepEqual(parseBasicCredentials(encode('user:pass')), { username: 'user', password: 'pass' })
})
it('keeps colons found in the password', () => {
assert.deepEqual(parseBasicCredentials(encode('user:a:b')), { username: 'user', password: 'a:b' })
assert.deepEqual(parseBasicCredentials(encode('user::')), { username: 'user', password: ':' })
})
it('supports an empty password', () => {
assert.deepEqual(parseBasicCredentials(encode('user:')), { username: 'user', password: '' })
})
it('has no password when there is no colon', () => {
assert.deepEqual(parseBasicCredentials(encode('user')), { username: 'user', password: undefined })
})
})

View File

@@ -1,31 +0,0 @@
import type { NextFunction, Response, Request } from 'express'
import { ApiError } from '../helpers/error.helper.mjs'
const SAFE_METHODS = new Set(['GET', 'HEAD', 'OPTIONS'])
function isCrossSite(req: Request): boolean {
const secFetchSite = req.headers['sec-fetch-site']
if (secFetchSite !== undefined) {
return secFetchSite === 'cross-site'
}
const { origin } = req.headers
if (origin !== undefined) {
try {
return new URL(origin).host !== req.headers.host
} catch (error) {
return true
}
}
return false
}
export function rejectCrossSiteMutation(req: Request, res: Response, next: NextFunction) {
// res.locals.authType is setup by authentication.middleware#setupApiContext
if (!SAFE_METHODS.has(req.method) && res.locals.authType === 'token' && isCrossSite(req)) {
return next(new ApiError('cross-site request rejected', 403))
}
next()
}

View File

@@ -1,78 +0,0 @@
import assert from 'node:assert/strict'
import { describe, it } from 'node:test'
import { Request, Response } from 'express'
import { ApiError } from '../helpers/error.helper.mjs'
import { rejectCrossSiteMutation } from './csrf.middleware.mjs'
const run = (method: string, opts: { authType?: 'token' | 'basic'; headers?: Request['headers'] }) => {
const req = { method, headers: opts.headers ?? {} } as Request
const res = { locals: { authType: 'authType' in opts ? opts.authType : 'token' } } as unknown as Response
let next: unknown
rejectCrossSiteMutation(req, res, (err?: unknown) => {
next = err
})
return next
}
const UNSAFE = ['POST', 'PUT', 'PATCH', 'DELETE']
describe('rejectCrossSiteMutation', () => {
describe('lets through', () => {
it('a safe method, even cross-site with a cookie', () => {
assert.equal(run('GET', { headers: { 'sec-fetch-site': 'cross-site' } }), undefined)
})
for (const method of UNSAFE) {
it(`${method} authenticated by basic, even cross-site`, () => {
assert.equal(run(method, { authType: 'basic', headers: { 'sec-fetch-site': 'cross-site' } }), undefined)
})
it(`${method} unauthenticated, even cross-site`, () => {
assert.equal(run(method, { authType: undefined, headers: { 'sec-fetch-site': 'cross-site' } }), undefined)
})
it(`${method} cookie + Sec-Fetch-Site same-origin`, () => {
assert.equal(run(method, { headers: { 'sec-fetch-site': 'same-origin' } }), undefined)
})
it(`${method} cookie + Sec-Fetch-Site same-site`, () => {
assert.equal(run(method, { headers: { 'sec-fetch-site': 'same-site' } }), undefined)
})
it(`${method} cookie + Sec-Fetch-Site none`, () => {
assert.equal(run(method, { headers: { 'sec-fetch-site': 'none' } }), undefined)
})
it(`${method} cookie + no metadata (xo-cli, curl)`, () => {
assert.equal(run(method, { headers: {} }), undefined)
})
it(`${method} cookie + Origin matches Host`, () => {
assert.equal(run(method, { headers: { origin: 'https://xo.example.com', host: 'xo.example.com' } }), undefined)
})
it(`${method} cookie: Sec-Fetch-Site wins over a mismatching Origin`, () => {
assert.equal(
run(method, {
headers: { 'sec-fetch-site': 'same-origin', origin: 'https://evil.com', host: 'xo.example.com' },
}),
undefined
)
})
}
})
describe('rejects (403)', () => {
const assertRejected = (error: unknown) => {
assert.ok(error instanceof ApiError)
assert.equal((error as ApiError).status, 403)
}
for (const method of UNSAFE) {
it(`${method} cookie + Sec-Fetch-Site cross-site`, () => {
assertRejected(run(method, { headers: { 'sec-fetch-site': 'cross-site' } }))
})
it(`${method} cookie + Origin host != Host`, () => {
assertRejected(run(method, { headers: { origin: 'https://evil.com', host: 'xo.example.com' } }))
})
it(`${method} cookie + malformed Origin (fail closed)`, () => {
assertRejected(run(method, { headers: { origin: 'null', host: 'xo.example.com' } }))
})
}
})
})

View File

@@ -27,9 +27,3 @@ 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,8 +1,10 @@
import {
Body,
Example,
Extension,
Get,
Middlewares,
Patch,
Path,
Query,
Request,
@@ -13,28 +15,26 @@ 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 { XoApp, XoProxy } from '@vates/types'
import type { XoProxy, XoVm } from '@vates/types'
import { forbiddenOperation } from 'xo-common/api-errors.js'
import { acl } from '../middlewares/acl.middleware.mjs'
import { acl, actionFromBody } from '../middlewares/acl.middleware.mjs'
import { ApiError } from '../helpers/error.helper.mjs'
import {
badRequestResp,
forbiddenOperationResp,
internalServerErrorResp,
invalidParameters,
noContentResp,
notFoundResp,
proxyUnreachableResp,
unauthorizedResp,
type Unbrand,
} from '../open-api/common/response.common.mjs'
import {
partialProxies,
proxy,
proxyHealth,
proxyIds,
proxyApplianceUpdaterState,
} from '../open-api/oa-examples/proxy.oa-example.mjs'
import { partialProxies, proxy, proxyHealth, proxyIds } 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'
@@ -154,33 +154,51 @@ export class ProxyController extends XoController<XoProxy> {
}
/**
* Returns the state of the proxy appliance updater (e.g. `xoa-up-to-date`, or a state ending with `-upgrade-needed`)
* Updates a proxy
*
* 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.
* Set `address` or `vmUuid` to `null` to remove it.
*
* Required privilege:
* - resource: proxy, action: read
* Only an administrator can change `address` or `vmUuid`
*
* Required privileges:
* - resource: proxy, action: update (grants all fields)
* - resource: proxy, action: update:name (if name is passed)
*
* @example id "e625ea0c-a876-405a-b838-109d762efe88"
* @example body { "name": "My proxy" }
*/
@Example(proxyApplianceUpdaterState)
@Extension('x-mcp-exposure', 'allow')
@Get('{id}/appliance_updater_state')
@Middlewares(
@Extension('x-mcp-exposure', 'confirm')
@Patch('{id}')
@Middlewares([
json(),
acl({
resource: 'proxy',
action: 'read',
action: actionFromBody<'proxy'>('update:name'),
objectId: 'params.id',
getObject: ({ restApi }) => restApi.xoApp.getProxy,
})
)
@SuccessResponse(200, 'OK')
}),
])
@SuccessResponse(noContentResp.status, noContentResp.description)
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
@Response(notFoundResp.status, notFoundResp.description)
@Response(invalidParameters.status, invalidParameters.description)
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
@Response(proxyUnreachableResp.status, proxyUnreachableResp.description)
getProxyApplianceUpdaterState(@Path() id: string): ReturnType<XoApp['getProxyApplianceUpdaterState']> {
return callProxy(this.restApi.xoApp.getProxyApplianceUpdaterState(id as XoProxy['id']))
async updateProxy(
@Path() id: string,
@Body() body: { address?: string | null; name?: string; vmUuid?: string | null }
): Promise<void> {
const user = this.restApi.getCurrentUser()
if (user.permission !== 'admin' && (body.address !== undefined || body.vmUuid !== undefined)) {
throw forbiddenOperation('update proxy', 'only an administrator can change address or vmUuid')
}
if (typeof body.vmUuid === 'string') {
this.restApi.getObject<XoVm>(body.vmUuid as XoVm['id'], 'VM')
}
await this.restApi.xoApp.updateProxy(id as XoProxy['id'], {
...body,
vmUuid: body.vmUuid as XoVm['id'] | null | undefined,
})
}
}

View File

@@ -1,69 +1,112 @@
import assert from 'node:assert/strict'
import { describe, it } from 'node:test'
import { forbiddenOperation } from 'xo-common/api-errors.js'
import { ApiError } from '../helpers/error.helper.mjs'
import { ProxyController } from './proxy.controller.mjs'
import type { RestApi } from '../rest-api/rest-api.mjs'
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>) {
function createController(checkProxyHealth: (id: string) => Promise<void>) {
const calls: unknown[] = []
const record =
(method: string) =>
async (...args: unknown[]) => {
calls.push([method, ...args])
return result()
}
const restApi = {
xoApp: {
checkProxyHealth: record('checkProxyHealth'),
getProxyApplianceUpdaterState: record('getProxyApplianceUpdaterState'),
checkProxyHealth: async (id: string) => {
calls.push(['checkProxyHealth', id])
return checkProxyHealth(id)
},
},
} as unknown as RestApi
const controller = new ProxyController(restApi)
return { calls, controller }
}
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)
const proxyId = 'e625ea0c-a876-405a-b838-109d762efe88'
assert.deepEqual(await controller[method](proxyId), expected)
assert.deepEqual(calls, [[xoAppMethod, proxyId]])
})
describe('ProxyController.getProxyHealth', () => {
it('forwards the id and returns success when the proxy is reachable', async () => {
const { calls, controller } = createController(async () => {})
for (const unreachableError of unreachableErrors) {
it(`throws a 502 ApiError on "${unreachableError.message}"`, async () => {
const { controller } = createController(async () => {
throw unreachableError
})
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)
})
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' })
})
await assert.rejects(
controller.getProxyHealth(proxyId),
error => error instanceof ApiError && error.status === 502 && error.message === 'Proxy unreachable'
)
})
it('rethrows unrelated errors unchanged', async () => {
const unrelatedError = new Error('500 Internal Server Error')
const { controller } = createController(async () => {
throw unrelatedError
})
await assert.rejects(controller.getProxyHealth(proxyId), error => error === unrelatedError)
})
})
const vmUuid = '3d0c7bd6-8b7e-4b2a-9c1f-6f0e5d4c3b2a'
function createUpdateController({ permission = 'admin' }: { permission?: string } = {}) {
const calls: unknown[] = []
const restApi = {
getCurrentUser: () => ({ id: 'user-id', permission }),
getObject: (...args: unknown[]) => {
calls.push(['getObject', ...args])
},
xoApp: {
updateProxy: async (...args: unknown[]) => {
calls.push(['updateProxy', ...args])
},
},
} as unknown as RestApi
const controller = new ProxyController(restApi)
return { calls, controller }
}
describe('ProxyController.updateProxy', () => {
it('forwards the body to updateProxy after checking the VM exists', async () => {
const { calls, controller } = createUpdateController()
const body = { address: '192.168.1.10:443', name: 'My proxy', vmUuid }
await controller.updateProxy(proxyId, body)
assert.deepEqual(calls, [
['getObject', vmUuid, 'VM'],
['updateProxy', proxyId, body],
])
})
it('forwards null to remove address or vmUuid', async () => {
const { calls, controller } = createUpdateController()
await controller.updateProxy(proxyId, { address: null, vmUuid: null })
assert.deepEqual(calls, [['updateProxy', proxyId, { address: null, vmUuid: null }]])
})
it('lets a non-admin change the name', async () => {
const { calls, controller } = createUpdateController({ permission: 'none' })
await controller.updateProxy(proxyId, { name: 'My proxy' })
assert.deepEqual(calls, [['updateProxy', proxyId, { name: 'My proxy', vmUuid: undefined }]])
})
for (const body of [{ address: 'attacker:443' }, { address: null }, { vmUuid }, { vmUuid: null }]) {
it(`refuses ${JSON.stringify(body)} to a non-admin`, async () => {
const { calls, controller } = createUpdateController({ permission: 'none' })
await assert.rejects(controller.updateProxy(proxyId, { name: 'My proxy', ...body }), error =>
forbiddenOperation.is(error)
)
assert.deepEqual(calls, [])
})
}
})

View File

@@ -33,6 +33,7 @@ import type {
} from '@vates/types'
import { SUPPORTED_ACTIONS_BY_RESOURCE, type SupportedActions } from '@xen-orchestra/acl'
import { invalidParameters } from 'xo-common/api-errors.js'
import { acl, actionsFromBody } from '../middlewares/acl.middleware.mjs'
import { AlarmService } from '../alarms/alarm.service.mjs'
@@ -244,7 +245,11 @@ export class VdiController extends XapiXoController<XoVdi> {
await $xapi.call('VDI.set_name_description', $ref, name_description)
}
if (size !== undefined) {
await $xapi.VDI_resize($ref, size)
const currentSize = this.getObject(id as XoVdi['id']).size
if (size < currentSize) {
throw invalidParameters(`cannot set new size (${size}) below the current size (${currentSize})`)
}
await $xapi.callAsync('VDI.resize', $ref, size)
}
}

View File

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

@@ -1,13 +1,13 @@
{
"license": "ISC",
"private": false,
"version": "1.4.0",
"version": "1.2.0",
"name": "@xen-orchestra/vmware-explorer",
"description": "Reads the VMs and the disks of an ESXi host or a vCenter",
"dependencies": {
"@vates/async-each": "^1.0.3",
"@vates/node-vsphere-soap": "^2.2.1",
"@xen-orchestra/log": "^1.0.0",
"@vates/node-vsphere-soap": "^2.2.0",
"@xen-orchestra/log": "^0.7.2",
"promise-toolbox": "^0.21.0",
"undici": "^7.8.0"
},

View File

@@ -299,21 +299,6 @@ dependencies = [
"miniz_oxide",
]
[[package]]
name = "foreign-types"
version = "0.3.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1"
dependencies = [
"foreign-types-shared",
]
[[package]]
name = "foreign-types-shared"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b"
[[package]]
name = "fs_extra"
version = "1.3.0"
@@ -475,59 +460,12 @@ version = "1.70.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
[[package]]
name = "openssl"
version = "0.10.82"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "4de8111e94a56adca7ebfe6c365b6d42f99deb69b74b6becacd4204e2f193aa2"
dependencies = [
"bitflags",
"cfg-if",
"foreign-types",
"libc",
"openssl-macros",
"openssl-sys",
]
[[package]]
name = "openssl-macros"
version = "0.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c"
dependencies = [
"proc-macro2",
"quote",
"syn 2.0.119",
]
[[package]]
name = "openssl-probe"
version = "0.2.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7c87def4c32ab89d880effc9e097653c8da5d6ef28e6b539d313baaacfbafcbe"
[[package]]
name = "openssl-src"
version = "300.6.1+3.6.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "46eb8fb9fb3b61ce1c0f8a026c4c1a0714d3a9e138e7fbde78753ce2babc3846"
dependencies = [
"cc",
]
[[package]]
name = "openssl-sys"
version = "0.9.118"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "19c413d6ec9ebaf5e1c829d355cb3e9f783778d700f135be0921d52fce3c60ae"
dependencies = [
"cc",
"libc",
"openssl-src",
"pkg-config",
"vcpkg",
]
[[package]]
name = "pkg-config"
version = "0.3.34"
@@ -863,21 +801,13 @@ version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]]
name = "vcpkg"
version = "0.2.15"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
[[package]]
name = "vectura"
version = "0.3.0"
version = "0.2.1"
dependencies = [
"aws-lc-rs",
"clap",
"flate2",
"openssl",
"openssl-src",
"quick-xml",
"rcgen",
"rustls",

View File

@@ -1,6 +1,6 @@
[package]
name = "vectura"
version = "0.3.0"
version = "0.2.1"
edition = "2024"
description = "Standalone client for VMware's NFC disk-read protocol"
# The license of the Xen Orchestra application components, see LICENSE.md at
@@ -15,20 +15,12 @@ publish = false
aws-lc-rs = "1.18.1"
clap = { version = "4.6.6", features = ["derive"] }
flate2 = { version = "1.1.10", default-features = false, features = ["rust_backend"] }
openssl = { version = "0.10.82", features = ["vendored"] }
quick-xml = "0.42.0"
rustls = "0.23"
rustls-native-certs = "0.8.4"
rustls-pki-types = "1.15.1"
thiserror = "2.0.20"
[build-dependencies]
# Not used by a build script: the entry only turns on a feature of the
# OpenSSL build `openssl` asks for. Without DSO support OpenSSL cannot load
# an engine or a provider from a file at run time, whatever a configuration
# file or the environment asks.
openssl-src = { version = "300.6.1", features = ["no-dso"] }
[dev-dependencies]
rcgen = { version = "0.14.10", default-features = false, features = ["aws_lc_rs"] }
serde_json = "1.0.151"

View File

@@ -117,8 +117,7 @@ scripts/build.sh .
```
The build is reproducible: `scripts/build.sh` keeps the paths of the machine
out of the binary, builds under `/tmp/vectura-build`, a path OpenSSL writes
into the binary, and refuses any zig or cargo-zigbuild but the versions the
out of the binary and refuses any zig or cargo-zigbuild but the versions the
workflow installs. Linux x86_64 machines build the same binary; macOS and
aarch64 hosts are untested.
@@ -129,8 +128,3 @@ and Ubuntu 20.04. It needs [zig](https://ziglang.org/download/) 0.16.0 and:
```sh
cargo install --locked cargo-zigbuild@0.23.4
```
OpenSSL is compiled from its sources, which takes perl, to run its
`Configure` script, and make. Debian and Ubuntu install both with
`build-essential`; on Fedora and RHEL, `perl-core` brings the perl modules
`Configure` loads.

View File

@@ -29,10 +29,8 @@ unmaintained = "workspace"
unsound = "workspace"
[licenses]
# What may enter the binary. The OpenSSL license is on the list for
# aws-lc-sys, which the default rustls crypto provider builds on; nothing else
# needs it. The OpenSSL 3 sources the RSA key exchange fallback links are
# under Apache-2.0.
# What may enter the binary. OpenSSL is on the list for aws-lc-sys, which the
# default rustls crypto provider builds on; nothing else needs it.
allow = [
"0BSD",
"Apache-2.0",

View File

@@ -71,14 +71,10 @@ thirty minutes, makes the ordinary run not need one.
## Why rustls, synchronous I/O and two threads
- **rustls with aws-lc-rs, and OpenSSL for one handshake.** The TLS
stack is in the binary, with no system library to match at run time
and no shell out. ESXi 6.0, 7 and 8 hosts negotiate TLS 1.2 with ECDHE
and AES-GCM on both ports, which rustls speaks. The data port of some
ESXi 6.5 hosts accepts RSA key exchange alone, which rustls leaves out
on purpose, so a copy of OpenSSL is compiled in and used for that port
when the host has refused rustls, and for nothing else. The security
model says what such a session gives up.
- **rustls with aws-lc-rs, no OpenSSL.** One TLS stack, in the binary,
with no system library to match at run time and no shell out. ESXi 6.0,
7 and 8 hosts negotiate TLS 1.2 with ECDHE and AES-GCM on both ports,
which rustls speaks.
- **Synchronous `std` I/O, no async runtime.** A run is two sockets and
two pipes. Two threads joined by a bounded channel cover that with
back pressure for free and nothing to schedule. An async runtime would

View File

@@ -64,39 +64,6 @@ presenting the same certificate. There is no flag to accept or refuse
this: a 6.x host is served like any other, and the management port, which
carries the password, is verified the same way on every host.
The data port of some ESXi 6.5 hosts accepts no ECDHE suite. When the
host answers the first handshake with a `handshake_failure` alert, and
only then, Vectura connects again and offers TLS 1.2 with RSA key
exchange and AES-GCM. The certificate is judged by its thumbprint, compared
with the ticket's once the handshake completes. By then the client has
sent `ClientKeyExchange` and `Finished`, but no ticket and no application
data go out before the check, and the second session must present the
same certificate. With RSA key exchange the host signs
nothing: it proves it holds the private key by decrypting the secret the
client sent, which the `Finished` messages confirm, so the pinned
certificate still authenticates it. Two things are given up, on such a
host and on port 902 only:
- **Forward secrecy.** With RSA key exchange the session keys are sent
encrypted to the host's key. Whoever records the session and later
obtains that private key can read the disk that was carried.
- **The choice of suites.** An attacker on the network can forge the
alert, which is not authenticated, and so make Vectura offer RSA key
exchange to a host that has ECDHE. They gain nothing at once, since
the handshake still needs the host's private key, but the session
they record loses forward secrecy.
There is no flag to forbid the retry, as there is none for the 6.x
dialect. The transcript says when it happened, and the management port,
which carries the password, never uses it.
OpenSSL is in the binary, built without the means to load code from a
file. When the retry opens it, it still reads its configuration file if
one exists: `/usr/local/ssl/openssl.cnf`, or the file `OPENSSL_CONF`
names. Vectura sets the protocol version and the two suites itself after
that. Whoever can write that file or set the environment of the process
is already trusted with the password.
An attacker who controls the network between Vectura and the host sees
TLS on 443 and TLS on 902, and can complete neither handshake without the
host's private key. What they can do is drop the connection, which ends

View File

@@ -27,7 +27,6 @@ are most likely to meet, what each means and what to do.
| Message | Meaning | Do |
| ---------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------- |
| `host refused every supported TLS suite (ECDHE, then RSA key exchange with AES-GCM)` | The data port accepts neither ECDHE nor RSA key exchange with AES-GCM. | Not supported: Vectura offers nothing weaker. |
| `greeting: the host does not announce "NFCSSL supported"; announced: [...]` | The host cannot carry the disk inside a second TLS session. | Not seen on a supported host. `--transport nfc` would carry the disk in clear text; understand what that means before using it. |
| `open "[ds] vm/x.vmdk": the host reported error 11: NfcAioProcessOpenFileMsg: permission check failed ...` | The ticket covers the files of the virtual machine `--vm-id` names, and this path is not one of them, or the account may not read it. | Check `--vm-id` against `--disk`. |
| `... Thin/TBZ/Sparse disks cannot be opened in multiwriter mode` | The disk is the link a running virtual machine writes to. | Power the virtual machine off, or take a snapshot and read a base link. |

View File

@@ -9,7 +9,7 @@ documentation is cited where it states the limit.
| Requirement | Detail |
| ---------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| ESXi 6.x, 7.x or 8.x directly; 6.5, 6.7, 7.x or 8.x through a vCenter | With a vCenter, `--host` names the vCenter and the ticket names the ESXi host that holds the virtual machine; the data port is opened on that host. |
| ESXi 7.x or 8.x, directly or through a vCenter; ESXi 6.x directly | With a vCenter, `--host` names the vCenter and the ticket names the ESXi host that holds the virtual machine; the data port is opened on that host. |
| `SHA256 supported` in the data port's greeting, for the modern dialect | The ticket dialogue confirms the data port's certificate by its SHA-256. A host that does not announce it, ESXi 6.x, is read in the [legacy dialect](#esxi-6x-hosts). |
| `NFCSSL supported` in the greeting, for `--transport nfcssl` | Without it, only `--transport nfc` can run, in clear text. Every host measured, 6.0 included, announces it. |
| Port 443 and port 902 reachable | 443 for the management calls, on the vCenter when there is one; 902 for the greeting, the ticket dialogue and the disk, always on the ESXi host. |
@@ -31,8 +31,7 @@ NBD export are the same; the disk session differs:
| Compression | None, whatever `--compression` says: each read comes back as stored. | Measured on ESXi 6.0 |
| Capacity | Not in the open reply. Found by 512-byte reads from the size the disk's geometry gives: 26 reads for an 8 GiB disk, 6 for a 24 GiB disk. | Measured on ESXi 6.0 |
| Throughput | 3 to 5 MiB/s per process over a link with a 30 ms round trip. | Measured on ESXi 6.0 |
| Versions | ESXi 6.0.0, reached directly. ESXi 6.5 and 6.7, through a 6.x vCenter. | |
| Ticket of a vCenter | Known to vpxa, the vCenter's agent on the host, not to hostd: the dialogue asks `PROXY vpxa-nfcssl`, which hostd would drop as `session ticket ... not found`. | ESXi 6.5 and 6.7 |
| Versions | ESXi 6.0.0, reached directly. ESXi 6.5, 6.7 and a 6.x vCenter are untested. | |
Several `serve` processes can read the same disk at once, each over its
own session: two processes read about 9 MiB/s over the link above, where
@@ -87,12 +86,11 @@ A run longer than the session lifetime serves the whole disk and exits
## TLS
| Item | Value | Source |
| ---------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
| Versions the hosts negotiate | TLS 1.2 on both ports, `TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384` or the AES-128 variant | Measured; the vSphere 7 and 8 documentation on the default cipher suites |
| RSA key exchange on 902 | Offered only after the host refused the first handshake with a `handshake_failure` alert: TLS 1.2, `TLS_RSA_WITH_AES_256_GCM_SHA384` or the AES-128 variant, no forward secrecy. Never on 443. | Vectura; reported on an ESXi 6.5 U3 host, not measured |
| Certificate on 902 | The same certificate as on 443 on every host measured | Measured |
| Data port verification | The SHA-1 thumbprint in the ticket, the SHA-256 confirmed in the dialogue on ESXi 7 and later, and the second TLS session must present the certificate of the first | Vectura |
| Item | Value | Source |
| ---------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------ |
| Versions the hosts negotiate | TLS 1.2 on both ports, `TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384` or the AES-128 variant | Measured; the vSphere 7 and 8 documentation on the default cipher suites |
| Certificate on 902 | The same certificate as on 443 on every host measured | Measured |
| Data port verification | The SHA-1 thumbprint in the ticket, the SHA-256 confirmed in the dialogue on ESXi 7 and later, and the second TLS session must present the certificate of the first | Vectura |
## Throughput, measured

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