Compare commits

..

6 Commits

Author SHA1 Message Date
KAN-vates
16015b5fae test(qa-test): add a qa:network suite for PATCH /rest/v0/networks/{id}
The new route had unit tests only. qa:network runs it against a real XO on a
throwaway internal network of REFERENCE_VM_ID's pool: each field round-trips
through GET, the NBD purposes swap, a refused body (bad MTU, nbd with
insecureNbd, no field) changes nothing, an unknown network answers 404, and a
role holding only update:name_label and update:nbd gets 403 on MTU and on
nbd: true, which also needs update:insecureNbd. The create routes are checked
with the PATCH field names too.

A PATCH answers before XO's object cache has the XAPI event, so a GET right
after it still returns the old values: the suite reads until the expected
fields show, for 10 s at most.
2026-12-04 10:36:18 +01:00
KAN-vates
576d0670d5 feat(rest-api): accept the PATCH field names when creating a network
The network create routes take name, description and mtu, while PATCH
/networks/{id} takes the XoNetwork names name_label, name_description and
MTU, so a client had to learn two spellings for one network. The create
routes now accept the XoNetwork names too. normalizeNetworkCreateBody maps
them, in one place, to the names xapi.createNetwork reads. The old names
stay accepted and are marked deprecated, so no client breaks.

A body giving both spellings of one field, or no name at all, is refused
with a 422. The check runs in a middleware before the ACL: a refusal
inside the task would come back as a failed task, not a 422. The ACL then
matches the role's selectors against the normalized body, so a selector
on name still sees the name whichever spelling the client used.
tsoa cannot express "one of", so name and name_label are both optional in
the schema and the check is in the code.
2026-12-03 10:29:42 +01:00
KAN-vates
8eaa4c507a fix(xo-server): roll back network edits when one of their writes fails
editNetwork wrote its fields with a Promise.all, so they ran concurrently. A failure on one
field left the others applied, and the rejection reached the caller before the remaining
writes had ended: a multi-field PATCH /rest/v0/networks/{id}, or network.set, could answer
500 with part of the network already changed.

The writes now run one after the other. Each one that succeeds registers a $defer.onFailure
that restores its previous value: name_label, name_description, the automatic flag, the
default locking mode and the NBD purposes. MTU comes last because changing it replugs every
PIF and VIF, and its rollback replugs them again. On failure the rollbacks run in reverse
order; a rollback that fails itself is logged and the original error is the one rethrown.
2026-12-03 10:29:42 +01:00
KAN-vates
f22c27b863 fix(xo-server): skip the MTU replug when network.editNetwork's MTU is unchanged
editNetwork called network.$setMtu whenever the MTU key was present, even
with the value already set. $setMtu replugs every PIF and VIF, so a client
resending its full state on each update (Terraform) interrupted traffic on
every apply with no change.

editNetwork now calls $setMtu only when the requested MTU differs from the
network's current one. The comparison is numeric (+network.MTU), as in
xapi-object-to-xo. The shared Network.setMtu in @xen-orchestra/xapi is
unchanged.
2026-12-03 10:29:42 +01:00
KAN-vates
3e8658c906 feat(rest-api): add PATCH /rest/v0/networks/{id}
The REST API could read a network but not change it: the network controller had no PATCH
route, so a network's name, description, MTU, NBD purposes, automatic flag and default
locking mode could only be set through JSON-RPC network.set. The route is the REST
counterpart of network.set. It has one ACL action per field, update:name_label,
update:MTU and so on, named after the XoNetwork fields GET returns, so a client can send
back what it read. An action is checked only when its field is in the body. nbd: true also
removes the insecure_nbd purpose, and insecureNbd: true the nbd one, so each also requires
the other's action. A body with none of the fields is refused with a 422 before the ACL
runs, so it neither passes unchecked nor tells an existing network from a missing one.

The body is forwarded to Xapi.editNetwork, which holds the NBD rules shared with
JSON-RPC: copying them into rest-api would let the two drift. Changing the MTU unplugs
and replugs the network's interfaces, so the route is exposed to MCP with confirm.
2026-12-03 10:29:42 +01:00
KAN-vates
7b7fab8366 refactor(xo-server): share network.set's logic as Xapi editNetwork
network.set held the whole edit in the JSON-RPC method, where nothing
else could reach it. The REST route for PATCH /networks/{id} needs the
same edit, so the logic moves into Xapi.editNetwork, next to editVif,
and network.set calls it. JSON-RPC behaviour does not change.

The NBD rules (nbd and insecureNbd are exclusive, and a false value only
removes its own purpose) move with the edit. They must not be copied
into rest-api: they are subtle, and two copies would drift apart. The
mutual-exclusion check runs before any XAPI call, so a refused request
changes nothing.
2026-12-03 10:27:11 +01:00
371 changed files with 3559 additions and 9939 deletions

View File

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

View File

@@ -101,6 +101,21 @@ export interface EditVifProps {
txChecksumming?: boolean
}
/**
* Properties accepted by {@link Xapi.editNetwork}: the fields of `XoNetwork` it can change.
*
* `nbd` and `insecureNbd` cannot both be true: `editNetwork` throws `invalidParameters` when they are.
*/
export interface EditNetworkProps {
automatic?: boolean
defaultIsLocked?: boolean
insecureNbd?: boolean
MTU?: number
name_description?: string
name_label?: string
nbd?: boolean
}
export type XcpPatches = {
changelog?: {
author: string
@@ -335,6 +350,7 @@ export interface Xapi {
checkLimits?: (limits: Record<string, number>, vm: XenApiVmWrapped) => Promise<void>
): Promise<void>
editVif(id: XoVif['id'], props: EditVifProps): Promise<void>
editNetwork(id: XoNetwork['id'], props: EditNetworkProps): Promise<void>
startVm(
id: XoVm['id'],
opts?: {
@@ -481,8 +497,6 @@ export interface Xapi {
MAC?: string
}
): Promise<XenApiVif['$ref']>
/** ejects all removable media (e.g. CDs) then flags the VM as a template */
VM_convertToTemplate(vmRef: XenApiVm['$ref']): Promise<void>
VM_createCloudInitConfig(
vmRef: XenApiVm['$ref'],
cloudConfig: string,

View File

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

View File

@@ -5,5 +5,12 @@ export default {
update: {
tags: true,
other_config: true,
automatic: true,
defaultIsLocked: true,
insecureNbd: true,
MTU: true,
name_description: true,
name_label: true,
nbd: true,
},
}

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -5,7 +5,6 @@ import { importIncrementalVm } from './_incrementalVm.mjs'
import { liveMountXapiLabels } from './liveMountXapiLabels.mjs'
import { destroyOnAbort } from './_destroyOnAbort.mjs'
import { watchStreamSize } from './_watchStreamSize.mjs'
import { meterDisk, SourceReadTask } from './_SourceReadTask.mjs'
import { decorateClass } from '@vates/decorate-with'
import { Task } from '@vates/task'
import { createLogger } from '@xen-orchestra/log'
@@ -426,7 +425,6 @@ export class ImportVmBackup {
throw new Error('live mounting a disk is only supported when restoring an incremental backup')
}
backup = await adapter.readFullVmBackup(metadata)
sizeContainer.readTask = new SourceReadTask('read')
watchStreamSize(backup, sizeContainer)
// the restore stops once aborted (e.g. the health check of an aborted backup): a full backup is a stream that
@@ -442,9 +440,6 @@ export class ImportVmBackup {
// releases them, a successful one hands their ids back to the caller
$defer.onFailure(() => this.#releaseLiveMounts())
backup = await this._decorateIncrementalVmMetadata()
for (const key in backup.disks) {
backup.disks[key] = meterDisk(backup.disks[key], backup.vdis[key])
}
}
return Task.run(

View File

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

View File

@@ -38,7 +38,6 @@ import { watchStreamSize } from './_watchStreamSize.mjs'
import { RemoteVhdDisk, openDiskChain, openDisposableDisk } from '@xen-orchestra/backup-archive/disks'
import { toVhdStream, writeToVhdDirectory } from 'vhd-lib/disk-consumer/index.mjs'
import { ReadAhead } from '@xen-orchestra/disk-transform'
import { getVmBackupSizeOnDisk } from './formatVmBackups.mjs'
export const DIR_XO_CONFIG_BACKUPS = 'xo-config-backups'
@@ -688,11 +687,7 @@ export class RemoteAdapter {
return path
}
/**
* `signal` stops the write once aborted: the partial disk is then removed
*
* @returns {Promise<{size: number, sizeOnDisk: number}>}
*/
// `signal` stops the write once aborted: the partial disk is then removed
async writeVhd(path, disk, { signal, validator = noop, writeBlockConcurrency, uuid, parentUuid, parentPath } = {}) {
const handler = this._handler
@@ -724,8 +719,7 @@ export class RemoteAdapter {
checksum: false,
})
await validator(path)
const sizeOnDisk = await this._handler.getSizeOnDisk(path)
return { size, sizeOnDisk }
return size
}
}
@@ -895,11 +889,9 @@ export class RemoteAdapter {
return reduce(
backups,
(prev, backup) => {
const size = Array.isArray(backup)
? this.#computeTotalBackupSizeRecursively(backup).onDisk
: (getVmBackupSizeOnDisk(backup) ?? backup.size)
const _backup = Array.isArray(backup) ? this.#computeTotalBackupSizeRecursively(backup) : backup
return {
onDisk: prev.onDisk + size,
onDisk: prev.onDisk + (_backup.onDisk ?? _backup.size),
}
},
{ onDisk: 0 }

View File

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

View File

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

View File

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

View File

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

View File

@@ -5,7 +5,6 @@ import { FullRemoteWriter } from '../_writers/FullRemoteWriter.mjs'
import { forkStreamUnpipe } from '../_forkStreamUnpipe.mjs'
import { destroyOnAbort } from '../../_destroyOnAbort.mjs'
import { watchStreamSize } from '../../_watchStreamSize.mjs'
import { SourceReadTask } from '../../_SourceReadTask.mjs'
import { AggregatedFullRemoteWriter } from '../_writers/AggregatedFullRemoteWriter.mjs'
import { Task } from '@vates/task'
@@ -27,8 +26,7 @@ export const FullRemote = class FullRemoteVmBackupRunner extends AbstractRemote
for (const metadata of transferList) {
Task.abortSignal?.throwIfAborted()
const stream = this._throttleStream(await this._sourceRemoteAdapter.readFullVmBackup(metadata))
// the backup is read once, whatever the number of writers
const sizeContainer = watchStreamSize(stream, { size: 0, readTask: new SourceReadTask('read') })
const sizeContainer = watchStreamSize(stream)
let checksum
try {
// the unencrypted destinations store the same data as the source: no need to compute their checksum again

View File

@@ -5,7 +5,6 @@ import { forkStreamUnpipe } from '../_forkStreamUnpipe.mjs'
import { FullRemoteWriter } from '../_writers/FullRemoteWriter.mjs'
import { FullXapiWriter } from '../_writers/FullXapiWriter.mjs'
import { watchStreamSize } from '../../_watchStreamSize.mjs'
import { SourceReadTask } from '../../_SourceReadTask.mjs'
import { AbstractXapi } from './_AbstractXapi.mjs'
import { AggregatedFullRemoteWriter } from '../_writers/AggregatedFullRemoteWriter.mjs'
import { AggregatedFullXapiWriter } from '../_writers/AggregatedFullXapiWriter.mjs'
@@ -82,8 +81,7 @@ export const FullXapi = class FullXapiVmBackupRunner extends AbstractXapi {
maxStreamLength += XVA_BLOCK_SIZE * nbBlocks + headersSize
}
// the export is read once, whatever the number of writers
const sizeContainer = watchStreamSize(stream, { size: 0, readTask: new SourceReadTask('read') })
const sizeContainer = watchStreamSize(stream)
const transferStart = Date.now()
await this._callWriters(

View File

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

View File

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

View File

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

View File

@@ -280,7 +280,6 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
vtpms: deltaExport.vtpms,
}
let size = 0
const vhdsSizeOnDisk = {}
await Task.run({ properties: { name: 'transfer' } }, async () => {
// stops the writes once the backup is aborted
const signal = Task.abortSignal
@@ -300,7 +299,7 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
parentPath = relativeFromFile(path, parentDestPath)
}
const { size: transferred, sizeOnDisk } = await adapter.writeVhd(path, disk, {
const transferred = await adapter.writeVhd(path, disk, {
// no checksum for VHDs, because they will be invalidated by
// merges and chains
checksum: false,
@@ -312,7 +311,6 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
parentPath,
})
size += transferred
vhdsSizeOnDisk[diskRef] = sizeOnDisk
},
{
concurrency: settings.diskPerVmConcurrency,
@@ -328,7 +326,6 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
metadataContent.tags = await this.getLongTermRetentionTags(metadataContent)
metadataContent.size = size // @todo return exactly the size written by this writer
metadataContent.vhdsSizeOnDisk = vhdsSizeOnDisk
this._metadataFileName = await adapter.writeVmBackupMetadata(vm.uuid, metadataContent)
// TODO: run cleanup?

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -2,16 +2,8 @@
## **next**
- [VMs] The VMs tables work like in XO 6: side panel, per-VM actions menu, query builder search and bulk actions (PR [#10936](https://github.com/vatesfr/xen-orchestra/pull/10936))
## **0.28.1** (2026/12/04)
- [VM/Network] Add possibility to delete a VIF (PR [#10726](https://github.com/vatesfr/xen-orchestra/pull/10726))
- [Web-Core/VtsErrorModal] Add an optional details log viewer, unified icon (PR [#10536](https://github.com/vatesfr/xen-orchestra/pull/10536))
- [VM/Network] Add a link to the pool network in the VIF side panel and table (PR [#10686](https://github.com/vatesfr/xen-orchestra/pull/10686))
- [VIF] Add a VIF page with general and network information, linked from the VM network table and the VIF side panel (PR [#10686](https://github.com/vatesfr/xen-orchestra/pull/10686))
- [Host] Add possibility to enable SSH on XCP-ng 9 hosts, and to disable it with auto-enable if XAPI goes down. The SSH status is shown in the host dashboard and System tab (PR [#10974](https://github.com/vatesfr/xen-orchestra/pull/10974))
- [Forms] The VM creation and XOA deployment forms show why a field is disabled (PR [#10963](https://github.com/vatesfr/xen-orchestra/pull/10963))
## **0.28.0** (2026/12/01)

View File

@@ -1,6 +1,6 @@
{
"name": "@xen-orchestra/lite",
"version": "0.28.1",
"version": "0.28.0",
"type": "module",
"scripts": {
"dev": "GIT_HEAD=$(git rev-parse HEAD) vite",

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -1,12 +1,14 @@
<template>
<MenuItem
v-tooltip="!isExportable && t('vm-is-running')"
v-tooltip="
vmRefs.length > 0 && !isSomeExportable && t(isSingleAction ? 'vm-is-running' : 'no-selected-vm-can-be-exported')
"
accent="neutral"
:disabled="isDisabled"
icon="action:download"
@click="openExportModal()"
>
{{ t('action:export-vm', 1) }}
{{ t('action:export-vm', isSingleAction ? 1 : 2) }}
</MenuItem>
</template>
@@ -15,6 +17,7 @@ import { useVmExport } from '@/composables/vm-export.composable.ts'
import { areSomeVmOperationAllowed } from '@/libs/vm.ts'
import { VM_OPERATION } from '@/libs/xen-api/xen-api.enums.ts'
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
import MenuItem from '@core/components/menu/MenuItem.vue'
import { useDisabled } from '@core/composables/disabled.composable.ts'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
@@ -22,27 +25,32 @@ import { useOverlay } from '@core/packages/overlay/use-overlay.ts'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { vm } = defineProps<{
vm: XenApiVm
const { vmRefs } = defineProps<{
vmRefs: XenApiVm['$ref'][]
isSingleAction?: boolean
}>()
const { t } = useI18n()
const isExportable = computed(() => areSomeVmOperationAllowed(vm, VM_OPERATION.EXPORT))
const { getByOpaqueRefs } = useVmStore().subscribe()
const isDisabled = useDisabled(() => !isExportable.value)
const isSomeExportable = computed(() =>
getByOpaqueRefs(vmRefs).some(vm => areSomeVmOperationAllowed(vm, VM_OPERATION.EXPORT))
)
const isDisabled = useDisabled(() => !isSomeExportable.value)
const { exportVms } = useVmExport()
const { open: openModal } = useOverlay({
component: () => import('@/components/modals/VmExportModal.vue'),
events: {
onConfirm: compressionType => exportVms([vm.$ref], compressionType),
onConfirm: compressionType => exportVms(vmRefs, compressionType),
onCancel: true,
},
})
function openExportModal() {
return openModal({ props: { count: 1 } })
return openModal({ props: { count: vmRefs.length } })
}
</script>

View File

@@ -0,0 +1,41 @@
<template>
<MenuItem accent="neutral" icon="fa:file-export">
{{ t('action:export') }}
<template #submenu>
<VmActionExportItem :vm-refs="vmRefs" />
<MenuItem
accent="neutral"
icon="fa:code"
@click="exportVmsAsJsonFile(vms, `vms_${new Date().toISOString()}.json`)"
>
{{ t('action:export-table-to', { type: '.json' }) }}
</MenuItem>
<MenuItem
accent="neutral"
icon="fa:file-csv"
@click="exportVmsAsCsvFile(vms, `vms_${new Date().toISOString()}.csv`)"
>
{{ t('action:export-table-to', { type: '.csv' }) }}
</MenuItem>
</template>
</MenuItem>
</template>
<script lang="ts" setup>
import VmActionExportItem from '@/components/vm/VmActionItems/VmActionExportItem.vue'
import { exportVmsAsCsvFile, exportVmsAsJsonFile } from '@/libs/vm.ts'
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
import MenuItem from '@core/components/menu/MenuItem.vue'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const props = defineProps<{
vmRefs: XenApiVm['$ref'][]
}>()
const { t } = useI18n()
const { getByOpaqueRef: getVm } = useVmStore().subscribe()
const vms = computed(() => props.vmRefs.map(getVm).filter((vm): vm is XenApiVm => vm !== undefined))
</script>

View File

@@ -2,30 +2,83 @@
<VtsActionButton
variant="tertiary"
accent="brand"
:busy="isMigratingVms"
:busy="isMigrating"
:disabled="isDisabled"
icon="fa:route"
:hint="migrateVmsErrorMessage"
@click="migrateVms()"
:hint="disabledReason"
@click="openMigrateModal()"
>
{{ t('action:migrate') }}
</VtsActionButton>
</template>
<script lang="ts" setup>
import { useVmMigration } from '@/composables/vm-migration.composable.ts'
import { areSomeVmOperationAllowed, isVmOperationPending } from '@/libs/vm.ts'
import { VM_OPERATION } from '@/libs/xen-api/xen-api.enums.ts'
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import { useVmMigrate } from '@/modules/vm/composables/vm-migrate.composable.ts'
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
import VtsActionButton from '@core/components/action-button/VtsActionButton.vue'
import { useDisabled } from '@core/composables/disabled.composable.ts'
import { KEEP_OVERLAY_OPEN } from '@core/packages/overlay/symbols.ts'
import { useOverlay } from '@core/packages/overlay/use-overlay.ts'
import { reactiveComputed } from '@vueuse/core'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { vm } = defineProps<{
vm: XenApiVm
const { selectedRefs, isSingleAction } = defineProps<{
selectedRefs: XenApiVm['$ref'][]
isSingleAction?: boolean
}>()
const { t } = useI18n()
const { migrateVms, canMigrateVms, isMigratingVms, migrateVmsErrorMessage } = useVmMigrate(() => [vm])
const { getByOpaqueRefs } = useVmStore().subscribe()
const isDisabled = useDisabled(() => !canMigrateVms.value && !isMigratingVms.value)
const isMigratable = computed(() =>
getByOpaqueRefs(selectedRefs).some(vm =>
areSomeVmOperationAllowed(vm, [VM_OPERATION.POOL_MIGRATE, VM_OPERATION.MIGRATE_SEND])
)
)
const isMigrating = computed(() =>
getByOpaqueRefs(selectedRefs).some(vm =>
isVmOperationPending(vm, [VM_OPERATION.POOL_MIGRATE, VM_OPERATION.MIGRATE_SEND])
)
)
const isDisabled = useDisabled(() => !isMigratable.value)
const disabledReason = computed(() =>
selectedRefs.length > 0 && !isMigratable.value
? t(isSingleAction ? 'this-vm-cant-be-migrated' : 'no-selected-vm-can-be-migrated')
: undefined
)
const { selectedHost, availableHosts, isValid, migrate } = useVmMigration(() => selectedRefs)
const { open: openModal } = useOverlay({
component: () => import('@/components/modals/VmMigrateModal.vue'),
events: {
onConfirm: async host => {
selectedHost.value = host
if (!isValid.value) {
return KEEP_OVERLAY_OPEN
}
await migrate()
},
onCancel: true,
},
})
const modalProps = reactiveComputed(() => ({
count: selectedRefs.length,
availableHosts: availableHosts.value,
}))
function openMigrateModal() {
return openModal({ props: modalProps })
}
</script>

View File

@@ -1,9 +1,15 @@
<template>
<VmPowerStateActionButton v-if="!exclude.start" :action="actions.start" />
<MenuItem v-if="canStartOnHost || isStartingOnHost" accent="neutral" :busy="isStartingOnHost" icon="object:host">
<MenuItem accent="neutral" :busy="isStartingOnHost" :disabled="!areVmsHalted" icon="object:host">
{{ t('action:start-on-host') }}
<template #submenu>
<MenuItem v-for="host in hosts" :key="host.$ref" accent="neutral" icon="object:host" @click="startOn(host)">
<MenuItem
v-for="host in hosts"
:key="host.$ref"
accent="neutral"
icon="object:host"
@click="xenApi.vm.startOn(vmRefs, host.$ref)"
>
<div class="wrapper">
{{ host.name_label }}
<div>
@@ -19,9 +25,7 @@
<script lang="ts" setup>
import PowerStateIcon from '@/components/PowerStateIcon.vue'
import { useVmStartOnJob } from '@/jobs/vm-start-on.job.ts'
import { areSomeVmOperationAllowed } from '@/libs/vm.ts'
import { VM_OPERATION, VM_POWER_STATE } from '@/libs/xen-api/xen-api.enums.ts'
import { VM_POWER_STATE } from '@/libs/xen-api/xen-api.enums.ts'
import type { XenApiHost, XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import VmPowerStateActionButton from '@/modules/vm/components/actions/VmPowerStateActionButton.vue'
import { useVmPowerStateActions } from '@/modules/vm/composables/vm-power-state-actions.composable.ts'
@@ -29,13 +33,14 @@ import type { VmPowerStateAction } from '@/modules/vm/utils/vm.util.ts'
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
import { useHostStore } from '@/stores/xen-api/host.store.ts'
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
import { useXenApiStore } from '@/stores/xen-api.store.ts'
import VtsIcon from '@core/components/icon/VtsIcon.vue'
import MenuItem from '@core/components/menu/MenuItem.vue'
import { computed, ref } from 'vue'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { vm, exclude = {} } = defineProps<{
vm: XenApiVm
const { vmRefs, exclude = {} } = defineProps<{
vmRefs: XenApiVm['$ref'][]
exclude?: Partial<Record<VmPowerStateAction, boolean>>
}>()
@@ -45,16 +50,7 @@ const { records: hosts } = useHostStore().subscribe()
const { pool } = usePoolStore().subscribe()
const { isHostRunning } = useHostMetricsStore().subscribe()
const selectedHost = ref<XenApiHost>()
const { run: runStartOn, isRunning: isStartingOnHost } = useVmStartOnJob(() => [vm], selectedHost)
const canStartOnHost = computed(() => areSomeVmOperationAllowed(vm, VM_OPERATION.START_ON))
function startOn(host: XenApiHost) {
selectedHost.value = host
runStartOn({ detached: true })
}
const xenApi = useXenApiStore().getXapi()
const MENU_ACTIONS: VmPowerStateAction[] = [
'pause',
@@ -66,7 +62,7 @@ const MENU_ACTIONS: VmPowerStateAction[] = [
'force-shutdown',
]
const { actions } = useVmPowerStateActions(() => [vm])
const { actions, areVmsHalted, isStartingOnHost } = useVmPowerStateActions(() => vmRefs)
const menuActions = computed(() => MENU_ACTIONS.filter(action => !exclude[action]))

View File

@@ -2,25 +2,45 @@
<VtsActionButton
variant="tertiary"
accent="brand"
:busy="isSnapshotting"
:busy="areSomeVmsSnapshotting"
:disabled="isDisabled"
icon="fa:camera"
@click="snapshotVm({ detached: true })"
@click="handleSnapshot()"
>
{{ t('snapshot') }}
</VtsActionButton>
</template>
<script lang="ts" setup>
import { useVmSnapshotJob } from '@/jobs/vm-snapshot.job.ts'
import { isVmOperationPending } from '@/libs/vm.ts'
import { VM_OPERATION } from '@/libs/xen-api/xen-api.enums.ts'
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
import { useXenApiStore } from '@/stores/xen-api.store.ts'
import VtsActionButton from '@core/components/action-button/VtsActionButton.vue'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { vm } = defineProps<{
vm: XenApiVm
const props = defineProps<{
vmRefs: XenApiVm['$ref'][]
}>()
const { t } = useI18n()
const { run: snapshotVm, isRunning: isSnapshotting } = useVmSnapshotJob(() => [vm])
const { getByOpaqueRef } = useVmStore().subscribe()
const vms = computed(() =>
props.vmRefs.map(vmRef => getByOpaqueRef(vmRef)).filter((vm): vm is XenApiVm => vm !== undefined)
)
const areSomeVmsSnapshotting = computed(() => vms.value.some(vm => isVmOperationPending(vm, VM_OPERATION.SNAPSHOT)))
const isDisabled = computed(() => vms.value.length === 0 || areSomeVmsSnapshotting.value)
const handleSnapshot = () => {
const vmRefsToSnapshot = Object.fromEntries(
vms.value.map(vm => [vm.$ref, `${vm.name_label}_${new Date().toISOString()}`])
)
return useXenApiStore().getXapi().vm.snapshot(vmRefsToSnapshot)
}
</script>

View File

@@ -0,0 +1,52 @@
<template>
<VtsMobileMenu v-if="uiStore.isSmall" :title="t('actions')">
<template #trigger="{ isOpen, open, bindings }">
<UiButtonIcon
v-bind="bindings"
accent="brand"
size="small"
:disabled="selectedRefs.length === 0"
:selected="isOpen"
icon="fa:ellipsis"
@click="open()"
/>
</template>
<VmsBulkActionItems :selected-refs />
</VtsMobileMenu>
<MenuList
v-else
:disabled="selectedRefs.length === 0"
class="vms-actions-bar"
horizontal
no-border
placement="bottom-end"
>
<VmsBulkActionItems :selected-refs />
</MenuList>
</template>
<script lang="ts" setup>
import VmsBulkActionItems from '@/components/vm/VmsBulkActionItems.vue'
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import MenuList from '@core/components/menu/MenuList.vue'
import VtsMobileMenu from '@core/components/menu/VtsMobileMenu.vue'
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
import { useUiStore } from '@core/stores/ui.store.ts'
import { useI18n } from 'vue-i18n'
defineProps<{
selectedRefs: XenApiVm['$ref'][]
}>()
const { t } = useI18n()
const uiStore = useUiStore()
</script>
<style lang="postcss" scoped>
.vms-actions-bar {
padding-bottom: 1rem;
border-bottom: 1px solid var(--color-neutral-border);
background-color: var(--color-neutral-background-primary);
}
</style>

View File

@@ -0,0 +1,31 @@
<template>
<MenuItem accent="brand" icon="fa:power-off">
{{ t('action:change-state') }}
<template #submenu>
<VmActionPowerStateItems :vm-refs="selectedRefs" />
</template>
</MenuItem>
<VmActionMigrateItem :selected-refs />
<VmActionCopyItem :selected-refs />
<VmActionSnapshotItem :vm-refs="selectedRefs" />
<VmActionExportItems :vm-refs="selectedRefs" />
<VmActionDeleteItem :vm-refs="selectedRefs" />
</template>
<script lang="ts" setup>
import VmActionCopyItem from '@/components/vm/VmActionItems/VmActionCopyItem.vue'
import VmActionDeleteItem from '@/components/vm/VmActionItems/VmActionDeleteItem.vue'
import VmActionExportItems from '@/components/vm/VmActionItems/VmActionExportItems.vue'
import VmActionMigrateItem from '@/components/vm/VmActionItems/VmActionMigrateItem.vue'
import VmActionPowerStateItems from '@/components/vm/VmActionItems/VmActionPowerStateItems.vue'
import VmActionSnapshotItem from '@/components/vm/VmActionItems/VmActionSnapshotItem.vue'
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import MenuItem from '@core/components/menu/MenuItem.vue'
import { useI18n } from 'vue-i18n'
defineProps<{
selectedRefs: XenApiVm['$ref'][]
}>()
const { t } = useI18n()
</script>

View File

@@ -0,0 +1,185 @@
<template>
<UiCard class="vms-page-content">
<UiTitle>
{{ t('vms') }}
<template v-if="uiStore.isSmall" #right>
<VmsActionsBar :selected-refs="selectedVmsRefs" />
</template>
</UiTitle>
<VmsActionsBar v-if="!uiStore.isSmall" :selected-refs="selectedVmsRefs" />
<div>
<div class="filter-and-sort">
<CollectionFilter
:active-filters="filters"
:available-filters="availableFilters"
@add-filter="addFilter"
@remove-filter="removeFilter"
/>
<CollectionSorter
:active-sorts="sorts"
:available-sorts="availableFilters"
@add-sort="addSort"
@remove-sort="removeSort"
@toggle-sort-direction="toggleSortDirection"
/>
</div>
<VtsTable :state :pagination-bindings>
<thead>
<tr>
<VtsHeaderCell>
<UiCheckbox v-model="areAllVmsSelected" accent="brand" />
</VtsHeaderCell>
<HeadCells />
</tr>
</thead>
<tbody>
<VtsRow v-for="vm in paginatedVms" :key="vm.$ref">
<UiTableCell>
<UiCheckbox v-model="selectedVmsRefs" :value="vm.$ref" accent="brand" />
</UiTableCell>
<BodyCells :item="vm" />
</VtsRow>
</tbody>
</VtsTable>
</div>
</UiCard>
</template>
<script lang="ts" setup>
import CollectionFilter from '@/components/CollectionFilter.vue'
import CollectionSorter from '@/components/CollectionSorter.vue'
import VmsActionsBar from '@/components/vm/VmsActionsBar.vue'
import useCollectionFilter from '@/composables/collection-filter.composable.ts'
import useCollectionSorter from '@/composables/collection-sorter.composable.ts'
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import { usePageTitleStore } from '@/stores/page-title.store.ts'
import { useVbdStore } from '@/stores/xen-api/vbd.store.ts'
import { useVdiStore } from '@/stores/xen-api/vdi.store.ts'
import { useVmGuestMetricsStore } from '@/stores/xen-api/vm-guest-metrics.store.ts'
import { useVmMetricsStore } from '@/stores/xen-api/vm-metrics.store.ts'
import type { Filters } from '@/types/filter.ts'
import VtsHeaderCell from '@core/components/table/cells/VtsHeaderCell.vue'
import VtsRow from '@core/components/table/VtsRow.vue'
import VtsTable from '@core/components/table/VtsTable.vue'
import UiCard from '@core/components/ui/card/UiCard.vue'
import UiCheckbox from '@core/components/ui/checkbox/UiCheckbox.vue'
import UiTableCell from '@core/components/ui/table-cell/UiTableCell.vue'
import UiTitle from '@core/components/ui/title/UiTitle.vue'
import { usePagination } from '@core/composables/pagination.composable.ts'
import useMultiSelect from '@core/composables/table/multi-select.composable.ts'
import { useTableState } from '@core/composables/table-state.composable.ts'
import { objectIcon } from '@core/icons'
import { useUiStore } from '@core/stores/ui.store.ts'
import { useVmColumns } from '@core/tables/column-sets/vm-columns.ts'
import { renderBodyCell } from '@core/tables/helpers/render-body-cell.ts'
import { renderLoadingCell } from '@core/tables/helpers/render-loading-cell.ts'
import { formatSizeRaw } from '@core/utils/size.util.ts'
import { VM_POWER_STATE } from '@vates/types'
import { useSorted } from '@vueuse/core'
import { useArrayFilter } from '@vueuse/shared'
import { toLower } from 'lodash-es'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { vms, busy, error } = defineProps<{
vms: XenApiVm[]
busy?: boolean
error?: boolean
}>()
const { getByOpaqueRef: getGuestMetrics, isReady: areGuestMetricsReady } = useVmGuestMetricsStore().subscribe()
const { getByOpaqueRef: getVmMetrics } = useVmMetricsStore().subscribe()
const { getByOpaqueRefs: getVbds } = useVbdStore().subscribe()
const { getByOpaqueRefs: getVdis } = useVdiStore().subscribe()
const { t } = useI18n()
const uiStore = useUiStore()
const titleStore = usePageTitleStore()
titleStore.setTitle(t('vms'))
const availableFilters: Filters = {
name_label: { label: t('name'), type: 'string' },
name_description: { label: t('description'), type: 'string' },
power_state: {
label: t('power-state'),
icon: 'fa:power-off',
type: 'enum',
choices: Object.values(VM_POWER_STATE),
},
}
const { filters, addFilter, removeFilter, predicate } = useCollectionFilter<XenApiVm>({
queryStringParam: 'filter',
})
const { sorts, addSort, removeSort, toggleSortDirection, compareFn } = useCollectionSorter<XenApiVm>({
queryStringParam: 'sort',
})
const filteredVms = useArrayFilter(
() => vms,
vm => predicate.value(vm)
)
const filteredAndSortedVms = useSorted(filteredVms, (vm1, vm2) => compareFn.value(vm1, vm2))
const { pageRecords: paginatedVms, paginationBindings } = usePagination('vms', filteredAndSortedVms)
const { selected: selectedVmsRefs, areAllSelected: areAllVmsSelected } = useMultiSelect(
computed(() => vms.map(vm => vm.$ref)),
computed(() => paginatedVms.value.map(vm => vm.$ref))
)
titleStore.setCount(() => selectedVmsRefs.value.length)
const state = useTableState({
busy: () => busy,
error: () => error,
empty: () =>
vms.length === 0 ? t('no-vm-detected') : filteredVms.value.length === 0 ? { type: 'no-result' } : false,
})
const { HeadCells, BodyCells } = useVmColumns({
exclude: ['actions', 'checkbox', 'lastBackupDate'],
body: (vm: XenApiVm) => {
const guestMetrics = computed(() => getGuestMetrics(vm.guest_metrics))
const vmMetrics = computed(() => getVmMetrics(vm.metrics))
const ips = computed(() => [...new Set(Object.values(guestMetrics.value?.networks ?? {}).sort())])
const ram = computed(() => formatSizeRaw(vm.memory_dynamic_max, 0))
const vcpus = computed(() => vmMetrics.value?.VCPUs_number ?? vm.VCPUs_at_startup)
const vbds = computed(() => getVbds(vm.VBDs).filter(vbd => vbd.type === 'Disk'))
const vdis = computed(() => getVdis(vbds.value.map(vbd => vbd.VDI)))
const diskSpace = computed(() =>
formatSizeRaw(
vdis.value.reduce((total, vdi) => total + (vdi.virtual_size ?? 0), 0),
1
)
)
return {
vm: r =>
r({ label: vm.name_label, to: `/vm/${vm.uuid}/dashboard`, icon: objectIcon('vm', toLower(vm.power_state)) }),
ipAddresses: r => (areGuestMetricsReady.value ? r(ips.value) : renderLoadingCell()),
vcpus: r => (vcpus.value ? r(vcpus.value) : renderBodyCell()),
ram: r => (ram.value.value ? r(ram.value.value, ram.value.prefix) : renderBodyCell()),
diskSpace: r => r(diskSpace.value.value, diskSpace.value.prefix),
tags: r => r(vm.tags),
}
},
})
</script>
<style lang="postcss" scoped>
.vms-page-content {
overflow: auto;
margin: 1rem;
.filter-and-sort {
display: flex;
}
}
</style>

View File

@@ -17,7 +17,16 @@
<VtsKeyValueRow :label="t('uuid')" :value="vm.uuid" copy />
<VtsKeyValueRow :label="t('host')">
<template #value>
<HostLink v-if="host" :host size="medium" />
<UiLink
v-if="host"
:icon="hostIcon"
:is-primary="isPoolMaster"
:primary-tooltip="t('master')"
:to="`/host/${host.uuid}`"
size="medium"
>
{{ host.name_label }}
</UiLink>
<span v-else>
{{ t('none') }}
</span>
@@ -26,12 +35,12 @@
</VtsKeyValueList>
<VtsKeyValueList>
<VtsKeyValueRow :label="t('description')" :value="vm.name_description" />
<VtsKeyValueRow :label="t('os-name')" :value="osName" />
<VtsKeyValueRow :label="t('os-name')" :value="osVersion" />
<VtsKeyValueRow :label="t('virtualization-type')" :value="virtualizationType" />
<VtsKeyValueRow :label="t('guest-tools')" :value="guestTools" />
</VtsKeyValueList>
<VtsKeyValueList>
<VtsKeyValueRow :label="t('vcpus')" :value="String(vcpus)" />
<VtsKeyValueRow :label="t('vcpus')" :value="String(vm.VCPUs_at_startup)" />
<VtsKeyValueRow :label="t('ram')" :value="`${ram.value} ${ram.prefix}`" />
<VtsKeyValueRow :label="t('tags')">
<template #value>
@@ -46,10 +55,11 @@
<script lang="ts" setup>
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import HostLink from '@/modules/host/components/HostLink.vue'
import { useVmMetricsInfo } from '@/modules/vm/composables/vm-metrics-info.composable.ts'
import { getHostIcon } from '@/modules/host/utils/host.util.ts'
import { useVmUtils } from '@/modules/vm/composables/vm-utils.composable.ts'
import { getVmDomainType, getVmIpAddresses, getVmVcpus } from '@/modules/vm/utils/vm.util.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'
import { useVmMetricsStore } from '@/stores/xen-api/vm-metrics.store.ts'
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
@@ -58,8 +68,11 @@ import VtsKeyValueList from '@core/components/key-value-list/VtsKeyValueList.vue
import VtsKeyValueRow from '@core/components/key-value-row/VtsKeyValueRow.vue'
import VtsQuickInfoCard from '@core/components/quick-info-card/VtsQuickInfoCard.vue'
import VtsTag from '@core/components/tag/VtsTag.vue'
import UiLink from '@core/components/ui/link/UiLink.vue'
import UiTagsList from '@core/components/ui/tag/UiTagsList.vue'
import { useTimeAgo } from '@core/composables/locale-time-ago.composable.ts'
import { formatSizeRaw } from '@core/utils/size.util.ts'
import { formatDate, parseDateTime } from '@core/utils/time.util.ts'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
@@ -71,19 +84,55 @@ const { t } = useI18n()
const { isReady, getVmHost } = useVmStore().subscribe()
const { getByOpaqueRef: getGuestMetricsByOpaqueRef } = useVmGuestMetricsStore().subscribe()
const { getByOpaqueRef: getVmMetrics } = useVmMetricsStore().subscribe()
const { getByOpaqueRef: getMetricsByOpaqueRef } = useVmMetricsStore().subscribe()
const { getHostPowerState } = useHostMetricsStore().subscribe()
const { pool } = usePoolStore().subscribe()
const guestMetrics = computed(() => getGuestMetricsByOpaqueRef(vm.guest_metrics))
const vcpus = computed(() => getVmVcpus(vm, getVmMetrics(vm.metrics), guestMetrics.value))
const metrics = computed(() => getMetricsByOpaqueRef(vm.metrics))
const host = computed(() => getVmHost(vm))
const isPoolMaster = computed(() => pool.value?.master === host.value?.$ref)
const hostIcon = computed(() => getHostIcon(host.value, getHostPowerState(host.value)))
const { powerState } = useVmUtils(() => vm)
const { osName, guestTools, relativeStartTime, installDateFormatted } = useVmMetricsInfo(() => vm)
function getValidDateTime(dateTime: string | undefined): string | undefined {
return dateTime === '19700101T00:00:00Z' ? undefined : dateTime
}
const ram = computed(() => formatSizeRaw(vm.memory_dynamic_max, 1))
const startTime = computed(() => {
const dateTime = getValidDateTime(metrics.value?.start_time)
return dateTime ? new Date(parseDateTime(dateTime)) : undefined
})
const vmTimeAgo = useTimeAgo(() => startTime.value ?? 0)
const relativeStartTime = computed(() => {
if (startTime.value === undefined) {
return t('not-running')
}
return vmTimeAgo.value
})
const installDateFormatted = computed(() => {
const installTime = getValidDateTime(metrics.value?.install_time)
if (installTime === undefined) {
return t('unknown')
}
return formatDate(installTime)
})
const ram = computed(() => formatSizeRaw(vm.memory_dynamic_max, 0))
const osVersion = computed(() => guestMetrics.value?.os_version.name)
const domainType = computed(() => getVmDomainType(vm))
@@ -91,7 +140,27 @@ const virtualizationType = computed(() =>
domainType.value === 'hvm' && guestMetrics.value?.PV_drivers_detected ? 'pvhvm' : domainType.value
)
const mainIpAddress = computed(() => getVmIpAddresses(guestMetrics.value)[0])
const guestTools = computed(() => {
const version = guestMetrics.value?.PV_drivers_version
if (!guestMetrics.value?.PV_drivers_detected || !version) {
return ''
}
if (Object.entries(version).length === 0) {
return ''
}
return `${version.major}.${version.minor}.${version.micro}-${version.build}`
})
const mainIpAddress = computed(() => {
if (!guestMetrics.value?.networks) {
return undefined
}
return [...new Set(Object.values(guestMetrics.value.networks).sort())][0]
})
</script>
<style lang="postcss" scoped>

View File

@@ -33,3 +33,43 @@ const {
When using the `initialFilters` option with the `queryStringParam` option,
`initialFilters` will only be applied if no query string parameter is defined in the URL.
## Example of using the composable with the `CollectionFilter` component
```vue
<template>
<CollectionFilter
:active-filters="filters"
:available-filters="availableFilters"
@add-filter="addFilter"
@remove-filter="removeFilter"
/>
<div v-for="item in filteredCollection">...</div>
</template>
<script lang="ts" setup>
import CollectionFilter from '@/components/CollectionFilter.vue'
import useCollectionFilter from '@/composables/collection-filter.composable'
import { computed } from 'vue'
const collection = [
{ name: 'Foo', age: 5, registered: true },
{ name: 'Bar', age: 12, registered: false },
{ name: 'Foo Bar', age: 2, registered: true },
{ name: 'Bar Baz', age: 45, registered: false },
{ name: 'Foo Baz', age: 32, registered: false },
{ name: 'Foo Bar Baz', age: 32, registered: true },
]
const availableFilters: AvailableFilter[] = [
{ property: 'name', label: 'Name', type: 'string' },
{ property: 'age', label: 'Age', type: 'number' },
{ property: 'registered', label: 'Registered', type: 'boolean', icon: faKey },
]
const { filters, addFilter, removeFilter, predicate } = useCollectionFilter()
const filteredCollection = computed(() => collection.filter(predicate))
</script>
```

View File

@@ -0,0 +1,64 @@
import { VM_OPERATION } from '@/libs/xen-api/xen-api.enums.ts'
import type { XenApiHost, XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import { useHostStore } from '@/stores/xen-api/host.store.ts'
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
import { useXenApiStore } from '@/stores/xen-api.store.ts'
import { sortByNameLabel } from '@core/utils/sort-by-name-label.util.ts'
import { castArray } from 'lodash-es'
import type { MaybeRefOrGetter } from 'vue'
import { computed, ref, toValue } from 'vue'
export const useVmMigration = (vmRefs: MaybeRefOrGetter<XenApiVm['$ref'] | XenApiVm['$ref'][]>) => {
const $isMigrating = ref(false)
const selectedHost = ref<XenApiHost>()
const { getByOpaqueRef: getVm } = useVmStore().subscribe()
const { records: hosts } = useHostStore().subscribe()
const vms = computed(
() =>
castArray(toValue(vmRefs))
.map(vmRef => getVm(vmRef))
.filter(vm => vm !== undefined) as XenApiVm[]
)
const isMigrating = computed(
() =>
$isMigrating.value ||
vms.value.some(vm =>
Object.values(vm.current_operations).some(operation => operation === VM_OPERATION.POOL_MIGRATE)
)
)
const availableHosts = computed(() => {
return hosts.value.filter(host => vms.value.some(vm => vm.resident_on !== host.$ref)).sort(sortByNameLabel)
})
const isValid = computed(() => !isMigrating.value && vms.value.length > 0 && selectedHost.value !== undefined)
const migrate = async () => {
if (!isValid.value) {
return
}
try {
$isMigrating.value = true
const hostRef = selectedHost.value!.$ref
const xapi = useXenApiStore().getXapi()
await xapi.vm.migrate(
vms.value.map(vm => vm.$ref),
hostRef
)
} finally {
$isMigrating.value = false
}
}
return {
isMigrating,
availableHosts,
selectedHost,
isValid,
migrate,
}
}

View File

@@ -1,7 +1,6 @@
import { vmsArg } from '@/jobs/args.ts'
import { isVmOperationPending } from '@/libs/vm.ts'
import { VM_OPERATION } from '@/libs/xen-api/xen-api.enums.ts'
import { isVmDeletionBlocked } from '@/modules/vm/utils/vm.util.ts'
import { VM_OPERATION, VM_POWER_STATE } from '@/libs/xen-api/xen-api.enums.ts'
import { useXenApiStore } from '@/stores/xen-api.store.ts'
import { defineJob, JobError, JobRunningError } from '@core/packages/job'
import { useI18n } from 'vue-i18n'
@@ -11,17 +10,7 @@ export const useVmDeleteJob = defineJob('vm.delete', [vmsArg], () => {
const { t } = useI18n()
return {
run: async vms => {
const results = await Promise.allSettled(vms.map(vm => xapi.vm.delete(vm.$ref, { deleteDisks: true })))
results.forEach((result, index) => {
if (result.status === 'rejected') {
console.error(`Failed to delete VM ${vms[index].name_label}:`, result.reason)
}
})
return results
},
run: vms => xapi.vm.delete(vms.map(vm => vm.$ref)),
validate: (isRunning, vms) => {
if (vms.length === 0) {
throw new JobError(t('job:vm-delete:missing-vm'))
@@ -31,8 +20,8 @@ export const useVmDeleteJob = defineJob('vm.delete', [vmsArg], () => {
throw new JobRunningError(t('job:delete:in-progress'))
}
if (vms.some(vm => isVmDeletionBlocked(vm))) {
throw new JobError(t('job:vm-delete:blocked-operation'))
if (!vms.every(vm => vm.power_state === VM_POWER_STATE.HALTED)) {
throw new JobError(t('job:vm-delete:bad-power-state'))
}
},
}

View File

@@ -1,7 +1,6 @@
import { vmsArg } from '@/jobs/args.ts'
import { isVmOperationPending } from '@/libs/vm.ts'
import { VM_OPERATION } from '@/libs/xen-api/xen-api.enums.ts'
import { areAllVmsAllowingPowerStateAction, isVmOperationBlocked } from '@/modules/vm/utils/vm.util.ts'
import { VM_OPERATION, VM_POWER_STATE } from '@/libs/xen-api/xen-api.enums.ts'
import { useXenApiStore } from '@/stores/xen-api.store.ts'
import { defineJob, JobError, JobRunningError } from '@core/packages/job'
import { useI18n } from 'vue-i18n'
@@ -25,13 +24,9 @@ export const useVmForceRebootJob = defineJob('vm.force-reboot', [vmsArg], () =>
throw new JobRunningError(t('job:vm-force-reboot:in-progress'))
}
if (!areAllVmsAllowingPowerStateAction(vms, 'force-reboot')) {
if (!vms.every(vm => vm.power_state === VM_POWER_STATE.RUNNING || vm.power_state === VM_POWER_STATE.PAUSED)) {
throw new JobError(t('job:vm-force-reboot:bad-power-state'))
}
if (vms.some(vm => isVmOperationBlocked(vm, VM_OPERATION.HARD_REBOOT))) {
throw new JobError(t('job:vm-force-reboot:blocked-operation'))
}
},
}
})

View File

@@ -1,7 +1,6 @@
import { vmsArg } from '@/jobs/args.ts'
import { isVmOperationPending } from '@/libs/vm.ts'
import { VM_OPERATION } from '@/libs/xen-api/xen-api.enums.ts'
import { areAllVmsAllowingPowerStateAction, isVmOperationBlocked } from '@/modules/vm/utils/vm.util.ts'
import { VM_OPERATION, VM_POWER_STATE } from '@/libs/xen-api/xen-api.enums.ts'
import { useXenApiStore } from '@/stores/xen-api.store.ts'
import { defineJob, JobError, JobRunningError } from '@core/packages/job'
import { useI18n } from 'vue-i18n'
@@ -25,13 +24,16 @@ export const useVmForceShutdownJob = defineJob('vm.force-shutdown', [vmsArg], ()
throw new JobRunningError(t('job:vm-force-shutdown:in-progress'))
}
if (!areAllVmsAllowingPowerStateAction(vms, 'force-shutdown')) {
if (
!vms.every(
vm =>
vm.power_state === VM_POWER_STATE.RUNNING ||
vm.power_state === VM_POWER_STATE.SUSPENDED ||
vm.power_state === VM_POWER_STATE.PAUSED
)
) {
throw new JobError(t('job:vm-force-shutdown:bad-power-state'))
}
if (vms.some(vm => isVmOperationBlocked(vm, VM_OPERATION.HARD_SHUTDOWN))) {
throw new JobError(t('job:vm-force-shutdown:blocked-operation'))
}
},
}
})

View File

@@ -1,7 +1,7 @@
import { vmsArg } from '@/jobs/args.ts'
import { areSomeVmOperationAllowed, isVmOperationPending } from '@/libs/vm.ts'
import { VM_OPERATION, VM_POWER_STATE } from '@/libs/xen-api/xen-api.enums.ts'
import { hostArg } from '@/modules/host/jobs/host-args.ts'
import { useVmMigrationBlockerMessage } from '@/modules/vm/composables/vm-migration-blocker-message.composable.ts'
import { getVmMigrationBlocker } from '@/modules/vm/utils/vm.util.ts'
import { useXenApiStore } from '@/stores/xen-api.store.ts'
import { defineJob, JobError, JobRunningError } from '@core/packages/job'
import { useI18n } from 'vue-i18n'
@@ -9,40 +9,35 @@ import { useI18n } from 'vue-i18n'
export const useVmMigrateJob = defineJob('vm.migrate', [vmsArg, hostArg], () => {
const xapi = useXenApiStore().getXapi()
const { t } = useI18n()
const { getMigrationBlockerMessage } = useVmMigrationBlockerMessage()
return {
run: (vms, host) => {
if (host === undefined) {
throw new JobError(t('job:vm-migrate:missing-host'))
}
return xapi.vm.migrate(
run: (vms, host) =>
xapi.vm.migrate(
vms.map(vm => vm.$ref),
host.$ref
)
},
validate: (isRunning, vms) => {
),
validate: (isRunning, vms, host) => {
if (vms.length === 0) {
throw new JobError(t('job:vm-migrate:missing-vm'))
}
const blockers = new Set(vms.map(vm => getVmMigrationBlocker(vm)))
if (isRunning || blockers.has('in-progress')) {
throw new JobRunningError(getMigrationBlockerMessage('in-progress'))
if (!host) {
throw new JobError(t('job:vm-migrate:missing-host'))
}
if (blockers.has('blocked-operation')) {
throw new JobError(getMigrationBlockerMessage('blocked-operation'))
if (
isRunning ||
vms.some(vm => isVmOperationPending(vm, [VM_OPERATION.POOL_MIGRATE, VM_OPERATION.MIGRATE_SEND]))
) {
throw new JobRunningError(t('job:vm-migrate:in-progress'))
}
if (blockers.has('bad-power-state')) {
throw new JobError(getMigrationBlockerMessage('bad-power-state'))
if (!vms.every(vm => vm.power_state === VM_POWER_STATE.RUNNING)) {
throw new JobError(t('job:vm-migrate:bad-power-state'))
}
if (blockers.has('not-allowed')) {
throw new JobError(getMigrationBlockerMessage('not-allowed'))
if (!vms.every(vm => areSomeVmOperationAllowed(vm, [VM_OPERATION.POOL_MIGRATE, VM_OPERATION.MIGRATE_SEND]))) {
throw new JobError(t('job:vm-export:not-allowed'))
}
},
}

View File

@@ -1,7 +1,6 @@
import { vmsArg } from '@/jobs/args.ts'
import { isVmOperationPending } from '@/libs/vm.ts'
import { VM_OPERATION } from '@/libs/xen-api/xen-api.enums.ts'
import { areAllVmsAllowingPowerStateAction, isVmOperationBlocked } from '@/modules/vm/utils/vm.util.ts'
import { VM_OPERATION, VM_POWER_STATE } from '@/libs/xen-api/xen-api.enums.ts'
import { useXenApiStore } from '@/stores/xen-api.store.ts'
import { defineJob, JobError, JobRunningError } from '@core/packages/job'
import { useI18n } from 'vue-i18n'
@@ -21,13 +20,9 @@ export const useVmPauseJob = defineJob('vm.pause', [vmsArg], () => {
throw new JobRunningError(t('job:vm-pause:in-progress'))
}
if (!areAllVmsAllowingPowerStateAction(vms, 'pause')) {
if (!vms.every(vm => vm.power_state === VM_POWER_STATE.RUNNING)) {
throw new JobError(t('job:vm-pause:bad-power-state'))
}
if (vms.some(vm => isVmOperationBlocked(vm, VM_OPERATION.PAUSE))) {
throw new JobError(t('job:vm-pause:blocked-operation'))
}
},
}
})

View File

@@ -1,7 +1,6 @@
import { vmsArg } from '@/jobs/args.ts'
import { isVmOperationPending } from '@/libs/vm.ts'
import { VM_OPERATION } from '@/libs/xen-api/xen-api.enums.ts'
import { areAllVmsAllowingPowerStateAction, isVmOperationBlocked } from '@/modules/vm/utils/vm.util.ts'
import { VM_OPERATION, VM_POWER_STATE } from '@/libs/xen-api/xen-api.enums.ts'
import { useXenApiStore } from '@/stores/xen-api.store.ts'
import { defineJob, JobError, JobRunningError } from '@core/packages/job'
import { useI18n } from 'vue-i18n'
@@ -21,13 +20,9 @@ export const useVmRebootJob = defineJob('vm.reboot', [vmsArg], () => {
throw new JobRunningError(t('job:vm-reboot:in-progress'))
}
if (!areAllVmsAllowingPowerStateAction(vms, 'reboot')) {
if (!vms.every(vm => vm.power_state === VM_POWER_STATE.RUNNING || vm.power_state === VM_POWER_STATE.PAUSED)) {
throw new JobError(t('job:vm-reboot:bad-power-state'))
}
if (vms.some(vm => isVmOperationBlocked(vm, VM_OPERATION.CLEAN_REBOOT))) {
throw new JobError(t('job:vm-reboot:blocked-operation'))
}
},
}
})

View File

@@ -1,7 +1,6 @@
import { vmsArg } from '@/jobs/args.ts'
import { isVmOperationPending } from '@/libs/vm.ts'
import { VM_OPERATION } from '@/libs/xen-api/xen-api.enums.ts'
import { areAllVmsAllowingPowerStateAction } from '@/modules/vm/utils/vm.util.ts'
import { VM_OPERATION, VM_POWER_STATE } from '@/libs/xen-api/xen-api.enums.ts'
import { useXenApiStore } from '@/stores/xen-api.store.ts'
import { defineJob, JobError, JobRunningError } from '@core/packages/job'
import { useI18n } from 'vue-i18n'
@@ -21,7 +20,7 @@ export const useVmResumeJob = defineJob('vm.resume', [vmsArg], () => {
throw new JobRunningError(t('job:vm-resume:in-progress'))
}
if (!areAllVmsAllowingPowerStateAction(vms, 'resume')) {
if (!vms.every(vm => vm.power_state === VM_POWER_STATE.PAUSED || vm.power_state === VM_POWER_STATE.SUSPENDED)) {
throw new JobError(t('job:vm-resume:bad-power-state'))
}
},

View File

@@ -1,7 +1,6 @@
import { vmsArg } from '@/jobs/args.ts'
import { isVmOperationPending } from '@/libs/vm.ts'
import { VM_OPERATION } from '@/libs/xen-api/xen-api.enums.ts'
import { areAllVmsAllowingPowerStateAction, isVmOperationBlocked } from '@/modules/vm/utils/vm.util.ts'
import { VM_OPERATION, VM_POWER_STATE } from '@/libs/xen-api/xen-api.enums.ts'
import { useXenApiStore } from '@/stores/xen-api.store.ts'
import { defineJob, JobError, JobRunningError } from '@core/packages/job'
import { useI18n } from 'vue-i18n'
@@ -21,13 +20,9 @@ export const useVmShutdownJob = defineJob('vm.shutdown', [vmsArg], () => {
throw new JobRunningError(t('job:vm-shutdown:in-progress'))
}
if (!areAllVmsAllowingPowerStateAction(vms, 'shutdown')) {
if (!vms.every(vm => vm.power_state === VM_POWER_STATE.RUNNING)) {
throw new JobError(t('job:vm-shutdown:bad-power-state'))
}
if (vms.some(vm => isVmOperationBlocked(vm, VM_OPERATION.CLEAN_SHUTDOWN))) {
throw new JobError(t('job:vm-shutdown:blocked-operation'))
}
},
}
})

View File

@@ -21,14 +21,14 @@ export const useVmStartOnJob = defineJob('vm.start-on', [vmsArg, hostArg], () =>
throw new JobError(t('job:vm-start-on:missing-vm'))
}
if (isRunning || vms.some(vm => isVmOperationPending(vm, VM_OPERATION.START_ON))) {
throw new JobRunningError(t('job:vm-start-on:in-progress'))
}
if (!host) {
throw new JobError(t('job:vm-start-on:missing-host'))
}
if (isRunning || vms.some(vm => isVmOperationPending(vm, VM_OPERATION.START_ON))) {
throw new JobRunningError(t('job:vm-start-on:in-progress'))
}
if (!vms.every(vm => vm.power_state === VM_POWER_STATE.HALTED)) {
throw new JobError(t('job:vm-start-on:bad-power-state'))
}

View File

@@ -1,7 +1,6 @@
import { vmsArg } from '@/jobs/args.ts'
import { isVmOperationPending } from '@/libs/vm.ts'
import { VM_OPERATION } from '@/libs/xen-api/xen-api.enums.ts'
import { areAllVmsAllowingPowerStateAction } from '@/modules/vm/utils/vm.util.ts'
import { VM_OPERATION, VM_POWER_STATE } from '@/libs/xen-api/xen-api.enums.ts'
import { useXenApiStore } from '@/stores/xen-api.store.ts'
import { defineJob, JobError, JobRunningError } from '@core/packages/job'
import { useI18n } from 'vue-i18n'
@@ -21,7 +20,7 @@ export const useVmStartJob = defineJob('vm.start', [vmsArg], () => {
throw new JobRunningError(t('job:vm-start:in-progress'))
}
if (!areAllVmsAllowingPowerStateAction(vms, 'start')) {
if (!vms.every(vm => vm.power_state === VM_POWER_STATE.HALTED)) {
throw new JobError(t('job:vm-start:bad-power-state'))
}
},

View File

@@ -1,7 +1,6 @@
import { vmsArg } from '@/jobs/args.ts'
import { isVmOperationPending } from '@/libs/vm.ts'
import { VM_OPERATION } from '@/libs/xen-api/xen-api.enums.ts'
import { areAllVmsAllowingPowerStateAction, isVmOperationBlocked } from '@/modules/vm/utils/vm.util.ts'
import { VM_OPERATION, VM_POWER_STATE } from '@/libs/xen-api/xen-api.enums.ts'
import { useXenApiStore } from '@/stores/xen-api.store.ts'
import { defineJob, JobError, JobRunningError } from '@core/packages/job'
import { useI18n } from 'vue-i18n'
@@ -21,13 +20,9 @@ export const useVmSuspendJob = defineJob('vm.suspend', [vmsArg], () => {
throw new JobRunningError(t('job:vm-suspend:in-progress'))
}
if (!areAllVmsAllowingPowerStateAction(vms, 'suspend')) {
if (!vms.every(vm => vm.power_state === VM_POWER_STATE.RUNNING)) {
throw new JobError(t('job:vm-suspend:bad-power-state'))
}
if (vms.some(vm => isVmOperationBlocked(vm, VM_OPERATION.SUSPEND))) {
throw new JobError(t('job:vm-suspend:blocked-operation'))
}
},
}
})

View File

@@ -0,0 +1,118 @@
import { escapeRegExp } from '@/libs/utils.ts'
import type { FilterComparisonType } from '@/types/filter.ts'
import type { ComparisonOperator, Node } from 'complex-matcher'
import * as CM from 'complex-matcher'
function buildStringNode(property: string, value: string, negate = false) {
if (!value) {
return
}
const node = new CM.Property(property, new CM.StringNode(value))
if (negate) {
return new CM.Not(node)
}
return node
}
function buildRegexNode(property: string, value: string, prefix = '', suffix = '', escape = false, negate = false) {
if (!value) {
return
}
if (escape) {
value = escapeRegExp(value)
}
const node = new CM.Property(property, new CM.RegExpNode(`${prefix}${value}${suffix}`, 'i'))
if (negate) {
return new CM.Not(node)
}
return node
}
function buildNumberComparisonNode(
property: string,
value: string | number,
comparisonOperator: ComparisonOperator | '='
) {
if (typeof value === 'string') {
value = parseInt(value, 10)
}
if (isNaN(value)) {
return
}
if (comparisonOperator === '=') {
return new CM.Property(property, new CM.Number(value))
}
return new CM.Property(property, new CM.Comparison(comparisonOperator, value))
}
function buildBooleanNode(property: string, value: boolean) {
const node = new CM.TruthyProperty(property)
if (!value) {
return new CM.Not(node)
}
return node
}
export function buildComplexMatcherNode(
comparisonType: FilterComparisonType,
property: string,
value: string
): Node | undefined {
switch (comparisonType) {
case 'stringContains':
case 'stringDoesNotContains':
return buildStringNode(property, value, comparisonType === 'stringDoesNotContains')
case 'stringStartsWith':
case 'stringDoesNotStartWith':
return buildRegexNode(property, value, '^', '', true, comparisonType === 'stringDoesNotStartWith')
case 'stringEndsWith':
case 'stringDoesNotEndWith':
return buildRegexNode(property, value, '', '$', true, comparisonType === 'stringDoesNotEndWith')
case 'stringEquals':
case 'stringDoesNotEqual':
case 'enumIs':
case 'enumIsNot':
return buildRegexNode(
property,
value,
'^',
'$',
true,
['stringDoesNotEqual', 'enumIsNot'].includes(comparisonType)
)
case 'stringMatchesRegex':
case 'stringDoesNotMatchRegex':
return buildRegexNode(property, value, '', '', false, comparisonType === 'stringDoesNotMatchRegex')
case 'numberLessThan':
return buildNumberComparisonNode(property, value, '<')
case 'numberLessThanOrEquals':
return buildNumberComparisonNode(property, value, '<=')
case 'numberEquals':
return buildNumberComparisonNode(property, value, '=')
case 'numberGreaterThanOrEquals':
return buildNumberComparisonNode(property, value, '>=')
case 'numberGreaterThan':
return buildNumberComparisonNode(property, value, '>')
case 'booleanTrue':
return buildBooleanNode(property, true)
case 'booleanFalse':
return buildBooleanNode(property, false)
}
}

View File

@@ -1,11 +1,36 @@
import { VM_POWER_STATE } from '@/libs/xen-api/xen-api.enums.ts'
import type { Filter } from '@/types/filter.ts'
import type { IconName } from '@core/icons'
import format from 'human-format'
import { find, forEach, round, size, sum } from 'lodash-es'
export function escapeRegExp(string: string) {
return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
}
const iconsByType: Record<string, IconName> = {
string: 'fa:font',
number: 'fa:hashtag',
boolean: 'fa:square-check',
enum: 'fa:list',
}
export function formatSize(bytes: number) {
return bytes != null ? format(bytes, { scale: 'binary', unit: 'B' }) : 'N/D'
}
export function getFilterIcon(filter: Filter | undefined) {
if (!filter) {
return
}
if (filter.icon) {
return filter.icon
}
return iconsByType[filter.type]
}
export function percent(currentValue: number, maxValue: number, precision = 2) {
return round((currentValue / maxValue) * 100, precision)
}

View File

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

View File

@@ -1,16 +1,12 @@
import { type VM_COMPRESSION_TYPE, VM_OPERATION, VM_POWER_STATE } from '@/libs/xen-api/xen-api.enums.ts'
import type { VM_COMPRESSION_TYPE } from '@/libs/xen-api/xen-api.enums.ts'
import type XenApi from '@/libs/xen-api/xen-api.ts'
import type { XenApiHost, XenApiSr, XenApiVbd, XenApiVdi, XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import type { XenApiHost, XenApiSr, XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import type { MaybeArray } from '@core/types/utility.type.ts'
import { toArray } from '@core/utils/to-array.utils.ts'
import { OPAQUE_REF, type OPAQUE_REF_NULL, VBD_TYPE } from '@vates/types/common'
import type { OPAQUE_REF_NULL } from '@vates/types/common'
export function createVmOperations(xenApi: XenApi) {
type VmRef = XenApiVm['$ref']
type VmRefs = MaybeArray<VmRef>
type VdiRef = XenApiVdi['$ref']
type VmRefs = MaybeArray<XenApiVm['$ref']>
type HostRef = XenApiHost['$ref']
@@ -28,71 +24,6 @@ export function createVmOperations(xenApi: XenApi) {
})
)
async function getDiskRefs(vbdRefs: XenApiVbd['$ref'][]) {
const vbds = await Promise.all(
vbdRefs.map(vbdRef => xenApi.call<Pick<XenApiVbd, 'type' | 'VDI'>>('VBD.get_record', [vbdRef]))
)
const diskRefs = vbds.filter(vbd => vbd.type === VBD_TYPE.DISK && vbd.VDI !== OPAQUE_REF.EMPTY).map(vbd => vbd.VDI)
return [...new Set(diskRefs)]
}
async function isDiskAttachedToAnotherVm(vdiRef: VdiRef, vmRef: VmRef) {
const vbdRefs = await xenApi.getField<XenApiVbd['$ref'][]>('VDI', vdiRef, 'VBDs')
for (const vbdRef of vbdRefs) {
const otherVmRef = await xenApi.getField<VmRef>('VBD', vbdRef, 'VM')
if (otherVmRef !== vmRef && !(await xenApi.getField<boolean>('VM', otherVmRef, 'is_control_domain'))) {
return true
}
}
return false
}
/**
* Adapted from `VM_destroy` in `@xen-orchestra/xapi/vm.mjs`.
*
* @see https://github.com/vatesfr/xen-orchestra/blob/master/@xen-orchestra/xapi/vm.mjs
*/
async function destroyVm(vmRef: VmRef, deleteDisks: boolean): Promise<void> {
const vm = await xenApi.call<Pick<XenApiVm, 'blocked_operations' | 'power_state' | 'snapshots' | 'VBDs'>>(
'VM.get_record',
[vmRef]
)
if (vm.blocked_operations[VM_OPERATION.DESTROY] !== undefined) {
throw new Error('VM deletion is blocked')
}
if (vm.power_state !== VM_POWER_STATE.HALTED) {
await xenApi.call('VM.hard_shutdown', [vmRef])
}
const diskRefs = deleteDisks ? await getDiskRefs(vm.VBDs) : []
await xenApi.call('VM.destroy', [vmRef])
await Promise.all([
...vm.snapshots.map(snapshotRef =>
destroyVm(snapshotRef, deleteDisks).catch(error =>
console.warn('Failed to destroy snapshot', { error, snapshotRef, vmRef })
)
),
...diskRefs.map(async vdiRef => {
try {
if (!(await isDiskAttachedToAnotherVm(vdiRef, vmRef))) {
await xenApi.call('VDI.destroy', [vdiRef])
}
} catch (error) {
console.warn('Failed to destroy VDI', { error, vdiRef, vmRef })
}
}),
])
}
return {
clone: (vmRefsToClone: VmRefsWithNameLabel) => {
const vmRefs = Object.keys(vmRefsToClone) as XenApiVm['$ref'][]
@@ -108,8 +39,7 @@ export function createVmOperations(xenApi: XenApi) {
)
},
delete: (vmRefs: VmRefs, { deleteDisks = false }: { deleteDisks?: boolean } = {}) =>
Promise.all(toArray(vmRefs).map(vmRef => destroyVm(vmRef, deleteDisks))),
delete: (vmRefs: VmRefs) => Promise.all(toArray(vmRefs).map(vmRef => xenApi.call('VM.destroy', [vmRef]))),
export: async (vmRefs: VmRefs, compression: VM_COMPRESSION_TYPE) => {
const blockedUrls: URL[] = []

View File

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

View File

@@ -1,37 +0,0 @@
<template>
<UiLink
:to="to ?? { name: '/host/[uuid]/dashboard', params: { uuid: host.uuid } }"
:size
:icon
:is-primary="isMaster"
:primary-tooltip="t('master')"
>
<slot>{{ host.name_label }}</slot>
</UiLink>
</template>
<script lang="ts" setup>
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import { getHostIcon } from '@/modules/host/utils/host.util.ts'
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
import type { LinkOptions } from '@core/composables/link-component.composable.ts'
import UiLink from '@core/components/ui/link/UiLink.vue'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { host, to } = defineProps<{
host: XenApiHost
size: 'small' | 'medium'
to?: LinkOptions['to']
}>()
const { t } = useI18n()
const { isMasterHost } = usePoolStore().subscribe()
const { getHostPowerState } = useHostMetricsStore().subscribe()
const icon = computed(() => getHostIcon(host, getHostPowerState(host)))
const isMaster = computed(() => isMasterHost(host.$ref))
</script>

View File

@@ -13,10 +13,6 @@
<HostRestartToolstackButton :host />
<HostDisableButton v-if="displayDisableButton" :host />
<HostEnableButton v-else :host />
<template v-if="isSshManageable">
<HostDisableSshButton v-if="host.ssh_enabled" :host />
<HostEnableSshButton v-else :host />
</template>
<HostDetachButton :host />
<HostForgetButton :host />
<VtsDivider v-if="layout !== 'sections'" type="stretch" />
@@ -27,15 +23,12 @@
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import HostDetachButton from '@/modules/host/components/actions/detach/HostDetachButton.vue'
import HostDisableButton from '@/modules/host/components/actions/disable/HostDisableButton.vue'
import HostDisableSshButton from '@/modules/host/components/actions/disable-ssh/HostDisableSshButton.vue'
import HostDownloadButton from '@/modules/host/components/actions/download/HostDownloadButton.vue'
import HostEnableButton from '@/modules/host/components/actions/enable/HostEnableButton.vue'
import HostEnableSshButton from '@/modules/host/components/actions/enable-ssh/HostEnableSshButton.vue'
import HostForgetButton from '@/modules/host/components/actions/forget/HostForgetButton.vue'
import HostPowerStateActions from '@/modules/host/components/actions/HostPowerStateActions.vue'
import HostRestartToolstackButton from '@/modules/host/components/actions/restart-toolstack/HostRestartToolstackButton.vue'
import type { HostQuickAction } from '@/modules/host/composables/host-quick-actions.composable.ts'
import { isHostSshManageable } from '@/modules/host/utils/host.util.ts'
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
import VtsDivider from '@core/components/divider/VtsDivider.vue'
import VtsChangeStateMenuItem from '@core/components/menu/VtsChangeStateMenuItem.vue'
@@ -61,6 +54,4 @@ const { getHostPowerState } = useHostMetricsStore().subscribe()
const isHostHalted = computed(() => getHostPowerState(host) === HOST_POWER_STATE.HALTED)
const displayDisableButton = computed(() => host.enabled || isHostHalted.value)
const isSshManageable = computed(() => isHostSshManageable(host))
</script>

View File

@@ -1,52 +0,0 @@
<template>
<MenuItem
v-tooltip="!canDisableSsh && disableSshErrorMessage"
accent="neutral"
:busy="isDisablingSsh"
:disabled="!canDisableSsh"
icon="action:disable"
@click="disableSsh()"
>
{{ t('action:disable-ssh') }}
<i class="em-dash-prefix">{{ t('auto-enable-if-xapi-goes-down') }}</i>
</MenuItem>
</template>
<script lang="ts" setup>
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import { useHostDisableSshJob } from '@/modules/host/jobs/host-disable-ssh.job.ts'
import MenuItem from '@core/components/menu/MenuItem.vue'
import { useActionModal } from '@core/composables/modals/use-action-modal.ts'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import { useI18n } from 'vue-i18n'
const { host } = defineProps<{
host: XenApiHost
}>()
const { t } = useI18n()
const { open: openActionModal } = useActionModal()
const {
run,
canRun: canDisableSsh,
isRunning: isDisablingSsh,
errorMessage: disableSshErrorMessage,
} = useHostDisableSshJob(() => host)
function disableSsh() {
return openActionModal({
props: {
accent: 'info',
action: 'disable-ssh',
object: 'host',
hostName: host.name_label,
icon: 'status:info-picto',
},
events: {
onConfirm: () => run({ detached: true }),
},
})
}
</script>

View File

@@ -7,7 +7,7 @@
icon="action:disable"
@click="disableHost()"
>
{{ t('action:disable-host') }}
{{ t('action:disable') }}
</MenuItem>
</template>

View File

@@ -1,51 +0,0 @@
<template>
<MenuItem
v-tooltip="!canEnableSsh && enableSshErrorMessage"
accent="neutral"
:busy="isEnablingSsh"
:disabled="!canEnableSsh"
icon="status:success-circle"
@click="enableSsh()"
>
{{ t('action:enable-ssh') }}
</MenuItem>
</template>
<script lang="ts" setup>
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import { useHostEnableSshJob } from '@/modules/host/jobs/host-enable-ssh.job.ts'
import MenuItem from '@core/components/menu/MenuItem.vue'
import { useActionModal } from '@core/composables/modals/use-action-modal.ts'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import { useI18n } from 'vue-i18n'
const { host } = defineProps<{
host: XenApiHost
}>()
const { t } = useI18n()
const { open: openActionModal } = useActionModal()
const {
run,
canRun: canEnableSsh,
isRunning: isEnablingSsh,
errorMessage: enableSshErrorMessage,
} = useHostEnableSshJob(() => host)
function enableSsh() {
return openActionModal({
props: {
accent: 'info',
action: 'enable-ssh',
object: 'host',
hostName: host.name_label,
icon: 'status:info-picto',
},
events: {
onConfirm: () => run({ detached: true }),
},
})
}
</script>

View File

@@ -7,7 +7,7 @@
icon="status:success-circle"
@click="enableHost()"
>
{{ t('action:enable-host') }}
{{ t('action:enable') }}
</MenuItem>
</template>

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