mirror of
https://github.com/vatesfr/xen-orchestra.git
synced 2026-12-03 13:50:18 -06:00
Compare commits
13 Commits
web-core/r
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5b854557e9 | ||
|
|
90cd1de6a2 | ||
|
|
62dcf1c0ca | ||
|
|
0e5353a4c8 | ||
|
|
157be98c91 | ||
|
|
9f568d0893 | ||
|
|
b890851a31 | ||
|
|
22bcc37439 | ||
|
|
5ca2958d2a | ||
|
|
205ae67940 | ||
|
|
addfdd5475 | ||
|
|
5512fc65a6 | ||
|
|
1f8f265afc |
@@ -481,6 +481,8 @@ 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,
|
||||
|
||||
@@ -193,12 +193,21 @@ export type XoVmBackupArchive = {
|
||||
id: Branded<'vm-backup-archive'>
|
||||
type: 'xo-vm-backup'
|
||||
backupRepository: XoBackupRepository['id']
|
||||
disks: { id: string; name: string; uuid: XoVdiSnapshot['uuid'] }[]
|
||||
disks: {
|
||||
id: string
|
||||
name: string
|
||||
uuid: XoVdiSnapshot['uuid']
|
||||
sizeOnDisk?: number
|
||||
isDifferencing?: boolean
|
||||
}[]
|
||||
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']
|
||||
@@ -209,6 +218,7 @@ export type XoVmBackupArchive = {
|
||||
differencingVhds?: number
|
||||
dynamicVhds?: number
|
||||
withMemory: boolean
|
||||
tags: string[]
|
||||
}
|
||||
|
||||
type XoMetadataBackupArchive = {
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
export default {
|
||||
clone: true,
|
||||
'convert-to-template': true,
|
||||
delete: true,
|
||||
export: true,
|
||||
'migrate-send': true,
|
||||
|
||||
@@ -8,9 +8,28 @@ export type SupportedResource = XoAclSupportedResource<SupportedActionsByResourc
|
||||
export type SupportedActions<T extends SupportedResource> = XoAclSupportedActions<SupportedActionsByResource, T>
|
||||
export type TPrivilege<T extends SupportedResource> = XoAclPrivilege<SupportedActionsByResource, T>
|
||||
|
||||
export const UNKNOWN = Symbol('UNKNOWN')
|
||||
|
||||
/**
|
||||
* Lists the top-level fields read by a selector.
|
||||
*/
|
||||
function getSelectorFields(node: CM.Node): string[] {
|
||||
if (node instanceof CM.Property || node instanceof CM.TruthyProperty) {
|
||||
return [node.name]
|
||||
}
|
||||
if (node instanceof CM.Not) {
|
||||
return getSelectorFields(node.child)
|
||||
}
|
||||
if (node instanceof CM.And || node instanceof CM.Or) {
|
||||
return node.children.flatMap(getSelectorFields)
|
||||
}
|
||||
return node instanceof CM.Null ? [] : ['*']
|
||||
}
|
||||
|
||||
export class Privilege<T extends SupportedResource> {
|
||||
#action: TPrivilege<T>['action']
|
||||
#selector?: (object: object) => boolean
|
||||
#selectorFields: string[] = []
|
||||
#resource: TPrivilege<T>['resource']
|
||||
#effect: TPrivilege<T>['effect']
|
||||
|
||||
@@ -28,9 +47,14 @@ export class Privilege<T extends SupportedResource> {
|
||||
Privilege.checkActionIsValid(resource, action)
|
||||
|
||||
this.#action = action
|
||||
this.#selector = selector !== undefined ? CM.parse(selector).createPredicate() : undefined
|
||||
this.#resource = resource
|
||||
this.#effect = effect
|
||||
|
||||
if (selector !== undefined) {
|
||||
const node = CM.parse(selector)
|
||||
this.#selector = node.createPredicate()
|
||||
this.#selectorFields = getSelectorFields(node)
|
||||
}
|
||||
}
|
||||
|
||||
get effect() {
|
||||
@@ -44,11 +68,20 @@ export class Privilege<T extends SupportedResource> {
|
||||
return this.#action === '*' || this.#action === action || action.startsWith(`${this.#action}:`)
|
||||
}
|
||||
|
||||
#matchSelector(object: object) {
|
||||
#matchSelector(object: object, knownFields?: string[]) {
|
||||
if (this.#selector === undefined) {
|
||||
return true
|
||||
}
|
||||
|
||||
// `*` is a term not bound to a property (e.g. `foo`), it may match any field, including missing ones
|
||||
// The `*` check is there to handle the case where a `*` field would exist
|
||||
if (
|
||||
knownFields !== undefined &&
|
||||
this.#selectorFields.some(field => field === '*' || !(field in object || knownFields.includes(field)))
|
||||
) {
|
||||
return UNKNOWN
|
||||
}
|
||||
|
||||
return this.#selector(object)
|
||||
}
|
||||
|
||||
@@ -60,11 +93,12 @@ export class Privilege<T extends SupportedResource> {
|
||||
action: SupportedActions<Resource>
|
||||
resource: Resource
|
||||
object: object
|
||||
}): boolean {
|
||||
knownFields?: string[]
|
||||
}): boolean | typeof UNKNOWN {
|
||||
return (
|
||||
this.#matchResource(constraint.resource) &&
|
||||
this.#matchAction(constraint.action) &&
|
||||
this.#matchSelector(constraint.object)
|
||||
this.#matchSelector(constraint.object, constraint.knownFields)
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
SupportedActions,
|
||||
SupportedActionsByResource,
|
||||
SupportedResource,
|
||||
UNKNOWN,
|
||||
} from './class/privilege.mjs'
|
||||
|
||||
// Export all types constructed using SUPPORTED_ACTIONS_BY_RESOURCE
|
||||
@@ -23,6 +24,7 @@ export type AnyPrivilegeOnParam = {
|
||||
resource: Resource
|
||||
action: SupportedActions<Resource>
|
||||
objects: object | object[]
|
||||
knownFields?: string[]
|
||||
}
|
||||
}[SupportedResource]
|
||||
|
||||
@@ -32,12 +34,14 @@ export function hasPrivilegeOn<T extends SupportedResource>({
|
||||
resource,
|
||||
objects,
|
||||
userPrivileges,
|
||||
knownFields,
|
||||
}: {
|
||||
user: XoUser
|
||||
resource: T
|
||||
action: SupportedActions<T>
|
||||
objects: object | object[]
|
||||
userPrivileges: AnyPrivilege[]
|
||||
knownFields?: string[]
|
||||
}) {
|
||||
// Function that will be called outside of the module
|
||||
// We cannot be sure types are respected
|
||||
@@ -63,7 +67,7 @@ export function hasPrivilegeOn<T extends SupportedResource>({
|
||||
return true
|
||||
}
|
||||
|
||||
const effectsByObject = new Map<object, Privilege<T>['effect'][]>()
|
||||
const effectsByObject = new Map<object, { known: boolean; effect: Privilege<T>['effect'] }[]>()
|
||||
if (Array.isArray(objects)) {
|
||||
objects.forEach(obj => effectsByObject.set(obj, []))
|
||||
} else {
|
||||
@@ -74,20 +78,49 @@ export function hasPrivilegeOn<T extends SupportedResource>({
|
||||
const privilege = new CPrivilege(userPrivilege as Privilege<typeof userPrivilege.resource>)
|
||||
|
||||
for (const [object, effects] of effectsByObject.entries()) {
|
||||
if (!privilege.match({ action, resource, object })) {
|
||||
const result = privilege.match({ action, resource, object, knownFields })
|
||||
if (!result) {
|
||||
continue
|
||||
}
|
||||
effects.push(privilege.effect)
|
||||
effects.push({ known: result !== UNKNOWN, effect: privilege.effect })
|
||||
}
|
||||
}
|
||||
|
||||
if (
|
||||
Array.from(effectsByObject.values()).some(
|
||||
effects => effects.length === 0 || effects.some(effect => effect === 'deny')
|
||||
)
|
||||
) {
|
||||
return false
|
||||
let isUndecidable = false
|
||||
for (const effects of effectsByObject.values()) {
|
||||
let hasAllow = false
|
||||
let hasKnownAllow = false
|
||||
let hasUnknownDeny = false
|
||||
|
||||
for (const { known, effect } of effects) {
|
||||
if (effect === 'allow') {
|
||||
hasAllow = true
|
||||
hasKnownAllow ||= known
|
||||
} else if (known) {
|
||||
return false
|
||||
} else {
|
||||
hasUnknownDeny = true
|
||||
}
|
||||
}
|
||||
|
||||
if (!hasAllow) {
|
||||
return false
|
||||
}
|
||||
|
||||
// do not throw yet: another object may still be known to be denied
|
||||
if (hasUnknownDeny || !hasKnownAllow) {
|
||||
isUndecidable = true
|
||||
}
|
||||
}
|
||||
|
||||
if (isUndecidable) {
|
||||
const error: Error & { code?: string } = new Error(
|
||||
`The privilege couldn't be decided because the object is missing fields the selectors need. action: ${action}, resource: ${resource}`
|
||||
)
|
||||
error.code = 'RBAC_UNKNOWN_RESULT'
|
||||
throw error
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
@@ -101,6 +134,7 @@ export function getMissingPrivileges(params: AnyPrivilegeOnParam[], userPrivileg
|
||||
action: param.action as SupportedActions<typeof param.resource>,
|
||||
objects: param.objects,
|
||||
userPrivileges,
|
||||
knownFields: param.knownFields,
|
||||
})
|
||||
)
|
||||
.map(({ action, objects, resource }) => {
|
||||
@@ -142,6 +176,7 @@ export function filterObjectsWithPrivilege<Resource extends SupportedResource, O
|
||||
action: SupportedActions<Resource>
|
||||
objects: Object[]
|
||||
userPrivileges: AnyPrivilege[]
|
||||
knownFields?: string[]
|
||||
}) {
|
||||
return param.objects.filter(obj => hasPrivilegeOn({ ...param, objects: obj }))
|
||||
}
|
||||
|
||||
@@ -3,7 +3,7 @@ import assert from 'node:assert'
|
||||
import type { Branded } from '@vates/types/common'
|
||||
import type { XoUser } from '@vates/types/xo'
|
||||
|
||||
import { Privilege } from '../class/privilege.mjs'
|
||||
import { Privilege, UNKNOWN } from '../class/privilege.mjs'
|
||||
import type { Privilege as TPrivilege } from '../index.mjs'
|
||||
import {
|
||||
filterObjectsWithPrivilege,
|
||||
@@ -81,6 +81,108 @@ suite('Privilege.match behavior', () => {
|
||||
const vmImportPrivilege = new Privilege({ action: 'import:vm', resource: 'sr', effect: 'allow' })
|
||||
assert.strictEqual(vmImportPrivilege.match({ resource: 'sr', action: 'import:vdi:url', object }), false)
|
||||
})
|
||||
|
||||
suite('on a partial object', () => {
|
||||
const ownVmPrivilege = new Privilege({
|
||||
action: 'read',
|
||||
resource: 'vm',
|
||||
selector: 'creation:creator:2',
|
||||
effect: 'allow',
|
||||
})
|
||||
const partialObject = { id: 'alma' }
|
||||
|
||||
test('Should not match a missing property if known fields are not provided', () => {
|
||||
assert.strictEqual(ownVmPrivilege.match({ resource: 'vm', action: 'read', object: partialObject }), false)
|
||||
})
|
||||
|
||||
test('Should not match a missing property if it is a known field', () => {
|
||||
assert.strictEqual(
|
||||
ownVmPrivilege.match({
|
||||
resource: 'vm',
|
||||
action: 'read',
|
||||
object: partialObject,
|
||||
knownFields: ['id', 'creation'],
|
||||
}),
|
||||
false
|
||||
)
|
||||
})
|
||||
|
||||
test('Should return UNKNOWN if the selector uses an unknown field', () => {
|
||||
assert.strictEqual(
|
||||
ownVmPrivilege.match({ resource: 'vm', action: 'read', object: partialObject, knownFields: ['id'] }),
|
||||
UNKNOWN
|
||||
)
|
||||
})
|
||||
|
||||
test('Should not match because of the resource even if the selector is unknown', () => {
|
||||
assert.strictEqual(
|
||||
ownVmPrivilege.match({ resource: 'host', action: 'read', object: partialObject, knownFields: ['id'] }),
|
||||
false
|
||||
)
|
||||
})
|
||||
|
||||
test('Should not match because of the action even if the selector is unknown', () => {
|
||||
assert.strictEqual(
|
||||
ownVmPrivilege.match({ resource: 'vm', action: 'start', object: partialObject, knownFields: ['id'] }),
|
||||
false
|
||||
)
|
||||
})
|
||||
|
||||
test('Should match without selector', () => {
|
||||
assert.strictEqual(
|
||||
privilege.match({ resource: 'vm', action: 'read', object: partialObject, knownFields: [] }),
|
||||
true
|
||||
)
|
||||
})
|
||||
|
||||
test('Should resolve a field present on the object even if it is not listed', () => {
|
||||
assert.strictEqual(
|
||||
ownVmPrivilege.match({
|
||||
resource: 'vm',
|
||||
action: 'read',
|
||||
object: { creation: { creator: '2' } },
|
||||
knownFields: [],
|
||||
}),
|
||||
true
|
||||
)
|
||||
})
|
||||
|
||||
test('Should resolve a field provided by a getter', () => {
|
||||
class Vm {
|
||||
get creation() {
|
||||
return { creator: '2' }
|
||||
}
|
||||
}
|
||||
|
||||
assert.strictEqual(
|
||||
ownVmPrivilege.match({ resource: 'vm', action: 'read', object: new Vm(), knownFields: [] }),
|
||||
true
|
||||
)
|
||||
})
|
||||
|
||||
test('Should return UNKNOWN on a term not bound to a property', () => {
|
||||
const bareTermPrivilege = new Privilege({ action: 'read', resource: 'vm', selector: 'alma', effect: 'allow' })
|
||||
|
||||
assert.strictEqual(
|
||||
bareTermPrivilege.match({ resource: 'vm', action: 'read', object: partialObject, knownFields: ['id'] }),
|
||||
UNKNOWN
|
||||
)
|
||||
})
|
||||
|
||||
test('Should return UNKNOWN if one of the fields is unknown, even if the others decide the result', () => {
|
||||
const orPrivilege = new Privilege({
|
||||
action: 'read',
|
||||
resource: 'vm',
|
||||
selector: '|(id:alma creation:creator:2)',
|
||||
effect: 'allow',
|
||||
})
|
||||
|
||||
assert.strictEqual(
|
||||
orPrivilege.match({ resource: 'vm', action: 'read', object: partialObject, knownFields: ['id'] }),
|
||||
UNKNOWN
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
suite('ACL V2 behavior', async () => {
|
||||
@@ -397,6 +499,205 @@ suite('ACL V2 behavior', async () => {
|
||||
assert.strictEqual(vms.length, 2)
|
||||
})
|
||||
})
|
||||
|
||||
suite('partial objects behavior', () => {
|
||||
const UNKNOWN_RESULT = { code: 'RBAC_UNKNOWN_RESULT' }
|
||||
|
||||
const vmReadAll = {
|
||||
id: privilegeId,
|
||||
action: 'read',
|
||||
resource: 'vm',
|
||||
effect: 'allow',
|
||||
roleId,
|
||||
} satisfies TPrivilege<'vm'>
|
||||
const vmReadOwn = {
|
||||
id: privilegeId,
|
||||
action: 'read',
|
||||
resource: 'vm',
|
||||
selector: `creation:creator:${user.id}`,
|
||||
effect: 'allow',
|
||||
roleId,
|
||||
} satisfies TPrivilege<'vm'>
|
||||
const vmDenyReadOnPool = {
|
||||
id: privilegeId,
|
||||
action: 'read',
|
||||
resource: 'vm',
|
||||
selector: '$pool:2',
|
||||
effect: 'deny',
|
||||
roleId,
|
||||
} satisfies TPrivilege<'vm'>
|
||||
|
||||
const partialVm = { id: 'partial-vm' }
|
||||
const partialVmOnDeniedPool = { id: 'partial-vm-denied', $pool: '2' }
|
||||
|
||||
suite('hasPrivilegeOn', () => {
|
||||
test('Should always return true for admin', () => {
|
||||
assert.strictEqual(
|
||||
hasPrivilegeOn({
|
||||
user: admin,
|
||||
action: 'read',
|
||||
resource: 'vm',
|
||||
objects: partialVm,
|
||||
knownFields: ['id'],
|
||||
userPrivileges: [vmReadOwn],
|
||||
}),
|
||||
true
|
||||
)
|
||||
})
|
||||
|
||||
test('Should keep the current behavior if known fields are not provided', () => {
|
||||
assert.strictEqual(
|
||||
hasPrivilegeOn({ user, action: 'read', resource: 'vm', objects: partialVm, userPrivileges: [vmReadOwn] }),
|
||||
false
|
||||
)
|
||||
})
|
||||
|
||||
test('Should throw if the only allow privilege is unknown', () => {
|
||||
assert.throws(
|
||||
() =>
|
||||
hasPrivilegeOn({
|
||||
user,
|
||||
action: 'read',
|
||||
resource: 'vm',
|
||||
objects: partialVm,
|
||||
knownFields: ['id'],
|
||||
userPrivileges: [vmReadOwn],
|
||||
}),
|
||||
UNKNOWN_RESULT
|
||||
)
|
||||
})
|
||||
|
||||
test('Should return false if the unknown field is known to be absent', () => {
|
||||
assert.strictEqual(
|
||||
hasPrivilegeOn({
|
||||
user,
|
||||
action: 'read',
|
||||
resource: 'vm',
|
||||
objects: partialVm,
|
||||
knownFields: ['id', 'creation'],
|
||||
userPrivileges: [vmReadOwn],
|
||||
}),
|
||||
false
|
||||
)
|
||||
})
|
||||
|
||||
test('Should return true if an allow privilege is known even if another one is unknown', () => {
|
||||
assert.strictEqual(
|
||||
hasPrivilegeOn({
|
||||
user,
|
||||
action: 'read',
|
||||
resource: 'vm',
|
||||
objects: partialVm,
|
||||
knownFields: ['id'],
|
||||
userPrivileges: [vmReadOwn, vmReadAll],
|
||||
}),
|
||||
true
|
||||
)
|
||||
})
|
||||
|
||||
test('Should throw if a deny privilege is unknown, even with a known allow privilege', () => {
|
||||
assert.throws(
|
||||
() =>
|
||||
hasPrivilegeOn({
|
||||
user,
|
||||
action: 'read',
|
||||
resource: 'vm',
|
||||
objects: partialVm,
|
||||
knownFields: ['id'],
|
||||
userPrivileges: [vmReadAll, vmDenyReadOnPool],
|
||||
}),
|
||||
UNKNOWN_RESULT
|
||||
)
|
||||
})
|
||||
|
||||
test('Should return true if a deny privilege is known not to match', () => {
|
||||
assert.strictEqual(
|
||||
hasPrivilegeOn({
|
||||
user,
|
||||
action: 'read',
|
||||
resource: 'vm',
|
||||
objects: partialVm,
|
||||
knownFields: ['id', '$pool'],
|
||||
userPrivileges: [vmReadAll, vmDenyReadOnPool],
|
||||
}),
|
||||
true
|
||||
)
|
||||
})
|
||||
|
||||
test('Should return false if a deny privilege is known to match, even with an unknown allow privilege', () => {
|
||||
assert.strictEqual(
|
||||
hasPrivilegeOn({
|
||||
user,
|
||||
action: 'read',
|
||||
resource: 'vm',
|
||||
objects: partialVmOnDeniedPool,
|
||||
knownFields: ['id', '$pool'],
|
||||
userPrivileges: [vmReadOwn, vmDenyReadOnPool],
|
||||
}),
|
||||
false
|
||||
)
|
||||
})
|
||||
|
||||
test('Should return false if one of the objects is known to be denied, even if another one is unknown', () => {
|
||||
assert.strictEqual(
|
||||
hasPrivilegeOn({
|
||||
user,
|
||||
action: 'read',
|
||||
resource: 'vm',
|
||||
objects: [partialVm, partialVmOnDeniedPool],
|
||||
knownFields: ['id'],
|
||||
userPrivileges: [vmReadAll, vmDenyReadOnPool],
|
||||
}),
|
||||
false
|
||||
)
|
||||
})
|
||||
|
||||
test('Should throw if the other objects are allowed and one is unknown', () => {
|
||||
assert.throws(
|
||||
() =>
|
||||
hasPrivilegeOn({
|
||||
user,
|
||||
action: 'read',
|
||||
resource: 'vm',
|
||||
objects: [{ id: 'allowed-vm', $pool: '1' }, partialVm],
|
||||
knownFields: ['id'],
|
||||
userPrivileges: [vmReadAll, vmDenyReadOnPool],
|
||||
}),
|
||||
UNKNOWN_RESULT
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
suite('getMissingPrivileges', () => {
|
||||
test('Should throw if a privilege is unknown', () => {
|
||||
assert.throws(
|
||||
() =>
|
||||
getMissingPrivileges(
|
||||
[{ user, action: 'read', resource: 'vm', objects: partialVm, knownFields: ['id'] }],
|
||||
[vmReadOwn]
|
||||
),
|
||||
UNKNOWN_RESULT
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
suite('filterObjectsWithPrivilege', () => {
|
||||
test('Should throw if a privilege is unknown on one of the objects', () => {
|
||||
assert.throws(
|
||||
() =>
|
||||
filterObjectsWithPrivilege({
|
||||
user,
|
||||
action: 'read',
|
||||
resource: 'vm',
|
||||
objects: [partialVm],
|
||||
knownFields: ['id'],
|
||||
userPrivileges: [vmReadOwn],
|
||||
}),
|
||||
UNKNOWN_RESULT
|
||||
)
|
||||
})
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
suite('getActionStrings', () => {
|
||||
|
||||
@@ -13,6 +13,7 @@ import {
|
||||
CleanResult,
|
||||
DEFAULT_MERGE_CONCURRENCY,
|
||||
DEFAULT_REMOVE_CONCURRENCY,
|
||||
MergedDisk,
|
||||
ResolvedBackupCleanOptions,
|
||||
} from './VmBackup.types.mjs'
|
||||
import { asyncEach } from '@vates/async-each'
|
||||
@@ -425,16 +426,19 @@ export class RemoteDiskLineage {
|
||||
this.#opts.logInfo('Disk chain needs merging', { count: toMerge.length })
|
||||
}
|
||||
|
||||
// mergeTargetPath: final size of the disk everything was merged into
|
||||
const mergedSizes = new Map<string, number>()
|
||||
// mergeTargetPath: the disk everything was merged into
|
||||
const mergedDisks = new Map<string, MergedDisk>()
|
||||
if (merge) {
|
||||
const limitedMergeChain = defaultMergeLimiter(this.#mergeChain.bind(this))
|
||||
const doMerge = async () => {
|
||||
await asyncEach(
|
||||
toMerge,
|
||||
async ({ chain, isResuming }) => {
|
||||
const { finalDiskSize, mergeTargetPath } = await limitedMergeChain([...chain], isResuming)
|
||||
mergedSizes.set(mergeTargetPath, (mergedSizes.get(mergeTargetPath) ?? 0) + finalDiskSize)
|
||||
const { finalSizeOnDisk, mergeTargetPath, streamSize, isDifferencing } = await limitedMergeChain(
|
||||
[...chain],
|
||||
isResuming
|
||||
)
|
||||
mergedDisks.set(mergeTargetPath, { sizeOnDisk: finalSizeOnDisk, streamSize, isDifferencing })
|
||||
// parentPath alias deleted by parentDisk.rename(mergeTargetPath)
|
||||
// intermediates deleted by childDisk.unlink() when removeUnused=true
|
||||
// Unregister so #cleanOrphanDataFiles does not read already-deleted aliases
|
||||
@@ -453,19 +457,31 @@ export class RemoteDiskLineage {
|
||||
|
||||
await this.#cleanOrphanDataFiles(remove)
|
||||
|
||||
const sizeOnDisks = [...mergedDisks.values()].map(({ sizeOnDisk }) => sizeOnDisk)
|
||||
return {
|
||||
removedFiles: Array.from(toDelete),
|
||||
merge: toMerge.length > 0,
|
||||
size: [...mergedSizes.values()].reduce((total, subSize) => total + subSize, 0),
|
||||
mergedSizes,
|
||||
size: sizeOnDisks.reduce<number | undefined>(
|
||||
(total, subSize) => (total !== undefined && subSize !== undefined ? total + subSize : undefined),
|
||||
0
|
||||
),
|
||||
mergedDisks,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Merges ancestors into the active child at the end of the chain.
|
||||
* Returns the final size of the merge target and its path.
|
||||
* Returns the final size of the merge target and its path, undefined if unknown.
|
||||
*/
|
||||
async #mergeChain(chain: string[], isResuming: boolean): Promise<{ finalDiskSize: number; mergeTargetPath: string }> {
|
||||
async #mergeChain(
|
||||
chain: string[],
|
||||
isResuming: boolean
|
||||
): Promise<{
|
||||
finalSizeOnDisk: number | undefined
|
||||
mergeTargetPath: string
|
||||
streamSize: number
|
||||
isDifferencing: boolean
|
||||
}> {
|
||||
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
|
||||
@@ -489,8 +505,8 @@ export class RemoteDiskLineage {
|
||||
force: isResuming,
|
||||
})
|
||||
|
||||
const { finalDiskSize } = (await merger.merge(parentDisk, childDisk!))!
|
||||
return { finalDiskSize, mergeTargetPath }
|
||||
const { finalSizeOnDisk, streamSize, isDifferencing } = (await merger.merge(parentDisk, childDisk!))!
|
||||
return { finalSizeOnDisk, mergeTargetPath, streamSize, isDifferencing }
|
||||
} finally {
|
||||
await parentDisk?.close().catch(error => {
|
||||
this.#opts.logWarn('Error closing parent Disk', error)
|
||||
|
||||
@@ -6,7 +6,12 @@ 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
|
||||
@@ -38,7 +43,7 @@ export type ResolvedBackupCleanOptions = BackupCleanOptions & {
|
||||
export interface ArchiveCleanOptions {
|
||||
remove?: boolean
|
||||
merge?: boolean
|
||||
mergedSizes?: Map<string, number>
|
||||
mergedDisks?: Map<string, MergedDisk>
|
||||
}
|
||||
|
||||
export interface CheckResult {
|
||||
@@ -55,11 +60,11 @@ export interface CheckResult {
|
||||
|
||||
export type CleanResult = {
|
||||
removedFiles: string[]
|
||||
// Files rewritten in place (e.g. metadata whose size was updated after a merge)
|
||||
// Files rewritten in place (e.g. metadata recording the size on disk of the disks a merge rewrote)
|
||||
changedFiles?: string[]
|
||||
merge?: boolean
|
||||
size?: number
|
||||
mergedSizes?: Map<string, number>
|
||||
mergedDisks?: Map<string, MergedDisk>
|
||||
}
|
||||
|
||||
export interface VmBackupInterface {
|
||||
@@ -74,3 +79,9 @@ export interface VmBackupInterface {
|
||||
clean(opts?: ArchiveCleanOptions): Promise<CleanResult>
|
||||
getAssociatedFiles(opts: object): Array<string>
|
||||
}
|
||||
|
||||
export type MergedDisk = {
|
||||
sizeOnDisk: number | undefined
|
||||
streamSize: number
|
||||
isDifferencing: boolean
|
||||
}
|
||||
|
||||
@@ -13,6 +13,7 @@ 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'
|
||||
@@ -138,19 +139,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 allMergedSizes = new Map<string, number>()
|
||||
const allMergedDisks = new Map<string, MergedDisk>()
|
||||
await asyncEach(
|
||||
Array.from(this.#uniqueLineages!.entries()),
|
||||
async ([_vdiDir, lineage]) => {
|
||||
const { mergedSizes, removedFiles, merge: hasPendingMerge } = await lineage.clean({ remove, merge })
|
||||
const { mergedDisks, removedFiles, merge: hasPendingMerge } = await lineage.clean({ remove, merge })
|
||||
if (removedFiles.length > 0) {
|
||||
cacheNeedsRegen = true
|
||||
}
|
||||
if (hasPendingMerge) {
|
||||
someLineageMergedOrShouldBe = true
|
||||
}
|
||||
for (const [diskPath, size] of mergedSizes || []) {
|
||||
allMergedSizes.set(diskPath, (allMergedSizes.get(diskPath) ?? 0) + size)
|
||||
for (const [diskPath, mergedDisk] of mergedDisks || []) {
|
||||
allMergedDisks.set(diskPath, mergedDisk)
|
||||
}
|
||||
},
|
||||
{ concurrency: DEFAULT_MERGE_CONCURRENCY }
|
||||
@@ -174,7 +175,7 @@ export class VmBackupDirectory implements VmBackupInterface {
|
||||
async ([metadataPath, archive]: [string, VmBackupInterface]) => {
|
||||
const { removedFiles, changedFiles: archiveChangedFiles } = await archive.clean({
|
||||
remove,
|
||||
mergedSizes: allMergedSizes,
|
||||
mergedDisks: allMergedDisks,
|
||||
})
|
||||
if (removedFiles.length > 0) {
|
||||
cacheNeedsRegen = true
|
||||
@@ -194,7 +195,7 @@ export class VmBackupDirectory implements VmBackupInterface {
|
||||
this.backupArchives.delete(metadataPath)
|
||||
}
|
||||
|
||||
if (this.#cacheExisted && (allMergedSizes.size > 0 || cacheNeedsRegen || this.#cacheOutOfSync)) {
|
||||
if (this.#cacheExisted && (allMergedDisks.size > 0 || cacheNeedsRegen || this.#cacheOutOfSync)) {
|
||||
await this.#regenerateCache()
|
||||
}
|
||||
|
||||
@@ -216,7 +217,12 @@ export class VmBackupDirectory implements VmBackupInterface {
|
||||
{ concurrency: 2 }
|
||||
)
|
||||
}
|
||||
const size = [...allMergedSizes.values()].reduce((total, merged) => total + merged, 0)
|
||||
|
||||
const sizeOnDisks = [...allMergedDisks.values()].map(({ sizeOnDisk }) => sizeOnDisk)
|
||||
const size = sizeOnDisks.reduce<number | undefined>(
|
||||
(total, merged) => (total !== undefined && merged !== undefined ? total + merged : undefined),
|
||||
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.
|
||||
|
||||
@@ -14,11 +14,13 @@ 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 } from 'vhd-lib'
|
||||
import { VhdFile, Constants, VhdDirectory, VhdAbstract, openVhd } from 'vhd-lib'
|
||||
import Disposable from 'promise-toolbox/Disposable'
|
||||
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
|
||||
|
||||
@@ -51,6 +53,42 @@ 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
|
||||
|
||||
@@ -336,7 +374,7 @@ test('it merges delta of non destroyed chain', async () => {
|
||||
`${rootPath}/metadata.json`,
|
||||
JSON.stringify({
|
||||
mode: 'delta',
|
||||
size: 12000, // a size too small
|
||||
size: 12000,
|
||||
vhds: [
|
||||
`${relativePath}/grandchild.vhd`, // grand child should not be merged
|
||||
`${relativePath}/child.vhd`,
|
||||
@@ -381,7 +419,152 @@ 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, 4299776, 'metadata.size should be updated after merge')
|
||||
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')
|
||||
})
|
||||
|
||||
test('it merges a chain of multiple consecutive orphan ancestors in one pass', async () => {
|
||||
@@ -727,8 +910,28 @@ 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`))
|
||||
// size should be the size of children + grand children + clean after the merge
|
||||
assert.deepEqual(metadata.size, 6501888)
|
||||
// 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)
|
||||
// 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'),
|
||||
@@ -864,7 +1067,7 @@ test('it regenerates a pre-existing cache after a merge', async () => {
|
||||
`${rootPath}/metadata.json`,
|
||||
JSON.stringify({
|
||||
mode: 'delta',
|
||||
size: 12000, // a size too small, the merge will fix it
|
||||
size: 12000,
|
||||
vhds: [`${relativePath}/grandchild.vhd`, `${relativePath}/child.vhd`],
|
||||
})
|
||||
)
|
||||
@@ -900,13 +1103,26 @@ test('it regenerates a pre-existing cache after a merge', async () => {
|
||||
})
|
||||
|
||||
const metadata = JSON.parse(await handler.readFile(`${rootPath}/metadata.json`))
|
||||
// size of child + grandchild after orphan has been merged into child
|
||||
assert.equal(metadata.size, 4299776, 'metadata.size should be updated after merge')
|
||||
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'
|
||||
)
|
||||
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.equal(Object.values(cache)[0].size, metadata.size, 'cache entry should carry the post-merge size')
|
||||
assert.deepEqual(
|
||||
Object.values(cache)[0].vhdsSizeOnDisk,
|
||||
metadata.vhdsSizeOnDisk,
|
||||
'cache entry should carry the post-merge size on disk'
|
||||
)
|
||||
})
|
||||
|
||||
test('it regenerates a pre-existing cache when its entry count is out of sync, even with nothing to merge/remove', async () => {
|
||||
|
||||
@@ -6,9 +6,10 @@ import {
|
||||
VmBackupInterface,
|
||||
PartialBackupMetadata,
|
||||
DEFAULT_REMOVE_CONCURRENCY,
|
||||
MergedDisk,
|
||||
} from './VmBackup.types.mjs'
|
||||
import { RemoteHandlerAbstract } from '@xen-orchestra/fs'
|
||||
import { basename, dirname, normalize } from '@xen-orchestra/fs/path'
|
||||
import { basename, dirname, normalize, resolveFromFile } from '@xen-orchestra/fs/path'
|
||||
import { RemoteDiskLineage } from './RemoteDiskLineage.mjs'
|
||||
import { asyncEach } from '@vates/async-each'
|
||||
|
||||
@@ -126,10 +127,13 @@ export class VmIncrementalBackupArchive implements VmBackupInterface {
|
||||
|
||||
/**
|
||||
* Removes the metadata file if the backup is incomplete (missing disks).
|
||||
* If mergedSizes is provided, updates metadata with the total merged size for this archive's 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.
|
||||
* Actual disk merge/deletion is handled by RemoteDiskLineage.
|
||||
*/
|
||||
async clean({ remove = this.opts.remove ?? false, mergedSizes }: ArchiveCleanOptions = {}): Promise<CleanResult> {
|
||||
async clean({ remove = this.opts.remove ?? false, mergedDisks }: ArchiveCleanOptions = {}): Promise<CleanResult> {
|
||||
if (!this.#isChecked) {
|
||||
await this.check()
|
||||
}
|
||||
@@ -150,13 +154,18 @@ export class VmIncrementalBackupArchive implements VmBackupInterface {
|
||||
}
|
||||
|
||||
const changedFiles: string[] = []
|
||||
let mergedSize = 0
|
||||
if (mergedSizes !== undefined) {
|
||||
for (const diskPath of this.diskPaths) {
|
||||
mergedSize += mergedSizes.get(diskPath) ?? 0
|
||||
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
|
||||
}
|
||||
}
|
||||
if (mergedSize > 0) {
|
||||
await this.updateMetadata(mergedSize)
|
||||
|
||||
if (Object.keys(updates).length > 0) {
|
||||
await this.updateMetadata(updates)
|
||||
changedFiles.push(this.metadataPath)
|
||||
}
|
||||
}
|
||||
@@ -165,17 +174,30 @@ export class VmIncrementalBackupArchive implements VmBackupInterface {
|
||||
}
|
||||
|
||||
/**
|
||||
* 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).
|
||||
* 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.
|
||||
*/
|
||||
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
|
||||
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
|
||||
}
|
||||
}
|
||||
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' })
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,7 @@ 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')
|
||||
@@ -23,7 +24,9 @@ const { warn } = createLogger('remote-disk:merge')
|
||||
* @property {number} currentBlock
|
||||
* @property {number} mergedDataSize
|
||||
* @property {'mergeBlocks' | 'cleanup'} step
|
||||
* @property {number} diskSize
|
||||
* @property {number} [sizeOnDisk]
|
||||
* @property {number} [streamSize]
|
||||
* @property {boolean} [isDifferencing]
|
||||
* @typedef {(message: string, data?: Record<string, unknown>) => void} Logger
|
||||
*/
|
||||
|
||||
@@ -38,7 +41,6 @@ export class MergeRemoteDisk {
|
||||
currentBlock: 0,
|
||||
mergedDataSize: 0,
|
||||
step: 'mergeBlocks',
|
||||
diskSize: 0,
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -220,10 +222,28 @@ 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)
|
||||
this.#state.diskSize = parentDisk.getSizeOnDisk()
|
||||
|
||||
// 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 })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -301,6 +321,36 @@ 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
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -308,11 +358,13 @@ export class MergeRemoteDisk {
|
||||
* @param {RemoteDisk} childDisk
|
||||
* @param {boolean} cleanStateFile
|
||||
*
|
||||
* @returns {Promise<{mergedDataSize: number, finalDiskSize: number}>} result
|
||||
* @returns {Promise<{mergedDataSize: number, finalSizeOnDisk: number | undefined, streamSize: number, isDifferencing: boolean}>} result
|
||||
*/
|
||||
async #cleanup(parentDisk, childDisk, cleanStateFile) {
|
||||
const finalDiskSize = this.#state?.diskSize ?? 0
|
||||
const finalSizeOnDisk = this.#state?.sizeOnDisk
|
||||
const streamSize = this.#state?.streamSize ?? 0
|
||||
const mergedDataSize = this.#state?.mergedDataSize ?? 0
|
||||
const isDifferencing = this.#state?.isDifferencing ?? false
|
||||
await parentDisk.close().catch(warn)
|
||||
await childDisk.close().catch(warn)
|
||||
|
||||
@@ -320,7 +372,7 @@ export class MergeRemoteDisk {
|
||||
await this.#handler.unlink(this.#statePath).catch(warn)
|
||||
}
|
||||
|
||||
return { mergedDataSize, finalDiskSize }
|
||||
return { mergedDataSize, finalSizeOnDisk, streamSize, isDifferencing }
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -36,8 +36,8 @@ export class RemoteDisk extends RandomAccessDisk {
|
||||
* Abstract
|
||||
* @returns {number} size
|
||||
*/
|
||||
getSizeOnDisk() {
|
||||
throw new Error(`getSizeOnDisk must be implemented`)
|
||||
getStreamSize() {
|
||||
throw new Error(`getStreamSize must be implemented`)
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -294,4 +294,22 @@ 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`)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -13,12 +13,35 @@ 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}` })
|
||||
@@ -75,6 +98,9 @@ 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
|
||||
}
|
||||
|
||||
@@ -350,9 +376,12 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
|
||||
|
||||
const result = await mergeRemoteDisk.merge(parent, child)
|
||||
|
||||
assert.ok(result.finalDiskSize > 0, 'merged disks should have non-zero size')
|
||||
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.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)
|
||||
@@ -362,6 +391,27 @@ 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 = () => {
|
||||
@@ -412,7 +462,7 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
|
||||
|
||||
const result = await mergeRemoteDisk.merge(parent, childDiskChain)
|
||||
|
||||
assert.ok(result.finalDiskSize > 0, 'merged disks should have non-zero size')
|
||||
assert.ok(result.finalSizeOnDisk > 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')
|
||||
|
||||
@@ -450,7 +500,7 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
|
||||
|
||||
const result = await mergeRemoteDisk.merge(parent, child)
|
||||
|
||||
assert.ok(result.finalDiskSize > 0, 'merged disks should have non-zero size')
|
||||
assert.ok(result.finalSizeOnDisk > 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')
|
||||
|
||||
@@ -505,7 +555,7 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
|
||||
|
||||
const result = await mergeRemoteDisk.merge(parent, childDiskChain)
|
||||
|
||||
assert.ok(result.finalDiskSize > 0, 'merged disks should have non-zero size')
|
||||
assert.ok(result.finalSizeOnDisk > 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')
|
||||
|
||||
@@ -546,7 +596,7 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
|
||||
|
||||
const result = await mergeRemoteDisk.merge(parent, child)
|
||||
|
||||
assert.ok(result.finalDiskSize > 0, 'merged disks should have non-zero size')
|
||||
assert.ok(result.finalSizeOnDisk > 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')
|
||||
|
||||
@@ -587,7 +637,7 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
|
||||
|
||||
const result = await mergeRemoteDisk.merge(parent, child)
|
||||
|
||||
assert.ok(result.finalDiskSize > 0, 'merged disks should have non-zero size')
|
||||
assert.ok(result.finalSizeOnDisk > 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')
|
||||
|
||||
@@ -595,11 +645,33 @@ 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, [])
|
||||
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))
|
||||
)
|
||||
|
||||
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 () => {
|
||||
@@ -628,7 +700,7 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
|
||||
|
||||
const result = await mergeRemoteDisk.merge(parent, child)
|
||||
|
||||
assert.ok(result.finalDiskSize > 0, 'merged disks should have non-zero size')
|
||||
assert.ok(result.finalSizeOnDisk > 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')
|
||||
|
||||
@@ -767,7 +839,7 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
|
||||
const result = await mergeRemoteDisk.merge(parent2, child2)
|
||||
|
||||
// Verify merge completed
|
||||
assert.ok(result.finalDiskSize > 0, 'final disk size should be > 0')
|
||||
assert.ok(result.finalSizeOnDisk > 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
|
||||
@@ -863,7 +935,7 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
|
||||
const result = await mergeRemoteDisk.merge(parent2, child2)
|
||||
|
||||
// Verify merge completed
|
||||
assert.ok(result.finalDiskSize > 0, 'final disk size should be > 0')
|
||||
assert.strictEqual(result.finalSizeOnDisk, undefined, 'the size of a resumed merge is unknown')
|
||||
assert.ok(result.mergedDataSize > 0, 'merged data size should be > 0')
|
||||
|
||||
// Verify state file removed after successful resume
|
||||
@@ -957,7 +1029,7 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
|
||||
|
||||
const result = await mergeRemoteDisk.merge(parent2, childDiskChain2)
|
||||
|
||||
assert.ok(result.finalDiskSize > 0, 'final disk size should be > 0')
|
||||
assert.ok(result.finalSizeOnDisk > 0, 'final disk size should be > 0')
|
||||
|
||||
assert.equal(
|
||||
(await handler.list(basePath)).includes(stateFileName),
|
||||
@@ -1047,6 +1119,281 @@ 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)
|
||||
})
|
||||
})
|
||||
|
||||
/**
|
||||
|
||||
@@ -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 } from 'node:path'
|
||||
import { dirname, join, basename } 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
|
||||
*/
|
||||
getSizeOnDisk() {
|
||||
getStreamSize() {
|
||||
if (this.#vhd === undefined) {
|
||||
throw new Error(`can't call getVirtualSize of a RemoteVhdDisk before init`)
|
||||
throw new Error(`can't call getStreamSize of a RemoteVhdDisk before init`)
|
||||
}
|
||||
|
||||
return this.#vhd.streamSize()
|
||||
@@ -322,9 +322,7 @@ export class RemoteVhdDisk extends RemoteDisk {
|
||||
(await childDisk.isDirectory())
|
||||
) {
|
||||
try {
|
||||
await this.#handler.rename(childDisk.getBlockPath(index), this.getBlockPath(index))
|
||||
|
||||
this.setAllocatedBlocks([index])
|
||||
await /** @type {VhdDirectory} */ (this.#vhd).moveBlockFrom(index, childDisk.getBlockPath(index))
|
||||
} catch (error) {
|
||||
// @ts-ignore
|
||||
if (error.code === 'ENOENT' && isResumingMerge === true) {
|
||||
@@ -333,9 +331,6 @@ 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
|
||||
@@ -395,6 +390,39 @@ 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
|
||||
@@ -487,15 +515,29 @@ 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)) {
|
||||
const dataPath = await resolveVhdAlias(this.#handler, this.#path)
|
||||
if (isVhdAlias(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)
|
||||
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)
|
||||
}
|
||||
|
||||
this.#path = newPath
|
||||
} else {
|
||||
|
||||
@@ -93,7 +93,7 @@ export class RemoteVhdDiskChain extends RemoteDisk {
|
||||
/**
|
||||
* @returns {number} size
|
||||
*/
|
||||
getSizeOnDisk() {
|
||||
getStreamSize() {
|
||||
const batEntrySize = 4
|
||||
const sectorSize = 512
|
||||
const batSize = Math.ceil((this.getMaxBlockCount() * batEntrySize) / sectorSize) * sectorSize
|
||||
@@ -253,6 +253,24 @@ 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>}
|
||||
|
||||
@@ -5,6 +5,7 @@ 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'
|
||||
@@ -425,6 +426,7 @@ export class ImportVmBackup {
|
||||
throw new Error('live mounting a disk is only supported when restoring an incremental backup')
|
||||
}
|
||||
backup = await adapter.readFullVmBackup(metadata)
|
||||
sizeContainer.readTask = new SourceReadTask('read')
|
||||
watchStreamSize(backup, sizeContainer)
|
||||
|
||||
// the restore stops once aborted (e.g. the health check of an aborted backup): a full backup is a stream that
|
||||
@@ -440,6 +442,9 @@ 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(
|
||||
|
||||
@@ -16,6 +16,7 @@ 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
|
||||
|
||||
@@ -23,6 +24,27 @@ 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()
|
||||
@@ -256,11 +278,20 @@ describe('RemoteAdapter#writeVhd validated by checkDisk', { concurrency: 1 }, ()
|
||||
const adapter = await getAdapter({ useVhdDirectory })
|
||||
const path = `${basePath}/${adapter.getVhdFileName('base')}`
|
||||
|
||||
const size = await adapter.writeVhd(path, new MockDisk(2, [0, 1], 0x42), {
|
||||
const { size, sizeOnDisk } = 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 => {
|
||||
|
||||
@@ -38,6 +38,7 @@ 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'
|
||||
|
||||
@@ -687,7 +688,11 @@ export class RemoteAdapter {
|
||||
return path
|
||||
}
|
||||
|
||||
// `signal` stops the write once aborted: the partial disk is then removed
|
||||
/**
|
||||
* `signal` stops the write once aborted: the partial disk is then removed
|
||||
*
|
||||
* @returns {Promise<{size: number, sizeOnDisk: number}>}
|
||||
*/
|
||||
async writeVhd(path, disk, { signal, validator = noop, writeBlockConcurrency, uuid, parentUuid, parentPath } = {}) {
|
||||
const handler = this._handler
|
||||
|
||||
@@ -719,7 +724,8 @@ export class RemoteAdapter {
|
||||
checksum: false,
|
||||
})
|
||||
await validator(path)
|
||||
return size
|
||||
const sizeOnDisk = await this._handler.getSizeOnDisk(path)
|
||||
return { size, sizeOnDisk }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -889,9 +895,11 @@ export class RemoteAdapter {
|
||||
return reduce(
|
||||
backups,
|
||||
(prev, backup) => {
|
||||
const _backup = Array.isArray(backup) ? this.#computeTotalBackupSizeRecursively(backup) : backup
|
||||
const size = Array.isArray(backup)
|
||||
? this.#computeTotalBackupSizeRecursively(backup).onDisk
|
||||
: (getVmBackupSizeOnDisk(backup) ?? backup.size)
|
||||
return {
|
||||
onDisk: prev.onDisk + (_backup.onDisk ?? _backup.size),
|
||||
onDisk: prev.onDisk + size,
|
||||
}
|
||||
},
|
||||
{ onDisk: 0 }
|
||||
|
||||
125
@xen-orchestra/backups/_SourceReadTask.mjs
Normal file
125
@xen-orchestra/backups/_SourceReadTask.mjs
Normal file
@@ -0,0 +1,125 @@
|
||||
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}`))
|
||||
}
|
||||
300
@xen-orchestra/backups/_SourceReadTask.test.mjs
Normal file
300
@xen-orchestra/backups/_SourceReadTask.test.mjs
Normal file
@@ -0,0 +1,300 @@
|
||||
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')
|
||||
})
|
||||
})
|
||||
@@ -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 its size after merging its disks
|
||||
* - `merge`: `cleanVm()` rewrote it after merging its disks, to record their new size on disk
|
||||
*
|
||||
* @typedef {'backup'|'retention'|'user'|'clean-vm'|'merge'} BackupJournalReason
|
||||
*/
|
||||
|
||||
@@ -8,7 +8,8 @@ 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 } from 'vhd-lib'
|
||||
import { VhdFile, Constants, VhdDirectory, VhdAbstract, openVhd } from 'vhd-lib'
|
||||
import Disposable from 'promise-toolbox/Disposable'
|
||||
import { dirname, basename } from 'node:path'
|
||||
import { rimraf } from 'rimraf'
|
||||
|
||||
@@ -34,6 +35,14 @@ 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))
|
||||
|
||||
@@ -198,7 +207,7 @@ test('it merges delta of non destroyed chain', async () => {
|
||||
`${rootPath}/metadata.json`,
|
||||
JSON.stringify({
|
||||
mode: 'delta',
|
||||
size: 12000, // a size too small
|
||||
size: 12000,
|
||||
vhds: [
|
||||
`${relativePath}/grandchild.vhd`, // grand child should not be merged
|
||||
`${relativePath}/child.vhd`,
|
||||
@@ -239,7 +248,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, 4299776)
|
||||
assert.equal(metadata.size, 12000)
|
||||
|
||||
// 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
|
||||
@@ -453,8 +462,15 @@ 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`))
|
||||
// size is the sum of the merged chains' final on-disk sizes:
|
||||
assert.deepEqual(metadata.size, 6501888)
|
||||
// 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
|
||||
)
|
||||
|
||||
// broken vhd, non referenced, abandoned should be deleted ( alias and data)
|
||||
// ancestor and child should be merged
|
||||
|
||||
@@ -5,6 +5,7 @@ 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'
|
||||
|
||||
@@ -26,7 +27,8 @@ export const FullRemote = class FullRemoteVmBackupRunner extends AbstractRemote
|
||||
for (const metadata of transferList) {
|
||||
Task.abortSignal?.throwIfAborted()
|
||||
const stream = this._throttleStream(await this._sourceRemoteAdapter.readFullVmBackup(metadata))
|
||||
const sizeContainer = watchStreamSize(stream)
|
||||
// the backup is read once, whatever the number of writers
|
||||
const sizeContainer = watchStreamSize(stream, { size: 0, readTask: new SourceReadTask('read') })
|
||||
let checksum
|
||||
try {
|
||||
// the unencrypted destinations store the same data as the source: no need to compute their checksum again
|
||||
|
||||
@@ -5,6 +5,7 @@ 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'
|
||||
@@ -81,7 +82,8 @@ export const FullXapi = class FullXapiVmBackupRunner extends AbstractXapi {
|
||||
maxStreamLength += XVA_BLOCK_SIZE * nbBlocks + headersSize
|
||||
}
|
||||
|
||||
const sizeContainer = watchStreamSize(stream)
|
||||
// the export is read once, whatever the number of writers
|
||||
const sizeContainer = watchStreamSize(stream, { size: 0, readTask: new SourceReadTask('read') })
|
||||
|
||||
const transferStart = Date.now()
|
||||
await this._callWriters(
|
||||
|
||||
@@ -13,6 +13,7 @@ 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 {
|
||||
@@ -101,6 +102,8 @@ 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)
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ 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')
|
||||
|
||||
@@ -69,6 +70,8 @@ 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)
|
||||
}
|
||||
|
||||
@@ -69,6 +69,7 @@ export class FullRemoteWriter extends MixinRemoteWriter(AbstractFullWriter) {
|
||||
await deleteOldBackups()
|
||||
}
|
||||
|
||||
let sizeOnDisk = 0
|
||||
await Task.run({ properties: { name: 'transfer' } }, async () => {
|
||||
await adapter.outputStream(dataFilename, stream, {
|
||||
checksum,
|
||||
@@ -76,9 +77,20 @@ 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)
|
||||
|
||||
|
||||
@@ -280,6 +280,7 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
|
||||
vtpms: deltaExport.vtpms,
|
||||
}
|
||||
let size = 0
|
||||
const vhdsSizeOnDisk = {}
|
||||
await Task.run({ properties: { name: 'transfer' } }, async () => {
|
||||
// stops the writes once the backup is aborted
|
||||
const signal = Task.abortSignal
|
||||
@@ -299,7 +300,7 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
|
||||
parentPath = relativeFromFile(path, parentDestPath)
|
||||
}
|
||||
|
||||
const transferred = await adapter.writeVhd(path, disk, {
|
||||
const { size: transferred, sizeOnDisk } = await adapter.writeVhd(path, disk, {
|
||||
// no checksum for VHDs, because they will be invalidated by
|
||||
// merges and chains
|
||||
checksum: false,
|
||||
@@ -311,6 +312,7 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
|
||||
parentPath,
|
||||
})
|
||||
size += transferred
|
||||
vhdsSizeOnDisk[diskRef] = sizeOnDisk
|
||||
},
|
||||
{
|
||||
concurrency: settings.diskPerVmConcurrency,
|
||||
@@ -326,6 +328,7 @@ 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?
|
||||
|
||||
@@ -1,17 +1,34 @@
|
||||
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 = container.progressHandler ?? new TaskProgressHandler()
|
||||
const { progressHandler = new TaskProgressHandler(), readTask } = container
|
||||
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
|
||||
}
|
||||
|
||||
@@ -29,7 +29,17 @@ import { normalize } from '@xen-orchestra/fs/path'
|
||||
*/
|
||||
|
||||
/**
|
||||
* @returns {import('@vates/types').XoVmBackupArchive & { tags: string[] }}
|
||||
* 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}
|
||||
*/
|
||||
export function formatVmBackup(backup) {
|
||||
const { isVhdDifferencing, vmSnapshot } = backup
|
||||
@@ -59,6 +69,8 @@ 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],
|
||||
}
|
||||
}),
|
||||
|
||||
@@ -68,6 +80,7 @@ export function formatVmBackup(backup) {
|
||||
mode: backup.mode,
|
||||
scheduleId: backup.scheduleId,
|
||||
size: backup.size,
|
||||
sizeOnDisk: getVmBackupSizeOnDisk(backup),
|
||||
timestamp: backup.timestamp,
|
||||
vm: {
|
||||
uuid: backup.vm.uuid,
|
||||
@@ -131,3 +144,30 @@ 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
|
||||
}
|
||||
|
||||
@@ -54,7 +54,13 @@ describe('formatVmBackupAt()', () => {
|
||||
|
||||
for (const filename of [FILENAME, FILENAME.slice(1)]) {
|
||||
assert.deepEqual(formatVmBackupAt(metadata, filename, REPOSITORY).disks, [
|
||||
{ id: `/xo-vm-backups/${VM}/vdi.vhd`, name: 'a disk', uuid: 'a-vdi-uuid' },
|
||||
{
|
||||
id: `/xo-vm-backups/${VM}/vdi.vhd`,
|
||||
isDifferencing: undefined,
|
||||
name: 'a disk',
|
||||
uuid: 'a-vdi-uuid',
|
||||
sizeOnDisk: undefined,
|
||||
},
|
||||
])
|
||||
}
|
||||
})
|
||||
@@ -99,6 +105,87 @@ 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()
|
||||
|
||||
@@ -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 size on disk
|
||||
list List all disks at a path and display their properties in a table; --size adds the size on disk
|
||||
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
|
||||
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 size on disk. Pass `--size` to read
|
||||
the block allocation table and print the size on disk as an extra line:
|
||||
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:
|
||||
|
||||
```
|
||||
$ 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)
|
||||
Size on disk: 128.00 MiB (134217728 bytes)
|
||||
Stream size: 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 "Size on disk" column is omitted:
|
||||
so the "Stream size" 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 "Size on disk" column:
|
||||
Pass `--size` to read each disk's block allocation table and add the "Stream size" column:
|
||||
|
||||
```
|
||||
$ xo-disk-cli list file:///mnt/backups /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/ --size
|
||||
┌──────────────┬──────────────────────────────────────┬─────────────┬──────────────┬─────────────┬──────────────────────────────────────┐
|
||||
│ File │ UID │ Size on disk│ Virtual size │ Differencing │ Parent UID │
|
||||
│ File │ UID │ Stream size │ 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 │ ↑ │
|
||||
|
||||
@@ -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 size on disk
|
||||
list List all disks at a path and display their properties in a table; --size adds the size on disk
|
||||
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
|
||||
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 size on disk. Pass `--size` to read
|
||||
the block allocation table and print the size on disk as an extra line:
|
||||
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:
|
||||
|
||||
```
|
||||
$ 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)
|
||||
Size on disk: 128.00 MiB (134217728 bytes)
|
||||
Stream size: 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 "Size on disk" column is omitted:
|
||||
so the "Stream size" 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 "Size on disk" column:
|
||||
Pass `--size` to read each disk's block allocation table and add the "Stream size" column:
|
||||
|
||||
```
|
||||
$ xo-disk-cli list file:///mnt/backups /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/ --size
|
||||
┌──────────────┬──────────────────────────────────────┬─────────────┬──────────────┬─────────────┬──────────────────────────────────────┐
|
||||
│ File │ UID │ Size on disk│ Virtual size │ Differencing │ Parent UID │
|
||||
│ File │ UID │ Stream size │ 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 │ ↑ │
|
||||
|
||||
@@ -10,7 +10,7 @@ type DiskInfoLine = {
|
||||
virtualSize: number
|
||||
blockSize: number
|
||||
// Only computed with --size; requires reading the block allocation table.
|
||||
sizeOnDisk?: number
|
||||
streamSize?: 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(),
|
||||
sizeOnDisk: showSize ? disk.getSizeOnDisk() : undefined,
|
||||
streamSize: showSize ? disk.getStreamSize() : 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.sizeOnDisk !== undefined) {
|
||||
console.log(` Size on disk: ${formatBytes(info.sizeOnDisk)} (${info.sizeOnDisk} bytes)`)
|
||||
if (info.streamSize !== undefined) {
|
||||
console.log(` Stream size: ${formatBytes(info.streamSize)} (${info.streamSize} bytes)`)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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 "Size on disk" column is only shown with --size: computing it requires
|
||||
// The "Stream size" 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 ? ['Size on disk'] : []), 'Virtual size', 'Differencing', 'Parent UID']
|
||||
return ['File', 'UID', ...(showSize ? ['Stream size'] : []), 'Virtual size', 'Differencing', 'Parent UID']
|
||||
}
|
||||
|
||||
export type OkDiskInfo = {
|
||||
ok: true
|
||||
filename: string
|
||||
uid: string
|
||||
sizeOnDisk?: string
|
||||
streamSize?: 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.sizeOnDisk ?? '-'] : []),
|
||||
...(showSize ? [disk.streamSize ?? '-'] : []),
|
||||
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(),
|
||||
sizeOnDisk: showSize ? formatBytes(disk.getSizeOnDisk()) : undefined,
|
||||
streamSize: showSize ? formatBytes(disk.getStreamSize()) : undefined,
|
||||
virtualSize: formatBytes(disk.getVirtualSize()),
|
||||
differencing,
|
||||
parentUid: differencing ? disk.getParentUuid() : null,
|
||||
|
||||
@@ -51,7 +51,7 @@ declare module '@xen-orchestra/backup-archive/disks' {
|
||||
import type { RandomAccessDisk } from '@xen-orchestra/disk-transform'
|
||||
|
||||
export interface RemoteDisk extends RandomAccessDisk {
|
||||
getSizeOnDisk(): number
|
||||
getStreamSize(): number
|
||||
getPath(): string
|
||||
getPaths(): string[]
|
||||
getUuid(): string
|
||||
|
||||
@@ -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 size on disk',
|
||||
list: 'List all disks at a path and display their properties in a table; --size adds the size on disk',
|
||||
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',
|
||||
transform: 'Convert a disk to another format and write to stdout (raw | vhd | qcow2)',
|
||||
}
|
||||
|
||||
|
||||
@@ -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 size on disk.
|
||||
* opens with ignoreBlockIndexes: false and prints the stream size.
|
||||
* - --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,
|
||||
getSizeOnDisk: () => 128 * 1024 * 1024,
|
||||
getStreamSize: () => 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 size on disk', async () => {
|
||||
test('by default opens the disk with ignoreBlockIndexes: true and hides stream size', 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('Size on disk'), 'size on disk must not be printed without --size')
|
||||
assert.ok(!output.includes('Stream size'), 'stream size must not be printed without --size')
|
||||
})
|
||||
|
||||
test('--size opens the disk with ignoreBlockIndexes: false and prints size on disk', async () => {
|
||||
test('--size opens the disk with ignoreBlockIndexes: false and prints stream size', 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('Size on disk'), 'size on disk must be printed with --size')
|
||||
assert.ok(output.includes('Stream size'), 'stream size 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 size on disk for each disk', async () => {
|
||||
test('--chain --size reads block indexes and prints stream size 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('Size on disk'))
|
||||
assert.strictEqual(sizeLines.length, chainPaths.length, 'size on disk must be printed for each disk')
|
||||
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')
|
||||
})
|
||||
|
||||
test('--chain: chain is closed even when opening a disk in it throws', async () => {
|
||||
|
||||
@@ -21,7 +21,7 @@ const diskDispose = mock.fn(() => Promise.resolve())
|
||||
|
||||
const baseDisk = {
|
||||
isDifferencing: () => false,
|
||||
getSizeOnDisk: () => 1024 * 1024 * 1024,
|
||||
getStreamSize: () => 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('Size on disk'), 'the size column must be hidden without --size')
|
||||
assert.ok(!output.includes('Stream size'), '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('Size on disk'), 'the size column must appear with --size')
|
||||
assert.ok(output.includes('Stream size'), 'the size column must appear with --size')
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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 "Size on disk" column), so
|
||||
// These tests assert on the full-width row (with the "Stream size" 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,
|
||||
sizeOnDisk: '1.00 GiB',
|
||||
streamSize: '1.00 GiB',
|
||||
virtualSize: '8.00 GiB',
|
||||
differencing: parentUid !== null,
|
||||
parentUid,
|
||||
|
||||
48
@xen-orchestra/disk-transform/src/MeteredDisk.mts
Normal file
48
@xen-orchestra/disk-transform/src/MeteredDisk.mts
Normal file
@@ -0,0 +1,48 @@
|
||||
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()
|
||||
}
|
||||
}
|
||||
123
@xen-orchestra/disk-transform/src/MeteredDisk.test.mts
Normal file
123
@xen-orchestra/disk-transform/src/MeteredDisk.test.mts
Normal file
@@ -0,0 +1,123 @@
|
||||
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])
|
||||
})
|
||||
})
|
||||
@@ -9,5 +9,7 @@ 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'
|
||||
|
||||
@@ -23,6 +23,14 @@ 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
|
||||
|
||||
@@ -407,6 +415,7 @@ export default class RemoteHandlerAbstract {
|
||||
encryptedData = Buffer.concat(encryptedData)
|
||||
}
|
||||
await this._outputFile(normalizePath(file), encryptedData, { dirMode, flags })
|
||||
return getDataSize(encryptedData)
|
||||
}
|
||||
|
||||
async read(file, buffer, position) {
|
||||
@@ -596,6 +605,7 @@ 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
|
||||
|
||||
@@ -248,4 +248,21 @@ 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))
|
||||
}
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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, data.length)
|
||||
await blobClient.upload(data, Buffer.byteLength(data))
|
||||
}
|
||||
|
||||
async _createReadStream(file) {
|
||||
|
||||
@@ -190,6 +190,33 @@ 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()', () => {
|
||||
|
||||
@@ -3,6 +3,10 @@
|
||||
## **next**
|
||||
|
||||
- [VM/Network] Add possibility to delete a VIF (PR [#10726](https://github.com/vatesfr/xen-orchestra/pull/10726))
|
||||
- [Web-Core/VtsErrorModal] Add an optional details log viewer, unified icon (PR [#10536](https://github.com/vatesfr/xen-orchestra/pull/10536))
|
||||
- [VM/Network] Add a link to the pool network in the VIF side panel and table (PR [#10686](https://github.com/vatesfr/xen-orchestra/pull/10686))
|
||||
- [VIF] Add a VIF page with general and network information, linked from the VM network table and the VIF side panel (PR [#10686](https://github.com/vatesfr/xen-orchestra/pull/10686))
|
||||
- [Host] Add possibility to enable SSH on XCP-ng 9 hosts, and to disable it with auto-enable if XAPI goes down. The SSH status is shown in the host dashboard and System tab (PR [#10974](https://github.com/vatesfr/xen-orchestra/pull/10974))
|
||||
|
||||
## **0.28.0** (2026/12/01)
|
||||
|
||||
|
||||
@@ -19,7 +19,7 @@ const props = defineProps<{
|
||||
id?: I
|
||||
}>()
|
||||
|
||||
const route = useRoute<'/pool/[uuid]' | '/host/[uuid]' | '/vm/[uuid]'>()
|
||||
const route = useRoute<'/pool/[uuid]' | '/host/[uuid]' | '/vm/[uuid]' | '/vif/[uuid]'>()
|
||||
|
||||
const id = computed(() => props.id ?? (route.params.uuid as I))
|
||||
|
||||
|
||||
@@ -8,6 +8,11 @@
|
||||
</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>
|
||||
@@ -49,7 +54,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 } from '@/modules/host/utils/host.util.ts'
|
||||
import { getHostCoreSocketInfo, getHostManufacturerInfo, isHostSshManageable } 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'
|
||||
@@ -57,6 +62,7 @@ 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'
|
||||
@@ -84,6 +90,8 @@ const manufacturerInfo = computed(() => getHostManufacturerInfo(host))
|
||||
|
||||
const coreSocketInfo = computed(() => getHostCoreSocketInfo(host))
|
||||
|
||||
const isSshManageable = computed(() => isHostSshManageable(host))
|
||||
|
||||
const ram = computed(() => {
|
||||
const memory = getHostMemory(host)
|
||||
|
||||
|
||||
@@ -5,6 +5,11 @@
|
||||
</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')">
|
||||
@@ -18,16 +23,20 @@
|
||||
|
||||
<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'
|
||||
|
||||
defineProps<{
|
||||
const { host } = defineProps<{
|
||||
host: XenApiHost
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const isSshManageable = computed(() => isHostSshManageable(host))
|
||||
</script>
|
||||
|
||||
@@ -85,6 +85,7 @@
|
||||
<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'
|
||||
@@ -108,6 +109,7 @@ const emit = defineEmits<{
|
||||
}>()
|
||||
|
||||
const { getPifsByNetworkRef } = usePifStore().subscribe()
|
||||
const { getNetworkVlan } = useNetworkUtils()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
@@ -115,13 +117,7 @@ const { deleteNetworks, isDeletingNetworks } = useNetworkDelete(() => (network !
|
||||
|
||||
const pifs = computed(() => (network !== undefined ? getPifsByNetworkRef(network.$ref) : []))
|
||||
|
||||
const networkVlan = computed(() => {
|
||||
if (pifs.value.length === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
return pifs.value[0].VLAN !== -1 ? pifs.value[0].VLAN.toString() : t('none')
|
||||
})
|
||||
const networkVlan = computed(() => (network !== undefined ? getNetworkVlan(network) : undefined))
|
||||
|
||||
const networkNbd = computed(() => (network?.purpose[0] ? t('on') : t('off')))
|
||||
|
||||
|
||||
@@ -20,6 +20,10 @@ 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)
|
||||
|
||||
@@ -41,6 +45,8 @@ export function createHostOperations(xenApi: XenApi) {
|
||||
powerOn,
|
||||
destroy,
|
||||
restartAgent,
|
||||
enableSsh,
|
||||
setSshAutoMode,
|
||||
cleanReboot: async (hostRef: HostRef, forceReboot: boolean) => {
|
||||
await clearHost(hostRef, forceReboot)
|
||||
|
||||
|
||||
@@ -164,6 +164,7 @@ export interface XenApiHost extends XenApiRecord<'host'> {
|
||||
multipathing: boolean
|
||||
enabled: boolean
|
||||
PGPUs: XenApiPgpu['$ref'][]
|
||||
ssh_enabled?: boolean
|
||||
}
|
||||
|
||||
export interface XenApiSr extends XenApiRecord<'sr'> {
|
||||
|
||||
@@ -13,6 +13,10 @@
|
||||
<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" />
|
||||
@@ -23,12 +27,15 @@
|
||||
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'
|
||||
@@ -54,4 +61,6 @@ 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>
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
<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>
|
||||
@@ -7,7 +7,7 @@
|
||||
icon="action:disable"
|
||||
@click="disableHost()"
|
||||
>
|
||||
{{ t('action:disable') }}
|
||||
{{ t('action:disable-host') }}
|
||||
</MenuItem>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
<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>
|
||||
@@ -7,7 +7,7 @@
|
||||
icon="status:success-circle"
|
||||
@click="enableHost()"
|
||||
>
|
||||
{{ t('action:enable') }}
|
||||
{{ t('action:enable-host') }}
|
||||
</MenuItem>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import { hostArg } from '@/modules/host/jobs/host-args.ts'
|
||||
import { isHostSshManageable } from '@/modules/host/utils/host.util.ts'
|
||||
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
|
||||
import { useXenApiStore } from '@/stores/xen-api.store.ts'
|
||||
import { defineJob, JobError, JobRunningError } from '@core/packages/job'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
export const useHostDisableSshJob = defineJob('host.disable-ssh', [hostArg], () => {
|
||||
const xapi = useXenApiStore().getXapi()
|
||||
const { t } = useI18n()
|
||||
const { isHostRunning } = useHostMetricsStore().subscribe()
|
||||
|
||||
return {
|
||||
run: host => xapi.host.setSshAutoMode(host.$ref, true),
|
||||
|
||||
validate: (isRunning, host) => {
|
||||
if (host === undefined) {
|
||||
throw new JobError(t('job:host-disable-ssh:missing-host'))
|
||||
}
|
||||
|
||||
if (isRunning) {
|
||||
throw new JobRunningError(t('job:host-disable-ssh:in-progress'))
|
||||
}
|
||||
|
||||
if (!isHostSshManageable(host)) {
|
||||
throw new JobError(t('job:host-disable-ssh:unsupported-version'))
|
||||
}
|
||||
|
||||
if (!isHostRunning(host)) {
|
||||
throw new JobError(t('job:host-disable-ssh:bad-power-state'))
|
||||
}
|
||||
},
|
||||
}
|
||||
})
|
||||
@@ -0,0 +1,34 @@
|
||||
import { hostArg } from '@/modules/host/jobs/host-args.ts'
|
||||
import { isHostSshManageable } from '@/modules/host/utils/host.util.ts'
|
||||
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
|
||||
import { useXenApiStore } from '@/stores/xen-api.store.ts'
|
||||
import { defineJob, JobError, JobRunningError } from '@core/packages/job'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
export const useHostEnableSshJob = defineJob('host.enable-ssh', [hostArg], () => {
|
||||
const xapi = useXenApiStore().getXapi()
|
||||
const { t } = useI18n()
|
||||
const { isHostRunning } = useHostMetricsStore().subscribe()
|
||||
|
||||
return {
|
||||
run: host => xapi.host.enableSsh(host.$ref),
|
||||
|
||||
validate: (isRunning, host) => {
|
||||
if (host === undefined) {
|
||||
throw new JobError(t('job:host-enable-ssh:missing-host'))
|
||||
}
|
||||
|
||||
if (isRunning) {
|
||||
throw new JobRunningError(t('job:host-enable-ssh:in-progress'))
|
||||
}
|
||||
|
||||
if (!isHostSshManageable(host)) {
|
||||
throw new JobError(t('job:host-enable-ssh:unsupported-version'))
|
||||
}
|
||||
|
||||
if (!isHostRunning(host)) {
|
||||
throw new JobError(t('job:host-enable-ssh:bad-power-state'))
|
||||
}
|
||||
},
|
||||
}
|
||||
})
|
||||
@@ -3,6 +3,7 @@ import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { objectIcon } from '@core/icons'
|
||||
import { HOST_POWER_STATE } from '@vates/types'
|
||||
import { castArray } from 'lodash-es'
|
||||
import { coerce, satisfies } from 'semver'
|
||||
|
||||
export type HostState = Lowercase<HOST_POWER_STATE> | 'disabled'
|
||||
|
||||
@@ -45,6 +46,9 @@ export const getHostState = (host: XenApiHost | undefined, powerState: HOST_POWE
|
||||
return host.enabled ? 'running' : 'disabled'
|
||||
}
|
||||
|
||||
export const isHostSshManageable = (host: XenApiHost) =>
|
||||
satisfies(coerce(host.software_version.product_version) ?? '', '>=8.99')
|
||||
|
||||
export const getHostIcon = (host: XenApiHost | undefined, powerState: HOST_POWER_STATE) =>
|
||||
objectIcon('host', getHostState(host, powerState))
|
||||
|
||||
|
||||
@@ -2,9 +2,12 @@ import type { XenApiNetwork } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { usePifMetricsStore } from '@/stores/xen-api/pif-metrics.store.ts'
|
||||
import { usePifStore } from '@/stores/xen-api/pif.store.ts'
|
||||
import { getConnectionStatus } from '@core/utils/connection.util.ts'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
export function useNetworkUtils() {
|
||||
const { records: pifs } = usePifStore().subscribe()
|
||||
const { t } = useI18n()
|
||||
|
||||
const { records: pifs, getPifsByNetworkRef } = usePifStore().subscribe()
|
||||
const { getPifCarrier } = usePifMetricsStore().subscribe()
|
||||
|
||||
function getNetworkStatus(network: XenApiNetwork) {
|
||||
@@ -13,5 +16,15 @@ export function useNetworkUtils() {
|
||||
return getConnectionStatus(networkPifs.map(pif => pif.currently_attached && getPifCarrier(pif)))
|
||||
}
|
||||
|
||||
return { getNetworkStatus }
|
||||
function getNetworkVlan(network: XenApiNetwork) {
|
||||
const networkPifs = getPifsByNetworkRef(network.$ref)
|
||||
|
||||
if (networkPifs.length === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
return networkPifs[0].VLAN !== -1 ? networkPifs[0].VLAN.toString() : t('none')
|
||||
}
|
||||
|
||||
return { getNetworkStatus, getNetworkVlan }
|
||||
}
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
import type { XenApiNetwork } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { useNetworkDeleteJob } from '@/modules/network/jobs/network-delete.job.ts'
|
||||
import { useDeleteModal } from '@core/composables/modals/use-delete-modal.ts'
|
||||
import { useErrorModal } from '@core/composables/modals/use-error-modal.ts'
|
||||
import { useRouteQuery } from '@core/composables/route-query.composable.ts'
|
||||
import { useOverlay } from '@core/packages/overlay/use-overlay.ts'
|
||||
import { toComputed } from '@core/utils/to-computed.util.ts'
|
||||
import type { MaybeRefOrGetter } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
@@ -23,12 +23,7 @@ export function useNetworkDelete(rawNetworks: MaybeRefOrGetter<XenApiNetwork[]>)
|
||||
|
||||
const { open: openNetworkDeleteModal } = useDeleteModal()
|
||||
|
||||
const { open: openNetworkDeleteErrorModal } = useOverlay({
|
||||
component: () => import('@core/components/modal/VtsErrorModal.vue'),
|
||||
events: {
|
||||
onClose: true,
|
||||
},
|
||||
})
|
||||
const { open: openNetworkDeleteErrorModal } = useErrorModal()
|
||||
|
||||
function deleteNetworks() {
|
||||
if (!canDeleteNetworks.value) {
|
||||
|
||||
72
@xen-orchestra/lite/src/modules/vif/components/VifHeader.vue
Normal file
72
@xen-orchestra/lite/src/modules/vif/components/VifHeader.vue
Normal file
@@ -0,0 +1,72 @@
|
||||
<template>
|
||||
<div class="breadcrumb-container">
|
||||
<UiBreadcrumb :size>
|
||||
<UiLink v-if="vm" :size :to="{ name: '/vm/[uuid]/dashboard', params: { uuid: vm.uuid } }">
|
||||
<VtsObjectIcon type="vm" :state="vmPowerState" size="current" />
|
||||
{{ vm.name_label }}
|
||||
</UiLink>
|
||||
<UiLink v-if="vm && network" :size :to="{ name: '/vm/[uuid]/network', params: { uuid: vm.uuid } }">
|
||||
{{ t('network') }}
|
||||
</UiLink>
|
||||
<span>
|
||||
<VtsIcon name="object:vif" size="current" />
|
||||
{{ t('vif-device', { device: vif.device }) }}
|
||||
</span>
|
||||
</UiBreadcrumb>
|
||||
</div>
|
||||
<UiHeadBar icon="object:vif">
|
||||
{{ t('vif-device', { device: vif.device }) }}
|
||||
</UiHeadBar>
|
||||
<TabList :label="t('vif-device', { device: vif.device })">
|
||||
<RouterTab :to="{ name: '/vif/[uuid]/general', params: { uuid: vif.uuid } }">
|
||||
{{ t('general') }}
|
||||
</RouterTab>
|
||||
</TabList>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import RouterTab from '@/components/RouterTab.vue'
|
||||
import type { XenApiVif } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { useNetworkStore } from '@/stores/xen-api/network.store.ts'
|
||||
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
|
||||
import VtsIcon from '@core/components/icon/VtsIcon.vue'
|
||||
import VtsObjectIcon from '@core/components/object-icon/VtsObjectIcon.vue'
|
||||
import TabList from '@core/components/tab-list/TabList.vue'
|
||||
import UiBreadcrumb from '@core/components/ui/breadcrumb/UiBreadcrumb.vue'
|
||||
import UiHeadBar from '@core/components/ui/head-bar/UiHeadBar.vue'
|
||||
import UiLink from '@core/components/ui/link/UiLink.vue'
|
||||
import { useUiStore } from '@core/stores/ui.store.ts'
|
||||
import { toLower } from 'lodash-es'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const { vif } = defineProps<{ vif: XenApiVif }>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const uiStore = useUiStore()
|
||||
|
||||
const size = computed(() => (uiStore.isSmall ? 'small' : 'medium'))
|
||||
|
||||
const { getByOpaqueRef: getVmByOpaqueRef } = useVmStore().subscribe()
|
||||
const { getByOpaqueRef: getNetworkByOpaqueRef } = useNetworkStore().subscribe()
|
||||
|
||||
const vm = computed(() => getVmByOpaqueRef(vif.VM))
|
||||
const network = computed(() => getNetworkByOpaqueRef(vif.network))
|
||||
|
||||
const vmPowerState = computed(() => toLower(vm.value?.power_state))
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
.breadcrumb-container {
|
||||
min-height: 5.6rem;
|
||||
padding: 1.2rem 1.6rem;
|
||||
display: flex;
|
||||
gap: 1.6rem;
|
||||
align-items: center;
|
||||
border-bottom: 0.1rem solid var(--color-neutral-border);
|
||||
background-color: var(--color-neutral-background-primary);
|
||||
justify-content: space-between;
|
||||
overflow-y: auto;
|
||||
}
|
||||
</style>
|
||||
@@ -22,12 +22,16 @@
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import type { XenApiNetwork, XenApiVif, XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
|
||||
<script setup lang="ts">
|
||||
import type { XenApiVif, XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { getPoolNetworkRoute } from '@/modules/network/utils/network.util.ts'
|
||||
import { useVifConnection } from '@/modules/vif/composables/use-vif-connection.composable.ts'
|
||||
import { useVifDelete } from '@/modules/vif/composables/use-vif-delete.composable.ts'
|
||||
import { useVifEdit } from '@/modules/vif/composables/use-vif-edit.composable.ts'
|
||||
import { useVifUtils } from '@/modules/vif/composables/vif-utils.composable.ts'
|
||||
import { getVifRoute } from '@/modules/vif/utils/vif.util.ts'
|
||||
import { useNetworkStore } from '@/stores/xen-api/network.store.ts'
|
||||
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
|
||||
import { useVifStore } from '@/stores/xen-api/vif.store.ts'
|
||||
import { useVmGuestMetricsStore } from '@/stores/xen-api/vm-guest-metrics.store.ts'
|
||||
import VtsRow from '@core/components/table/VtsRow.vue'
|
||||
@@ -38,16 +42,18 @@ import { usePagination } from '@core/composables/pagination.composable.ts'
|
||||
import { useRouteQuery } from '@core/composables/route-query.composable.ts'
|
||||
import { useSearchFilter } from '@core/composables/search-filter.composable.ts'
|
||||
import { useTableState } from '@core/composables/table-state.composable.ts'
|
||||
import { icon } from '@core/icons'
|
||||
import { useMapper } from '@core/packages/mapper'
|
||||
import { type ActionItem } from '@core/tables/column-definitions/action-column.ts'
|
||||
import { useVifColumns } from '@core/tables/column-sets/vif-columns.ts'
|
||||
import { CONNECTION_ACTION } from '@core/types/connection.ts'
|
||||
import { useVifNetworkColumns } from '@core/tables/column-sets/vif-network-columns.ts'
|
||||
import { renderBodyCell } from '@core/tables/helpers/render-body-cell.ts'
|
||||
import { CONNECTION_ACTION, CONNECTION_STATUS } from '@core/types/connection.ts'
|
||||
import { getUniqueIpAddressesForDevice } from '@core/utils/ip-address.utils.ts'
|
||||
import { logicNot } from '@vueuse/math'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const { vifs, vm } = defineProps<{
|
||||
const { vifs: rawVifs, vm } = defineProps<{
|
||||
vifs: XenApiVif[]
|
||||
vm: XenApiVm
|
||||
}>()
|
||||
@@ -56,17 +62,29 @@ defineSlots<{
|
||||
'title-actions'(): any
|
||||
}>()
|
||||
|
||||
const { isReady, hasError } = useVifStore().subscribe()
|
||||
const { getByOpaqueRef: getNetworkByOpaqueRef } = useNetworkStore().subscribe()
|
||||
const { getByOpaqueRef: getGuestMetricsByOpaqueRef } = useVmGuestMetricsStore().subscribe()
|
||||
|
||||
const { isReady, hasError } = useVifStore().subscribe()
|
||||
const { pool } = usePoolStore().subscribe()
|
||||
const { t } = useI18n()
|
||||
|
||||
const { goToVifEdit } = useVifEdit()
|
||||
|
||||
const selectedVifId = useRouteQuery('id')
|
||||
|
||||
const getNetworkName = (networkRef: XenApiNetwork['$ref']) => getNetworkByOpaqueRef(networkRef)?.name_label ?? ''
|
||||
const getNetworkName = (vif: XenApiVif) => getNetworkByOpaqueRef(vif.network)?.name_label ?? ''
|
||||
|
||||
const { items: filteredVifs, searchBindings } = useSearchFilter(
|
||||
() => rawVifs,
|
||||
vif => [...Object.values(vif), getNetworkName(vif)]
|
||||
)
|
||||
|
||||
const state = useTableState({
|
||||
busy: logicNot(isReady),
|
||||
error: hasError,
|
||||
empty: () =>
|
||||
rawVifs.length === 0 ? t('no-vif-detected') : filteredVifs.value.length === 0 ? { type: 'no-result' } : false,
|
||||
})
|
||||
|
||||
const getIpAddresses = (vif: XenApiVif) => {
|
||||
const networks = getGuestMetricsByOpaqueRef(vm.guest_metrics)?.networks
|
||||
@@ -74,25 +92,20 @@ const getIpAddresses = (vif: XenApiVif) => {
|
||||
return getUniqueIpAddressesForDevice(networks, vif.device)
|
||||
}
|
||||
|
||||
const { items: filteredVifs, searchBindings } = useSearchFilter(
|
||||
() => vifs,
|
||||
vif => [...Object.values(vif), getNetworkName(vif.network)]
|
||||
)
|
||||
|
||||
const state = useTableState({
|
||||
busy: logicNot(isReady),
|
||||
error: hasError,
|
||||
empty: () =>
|
||||
vifs.length === 0 ? t('no-vif-detected') : filteredVifs.value.length === 0 ? { type: 'no-result' } : false,
|
||||
})
|
||||
|
||||
const { pageRecords: paginatedVifs, paginationBindings } = usePagination('vifs', filteredVifs)
|
||||
|
||||
const { HeadCells, BodyCells } = useVifColumns({
|
||||
const { HeadCells, BodyCells } = useVifNetworkColumns({
|
||||
body: (vif: XenApiVif) => {
|
||||
const name = computed(() => getNetworkName(vif.network))
|
||||
const ipAddresses = computed(() => getIpAddresses(vif))
|
||||
|
||||
const network = computed(() => getNetworkByOpaqueRef(vif.network))
|
||||
|
||||
const poolNetworkRoute = computed(() =>
|
||||
pool.value && network.value ? getPoolNetworkRoute(pool.value.uuid, network.value.uuid) : undefined
|
||||
)
|
||||
|
||||
const { lockingModeLabel } = useVifUtils(() => vif)
|
||||
|
||||
const {
|
||||
connectVifs,
|
||||
disconnectVifs,
|
||||
@@ -133,13 +146,26 @@ const { HeadCells, BodyCells } = useVifColumns({
|
||||
)
|
||||
|
||||
return {
|
||||
network: r => r({ label: name.value }),
|
||||
vif: r =>
|
||||
r({
|
||||
label: t('vif'),
|
||||
to: getVifRoute(vif.uuid),
|
||||
icon: icon('object:vif'),
|
||||
}),
|
||||
network: r =>
|
||||
network.value
|
||||
? r({
|
||||
label: network.value.name_label,
|
||||
to: poolNetworkRoute.value,
|
||||
icon: icon('object:network'),
|
||||
})
|
||||
: renderBodyCell(),
|
||||
device: r => r(t('vif-device', { device: vif.device })),
|
||||
status: r => r(vif.currently_attached ? 'connected' : 'disconnected'),
|
||||
status: r => r(vif.currently_attached ? CONNECTION_STATUS.CONNECTED : CONNECTION_STATUS.DISCONNECTED),
|
||||
ipsAddresses: r => r(ipAddresses.value),
|
||||
macAddresses: r => r(vif.MAC),
|
||||
mtu: r => r(vif.MTU),
|
||||
lockingMode: r => r(vif.locking_mode),
|
||||
lockingMode: r => r(lockingModeLabel.value),
|
||||
actions: r =>
|
||||
r({
|
||||
onClick: () => (selectedVifId.value = vif.uuid),
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
<template>
|
||||
<UiCard>
|
||||
<UiTitle>
|
||||
{{ t('general-information') }}
|
||||
</UiTitle>
|
||||
<VtsTabularKeyValueList>
|
||||
<VtsTabularKeyValueRow :label="t('name')" :value="vifDevice" />
|
||||
<VtsTabularKeyValueRow :label="t('uuid')">
|
||||
<template #value>
|
||||
<VtsCodeSnippet :content="vif.uuid" />
|
||||
</template>
|
||||
</VtsTabularKeyValueRow>
|
||||
<VtsTabularKeyValueRow :label="t('network')">
|
||||
<template v-if="network" #value>
|
||||
<UiLink size="medium" :to="networkTo" icon="object:network">
|
||||
{{ network.name_label }}
|
||||
</UiLink>
|
||||
</template>
|
||||
</VtsTabularKeyValueRow>
|
||||
<VtsTabularKeyValueRow :label="t('device')" :value="vifDevice" />
|
||||
<VtsTabularKeyValueRow :label="t('vif-status')">
|
||||
<template #value>
|
||||
<VtsStatus :status="vifStatus" />
|
||||
</template>
|
||||
</VtsTabularKeyValueRow>
|
||||
<VtsTabularKeyValueRow :label="t('vlan')" :value="networkVlan" />
|
||||
<VtsTabularKeyValueRow :label="t('mtu')" :value="String(vif.MTU)" />
|
||||
<VtsTabularKeyValueRow :label="t('rate-limit')" :value="rateLimit" />
|
||||
<VtsTabularKeyValueRow :label="t('locking-mode')" :value="lockingModeLabel">
|
||||
<template v-if="vif.locking_mode === VIF_LOCKING_MODE.DISABLED" #value>
|
||||
<VtsStatus status="disabled" />
|
||||
</template>
|
||||
</VtsTabularKeyValueRow>
|
||||
<VtsTabularKeyValueRow :label="t('check-summing')">
|
||||
<template #value>
|
||||
<VtsStatus :status="txChecksumming" />
|
||||
</template>
|
||||
</VtsTabularKeyValueRow>
|
||||
</VtsTabularKeyValueList>
|
||||
</UiCard>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { XenApiVif } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { useNetworkUtils } from '@/modules/network/composables/network-utils.composable.ts'
|
||||
import { getPoolNetworkRoute } from '@/modules/network/utils/network.util.ts'
|
||||
import { useVifUtils } from '@/modules/vif/composables/vif-utils.composable.ts'
|
||||
import { useNetworkStore } from '@/stores/xen-api/network.store.ts'
|
||||
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
|
||||
import VtsCodeSnippet from '@core/components/code-snippet/VtsCodeSnippet.vue'
|
||||
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 UiLink from '@core/components/ui/link/UiLink.vue'
|
||||
import UiTitle from '@core/components/ui/title/UiTitle.vue'
|
||||
import { CONNECTION_STATUS } from '@core/types/connection.ts'
|
||||
import { VIF_LOCKING_MODE } from '@vates/types'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const { vif } = defineProps<{ vif: XenApiVif }>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const { getByOpaqueRef: getNetworkByOpaqueRef } = useNetworkStore().subscribe()
|
||||
const { pool } = usePoolStore().subscribe()
|
||||
const { lockingModeLabel, rateLimit: rawRateLimit, txChecksumming } = useVifUtils(() => vif)
|
||||
const { getNetworkVlan } = useNetworkUtils()
|
||||
|
||||
const network = computed(() => getNetworkByOpaqueRef(vif.network))
|
||||
|
||||
const networkTo = computed(() =>
|
||||
pool.value && network.value ? getPoolNetworkRoute(pool.value.uuid, network.value.uuid) : undefined
|
||||
)
|
||||
|
||||
const networkVlan = computed(() => (network.value !== undefined ? getNetworkVlan(network.value) : undefined))
|
||||
|
||||
const vifStatus = computed(() =>
|
||||
vif.currently_attached ? CONNECTION_STATUS.CONNECTED : CONNECTION_STATUS.DISCONNECTED
|
||||
)
|
||||
|
||||
const vifDevice = computed(() => t('vif-device', { device: vif.device }))
|
||||
|
||||
const rateLimit = computed(() =>
|
||||
rawRateLimit.value !== undefined ? `${rawRateLimit.value} ${t('bytes:kbs')}` : undefined
|
||||
)
|
||||
</script>
|
||||
@@ -0,0 +1,55 @@
|
||||
<template>
|
||||
<UiCard>
|
||||
<UiTitle>
|
||||
{{ t('vif-network-info') }}
|
||||
</UiTitle>
|
||||
<VtsTabularKeyValueList>
|
||||
<VtsTabularKeyValueRow :label="t('ip-addresses')">
|
||||
<template v-if="ipAddresses.length" #value>
|
||||
<div class="ip-list">
|
||||
<span v-for="ip in ipAddresses" :key="ip">{{ ip }}</span>
|
||||
</div>
|
||||
</template>
|
||||
</VtsTabularKeyValueRow>
|
||||
<VtsTabularKeyValueRow :label="t('mac-address')" :value="vif.MAC" />
|
||||
</VtsTabularKeyValueList>
|
||||
</UiCard>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { XenApiVif } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { useVmGuestMetricsStore } from '@/stores/xen-api/vm-guest-metrics.store.ts'
|
||||
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
|
||||
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 { getUniqueIpAddressesForDevice } from '@core/utils/ip-address.utils.ts'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const { vif } = defineProps<{ vif: XenApiVif }>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const { getByOpaqueRef: getVmByOpaqueRef } = useVmStore().subscribe()
|
||||
const { getByOpaqueRef: getGuestMetricsByOpaqueRef } = useVmGuestMetricsStore().subscribe()
|
||||
|
||||
const ipAddresses = computed(() => {
|
||||
const vm = getVmByOpaqueRef(vif.VM)
|
||||
|
||||
if (vm === undefined) {
|
||||
return []
|
||||
}
|
||||
|
||||
return getUniqueIpAddressesForDevice(getGuestMetricsByOpaqueRef(vm.guest_metrics)?.networks, vif.device)
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped lang="postcss">
|
||||
.ip-list {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
</style>
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<VtsSidePanel :has-selection="!!vif" class="vm-vifs-side-panel" @close="emit('close')">
|
||||
<VtsSidePanel :has-selection="!!vif" class="vif-side-panel" @close="emit('close')">
|
||||
<template v-if="vif" #actions>
|
||||
<VifEditButton :vif />
|
||||
<VifConnectionToggleButton v-if="vm" :vif :vm />
|
||||
@@ -8,15 +8,19 @@
|
||||
<template v-if="vif" #default>
|
||||
<!-- VIF -->
|
||||
<UiPanelCard>
|
||||
<UiPanelCardTitle :id="vif.uuid" size="medium" :label="t('vif')" />
|
||||
<UiPanelCardTitle :id="vif.uuid" size="medium" :to="vifTo" :label="t('vif')" icon="object:vif" />
|
||||
<VtsCardRowList>
|
||||
<!-- NETWORK -->
|
||||
<VtsCardRowKeyValue>
|
||||
<template #key>
|
||||
{{ t('network') }}
|
||||
</template>
|
||||
<template #value>{{ network?.name_label }}</template>
|
||||
<template v-if="network?.name_label" #addons>
|
||||
<template #value>
|
||||
<UiLink v-if="network" size="small" :to="networkTo" icon="object:network">
|
||||
{{ network.name_label }}
|
||||
</UiLink>
|
||||
</template>
|
||||
<template v-if="network" #addons>
|
||||
<VtsCopyButton :value="network.name_label" />
|
||||
</template>
|
||||
</VtsCardRowKeyValue>
|
||||
@@ -68,7 +72,7 @@
|
||||
{{ t('locking-mode') }}
|
||||
</template>
|
||||
<template #value>
|
||||
{{ vif.locking_mode }}
|
||||
{{ lockingModeLabel }}
|
||||
</template>
|
||||
</VtsCardRowKeyValue>
|
||||
<!-- TX CHECK SUMMING -->
|
||||
@@ -77,12 +81,12 @@
|
||||
{{ t('check-summing') }}
|
||||
</template>
|
||||
<template #value>
|
||||
{{ isTxChecksummingEnabled(vif) }}
|
||||
{{ txChecksumming }}
|
||||
</template>
|
||||
</VtsCardRowKeyValue>
|
||||
</VtsCardRowList>
|
||||
</UiPanelCard>
|
||||
<!-- VIF NETWORK INFORMATION -->
|
||||
<!-- NETWORK INFORMATION -->
|
||||
<UiPanelCard>
|
||||
<UiPanelCardTitle size="medium" :label="t('network-information')" />
|
||||
<VtsCardRowList>
|
||||
@@ -110,11 +114,14 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { XenApiVif } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { getPoolNetworkRoute } from '@/modules/network/utils/network.util.ts'
|
||||
import VifConnectionToggleButton from '@/modules/vif/components/actions/connection/VifConnectionToggleButton.vue'
|
||||
import VifDeleteButton from '@/modules/vif/components/actions/delete/VifDeleteButton.vue'
|
||||
import VifEditButton from '@/modules/vif/components/actions/edit/VifEditButton.vue'
|
||||
import { isTxChecksummingEnabled } from '@/modules/vif/utils/vif-tx-checksumming.util.ts'
|
||||
import { useVifUtils } from '@/modules/vif/composables/vif-utils.composable.ts'
|
||||
import { getVifRoute } from '@/modules/vif/utils/vif.util.ts'
|
||||
import { useNetworkStore } from '@/stores/xen-api/network.store.ts'
|
||||
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
|
||||
import { useVmGuestMetricsStore } from '@/stores/xen-api/vm-guest-metrics.store.ts'
|
||||
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
|
||||
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
|
||||
@@ -122,8 +129,10 @@ import VtsCardRowList from '@core/components/card/VtsCardRowList.vue'
|
||||
import VtsCopyButton from '@core/components/copy-button/VtsCopyButton.vue'
|
||||
import VtsSidePanel from '@core/components/panel/VtsSidePanel.vue'
|
||||
import VtsStatus from '@core/components/status/VtsStatus.vue'
|
||||
import UiLink from '@core/components/ui/link/UiLink.vue'
|
||||
import UiPanelCard from '@core/components/ui/panel-card/UiPanelCard.vue'
|
||||
import UiPanelCardTitle from '@core/components/ui/panel-card-title/UiPanelCardTitle.vue'
|
||||
import { CONNECTION_STATUS } from '@core/types/connection.ts'
|
||||
import { getUniqueIpAddressesForDevice } from '@core/utils/ip-address.utils.ts'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
@@ -141,8 +150,13 @@ const { t } = useI18n()
|
||||
const { getByOpaqueRef: getNetworkByOpaqueRef } = useNetworkStore().subscribe()
|
||||
const { getByOpaqueRef: getGuestMetricsByOpaqueRef } = useVmGuestMetricsStore().subscribe()
|
||||
const { getByOpaqueRef: getVmByOpaqueRef } = useVmStore().subscribe()
|
||||
const { pool } = usePoolStore().subscribe()
|
||||
const { lockingModeLabel, rateLimit, txChecksumming } = useVifUtils(() => vif)
|
||||
|
||||
const vm = computed(() => (vif !== undefined ? getVmByOpaqueRef(vif.VM) : undefined))
|
||||
|
||||
const vifTo = computed(() => (vif !== undefined ? getVifRoute(vif.uuid) : undefined))
|
||||
|
||||
const ipAddresses = computed(() => {
|
||||
if (vif === undefined) {
|
||||
return []
|
||||
@@ -159,19 +173,15 @@ const ipAddresses = computed(() => {
|
||||
|
||||
const network = computed(() => (vif !== undefined ? getNetworkByOpaqueRef(vif.network) : undefined))
|
||||
|
||||
const status = computed(() => (vif?.currently_attached ? 'connected' : 'disconnected'))
|
||||
const networkTo = computed(() =>
|
||||
pool.value && network.value ? getPoolNetworkRoute(pool.value.uuid, network.value.uuid) : undefined
|
||||
)
|
||||
|
||||
const rateLimit = computed(() => {
|
||||
if (vif?.qos_algorithm_type !== 'ratelimit') {
|
||||
return undefined
|
||||
}
|
||||
|
||||
return vif.qos_algorithm_params.kbps
|
||||
})
|
||||
const status = computed(() => (vif?.currently_attached ? CONNECTION_STATUS.CONNECTED : CONNECTION_STATUS.DISCONNECTED))
|
||||
</script>
|
||||
|
||||
<style scoped lang="postcss">
|
||||
.vm-vifs-side-panel {
|
||||
.vif-side-panel {
|
||||
.value:empty::before {
|
||||
content: '-';
|
||||
}
|
||||
|
||||
@@ -5,7 +5,7 @@ export function useVifEdit() {
|
||||
const router = useRouter()
|
||||
|
||||
function goToVifEdit(vif: XenApiVif) {
|
||||
return router.push({ name: '/vif/[uuid]/edit', params: { uuid: vif.uuid } })
|
||||
return router.push({ name: '/vif/edit', query: { vifUuid: vif.uuid } })
|
||||
}
|
||||
|
||||
return { goToVifEdit }
|
||||
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { XenApiVif } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { isTxChecksummingEnabled } from '@/modules/vif/utils/vif-tx-checksumming.util.ts'
|
||||
import { getVifRateLimit } from '@/modules/vif/utils/vif.util.ts'
|
||||
import { useVifLockingModeLabel } from '@core/composables/vif-locking-mode-label.composable.ts'
|
||||
import { toComputed } from '@core/utils/to-computed.util.ts'
|
||||
import { computed, type MaybeRefOrGetter } from 'vue'
|
||||
|
||||
export function useVifUtils(rawVif: MaybeRefOrGetter<XenApiVif | undefined>) {
|
||||
const vif = toComputed(rawVif)
|
||||
|
||||
const lockingModeLabel = useVifLockingModeLabel(() => vif.value?.locking_mode)
|
||||
|
||||
const rateLimit = computed(() => (vif.value !== undefined ? getVifRateLimit(vif.value) : undefined))
|
||||
|
||||
const txChecksumming = computed(() => vif.value !== undefined && isTxChecksummingEnabled(vif.value))
|
||||
|
||||
return {
|
||||
lockingModeLabel,
|
||||
rateLimit,
|
||||
txChecksumming,
|
||||
}
|
||||
}
|
||||
@@ -1,18 +1,19 @@
|
||||
import type { XenApiVif } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { useVifForm } from '@/modules/vif/form/use-vif-form-base.ts'
|
||||
import { isTxChecksummingEnabled } from '@/modules/vif/utils/vif-tx-checksumming.util.ts'
|
||||
import { getVifRateLimit } from '@/modules/vif/utils/vif.util.ts'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
export function useEditVifForm(vif: XenApiVif) {
|
||||
const { t } = useI18n()
|
||||
|
||||
const { kbps } = vif.qos_algorithm_params
|
||||
const kbps = getVifRateLimit(vif)
|
||||
|
||||
return useVifForm(
|
||||
{
|
||||
network: vif.network,
|
||||
mac: vif.MAC,
|
||||
rateLimit: vif.qos_algorithm_type === 'ratelimit' && kbps !== undefined ? Number(kbps) : undefined,
|
||||
rateLimit: kbps !== undefined ? Number(kbps) : undefined,
|
||||
allowedIps: [...vif.ipv4_allowed, ...vif.ipv6_allowed].join('; '),
|
||||
txChecksumming: isTxChecksummingEnabled(vif),
|
||||
},
|
||||
|
||||
@@ -3,6 +3,7 @@ import { vifArg } from '@/modules/vif/jobs/vif-args.ts'
|
||||
import type { VifPayload } from '@/modules/vif/jobs/vif-create.job.ts'
|
||||
import { editVifPayloadArg } from '@/modules/vif/jobs/vif-edit-args.ts'
|
||||
import { isTxChecksummingEnabled } from '@/modules/vif/utils/vif-tx-checksumming.util.ts'
|
||||
import { getVifRateLimit } from '@/modules/vif/utils/vif.util.ts'
|
||||
import { useXenApiStore } from '@/stores/xen-api.store.ts'
|
||||
import { defineJob, JobError, JobRunningError } from '@core/packages/job'
|
||||
import { VIF_LOCKING_MODE } from '@vates/types'
|
||||
@@ -91,7 +92,7 @@ export const useVifEditJob = defineJob('vif.edit', [vifArg, editVifPayloadArg],
|
||||
}
|
||||
|
||||
const kbps = payload.qos_algorithm_params?.kbps
|
||||
const currentKbps = vif.qos_algorithm_type === 'ratelimit' ? vif.qos_algorithm_params.kbps : undefined
|
||||
const currentKbps = getVifRateLimit(vif)
|
||||
|
||||
if (kbps !== currentKbps) {
|
||||
await xapi.vif.setRateLimit(vif.$ref, kbps === undefined ? null : Number(kbps))
|
||||
|
||||
13
@xen-orchestra/lite/src/modules/vif/utils/vif.util.ts
Normal file
13
@xen-orchestra/lite/src/modules/vif/utils/vif.util.ts
Normal file
@@ -0,0 +1,13 @@
|
||||
import type { XenApiVif } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import type { RouteLocationAsRelative } from 'vue-router'
|
||||
|
||||
export function getVifRoute(vifId: XenApiVif['uuid']): RouteLocationAsRelative {
|
||||
return {
|
||||
name: '/vif/[uuid]/general',
|
||||
params: { uuid: vifId },
|
||||
}
|
||||
}
|
||||
|
||||
export function getVifRateLimit(vif: XenApiVif) {
|
||||
return vif.qos_algorithm_type === 'ratelimit' ? vif.qos_algorithm_params.kbps : undefined
|
||||
}
|
||||
29
@xen-orchestra/lite/src/pages/vif/[uuid].vue
Normal file
29
@xen-orchestra/lite/src/pages/vif/[uuid].vue
Normal file
@@ -0,0 +1,29 @@
|
||||
<template>
|
||||
<ObjectNotFoundWrapper :is-ready :uuid-checker="hasUuid">
|
||||
<template v-if="vif">
|
||||
<VifHeader v-if="uiStore.hasUi" :vif />
|
||||
<RouterView v-slot="{ Component }">
|
||||
<component :is="Component" :vif />
|
||||
</RouterView>
|
||||
</template>
|
||||
</ObjectNotFoundWrapper>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import ObjectNotFoundWrapper from '@/components/ObjectNotFoundWrapper.vue'
|
||||
import type { XenApiVif } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import VifHeader from '@/modules/vif/components/VifHeader.vue'
|
||||
import { useVifStore } from '@/stores/xen-api/vif.store.ts'
|
||||
import { useDefaultTab } from '@core/composables/default-tab.composable.ts'
|
||||
import { useUiStore } from '@core/stores/ui.store.ts'
|
||||
import { computed } from 'vue'
|
||||
import { useRoute } from 'vue-router'
|
||||
|
||||
useDefaultTab('/vif/[uuid]', 'general')
|
||||
|
||||
const route = useRoute<'/vif/[uuid]'>()
|
||||
const uiStore = useUiStore()
|
||||
const { getByUuid, hasUuid, isReady } = useVifStore().subscribe()
|
||||
|
||||
const vif = computed(() => getByUuid(route.params.uuid as XenApiVif['uuid']))
|
||||
</script>
|
||||
30
@xen-orchestra/lite/src/pages/vif/[uuid]/general.vue
Normal file
30
@xen-orchestra/lite/src/pages/vif/[uuid]/general.vue
Normal file
@@ -0,0 +1,30 @@
|
||||
<template>
|
||||
<div class="scroll-container">
|
||||
<VtsColumns extra-space-around>
|
||||
<VtsColumn>
|
||||
<VifGeneralInfoCard :vif />
|
||||
</VtsColumn>
|
||||
<VtsColumn>
|
||||
<VifNetworkInfoCard :vif />
|
||||
</VtsColumn>
|
||||
</VtsColumns>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { XenApiVif } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import VifGeneralInfoCard from '@/modules/vif/components/cards/VifGeneralInfoCard.vue'
|
||||
import VifNetworkInfoCard from '@/modules/vif/components/cards/VifNetworkInfoCard.vue'
|
||||
import VtsColumn from '@core/components/column/VtsColumn.vue'
|
||||
import VtsColumns from '@core/components/columns/VtsColumns.vue'
|
||||
|
||||
defineProps<{ vif: XenApiVif }>()
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
.scroll-container {
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-y: auto;
|
||||
}
|
||||
</style>
|
||||
@@ -52,14 +52,14 @@ import { type RouteLocationRaw, useRoute, useRouter } from 'vue-router'
|
||||
const { t } = useI18n()
|
||||
|
||||
const router = useRouter()
|
||||
const route = useRoute<'/vif/[uuid]/edit'>()
|
||||
const route = useRoute()
|
||||
|
||||
const { isReady: areVifsReady, getByUuid: getVifByUuid } = useVifStore().subscribe()
|
||||
const { getByOpaqueRef: getVmByOpaqueRef } = useVmStore().subscribe()
|
||||
|
||||
const vifUuid = computed(() => route.params.uuid as XenApiVif['uuid'])
|
||||
const vifUuid = computed(() => route.query.vifUuid as XenApiVif['uuid'] | undefined)
|
||||
|
||||
const vif = computed(() => getVifByUuid(vifUuid.value))
|
||||
const vif = computed(() => (vifUuid.value === undefined ? undefined : getVifByUuid(vifUuid.value)))
|
||||
|
||||
const vm = computed(() => (vif.value === undefined ? undefined : getVmByOpaqueRef(vif.value.VM)))
|
||||
|
||||
50
@xen-orchestra/lite/src/route-map.d.ts
vendored
50
@xen-orchestra/lite/src/route-map.d.ts
vendored
@@ -499,6 +499,13 @@ declare module 'vue-router/auto-routes' {
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/modal/vts-error-modal': RouteRecordInfo<
|
||||
'/story/web-core/modal/vts-error-modal',
|
||||
'/story/web-core/modal/vts-error-modal',
|
||||
Record<never, never>,
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/number-input/vts-number-input': RouteRecordInfo<
|
||||
'/story/web-core/number-input/vts-number-input',
|
||||
'/story/web-core/number-input/vts-number-input',
|
||||
@@ -1220,11 +1227,25 @@ declare module 'vue-router/auto-routes' {
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/vif/[uuid]/edit': RouteRecordInfo<
|
||||
'/vif/[uuid]/edit',
|
||||
'/vif/:uuid/edit',
|
||||
'/vif/[uuid]': RouteRecordInfo<
|
||||
'/vif/[uuid]',
|
||||
'/vif/:uuid',
|
||||
{ uuid: ParamValue<true> },
|
||||
{ uuid: ParamValue<false> },
|
||||
| '/vif/[uuid]/general'
|
||||
>,
|
||||
'/vif/[uuid]/general': RouteRecordInfo<
|
||||
'/vif/[uuid]/general',
|
||||
'/vif/:uuid/general',
|
||||
{ uuid: ParamValue<true> },
|
||||
{ uuid: ParamValue<false> },
|
||||
| never
|
||||
>,
|
||||
'/vif/edit': RouteRecordInfo<
|
||||
'/vif/edit',
|
||||
'/vif/edit',
|
||||
Record<never, never>,
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/vif/new': RouteRecordInfo<
|
||||
@@ -1737,6 +1758,12 @@ declare module 'vue-router/auto-routes' {
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/modal/vts-error-modal.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/modal/vts-error-modal'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/number-input/vts-number-input.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/number-input/vts-number-input'
|
||||
@@ -2355,9 +2382,22 @@ declare module 'vue-router/auto-routes' {
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/pages/vif/[uuid]/edit.vue': {
|
||||
'src/pages/vif/[uuid].vue': {
|
||||
routes:
|
||||
| '/vif/[uuid]/edit'
|
||||
| '/vif/[uuid]'
|
||||
| '/vif/[uuid]/general'
|
||||
views:
|
||||
| 'default'
|
||||
}
|
||||
'src/pages/vif/[uuid]/general.vue': {
|
||||
routes:
|
||||
| '/vif/[uuid]/general'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/pages/vif/edit.vue': {
|
||||
routes:
|
||||
| '/vif/edit'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
# Usage
|
||||
|
||||
Open the modal with `useErrorModal`.
|
||||
|
||||
```vue-script
|
||||
import { useErrorModal } from '@core/composables/modals/use-error-modal.ts'
|
||||
|
||||
const { open: openErrorModal } = useErrorModal()
|
||||
|
||||
try {
|
||||
// ...
|
||||
} catch (error) {
|
||||
void openErrorModal({
|
||||
props: {
|
||||
title: 'Unable to create cluster',
|
||||
error: 'An error occurred',
|
||||
details: error,
|
||||
},
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
The `details` prop is displayed below the message, even when the `content` slot is overridden:
|
||||
|
||||
```vue-template
|
||||
<VtsErrorModal title="Unable to delete network" :details @close="close()">
|
||||
<template #content>Custom error message</template>
|
||||
</VtsErrorModal>
|
||||
```
|
||||
@@ -0,0 +1,60 @@
|
||||
<template>
|
||||
<ComponentStory
|
||||
v-slot="{ properties, settings }"
|
||||
:params="[
|
||||
prop('title').str().required().preset('Unable to create cluster').widget(),
|
||||
prop('error').str().preset('An error occurred').widget(),
|
||||
prop('details')
|
||||
.type('string | object')
|
||||
.preset(details1)
|
||||
.widget(object())
|
||||
.help('When set, displayed in a log entry viewer below the error message'),
|
||||
event('close'),
|
||||
slot('content').help('Replaces the error message. The details are still displayed below it'),
|
||||
setting('contentSlotContent').widget(text()).help('Leave empty to use the error prop'),
|
||||
]"
|
||||
:presets
|
||||
>
|
||||
<VtsErrorModal class="story" v-bind="properties">
|
||||
<template v-if="settings.contentSlotContent" #content>{{ settings.contentSlotContent }}</template>
|
||||
</VtsErrorModal>
|
||||
</ComponentStory>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { event, prop, setting, slot } from '@/libs/story/story-param.ts'
|
||||
import { object, text } from '@/libs/story/story-widget.ts'
|
||||
import VtsErrorModal from '@core/components/modal/VtsErrorModal.vue'
|
||||
|
||||
const details1 = {
|
||||
code: 'HOST_NOT_ENOUGH_FREE_MEMORY',
|
||||
params: ['8589934592', '2147483648'],
|
||||
call: {
|
||||
method: 'VM.start',
|
||||
params: ['OpaqueRef:3f2a9c1e-7b4d-4e8a-9f6c-2d1b5a8e7c90', false, false],
|
||||
},
|
||||
}
|
||||
|
||||
const details2 =
|
||||
'TypeError: Failed to fetch\n at fetchApi (rest-api.ts:42:11)\n at async createCluster (cluster-create.job.ts:88:5)'
|
||||
|
||||
const presets = {
|
||||
'Without details': {
|
||||
props: { details: undefined },
|
||||
},
|
||||
'With details object': {
|
||||
props: { details: details1 },
|
||||
},
|
||||
'With details string': {
|
||||
props: { details: details2 },
|
||||
},
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
.story {
|
||||
position: relative;
|
||||
height: 100%;
|
||||
}
|
||||
</style>
|
||||
@@ -6,7 +6,6 @@
|
||||
prop('accent').required().enum('brand', 'info', 'warning', 'danger').preset('brand').widget(),
|
||||
prop('size').required().enum('small', 'medium', 'large').preset('medium').widget(),
|
||||
prop('disabled').bool().widget(),
|
||||
prop('restricted').bool().widget(),
|
||||
prop('selected').bool().widget(),
|
||||
prop('counter')
|
||||
.type('CounterValue | { value: CounterValue; accent: CounterAccent }')
|
||||
|
||||
@@ -12,7 +12,6 @@
|
||||
prop('size').type('ButtonSize').enum('small', 'medium').preset('medium').required().widget(),
|
||||
prop('busy').bool().widget(),
|
||||
prop('disabled').bool().widget().ctx(),
|
||||
prop('restricted').bool().widget(),
|
||||
prop('lockIcon').bool().widget(),
|
||||
iconProp('leftIcon'),
|
||||
iconProp('rightIcon'),
|
||||
|
||||
@@ -14,7 +14,7 @@ import {
|
||||
assertHealthCheckSuccess,
|
||||
getRequiredEnv,
|
||||
} from '../utils/index.js'
|
||||
import { assertBackupSuccess } from '../utils/backupUtils.js'
|
||||
import { assertBackupSuccess, assertArchivesSizeOnDisk } from '../utils/backupUtils.js'
|
||||
import { setup, teardown } from './setup.js'
|
||||
|
||||
const log = createLogger('qa:backup:base')
|
||||
@@ -164,6 +164,7 @@ describe('Backup basic tests', () => {
|
||||
assertHealthCheckSuccess(result)
|
||||
const healthCheckData = extractHealthCheckData(result)
|
||||
log.debug('Health check validated', { status: healthCheckData.status, duration: healthCheckData.duration })
|
||||
await assertArchivesSizeOnDisk(dispatchClient, backupRepository, vm.uuid)
|
||||
}
|
||||
})
|
||||
it('should run the backup job in full mode with health checks', async () => {
|
||||
@@ -181,6 +182,7 @@ describe('Backup basic tests', () => {
|
||||
assertHealthCheckSuccess(result)
|
||||
const healthCheckData = extractHealthCheckData(result)
|
||||
log.debug('Health check validated', { status: healthCheckData.status, duration: healthCheckData.duration })
|
||||
await assertArchivesSizeOnDisk(dispatchClient, backupRepository, vm.uuid)
|
||||
})
|
||||
it('should run backup without health check when SR not configured', async () => {
|
||||
const name = generateBackupJobName()
|
||||
|
||||
@@ -213,3 +213,41 @@ export const assertSynchronizedSnapshot = (result, vmCount) => {
|
||||
const latestSnapshotEnd = Math.max(...snapshots.map(t => t.end))
|
||||
assert(latestSnapshotEnd <= earliestStart, `Synchronized backup snapshots should be complete before transfer starts`)
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that every backup of the VM on the repository records the space it uses, consistently between the archive and its disks
|
||||
*
|
||||
* @param {import('../client/dispatchClient.js').DispatchClient} dispatchClient
|
||||
* @param {{ id: string, name: string }} backupRepository
|
||||
* @param {string} vmUuid
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
export const assertArchivesSizeOnDisk = async (dispatchClient, backupRepository, vmUuid) => {
|
||||
const backups = await dispatchClient.backup.listVmBackups([backupRepository.id])
|
||||
const archives = backups[backupRepository.id]?.[vmUuid] ?? []
|
||||
|
||||
assert.ok(archives.length > 0, `no backup of VM ${vmUuid} on repository ${backupRepository.name}`)
|
||||
|
||||
for (const archive of archives) {
|
||||
assert.strictEqual(typeof archive.sizeOnDisk, 'number', `${archive.id}: sizeOnDisk must be a number`)
|
||||
assert.ok(archive.sizeOnDisk > 0, `${archive.id}: sizeOnDisk must be higher than 0`)
|
||||
|
||||
if (archive.mode === 'delta') {
|
||||
let totalDiskSizeOnDisk = 0
|
||||
for (const disk of archive.disks) {
|
||||
assert.strictEqual(typeof disk.sizeOnDisk, 'number', `${archive.id} ${disk.id}: sizeOnDisk must be a number`)
|
||||
assert.ok(disk.sizeOnDisk > 0, `${archive.id} ${disk.id}: sizeOnDisk must be higher than 0`)
|
||||
|
||||
totalDiskSizeOnDisk += disk.sizeOnDisk
|
||||
}
|
||||
|
||||
assert.strictEqual(
|
||||
archive.sizeOnDisk,
|
||||
totalDiskSizeOnDisk,
|
||||
`${archive.id}: disks sizeOnDisk sum should match archive sizeOnDisk`
|
||||
)
|
||||
} else {
|
||||
assert.deepStrictEqual(archive.disks, [], `${archive.id}: disks should be empty`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -12,14 +12,19 @@ export const partialBackupArchives = [
|
||||
id: '/xo-vm-backups/6ef7c09e-677b-1e6f-0546-7ab30413c61c/vdis/8b650248-ddd6-4188-ad8b-c0502865ac6c/f1f3c902-dcaa-4ec6-943e-6162c9d85fb2/20250801T080832Z.vhd',
|
||||
name: 'debian 12 hub disk',
|
||||
uuid: 'cbe1e3ba-8e5c-4c79-9e4d-708144518d50',
|
||||
sizeOnDisk: 52428800,
|
||||
isDifferencing: true,
|
||||
},
|
||||
{
|
||||
id: '/xo-vm-backups/6ef7c09e-677b-1e6f-0546-7ab30413c61c/vdis/8b650248-ddd6-4188-ad8b-c0502865ac6c/870e6142-d4e4-4622-bd19-6b101c8da3cc/20250801T080832Z.vhd',
|
||||
name: 'XO CloudConfigDrive',
|
||||
uuid: 'bea8193d-80ba-4a72-94e4-901f03ffc225',
|
||||
sizeOnDisk: 1048576,
|
||||
isDifferencing: true,
|
||||
},
|
||||
],
|
||||
href: '/rest/v0/backup-archives/231264c3-af43-4ec0-a3be-394c5b1fdbfc/xo-vm-backups/6ef7c09e-677b-1e6f-0546-7ab30413c61c/20250801T080832Z.json',
|
||||
sizeOnDisk: 53477376,
|
||||
},
|
||||
{
|
||||
id: '1af95910-01b4-4e87-9c2f-d895cafe0776/xo-vm-backups/7cf6150f-a978-09e6-6b41-0d1d41967bdc/20250918T132942Z.json',
|
||||
@@ -29,9 +34,12 @@ export const partialBackupArchives = [
|
||||
id: '/xo-vm-backups/803c2676-c309-721e-7123-e6c3de854c32/vdis/ce91bf34-099c-4241-a608-3373f101c02b/7384cf5a-3202-4a21-bfd0-8da467449fa6/20250916T144850Z.vhd',
|
||||
name: 'AlmaLinux 9_ivopu',
|
||||
uuid: '73ed06ed-fdc8-43ef-a1c4-253e9005fbe0',
|
||||
sizeOnDisk: 100000,
|
||||
isDifferencing: false,
|
||||
},
|
||||
],
|
||||
href: '/rest/v0/backup-archives/1af95910-01b4-4e87-9c2f-d895cafe0776/xo-vm-backups/7cf6150f-a978-09e6-6b41-0d1d41967bdc/20250918T132942Z.json',
|
||||
sizeOnDisk: 100000,
|
||||
},
|
||||
]
|
||||
|
||||
@@ -52,13 +60,16 @@ export const backupArchive = {
|
||||
id: '/xo-vm-backups/7cf6150f-a978-09e6-6b41-0d1d41967bdc/vdis/f2599aa4-7bb4-434b-bf71-cf0ebe1e06a4/007e4f3e-6315-4779-aab5-461b519836f3/20250918T132942Z.alias.vhd',
|
||||
name: 'min-alpine-mra_alegi',
|
||||
uuid: 'c922ef3c-9d76-4482-87f8-a4da5849ee45',
|
||||
sizeOnDisk: 1048576,
|
||||
isDifferencing: true,
|
||||
},
|
||||
],
|
||||
id: '1af95910-01b4-4e87-9c2f-d895cafe0776/xo-vm-backups/7cf6150f-a978-09e6-6b41-0d1d41967bdc/20250918T132942Z.json',
|
||||
jobId: 'f2599aa4-7bb4-434b-bf71-cf0ebe1e06a4',
|
||||
mode: 'delta',
|
||||
scheduleId: '8db1c2da-2635-436f-8f78-62079fea3aa6',
|
||||
size: 0,
|
||||
size: 2058370,
|
||||
sizeOnDisk: 1048576,
|
||||
timestamp: 1758202182963,
|
||||
vm: {
|
||||
uuid: '7cf6150f-a978-09e6-6b41-0d1d41967bdc',
|
||||
|
||||
@@ -320,19 +320,22 @@ export const vmDashboard = {
|
||||
id: '1af95910-01b4-4e87-9c2f-d895cafe0776//xo-vm-backups/613f541c-4bed-fc77-7ca8-2db6b68f079c/20251102T230026Z.json',
|
||||
timestamp: 1762124426346,
|
||||
backupRepository: '1af95910-01b4-4e87-9c2f-d895cafe0776',
|
||||
size: 0,
|
||||
size: 1058370,
|
||||
sizeOnDisk: 48576,
|
||||
},
|
||||
{
|
||||
id: '1af95910-01b4-4e87-9c2f-d895cafe0776//xo-vm-backups/613f541c-4bed-fc77-7ca8-2db6b68f079c/20251101T230026Z.json',
|
||||
timestamp: 1762038026319,
|
||||
backupRepository: '1af95910-01b4-4e87-9c2f-d895cafe0776',
|
||||
size: 0,
|
||||
size: 2058370,
|
||||
sizeOnDisk: 1048576,
|
||||
},
|
||||
{
|
||||
id: '1af95910-01b4-4e87-9c2f-d895cafe0776//xo-vm-backups/613f541c-4bed-fc77-7ca8-2db6b68f079c/20251031T230025Z.json',
|
||||
timestamp: 1761951625256,
|
||||
backupRepository: '1af95910-01b4-4e87-9c2f-d895cafe0776',
|
||||
size: 0,
|
||||
size: 3058370,
|
||||
sizeOnDisk: 2048576,
|
||||
},
|
||||
],
|
||||
},
|
||||
|
||||
@@ -33,6 +33,7 @@ import type {
|
||||
XoVdi,
|
||||
XoVm,
|
||||
XoVmSnapshot,
|
||||
XoVmTemplate,
|
||||
XoMessage,
|
||||
XoNetwork,
|
||||
XoVif,
|
||||
@@ -638,6 +639,51 @@ export class VmController extends XapiXoController<XoVm> {
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* The VM must be halted. Removable media (e.g. CDs) are ejected before the conversion.
|
||||
*
|
||||
* The template keeps the same ID as the VM and is then available under `/vm-templates/{id}`.
|
||||
*
|
||||
* Required privilege:
|
||||
* - resource: vm, action: convert-to-template
|
||||
*
|
||||
* @example id "f07ab729-c0e8-721c-45ec-f11276377030"
|
||||
*/
|
||||
@Example(taskLocation)
|
||||
@Extension('x-mcp-exposure', 'confirm')
|
||||
@Post('{id}/actions/convert_to_template')
|
||||
@Middlewares(acl({ resource: 'vm', action: 'convert-to-template', objectId: 'params.id' }))
|
||||
@SuccessResponse(asynchronousActionResp.status, asynchronousActionResp.description)
|
||||
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
|
||||
@Response(createdResp.status, 'Template created')
|
||||
@Response(notFoundResp.status, notFoundResp.description)
|
||||
@Response(incorrectStateResp.status, incorrectStateResp.description)
|
||||
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
|
||||
async convertVmToTemplate(
|
||||
@Path() id: string,
|
||||
@Query() sync?: boolean
|
||||
): CreateActionReturnType<{ id: Unbrand<XoVmTemplate>['id'] }> {
|
||||
const vmId = id as XoVm['id']
|
||||
const action = async () => {
|
||||
await this.#vmService.convertToTemplate(vmId)
|
||||
|
||||
if (sync) {
|
||||
this.setHeader('Location', `${BASE_URL}/vm-templates/${vmId}`)
|
||||
}
|
||||
|
||||
return { id: vmId }
|
||||
}
|
||||
|
||||
return this.createAction<{ id: Unbrand<XoVmTemplate>['id'] }>(action, {
|
||||
sync,
|
||||
statusCode: createdResp.status,
|
||||
taskProperties: {
|
||||
name: 'convert VM to template',
|
||||
objectId: vmId,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Required privilege:
|
||||
* - resource: vm, action: revert-snapshot
|
||||
|
||||
@@ -22,6 +22,7 @@ import {
|
||||
type XoVmTemplate,
|
||||
} from '@vates/types'
|
||||
import { Response as ExResponse } from 'express'
|
||||
import { incorrectState } from 'xo-common/api-errors.js'
|
||||
import { Readable, Writable } from 'node:stream'
|
||||
|
||||
import type { CreateVmAfterCreateParams, CreateVmParams } from '../pools/pool.type.mjs'
|
||||
@@ -242,6 +243,22 @@ export class VmService {
|
||||
await xoApp.getXapi(id).editVm(id, editProps)
|
||||
}
|
||||
|
||||
async convertToTemplate(id: XoVm['id']): Promise<void> {
|
||||
const vm = this.#restApi.getObject<XoVm>(id, 'VM')
|
||||
// Checked before ejecting the media, so a VM that cannot be converted is left untouched
|
||||
if (vm.power_state !== VM_POWER_STATE.HALTED) {
|
||||
throw incorrectState({
|
||||
actual: vm.power_state,
|
||||
expected: VM_POWER_STATE.HALTED,
|
||||
object: vm.id,
|
||||
property: 'power_state',
|
||||
})
|
||||
}
|
||||
|
||||
const xapiVm = this.#restApi.getXapiObject<XoVm>(id, 'VM')
|
||||
await xapiVm.$xapi.VM_convertToTemplate(xapiVm.$ref)
|
||||
}
|
||||
|
||||
#getDashboardQuickInfo(id: XoVm['id']): VmDashboard['quickInfo'] {
|
||||
const {
|
||||
power_state,
|
||||
@@ -429,7 +446,13 @@ export class VmService {
|
||||
.flatMap(backupArchiveByVm => backupArchiveByVm[vm.id] ?? [])
|
||||
.sort((a, b) => b.timestamp - a.timestamp)
|
||||
.splice(0, 3)
|
||||
.map(ba => ({ id: ba.id, timestamp: ba.timestamp, backupRepository: ba.backupRepository, size: ba.size }))
|
||||
.map(ba => ({
|
||||
id: ba.id,
|
||||
timestamp: ba.timestamp,
|
||||
backupRepository: ba.backupRepository,
|
||||
size: ba.size,
|
||||
sizeOnDisk: ba.sizeOnDisk,
|
||||
}))
|
||||
}
|
||||
|
||||
async getVmDashboard(id: XoVm['id'], { stream }: { stream?: Writable } = {}): Promise<VmDashboard> {
|
||||
|
||||
@@ -23,6 +23,7 @@ type VmDashboardBackupArchive = {
|
||||
timestamp: XoVmBackupArchive['timestamp']
|
||||
backupRepository: XoVmBackupArchive['backupRepository']
|
||||
size: XoVmBackupArchive['size']
|
||||
sizeOnDisk?: XoVmBackupArchive['sizeOnDisk']
|
||||
}
|
||||
|
||||
export type VmDashboard = {
|
||||
|
||||
@@ -89,7 +89,7 @@ const CONTROLLER_PREFIXES = {
|
||||
* 'config.annotation'?: string,
|
||||
* 'config.instanceUuid'?: string,
|
||||
* 'config.firmware'?: string,
|
||||
* 'config.bootOptions.efiSecureBootEnabled'?: unknown,
|
||||
* 'config.bootOptions'?: { efiSecureBootEnabled?: unknown },
|
||||
* 'config.template'?: unknown,
|
||||
* 'config.hardware.numCPU'?: unknown,
|
||||
* 'config.hardware.memoryMB'?: unknown,
|
||||
@@ -379,7 +379,7 @@ export function buildInventory({
|
||||
annotation: properties['config.annotation'],
|
||||
instanceUuid: properties['config.instanceUuid'],
|
||||
firmware: firmware === 'efi' ? 'uefi' : firmware,
|
||||
secureBoot: isTrue(properties['config.bootOptions.efiSecureBootEnabled']),
|
||||
secureBoot: isTrue(properties['config.bootOptions']?.efiSecureBootEnabled),
|
||||
isTemplate: isTrue(properties['config.template']),
|
||||
cpus: toNumber(properties['config.hardware.numCPU']),
|
||||
memory: memoryMb === undefined ? undefined : memoryMb * 1024 * 1024,
|
||||
|
||||
@@ -1,7 +1,14 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { describe, it } from 'node:test'
|
||||
|
||||
import { countSnapshots, findDatacenter, parseDevices, parseGuestNics, parseVlan } from './_inventory.mjs'
|
||||
import {
|
||||
buildInventory,
|
||||
countSnapshots,
|
||||
findDatacenter,
|
||||
parseDevices,
|
||||
parseGuestNics,
|
||||
parseVlan,
|
||||
} from './_inventory.mjs'
|
||||
|
||||
// shaped as the SOAP library returns them: the nested references and types are not normalized
|
||||
const typed = (type, value) => ({ attributes: { 'xsi:type': type }, ...value })
|
||||
@@ -202,3 +209,37 @@ describe('findDatacenter', function () {
|
||||
assert.equal(findDatacenter('group-a', loop, datacenterIds), undefined)
|
||||
})
|
||||
})
|
||||
|
||||
describe('buildInventory', function () {
|
||||
const EMPTY = {
|
||||
about: {},
|
||||
datacenters: {},
|
||||
clusters: {},
|
||||
hosts: {},
|
||||
datastores: {},
|
||||
networks: {},
|
||||
portgroups: {},
|
||||
folders: {},
|
||||
computeResources: {},
|
||||
}
|
||||
|
||||
it('reads secure boot from the boot options, absent before vSphere 6.5', function () {
|
||||
const { vms } = buildInventory({
|
||||
...EMPTY,
|
||||
vms: {
|
||||
'vm-65': { 'config.bootOptions': { efiSecureBootEnabled: 'true' } },
|
||||
// ESXi 6.0: the boot options have no `efiSecureBootEnabled`
|
||||
'vm-60': { 'config.bootOptions': { bootDelay: '0' } },
|
||||
'vm-none': {},
|
||||
},
|
||||
})
|
||||
assert.deepEqual(
|
||||
vms.map(({ id, secureBoot }) => ({ id, secureBoot })),
|
||||
[
|
||||
{ id: 'vm-65', secureBoot: true },
|
||||
{ id: 'vm-60', secureBoot: false },
|
||||
{ id: 'vm-none', secureBoot: false },
|
||||
]
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -623,7 +623,9 @@ export default class Esxi extends EventEmitter {
|
||||
'config.annotation',
|
||||
'config.instanceUuid',
|
||||
'config.firmware',
|
||||
'config.bootOptions.efiSecureBootEnabled',
|
||||
// the whole object rather than `config.bootOptions.efiSecureBootEnabled`: that property only
|
||||
// exists since vSphere 6.5, and an unknown path fails the whole request (InvalidProperty)
|
||||
'config.bootOptions',
|
||||
'config.template',
|
||||
'config.hardware.numCPU',
|
||||
'config.hardware.memoryMB',
|
||||
@@ -1134,9 +1136,11 @@ export default class Esxi extends EventEmitter {
|
||||
* @returns {Promise<object>} the `info` of the successful task
|
||||
*/
|
||||
async snapshot(vmId, name, description, { signal, timeout = 30 * 60e3 } = {}) {
|
||||
// not `CreateSnapshotEx_Task`: it only exists since vSphere 8 (absent from the WSDL of older
|
||||
// hosts), and its only addition, the quiesce spec, is not used
|
||||
return this.#runTask(
|
||||
'CreateSnapshotEx_Task',
|
||||
{ _this: vmId, name, description, memory: false },
|
||||
'CreateSnapshot_Task',
|
||||
{ _this: vmId, name, description, memory: false, quiesce: false },
|
||||
{ signal, timeout }
|
||||
)
|
||||
}
|
||||
|
||||
@@ -696,7 +696,7 @@ describe('tasks', function () {
|
||||
const controller = new AbortController()
|
||||
const { esxi, vimClient } = await connectedEsxi({
|
||||
responses: {
|
||||
CreateSnapshotEx_Task: () => startedTask(),
|
||||
CreateSnapshot_Task: () => startedTask(),
|
||||
RetrievePropertiesEx: () => {
|
||||
controller.abort()
|
||||
return taskInfo('running')
|
||||
|
||||
@@ -172,6 +172,18 @@ These classes MUST be used to ensure the typography is consistent across all com
|
||||
>
|
||||
> `<div class="typo-body-regular` />
|
||||
|
||||
## Component MUST use the z-index variables
|
||||
|
||||
A z-index only means something compared to the others: a menu, a select dropdown and a modal can all show at the same time. To keep them in the right order, each layer is a variable of the [z-index file](../../lib/assets/css/_z-indexes.pcss), from bottom to top:
|
||||
|
||||
- `--z-index-panel`: the sidebar, the side panels and the mobile menu laid over the page, and the backdrop under them
|
||||
- `--z-index-popup`: the popups opened from the page (menus), which stay under an overlay opened from one of their items
|
||||
- `--z-index-overlay-backdrop` and `--z-index-overlay`: the overlays (modals, drawers) and their backdrop
|
||||
- `--z-index-overlay-popup`: the popups above the overlays: the menus opened from the current overlay, and the select dropdowns, which close as soon as something else is clicked
|
||||
- `--z-index-tooltip`: the tooltips, above everything
|
||||
|
||||
Use the variable of the layer the element belongs to rather than a number. If none fits, add a layer to the file.
|
||||
|
||||
## New CSS features support
|
||||
|
||||
We try to keep up to date with new CSS features and use them when they address a problem or specific integration use case.
|
||||
|
||||
@@ -18,7 +18,6 @@
|
||||
|
||||
# Directives
|
||||
|
||||
- [vRestricted](../lib/directives/restricted.directive.md)
|
||||
- [vTooltip](../lib/directives/tooltip.directive.md)
|
||||
|
||||
# Utils
|
||||
|
||||
@@ -59,13 +59,14 @@ Testing uses **Vitest 5** with a single `unit` project (see `vitest.config.ts`):
|
||||
| `test/expect-loader.ts` | `hasLoader(wrapper)`: whether a `UiLoader` is rendered; `expectLoaderInsteadOf(wrapper, findContent)`: a `UiLoader` shown and the content it stands for empty (also used by XO 6) |
|
||||
| `test/select.ts` | `openSelect`, `findShownSelections`, `findSelectOptionLabels`, `pickSelectOption(wrapper, label, { detailed? })`: opens a `VtsSelect`, reads the selection it shows, reads or picks its options (`detailed`: the option shows details after its label); `chooseSelectOption(wrapper, label, { container?, detailed? })`: opens the select inside `container`, then picks the option (also used by XO 6) |
|
||||
| `test/is-placeholder-shown.ts` | `isPlaceholderShown(field)`: whether a readonly input shows its placeholder in place of its value |
|
||||
| `test/can-focus-input.ts` | `canFocusInput(wrapper)`: whether the first input of a wrapper attached to the document takes the focus, which an `inert` ancestor prevents |
|
||||
| `test/inject-or-throw.ts` | `injectOrThrow(key)`: `inject(key)`, throwing when nothing provides it |
|
||||
| `test/mount-with-setup.ts` | `mountWithSetup(setup, { global?, attachTo? })`: mounts a component whose `setup` sets up what its render needs below it (a select, a provided context) and returns that render (XO 6 wraps it with its config); `mountWithSetupResult(setup, options)`: the same, keeping what `setup` builds (a form, a composable's return), `setup` returning `{ result, render }`, returns `{ wrapper, result }`; `mountComposableUnderSetup(setup, composable, options)`: runs `composable` (given what `setup` returned) in a child of the component whose `setup` provides what it injects, returns `{ provided, result }` |
|
||||
| `test/mount-with-select.ts` | `renderSelect(id, { accent?, ref? }, slots?)`: renders the `VtsSelect` of a select id, `neutral` accent by default; `mountSelect`: a `VtsSelect` of string sources, its config, accent, wrapper message, option slot and a callback receiving the mounted select |
|
||||
| `test/find-title.ts` | `findTitle`: the `.title` of a `VtsSuccessStateHero` or a list item, `undefined` without one (also used by XO 6) |
|
||||
| `test/create-task-item.ts` | `createTaskItem`: a `Task` as the task lists display it, with the given overrides (also used by XO 6) |
|
||||
| `test/find-tooltip-contents.ts` | `findTooltipContents`: the content of every tooltip currently shown, in order |
|
||||
| `test/hover.ts` | `hover`: moves the mouse over an element |
|
||||
| `test/overlay.ts` | `registerOverlay(key?)`: an open overlay in the store of the last mounted wrapper, on top of those already open; `provideOverlayKey(key)`: what that overlay provides to its content, nothing without a key |
|
||||
| `test/query-builder.ts` | `getLabels`: the label of each property of a query builder schema, or of each value of an operator, by its key (also used by XO 6); `useSchemaWithOptionalTag`: a schema of a name and a tag offered once `hasTag` is set, called in a setup; `getFirstFilter` (also used by XO 6), `findPropertyLabels`: the first filter of a group and the label of each property it offers |
|
||||
| `tsconfig.vitest.json` | Type-checks test files with the Vitest globals and the `@core-test` alias |
|
||||
| `tsconfig.app.json` | Type-checks the library, test files excluded |
|
||||
|
||||
|
||||
8
@xen-orchestra/web-core/lib/assets/css/_z-indexes.pcss
Normal file
8
@xen-orchestra/web-core/lib/assets/css/_z-indexes.pcss
Normal file
@@ -0,0 +1,8 @@
|
||||
:root {
|
||||
--z-index-panel: 1010;
|
||||
--z-index-popup: 1011;
|
||||
--z-index-overlay-backdrop: 1015;
|
||||
--z-index-overlay: 1016;
|
||||
--z-index-overlay-popup: 1020;
|
||||
--z-index-tooltip: 999999;
|
||||
}
|
||||
@@ -3,6 +3,7 @@
|
||||
@import '_fonts.pcss';
|
||||
@import '_context.pcss';
|
||||
@import '_shadows.pcss';
|
||||
@import '_z-indexes.pcss';
|
||||
@import '_typography.pcss';
|
||||
|
||||
:root {
|
||||
|
||||
@@ -14,6 +14,6 @@ defineSlots<{
|
||||
.vts-backdrop {
|
||||
position: fixed;
|
||||
inset: 0;
|
||||
z-index: 1010;
|
||||
z-index: var(--z-index-panel);
|
||||
}
|
||||
</style>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user