Compare commits

..

2 Commits

Author SHA1 Message Date
Florent BEAUCHAMP
791baca5f2 wip 2025-08-25 07:14:22 +00:00
Florent BEAUCHAMP
04d3231a0b feat: technical exploration 2025-08-15 15:02:34 +00:00
1453 changed files with 86302 additions and 67322 deletions

View File

@@ -233,26 +233,7 @@ module.exports = {
'@intlify/vue-i18n/no-duplicate-keys-in-locale': 'error',
'@intlify/vue-i18n/no-missing-keys-in-other-locales': [
'error',
{
ignoreLocales: [
'de',
'fa',
'cs',
'es',
'sv',
'it',
'ru',
'uk',
'nl',
'pt-BR',
'da',
'ko',
'nb-NO',
'ja',
'fi',
'pl',
],
},
{ ignoreLocales: ['de', 'fa', 'cs', 'es', 'sv', 'it', 'ru', 'uk', 'nl'] },
],
},
},

View File

@@ -73,20 +73,20 @@ exports.asyncEach = function asyncEach(iterable, iteratee, { concurrency = 10, s
}
nextIsRunning = true
if (running < concurrency) {
try {
const cursor = await it.next()
if (cursor.done) {
next = () => {
if (running === 0) {
if (errors.length === 0) {
resolve()
} else {
reject(new AggregateError(errors))
}
const cursor = await it.next()
if (cursor.done) {
next = () => {
if (running === 0) {
if (errors.length === 0) {
resolve()
} else {
reject(new AggregateError(errors))
}
}
} else {
++running
}
} else {
++running
try {
const result = iteratee.call(this, cursor.value, index++, iterable)
let then
if (result != null && typeof result === 'object' && typeof (then = result.then) === 'function') {
@@ -94,9 +94,9 @@ exports.asyncEach = function asyncEach(iterable, iteratee, { concurrency = 10, s
} else {
onFulfilled(result)
}
} catch (error) {
onRejected(error)
}
} catch (error) {
onRejected(error)
}
nextIsRunning = false
return next()

View File

@@ -114,20 +114,6 @@ describe('asyncEach', () => {
tracker.verify()
})
it('handle error on iterable', async () => {
const iteratee = spy(async () => {})
const iterable = async function* () {
for (const value of [1, 2, 3]) {
if (value === 2) {
throw new Error('iterator error')
}
await randomDelay()
yield value
}
}
await assert.rejects(() => asyncEach(iterable(), iteratee, { concurrency: 1 }), { message: 'iterator error' })
})
})
)
})

View File

@@ -24,7 +24,7 @@
"url": "https://vates.fr"
},
"license": "ISC",
"version": "1.0.1",
"version": "1.0.0",
"engines": {
"node": ">=8.10"
},

View File

@@ -62,7 +62,7 @@ exports.parseFlags = function (flags) {
case 'ax': info = {read:false, write:true, create:true, append:true, exclusive:true}; break;
case 'a+': info = {read:true, write:true, create:true, append:true}; break;
case 'ax+': info = {read:true, write:true, create:true, append:true, exclusive:true}; break;
default: throw Error("Unknown mode: "+flags); // TODO: throw as `S.err.INVAL`
default: throw Error("Uknown mode: "+flags); // TODO: throw as `S.err.INVAL`
}
if (info.sync) throw Error("Mode not implemented."); // TODO: what would this require of us?
if (_dir) info._openDir = true;

View File

@@ -1,7 +1,7 @@
{
"private": false,
"name": "@vates/fatfs",
"version": "0.11.1",
"version": "0.11.0",
"description": "fs implementation on top of raw FAT16/FAT32 block source",
"main": "index.js",
"scripts": {

View File

@@ -90,7 +90,7 @@ function startTests(vol, waitTime) {
assert(path === file, "Fixed fluffy path matches normal one.");
});
fs.realpath([BASE_DIR,"non","existent","path"].join('/'), function (e) {
assert(e, "Expected error calling fs.realpath on nonexistent file.");
assert(e, "Expected error calling fs.realpath on non-existent file.");
});
fs.readdir(BASE_DIR, function (e, arr) {

View File

@@ -19,12 +19,12 @@
},
"main": "./index.mjs",
"dependencies": {
"@xen-orchestra/fs": "^4.6.6",
"@xen-orchestra/fs": "^4.6.2",
"@xen-orchestra/log": "^0.7.1",
"fuse-native": "^2.2.6",
"lru-cache": "^7.14.0",
"promise-toolbox": "^0.21.0",
"vhd-lib": "^4.14.7"
"vhd-lib": "^4.14.0"
},
"bin": {
"xo-fuse-vhd": "./cli.mjs"

View File

@@ -1,13 +1,13 @@
{
"name": "@vates/generator-toolbox",
"version": "1.1.0",
"version": "1.0.4",
"main": "dist/index.mjs",
"license": "MIT",
"private": false,
"type": "module",
"devDependencies": {
"@eslint/js": "^9.19.0",
"rimraf": "^6.0.1",
"rimraf": "^5.0.1",
"@types/node": "^20.6",
"typescript": "~5.6",
"typescript-eslint": "^8.23.0"

View File

@@ -19,7 +19,7 @@ export class Throttle {
} else {
speed = this.#bytesPerSecond
}
assert.ok(speed >= 0, `speed must be positive, ${speed} computed`)
assert.ok(speed > 0, `speed must be greater than zero, ${speed} computed`)
return speed
}
constructor(speed: number | (() => number)) {
@@ -29,9 +29,7 @@ export class Throttle {
getNextSlot(length: number): { timeout?: ReturnType<typeof setTimeout>; promise?: Promise<unknown> } {
assert.notStrictEqual(length, undefined, `throttled stream need to expose a length property }`)
assert.ok(length > 0, `throttled stream must expose a positive length property , ${length} given }`)
if (this.speed === 0) {
return {}
}
const previous = this.#previousSlot
const nextSlot = Math.round(previous + (length * 1000) / this.speed)
if (nextSlot < Date.now()) {

View File

@@ -2,7 +2,6 @@
"compilerOptions": {
"target": "es2023",
"module": "ESNext",
"types": ["node"], // Only use types from Node.js and packages that are explicitly imported
"moduleResolution": "bundler",
"strict": true,
"declaration": true, // Generates `.d.ts` files for type safety

View File

@@ -1,132 +0,0 @@
import { RandomAccessDisk } from '@xen-orchestra/disk-transform'
import NbdClient from '@vates/nbd-client'
/**
* @typedef {{ offset: number, length: number }} DataRange
*/
/**
* @extends {RandomAccessDisk}
*/
export class NbdDisk extends RandomAccessDisk {
#nbdInfos
/** @type {NbdClient|undefined} */
#nbdClient
/** @type {Array<DataRange> | undefined} */
#dataMap
/** @type {number} */
#blockSize
constructor(nbdInfos, blockSize, { dataMap } = {}) {
super()
this.#blockSize = blockSize
this.#nbdInfos = nbdInfos
this.#dataMap = dataMap && this.#processDatamap(dataMap)
}
#processDatamap(rawDataMap) {
return rawDataMap
.filter(({ type }) => type === 0)
.map(({ offset, length }) => ({ offset, length }))
.sort(({ offset: offset1 }, { offset: offset2 }) => offset1 - offset2)
}
/**
* @param {number} index
* @returns {Promise<DiskBlock>}
*/
async readBlock(index) {
if (!this.#nbdClient) {
throw new Error("can't readBlock before init")
}
let data = await this.#nbdClient.readBlock(index, this.getBlockSize())
if (data.length !== this.getBlockSize()) {
// this condition only work on non aligned disks
// we won't accept truncated block from unaligned disks
if (index === Math.ceil(this.getVirtualSize() / this.getBlockSize()) - 1) {
// last block add zeros at the end
data = Buffer.concat([data], this.getBlockSize())
} else {
throw new Error(`Block ${index} is not at the right size, expecting ${this.getBlockSize()}, got ${data.length}`)
}
}
return {
index,
data,
}
}
/**
* @returns {number}
*/
getVirtualSize() {
if (!this.#nbdClient) {
throw new Error("can't get size before init")
}
return Number(this.#nbdClient.exportSize)
}
/**
* @returns {number}
*/
getBlockSize() {
return this.#blockSize
}
/**
* @returns {Promise<void>}
*/
async init() {
this.#nbdClient = new NbdClient(this.#nbdInfos)
await this.#nbdClient.connect()
if (this.#dataMap === undefined) {
this.#dataMap = this.#processDatamap(await this.#nbdClient.getMap())
}
}
/**
* @returns {Promise<void>}
*/
async close() {
await this.#nbdClient?.disconnect()
}
/**
* @returns {boolean}
*/
isDifferencing() {
return false
}
/**
* @returns {Array<number>}
*/
getBlockIndexes() {
const indexes = new Set()
this.#dataMap?.forEach(({ offset, length }) => {
if (length === 0) return
const firstBlockIndex = Math.floor(offset / this.getBlockSize())
const lastBlockIndex = Math.floor((offset + length - 1) / this.getBlockSize())
for (let blockIndex = firstBlockIndex; blockIndex <= lastBlockIndex; blockIndex++) {
indexes.add(blockIndex)
}
})
return [...indexes].sort((a, b) => a - b)
}
/**
* @param {number} index
* @returns {boolean}
*/
hasBlock(index) {
if (!this.#dataMap) {
throw new Error("can't hasBlock before init")
}
const blockStart = index * this.getBlockSize()
const blockEnd = (index + 1) * this.getBlockSize()
return this.#dataMap.some(({ offset, length }) => offset + length > blockStart && offset < blockEnd)
}
}

View File

@@ -20,7 +20,6 @@ import {
OPTS_MAGIC,
NBD_CMD_DISC,
} from './constants.mjs'
import { spawn } from 'node:child_process'
const { warn } = createLogger('vates:nbd-client')
@@ -359,40 +358,4 @@ export default class NbdClient {
},
})
}
/**
* returns the map of the file with holes, zeros and data, useful to handle efficiently sparse source
* to implement this internally: use structure response if the server supports it, and then ask for BLOCK_STATUS *
*
* @returns {Promise<{ offset: number, length: number, type: number }[]>}
* A promise that resolves to an array where each object represents a segment:
* - `offset` — The byte offset from the start.
* - `length` — The size of the segment in bytes.
* - `type` — A numeric code indicating the segment type ( 0 means data).
*/
/* async */ getMap() {
return new Promise((resolve, reject) => {
const process = spawn('nbdinfo', [
'--json',
'--map',
`nbd://${this.#serverAddress}:${this.#serverPort}/${encodeURIComponent(this.#exportName)}`,
])
let text = ''
let errText = ''
process.stdout.on('data', data => (text += data))
process.stderr.on('data', data => (errText += data))
process.on('error', reject)
process.on('close', code => {
if (code !== 0) {
return reject(new Error(`Error during getMap (code: ${code}): ${errText}`))
}
try {
const json = JSON.parse(text)
resolve(json)
} catch (error) {
reject(new Error(`${error} ${text}`))
}
})
})
}
}

View File

@@ -129,17 +129,4 @@ export default class MultiNbdClient {
yield readAhead.shift()
}
}
/**
* returns the map of the file with holes, zeros and data, useful to handle efficiently sparse source *
*
* @returns {Promise<{ offset: number, length: number, type: number }[]>}
* A promise that resolves to an array where each object represents a segment:
* - `offset` — The byte offset from the start.
* - `length` — The size of the segment in bytes.
* - `type` — A numeric code indicating the segment type (0 means no data).
*/
async getMap() {
// ask the map from one of the connected client
return this.#clients[Math.floor(this.#clients.length * Math.random())].getMap()
}
}

View File

@@ -13,19 +13,18 @@
"url": "https://vates.fr"
},
"license": "ISC",
"version": "3.2.3",
"version": "3.1.4",
"engines": {
"node": ">=14.0"
},
"main": "./index.mjs",
"dependencies": {
"@vates/async-each": "^1.0.1",
"@vates/read-chunk": "^1.2.1",
"@vates/async-each": "^1.0.0",
"@vates/read-chunk": "^1.2.0",
"@xen-orchestra/async-map": "^0.1.2",
"@xen-orchestra/disk-transform": "^1.2.1",
"@xen-orchestra/log": "^0.7.1",
"promise-toolbox": "^0.21.0",
"xen-api": "^4.7.6"
"xen-api": "^4.7.3"
},
"devDependencies": {
"tap": "^18.7.0",

View File

@@ -71,17 +71,13 @@ exports.readChunk = readChunk
* If `size` bytes are not available to be read, the returned promise is rejected.
*
* @param {Readable} stream - A readable stream to read from.
* @param {number?} [size] - The number of bytes to read for binary streams (ignored for object streams).
* @param {number} [size] - The number of bytes to read for binary streams (ignored for object streams).
* @returns {Promise<Buffer|string|unknown>} - A Promise that resolves to the read chunk.
*/
exports.readChunkStrict = async function readChunkStrict(stream, size) {
const chunk = await readChunk(stream, size)
if (chunk === null) {
if (size === undefined) {
throw new Error(`stream has ended without data`)
} else {
throw new Error(`stream has ended without data, was looking for ${size} bytes`)
}
throw new Error('stream has ended without data')
}
if (size !== undefined && chunk.length !== size) {

View File

@@ -19,7 +19,7 @@
"type": "git",
"url": "https://github.com/vatesfr/xen-orchestra.git"
},
"version": "1.2.1",
"version": "1.2.0",
"engines": {
"node": ">=8.10"
},

View File

@@ -2,17 +2,8 @@
import eslint from '@eslint/js'
import tseslint from 'typescript-eslint'
import { fileURLToPath } from 'node:url'
import path from 'node:path'
const __dirname = path.dirname(fileURLToPath(import.meta.url))
export default tseslint.config(eslint.configs.recommended, tseslint.configs.recommended, {
languageOptions: {
parserOptions: {
tsconfigRootDir: __dirname,
},
},
ignores: ['dist'],
rules: {
// Allow empty interface for recursive generic typing (E.g. interface XenApiNetworkWrapped)

View File

@@ -1,7 +1,7 @@
{
"name": "@vates/types",
"private": false,
"version": "1.19.0",
"version": "1.9.0",
"main": "./dist/index.mjs",
"exports": {
".": {
@@ -9,7 +9,6 @@
"types": "./dist/index.d.mts"
},
"./xo": "./dist/xo.d.mts",
"./xo-app": "./dist/xo-app.d.mts",
"./xen-api": "./dist/xen-api.d.mts",
"./common": {
"default": "./dist/common.mjs",
@@ -22,10 +21,6 @@
"./lib/xen-orchestra/*": {
"default": "./dist/lib/xen-orchestra-*.mjs",
"type": "./dist/lib/xen-orchestra-*.d.mts"
},
"./lib/complex-matcher": {
"default": "./dist/lib/complex-matcher.mjs",
"type": "./dist/lib/complex-matcher.d.mts"
}
},
"type": "module",

View File

@@ -655,14 +655,6 @@ export const BACKUP_TYPE = { backup: 'backup', metadata: 'metadataBackup', mirro
export type BACKUP_TYPE = (typeof BACKUP_TYPE)[keyof typeof BACKUP_TYPE]
export const SUPPORTED_VDI_FORMAT = {
raw: 'raw',
vhd: 'vhd',
qcow2: 'qcow2',
} as const
export type SUPPORTED_VDI_FORMAT = (typeof SUPPORTED_VDI_FORMAT)[keyof typeof SUPPORTED_VDI_FORMAT]
// ----- XAPI Stats
type XapiStatsResponse<T> = {

View File

@@ -1,6 +1,4 @@
export * from './common.mjs'
export * from './xen-api.mjs'
export * from './xo.mjs'
export * from './xo-app.mjs'
export * from './lib/xen-orchestra-xapi.mjs'
export * from './lib/complex-matcher.mjs'

View File

@@ -1,5 +0,0 @@
export type Or<T> = Id<{ __or: T[] }>
export type Id<T> = { id: T }
export type IdOr<T> = Id<T> | Or<T>

View File

@@ -1,21 +1,7 @@
import { Branded } from '../common.mjs'
export interface VatesTask {
_abortController: AbortController
_onProgress(data?: unknown): void
export type Task = {
id: Branded<'task'>
id: Branded<'vates-task'>
status: 'failure' | 'pending' | 'success'
abort(reason?: unknown): void
failure(error?: unknown): void
info(message: string, data: unknown): void
run<T>(fn: () => T | (() => Promise<T>)): Promise<T>
runInside<T>(fn: () => T | (() => Promise<T>)): Promise<T>
set(name: string, value: unknown): void
start(): void
success(result?: unknown): void
warning(message: string, data: unknown): void
wrap<T>(fn: () => T | (() => Promise<T>)): Promise<T>
wrapInside<T>(fn: () => T | (() => Promise<T>)): Promise<T>
run: <T>(fn: () => T) => Promise<T>
}

View File

@@ -1,32 +1,26 @@
import {
WrappedXenApiRecord,
XenApiHost,
XenApiNetwork,
XenApiNetworkWrapped,
XenApiRecord,
XenApiSr,
XenApiTask,
XenApiVbd,
XenApiVdi,
XenApiVif,
XenApiVm,
XenApiVmWrapped,
XenApiVtpm,
} from '../xen-api.mjs'
import type { OPAQUE_REF_NULL, SUPPORTED_VDI_FORMAT, VBD_MODE, VBD_TYPE, VIF_LOCKING_MODE } from '../common.mjs'
import type { PassThrough, Readable } from 'node:stream'
import type { Readable } from 'node:stream'
import type {
XoGpuGroup,
XoVgpuType,
XoHost,
XoNetwork,
XoPif,
XoSr,
XoUser,
XoVdi,
XoVgpuType,
XoVm,
XoVmTemplate,
XoVif,
} from '../xo.mjs'
export type XcpPatches = {
@@ -62,7 +56,6 @@ export interface Xapi {
call: <ReturnType>(...args: unknown[]) => Promise<ReturnType>
callAsync: <ReturnType>(...args: unknown[]) => Promise<ReturnType>
barrier<T extends XenApiRecord>(ref: T['$ref']): Promise<Extract<WrappedXenApiRecord, { $ref: T['$ref'] }>>
getField<T extends XenApiRecord, K extends keyof T>(
type: Extract<WrappedXenApiRecord, T>['$type'],
ref: T['$ref'],
@@ -85,42 +78,10 @@ export interface Xapi {
}
): Promise<XenApiNetworkWrapped>
deleteNetwork(id: XoNetwork['id']): Promise<void>
deleteVif(vifId: XoVif['id']): Promise<void>
exportVmOva(vmRef: XenApiVm['$ref']): Promise<PassThrough>
migrateVm(
vmId: XoVm['id'],
hostXapi: Xapi,
hostId: XoHost['id'],
opts?: {
force?: boolean
mapVdisSrs?: Record<XoVdi['id'], XoSr['id']>
mapVifsNetworks?: Record<XoVif['id'], XoNetwork['id']>
migrationNetworkId?: XoNetwork['id']
sr?: XoSr['id']
bypassAssert?: boolean
}
): Promise<void>
listMissingPatches(host: XoHost['id']): Promise<XcpPatches[] | XsPatches[]>
pool_emergencyShutdown(): Promise<void>
resumeVm(id: XoVm['id']): Promise<void>
unpauseVm(id: XoVm['id']): Promise<void>
SR_importVdi(
ref: XenApiSr['$ref'],
stream: Readable,
opts?: {
format?: SUPPORTED_VDI_FORMAT
name_description?: XoVdi['name_description']
name_label?: XoVdi['name_label']
other_config?: XoVdi['other_config']
read_only?: boolean
sharable?: boolean
SR?: XenApiSr['$ref']
tags?: XoVdi['tags']
type?: XoVdi['type']
virtual_size?: XoVdi['size']
xenstore_data?: Record<string, string>
}
): Promise<XenApiVdi['$ref']>
startVm(
id: XoVm['id'],
opts?: {
@@ -136,10 +97,6 @@ export interface Xapi {
startOnly?: boolean
}
): Promise<void>
VM_export(
vmRef: XenApiVm['$ref'],
opts?: { cancelToken?: unknown; compress?: boolean; useSnapshot?: boolean }
): ReturnType<Xapi['getResource']>
VM_import(
stream: Readable,
srRef?: XenApiSr['$ref'],
@@ -191,62 +148,12 @@ export interface Xapi {
vgpuType?: XoVgpuType['id']
gpuGroup?: XoGpuGroup['id']
copyHostBiosStrings?: boolean
hvmBootFirmware?: 'uefi' | 'bios'
secureBoot?: boolean
},
checkLimits?: boolean,
creatorId?: XoUser['id'],
opts?: { destroyAllVifs: boolean }
): Promise<XenApiVmWrapped>
moveVdi(
vdiId: XenApiVdi['$ref'] | XoVdi['id'],
srId: XenApiSr['$ref'] | XoSr['id'],
opts?: { _failOnCbtError?: boolean }
): Promise<XenApiVdi>
VBD_create(params: {
bootable?: boolean
empty?: boolean
mode?: VBD_MODE
other_config?: Record<string, string>
qos_algorithm_params?: Record<string, string>
qos_algorithm_type?: string
type?: VBD_TYPE
unpluggable?: boolean
userdevice?: string
VDI: XenApiVdi['$ref'] | OPAQUE_REF_NULL
VM: XenApiVm['$ref']
}): Promise<XenApiVbd['$ref']>
VBD_destroy(vbdRef: XenApiVbd['$ref']): Promise<void>
VBD_unplug(vbdRef: XenApiVbd['$ref']): Promise<void>
VDI_destroy(vdiRef: XenApiVdi['$ref']): Promise<void>
VDI_destroyCloudInitConfig(vdiRef: XenApiVdi['$ref'], opts?: { timeLimit?: number }): Promise<void>
VDI_exportContent(
vdiRef: XenApiVdi['$ref'],
opts: { baseRef?: string; cancelToken?: unknown; format: SUPPORTED_VDI_FORMAT }
): Promise<Readable & { length?: number }>
VDI_importContent(
vdiRef: XenApiVdi['$ref'],
stream: Readable,
opts: { cancelToken?: unknown; format: SUPPORTED_VDI_FORMAT }
): Promise<void>
VIF_create(
options: {
currently_attached?: boolean
device?: string
ipv4_allowed?: string[]
ipv6_allowed?: string[]
locking_mode?: VIF_LOCKING_MODE
MTU?: number
network: XenApiNetwork['$ref']
other_config?: Record<string, string>
qos_algorithm_params?: Record<string, string>
qos_algorithm_type?: string
VM: XenApiVm['$ref']
},
extraOptions?: {
MAC?: string
}
): Promise<XenApiVif['$ref']>
VM_createCloudInitConfig(
vmRef: XenApiVm['$ref'],
cloudConfig: string,
@@ -266,5 +173,4 @@ export interface Xapi {
params?: { host?: XenApiHost; query?: Record<string, unknown>; task?: boolean | XenApiTask['$ref'] }
): Promise<{ body: Readable }>
isHyperThreadingEnabled(hostId: XoHost['id']): Promise<boolean | null>
VTPM_create(params: { VM: XenApiVm['$ref']; is_unique?: boolean; contents?: string }): Promise<XenApiVtpm['$ref']>
}

View File

@@ -70,11 +70,6 @@ import type { Xapi } from './lib/xen-orchestra-xapi.mjs'
// https://github.com/vatesfr/xen-orchestra/tree/wip-xapi-types-generator/%40xen-orchestra/xapi-generator
// All properties added after XenServer 7.0 (dundee) release have been marked as optional
type TagCallMethods = {
(method: 'add_tags', tag: string): Promise<void>
(method: 'remove_tags', tag: string): Promise<void>
}
/**
* Add properties injected by `xen-api`.
* $ref property is also injected by XOLite, so she is not present here.
@@ -167,8 +162,6 @@ export interface XenApiEvent {
timestamp?: string
}
type XenApiPoolCallMethods = TagCallMethods & {}
export interface XenApiPool {
$ref: Branded<'pool'>
allowed_operations: POOL_ALLOWED_OPERATIONS[]
@@ -231,7 +224,7 @@ export interface XenApiPool {
/** @deprecated */
wlb_verify_cert?: boolean
}
export type XenApiPoolWrapped = WrapperXenApi<XenApiPool, 'pool', XenApiPoolCallMethods>
export type XenApiPoolWrapped = WrapperXenApi<XenApiPool, 'pool'>
/** @deprecated */
export interface XenApiPoolPatch {
@@ -263,7 +256,7 @@ export interface XenApiPoolUpdate {
version?: string
}
type XenApiVmCallMethods = TagCallMethods & {
type XenApiVmCallMethods = {
(method: 'start', start_paused: boolean, force: boolean): Promise<void>
(method: 'clean_shutdown'): Promise<void>
(method: 'hard_shutdown'): Promise<void>
@@ -490,7 +483,6 @@ export interface XenApiDrTask {
uuid: string
}
type XenApiHostCallMethods = TagCallMethods & {}
export interface XenApiHost {
$ref: Branded<'host'>
address: string
@@ -567,7 +559,7 @@ export interface XenApiHost {
uuid: string
virtual_hardware_platform_versions: number[]
}
export type XenApiHostWrapped = WrapperXenApi<XenApiHost, 'host', XenApiHostCallMethods>
export type XenApiHostWrapped = WrapperXenApi<XenApiHost, 'host'>
export interface XenApiHostCrashdump {
$ref: Branded<'host_crashdump'>
@@ -622,8 +614,6 @@ export interface XenApiHostCpu {
vendor: string
}
type XenApiNetworkCallMethods = TagCallMethods & {}
export interface XenApiNetwork {
$ref: Branded<'network'>
allowed_operations: NETWORK_OPERATIONS[]
@@ -643,7 +633,8 @@ export interface XenApiNetwork {
uuid: string
VIFs: XenApiVif['$ref'][]
}
export interface XenApiNetworkWrapped extends WrapperXenApi<XenApiNetwork, 'network', XenApiNetworkCallMethods> {}
export interface XenApiNetworkWrapped extends WrapperXenApi<XenApiNetwork, 'network'> {}
export interface XenApiVif {
$ref: Branded<'VIF'>
allowed_operations: VIF_OPERATIONS[]
@@ -791,7 +782,6 @@ export interface XenApiSm {
}
export type XenApiSmWrapped = WrapperXenApi<XenApiSm, 'SM'>
type XenApiSrCallMethods = TagCallMethods & {}
export interface XenApiSr {
$ref: Branded<'SR'>
allowed_operations: STORAGE_OPERATIONS[]
@@ -816,7 +806,7 @@ export interface XenApiSr {
VDIs: XenApiVdi['$ref'][]
virtual_allocation: number
}
export type XenApiSrWrapped = WrapperXenApi<XenApiSr, 'SR', XenApiSrCallMethods>
export type XenApiSrWrapped = WrapperXenApi<XenApiSr, 'SR'>
export interface XenApiSrStat {
$ref: Branded<'sr_stat'>
@@ -842,8 +832,6 @@ export interface XenApiLvhd {
uuid: string
}
type XenApiVdiCallMethods = TagCallMethods & {}
export interface XenApiVdi {
$ref: Branded<'VDI'>
allow_caching: boolean
@@ -880,7 +868,7 @@ export interface XenApiVdi {
virtual_size: number
xenstore_data: Record<string, string>
}
export type XenApiVdiWrapped = WrapperXenApi<XenApiVdi, 'VDI', XenApiVdiCallMethods>
export type XenApiVdiWrapped = WrapperXenApi<XenApiVdi, 'VDI'>
export interface XenApiVbd {
$ref: Branded<'VBD'>
@@ -933,7 +921,6 @@ export interface XenApiPbd {
SR: XenApiSr['$ref']
uuid: string
}
export type XenApiPbdWrapped = WrapperXenApi<XenApiPbd, 'PBD'>
/** @deprecated */
export interface XenApiCrashdump {
@@ -1008,7 +995,6 @@ export interface XenApiMessage {
timestamp: string
uuid: string
}
export type XenApiMessageWrapped = WrapperXenApi<XenApiMessage, 'message'>
export interface XenApiSecret {
$ref: Branded<'secret'>
@@ -1371,7 +1357,6 @@ export type XenApiRecord =
export type WrappedXenApiRecord =
| XenApiHostWrapped
| XenApiNetworkWrapped
| XenApiPbdWrapped
| XenApiPifWrapped
| XenApiPoolWrapped
| XenApiSrWrapped

View File

@@ -1,257 +0,0 @@
import { EventEmitter } from 'node:stream'
import type {
AnyXoBackupJob,
AnyXoJob,
AnyXoLog,
XapiXoRecord,
XoAuthenticationToken,
XoBackupRepository,
XoConfigBackupArchive,
XoGroup,
XoHost,
XoPool,
XoPoolBackupArchive,
XoProxy,
XoSchedule,
XoServer,
XoTask,
XoUser,
XoVm,
XoVmBackupArchive,
} from './xo.mjs'
import { VatesTask } from './lib/vates-task.mjs'
import {
Xapi,
XapiHostStats,
XapiPoolStats,
XapiStatsGranularity,
XapiVmStats,
XenApiGpuGroupWrapped,
XenApiHostWrapped,
XenApiMessageWrapped,
XenApiNetworkWrapped,
XenApiPbdWrapped,
XenApiPciWrapped,
XenApiPgpuWrapped,
XenApiPifWrapped,
XenApiPoolWrapped,
XenApiSmWrapped,
XenApiSrWrapped,
XenApiVbdWrapped,
XenApiVdiWrapped,
XenApiVgpuTypeWrapped,
XenApiVgpuWrapped,
XenApiVifWrapped,
XenApiVmWrapped,
XenApiVtpmWrapped,
} from './index.mjs'
export type XapiConnection = Xapi & {
status: string
pool?: { uuid: string }
sessionId: string
_url?: { protocol: string; hostname: string; port?: string }
}
type XapiRecordByXapiXoRecord = {
gpuGroup: XenApiGpuGroupWrapped
host: XenApiHostWrapped
message: XenApiMessageWrapped
network: XenApiNetworkWrapped
PBD: XenApiPbdWrapped
PCI: XenApiPciWrapped
PGPU: XenApiPgpuWrapped
PIF: XenApiPifWrapped
pool: XenApiPoolWrapped
SR: XenApiSrWrapped
SM: XenApiSmWrapped
VBD: XenApiVbdWrapped
VDI: XenApiVdiWrapped
'VDI-snapshot': XenApiVdiWrapped
'VDI-unmanaged': XenApiVdiWrapped
vgpu: XenApiVgpuWrapped
vgpuType: XenApiVgpuTypeWrapped
VIF: XenApiVifWrapped
VM: XenApiVmWrapped
'VM-controller': XenApiVmWrapped
'VM-snapshot': XenApiVmWrapped
'VM-template': XenApiVmWrapped
VTPM: XenApiVtpmWrapped
}
export type XoApp = {
config: {
get<T = string>(path: string): T
getOptional(path: string): Record<string, string> | undefined
getOptionalDuration(path: string): number | undefined
getGuiRoutes(): Promise<{
default: {
url: string
path: string
}
v5?: {
url: string
path: string
}
v6?: {
url: string
path: string
}
[key: string]:
| undefined
| {
url: string
path: string
}
}>
}
objects: EventEmitter & {
allIndexes: {
type: {
getEventEmitterByType(type: XapiXoRecord['type']): EventEmitter
}
}
}
tasks: EventEmitter & {
abort(id: XoTask['id'], reason?: string): Promise<void>
clearLogs(): Promise<void>
create: (params: { name: string; objectId?: string; type?: string }) => VatesTask
deleteLog(id: XoTask['id']): Promise<void>
get(id: XoTask['id']): Promise<XoTask>
list(opts?: { filter?: string | ((obj: XoTask) => boolean); limit?: number }): AsyncGenerator<XoTask>
watch(id: XoTask['id'], cb: (task: XoTask) => void): Promise<() => void>
}
apiContext: {
user?: XoUser
permission?: XoUser['permission'] | 'none' | null
}
// methods ------------
addUserToGroup: (userId: XoUser['id'], groupId: XoGroup['id']) => Promise<void>
authenticateUser: (
credentials: { token?: string; username?: string; password?: string },
userData?: { ip?: string },
opts?: { bypassOtp?: boolean; bypassTaskCreation?: boolean }
) => Promise<{ bypassOtp: boolean; expiration: number; user: XoUser }>
/* Throw if no authorization */
checkFeatureAuthorization(featureCode: string): Promise<void>
/* connect a server (XCP-ng/XenServer) */
connectXenServer(id: XoServer['id']): Promise<void>
createAuthenticationToken(opts: {
client?: {
id?: string
[key: string]: unknown
}
description?: string
expiresIn?: string | number
userId: XoUser['id']
}): Promise<XoAuthenticationToken>
createUser(params: { name?: string; password?: string; [key: string]: unknown }): Promise<XoUser>
deleteGroup(id: XoGroup['id']): Promise<void>
deleteUser(id: XoUser['id']): Promise<void>
createGroup(params: { name: string; provider?: string; providerGroup?: string }): Promise<XoGroup>
/* disconnect a server (XCP-ng/XenServer) */
disconnectXenServer(id: XoServer['id']): Promise<void>
getAllGroups(): Promise<XoGroup[]>
getAllProxies(): Promise<XoProxy[]>
getAllJobs<T extends AnyXoBackupJob['type']>(type: T): Promise<Extract<AnyXoBackupJob, { type: T }>[]>
getAllJobs(type?: string): Promise<AnyXoJob[]>
getProxy(id: XoProxy['id']): Promise<XoProxy>
getRemote(id: XoBackupRepository['id']): Promise<XoBackupRepository>
getAllRemotes(): Promise<XoBackupRepository[]>
getAllRemotesInfo(): Promise<
Record<
XoBackupRepository['id'],
{
size?: number
used?: number
available?: number
encryption?: {
algorithm: string
isLegacy: boolean
recommanded: string
}
}
>
>
getAllSchedules(): Promise<XoSchedule[]>
getAllUsers(): Promise<XoUser[]>
getAllXenServers(): Promise<XoServer[]>
getAuthenticationTokensForUser(userId: XoUser['id']): Promise<XoAuthenticationToken[]>
getBackupNgLogs(): Promise<Record<string, AnyXoLog>>
getBackupNgLogs(id: AnyXoLog['id']): Promise<AnyXoLog>
getBackupNgLogsSorted(opts: {
after?: number
before?: number
filter: (log: AnyXoLog) => boolean
limit?: number
}): Promise<AnyXoLog[]>
getGroup(id: XoGroup['id']): Promise<XoGroup>
getHVSupportedVersions: undefined | (() => Promise<{ [key: XoHost['productBrand']]: string }>)
getJob<T extends AnyXoJob>(id: T['id']): Promise<T>
getObject: <T extends XapiXoRecord>(id: T['id'], type?: T['type'] | T['type'][]) => T
getObjectsByType: <T extends XapiXoRecord>(
type: T['type'],
opts?: { filter?: string | ((obj: T) => boolean); limit?: number }
) => Record<T['id'], T> | undefined
getTotalBackupSizeOnRemote(id: XoBackupRepository['id']): Promise<{ onDisk: number }>
getSchedule(id: XoSchedule['id']): Promise<XoSchedule>
getUser: (id: XoUser['id']) => Promise<XoUser>
getXapi(maybeId: XapiXoRecord['id'] | XapiXoRecord): Xapi
getXapiHostStats: (hostId: XoHost['id'], granularity?: XapiStatsGranularity) => Promise<XapiHostStats>
getXapiObject: <T extends XapiXoRecord>(
maybeId: T['id'] | T,
type: T['type'] | T['type'][]
) => XapiRecordByXapiXoRecord[T['type']]
getXapiPoolStats(poolId: XoPool['id'], granularity?: XapiStatsGranularity): Promise<XapiPoolStats>
getXapiVmStats: (vmId: XoVm['id'], granularity?: XapiStatsGranularity) => Promise<XapiVmStats>
getXenServer(id: XoServer['id']): Promise<XoServer>
hasFeatureAuthorization(featureCode: string): Promise<boolean>
hasObject<T extends XapiXoRecord>(id: T['id'], type: T['type']): boolean
listMetadataBackups(backupRepositoryIds: XoBackupRepository['id'][]): Promise<{
xo: Record<XoBackupRepository['id'], XoConfigBackupArchive[]>
pool: Record<XoBackupRepository['id'], Record<XoPool['id'], XoPoolBackupArchive[]>>
}>
listVmBackupsNg(
backupRepositoryIds: XoBackupRepository['id'][],
opts?: { _forceRefresh?: boolean; vmId: XoVm['id'] }
): Promise<Record<XoBackupRepository['id'], Record<XoVm['id'], XoVmBackupArchive[]>>>
/** Allow to add a new server in the DB (XCP-ng/XenServer) */
registerXenServer(
body: Pick<XoServer, 'host' | 'httpProxy' | 'label' | 'username'> & {
allowUnauthorized?: XoServer['allowUnauthorized']
password: string
readOnly?: XoServer['readOnly']
}
): Promise<XoServer>
rollingPoolReboot(pool: XoPool, opts?: { parentTask?: VatesTask }): Promise<void>
rollingPoolUpdate(pool: XoPool, opts?: { rebootVm?: boolean; parentTask?: VatesTask }): Promise<void>
removeUserFromGroup(userId: XoUser['id'], id: XoGroup['id']): Promise<void>
runJob(job: AnyXoJob, schedule: XoSchedule): void
runWithApiContext: (user: XoUser | undefined, fn: () => void) => Promise<unknown>
/** Remove a server from the DB (XCP-ng/XenServer) */
unregisterXenServer(id: XoServer['id']): Promise<void>
updateUser(
id: XoUser['id'],
updates: {
/**
* @deprecated
*/
email?: string
authProviders?: Record<string, string>
name?: string
password?: string
permission?: string
preferences?: Record<string, string>
}
): Promise<void>
updateGroup(
id: XoGroup['id'],
updates: {
name?: string
}
): void
getAllXapis(): Record<string, XapiConnection>
getObjects(opts?: { filter?: Record<string, unknown>; limit?: number }): Record<string, XapiXoRecord>
}

View File

@@ -1,6 +1,7 @@
// Types based on xapi-object-to-xo
import type {
BACKUP_TYPE,
Branded,
DOMAIN_TYPE,
HOST_ALLOWED_OPERATIONS,
@@ -18,8 +19,6 @@ import type {
VM_OPERATIONS,
VM_POWER_STATE,
} from './common.mjs'
import type * as CMType from './lib/complex-matcher.mjs'
import type { XenApiHost, XenApiPool } from './xen-api.mjs'
type BaseXapiXo = {
$pool: XoPool['id']
@@ -134,67 +133,6 @@ export type XoAlarm = Omit<XoMessage, '$object' | 'body'> & {
}
}
// TODO: to be typed when Bastien.N has finished working on the XO task
type BaseXoLog = {
id: Branded<'xo-log'>
infos?: { data: unknown; message: string }[]
[key: string]: unknown
}
export type XoBackupLog = BaseXoLog & {
status: 'success' | 'skipped' | 'interrupted' | 'failure' | 'pending'
message: 'backup'
start: number
end?: number
tasks?: XoTask[]
jobId?: AnyXoBackupJob['id']
}
export type XoRestoreLog = BaseXoLog & {
message: 'restore'
}
export type XoVmBackupArchive = {
id: Branded<'vm-backup-archive'>
type: 'xo-vm-backup'
backupRepository: XoBackupRepository['id']
disks: { id: string; name: string; uuid: XoVdiSnapshot['uuid'] }[]
isImmutable?: boolean
jobId: XoVmBackupJob['id']
mode: XoVmBackupJob['mode']
scheduleId: XoSchedule['id']
size: number
timestamp: number
vm: {
uuid: XoVm['uuid']
name_description: string
name_label: string
tags: XoVm['tags']
}
differencingVhds?: number
dynamicVhds?: number
withMemory: boolean
}
type XoMetadataBackupArchive = {
id: Branded<'metadata-backup-archive'>
backupRepository: XoBackupRepository['id']
jobId: XoVmBackupJob['id']
jobName: XoVmBackupJob['name']
scheduleId: XoSchedule['id']
scheduleName: XoSchedule['name']
timestamp: number
}
export type XoConfigBackupArchive = XoMetadataBackupArchive & {
id: Branded<'config-backup-archive'>
data: string
type: 'xo-config-backup'
}
export type XoPoolBackupArchive = XoMetadataBackupArchive & {
id: Branded<'pool-backup-archive'>
pool: XenApiPool
poolMaster: XenApiHost
type: 'xo-pool-metadata-backup'
}
export type XoBackupRepository = {
benchmarks?: { readRate: number; timestamp: number; writeRate: number }[]
enabled: boolean
@@ -235,7 +173,7 @@ export type XoHost = BaseXapiXo & {
address: string
agentStartTime: null | number
bios_strings: Record<string, string>
bios_string: Record<string, string>
build: string
certificates?: {
fingerprint: string
@@ -244,7 +182,7 @@ export type XoHost = BaseXapiXo & {
chipset_info: {
iommu?: boolean
}
controlDomain?: XoVmController['id']
controlDomain?: XoVm['id']
cpus: {
cores?: number
sockets?: number
@@ -339,19 +277,7 @@ export type XoNetwork = BaseXapiXo & {
}
export type XoPbd = BaseXapiXo & {
attached: boolean
device_config:
| { device: string }
| { location: string }
| { path: string; location: string; legacy_mode: string }
| { provisioning: string; redundancy: string; 'group-name': string }
| { server: string; serverpath: string }
| { type: string; location: string }
| Record<string, string>
host: XoHost['id']
id: Branded<'PBD'>
otherConfig: Record<string, string>
SR: XoSr['id']
type: 'PBD'
}
@@ -392,7 +318,7 @@ export type XoPif = BaseXapiXo & {
attached: boolean
bondMaster?: XoPif['id']
bondSlaves?: XoPif['id'][]
bondSalves?: XoPif['id'][]
carrier: boolean
device: string
deviceName?: string
@@ -425,7 +351,7 @@ export type XoPool = BaseXapiXo & {
}
crashDumpSr?: XoSr['id']
current_operations: Record<string, POOL_ALLOWED_OPERATIONS>
default_SR?: XoSr['id']
defaultSr?: XoSr['id']
HA_enabled: boolean
haSrs: XoSr['id'][]
id: Branded<'pool'>
@@ -439,132 +365,69 @@ export type XoPool = BaseXapiXo & {
tags: string[]
type: 'pool'
vtpmSupported: boolean
xosanPackInstallationTime: number | null
zstdSupported: boolean
}
export type XoProxy = {
id: Branded<'proxy'>
url: string
version?: string
name: string
} & (
| { address?: undefined; vmUuid: XoVm['id'] }
| { address: string; vmUuid?: undefined }
| { address: string; vmUuid: XoVm['id'] }
)
}
type BaseXoJob = {
id: Branded<'job'>
name?: string
}
type XoBackupJobGeneralSettings = {
backupReportTpl?: 'compactMjml' | 'mjml'
reportWhen?: 'always' | 'error' | 'failure' | 'never'
reportRecipients?: string[]
hideSuccessfulItems?: boolean
[key: string]: unknown
}
export type XoVmBackupJobGeneralSettings = XoBackupJobGeneralSettings & {
cbtDestroySnapshotData?: boolean
concurrency?: number
longTermRetention?: {
daily?: { retention: number; settings: Record<string, unknown> }
weekly?: { retention: number; settings: Record<string, unknown> }
monthly?: { retention: number; settings: Record<string, unknown> }
yearly?: { retention: number; settings: Record<string, unknown> }
}
checkpointSnapshot?: boolean
offlineSnapshot?: boolean
maxExportRate?: number
nbdConcurrency?: number
nRetriesVmBackupFailures?: number
preferNbd?: boolean
timezone?: string
mergeBackupsSynchronously?: boolean
offlineBackup?: boolean
timeout?: number
}
export type XoVmBackupJobScheduleSettings = {
exportRetention?: number
healthCheckVmsWithTags?: XoVm['tags']
fullInterval?: number
copyRetention?: number
snapshotRetention?: number
cbtDestroySnapshotData?: boolean
healthCheckSr?: XoSr['id']
[key: string]: unknown
}
export type XoVmBackupJob = BaseXoJob & {
// @TODO: create type for complex matcher
export type XoBackupJob = BaseXoJob & {
compression?: 'native' | 'zstd' | ''
proxy?: XoProxy['id']
mode: 'full' | 'delta'
remotes?: CMType.IdOr<XoBackupRepository['id']>
vms: CMType.IdOr<XoVm['id']> | Record<string, unknown>
srs?: CMType.IdOr<XoSr['id']>
type: 'backup'
name?: string
remotes?: {
id: XoBackupRepository['id'] | { __or: XoBackupRepository['id'][] }
}
vms?: {
id: XoVm['id'] | { __or: XoVm['id'][] } | Record<string, unknown>
}
srs: {
id: XoSr['id'] | { __or: XoSr['id'][] }
}
type: BACKUP_TYPE
settings: {
'': XoVmBackupJobGeneralSettings
[key: XoSchedule['id']]: XoVmBackupJobScheduleSettings | undefined
'': {
cbtDestroySnapshotData?: boolean
concurrency?: number
longTermRetention?: {
daily?: { retention: number; settings: Record<string, unknown> }
weekly?: { retention: number; settings: Record<string, unknown> }
monthly?: { retention: number; settings: Record<string, unknown> }
yearly?: { retention: number; settings: Record<string, unknown> }
}
maxExportRate?: number
nbdConcurrency?: number
nRetriesVmBackupFailures?: number
preferNbd?: boolean
timezone?: string
[key: string]: unknown
}
[key: XoSchedule['id']]: {
exportRetention?: number
healthCheckSr?: XoSr['id']
healthCheckVmsWithTags?: string[]
fullInterval?: number
copyRetention?: number
snapshotRetention?: number
cbtDestroySnapshotData?: boolean
[key: string]: unknown
}
}
}
export type XoMetadataBackupJobGeneralSettings = XoBackupJobGeneralSettings
export type XoMetadataBackupJobScheduleSettings = {
retentionPoolMetadata?: number
retentionXoMetadata?: number
[key: string]: unknown
}
export type XoMetadataBackupJob = BaseXoJob & {
type: 'metadataBackup'
pools?: CMType.IdOr<XoPool['id']>
remotes: CMType.IdOr<XoBackupRepository['id']>
settings: {
''?: XoMetadataBackupJobGeneralSettings
[scheduleId: XoSchedule['id']]: XoMetadataBackupJobScheduleSettings | undefined
}
xoMetadata?: boolean
userId: XoUser['id']
proxy?: XoProxy['id']
}
export type XoMirrorBackupGeneralSettings = XoBackupJobGeneralSettings & {
concurrency?: number
nRetriesVmBackupFailures?: number
mergeBackupsSynchronously?: boolean
timeout?: number
maxExportRate?: number
backupReportTpl?: 'compactMjml'
reportWhen: 'failure'
}
export type XoMirrorBackupScheduleSettings = {
exportRetention?: number
healthCheckVmsWithTags?: XoVm['tags']
healthCheckSr?: XoSr['id']
[key: string]: unknown
}
export type XoMirrorBackupJob = BaseXoJob & {
type: 'mirrorBackup'
mode: 'full' | 'delta'
sourceRemote: XoBackupRepository['id']
remotes: CMType.IdOr<XoBackupRepository['id']>
proxy?: XoProxy['id']
settings: {
'': XoMirrorBackupGeneralSettings
[scheduleId: XoSchedule['id']]: XoMirrorBackupScheduleSettings | undefined
}
}
export type XoJob = BaseXoJob & {
type: 'call'
}
export type XoJob = BaseXoJob & {}
export type XoSchedule = {
cron: string
enabled: boolean
id: Branded<'schedule'>
jobId: AnyXoJob['id']
jobId: (XoJob | XoBackupJob)['id']
name?: string
timezone?: string
}
@@ -593,7 +456,7 @@ export type XoSr = BaseXapiXo & {
VDIs: AnyXoVdi['id'][]
allocationStrategy?: 'thin' | 'thick' | 'unknown'
allocationStrategy: 'thin' | 'thick' | 'unknown'
content_type: string
current_operations: Record<string, STORAGE_OPERATIONS>
id: Branded<'SR'>
@@ -626,46 +489,6 @@ export type XoSm = BaseXapiXo & {
type: 'SM'
}
export type XoTask = {
abortionRequestedAt?: number
data?: Record<string, string>
end?: number
id: Branded<'task'>
infos?: { data: unknown; message: string }[]
progress?: number
properties: {
method?: string
name?: string
objectId?: string
objectType?:
| XapiXoRecord['type']
| 'backup'
| 'backup-archive'
| 'backup-job'
| 'backup-log'
| 'backup-repository'
| 'group'
| 'proxy'
| 'restore'
| 'restore-log'
| 'schedule'
| 'server'
| 'task'
| 'user'
params?: Record<string, unknown>
progress?: number
type?: string
userId?: string
[key: string]: unknown | undefined
}
result: Record<string, unknown>
start: number
status: 'failure' | 'interrupted' | 'pending' | 'success'
tasks?: XoTask[]
updatedAt?: number
warnings?: { data: unknown; message: string }[]
}
export type XoUser = {
authProviders?: Record<string, string>
email: string
@@ -677,19 +500,6 @@ export type XoUser = {
preferences: Record<string, string>
}
export type XoAuthenticationToken = {
client?: {
id: string
[key: string]: unknown
}
created_at?: number
description?: string
user_id: XoUser['id']
expiration: number
last_uses?: Record<string, { timestamp: number }>
id: Branded<'authentication-token'>
}
export type XoVbd = BaseXapiXo & {
attached: boolean
bootable: boolean
@@ -825,7 +635,6 @@ export type XapiXoRecord =
| XoHost
| XoMessage
| XoNetwork
| XoPbd
| XoPci
| XoPgpu
| XoPif
@@ -845,20 +654,7 @@ export type XapiXoRecord =
| XoVtpm
| XoSm
export type NonXapiXoRecord =
| AnyXoBackupArchive
| AnyXoJob
| AnyXoLog
| XoGroup
| XoProxy
| XoGroup
| XoProxy
| XoJob
| XoBackupRepository
| XoSchedule
| XoServer
| XoTask
| XoUser
export type NonXapiXoRecord = XoGroup | XoProxy | XoJob | XoBackupRepository | XoSchedule | XoServer | XoUser
export type XoRecord = XapiXoRecord | NonXapiXoRecord
@@ -866,10 +662,4 @@ export type AnyXoVm = XoVm | XoVmSnapshot | XoVmTemplate | XoVmController
export type AnyXoVdi = XoVdi | XoVdiSnapshot | XoVdiUnmanaged
export type AnyXoJob = XoJob | AnyXoBackupJob
export type AnyXoBackupJob = XoVmBackupJob | XoMetadataBackupJob | XoMirrorBackupJob
export type AnyXoLog = XoBackupLog | XoRestoreLog
export type AnyXoBackupArchive = XoVmBackupArchive | XoConfigBackupArchive | XoPoolBackupArchive
export type AnyXoJob = XoJob | XoBackupJob

View File

@@ -5,8 +5,7 @@
"strict": true,
"module": "ESNext",
"target": "ES2022",
"skipLibCheck": true,
"types": ["node"] // Only use types from Node.js and packages that are explicitly imported
"skipLibCheck": true
},
"include": ["src/**/*"],
"exclude": ["node_modules", "dist"]

View File

@@ -6,10 +6,10 @@
"preferGlobal": true,
"bugs": "https://github.com/vatesfr/xen-orchestra/issues",
"dependencies": {
"@vates/async-each": "^1.0.1",
"@vates/async-each": "^1.0.0",
"@xen-orchestra/async-map": "^0.1.2",
"@xen-orchestra/backups": "^0.68.2",
"@xen-orchestra/fs": "^4.6.6",
"@xen-orchestra/backups": "^0.63.0",
"@xen-orchestra/fs": "^4.6.2",
"filenamify": "^6.0.0",
"getopts": "^2.2.5",
"lodash": "^4.17.15",
@@ -28,7 +28,7 @@
"scripts": {
"postversion": "npm publish --access public"
},
"version": "1.1.7",
"version": "1.1.2",
"license": "AGPL-3.0-or-later",
"author": {
"name": "Vates SAS",

View File

@@ -11,7 +11,6 @@ import pickBy from 'lodash/pickBy.js'
import { defer } from 'golike-defer'
import { NegativeDisk } from '@xen-orchestra/disk-transform'
import { openDiskChain } from './disks/openDiskChain.mjs'
import { resetVmOtherConfig } from './_otherConfig.mjs'
const { debug, info, warn } = createLogger('xo:backups:importVmBackup')
async function resolveUuid(xapi, cache, uuid, type) {
@@ -30,10 +29,10 @@ export class ImportVmBackup {
metadata,
srUuid,
xapi,
settings: { additionalVmTag, newMacAddresses, mapVdisSrs = {}, useDifferentialRestore = false } = {},
settings: { additionnalVmTag, newMacAddresses, mapVdisSrs = {}, useDifferentialRestore = false } = {},
}) {
this._adapter = adapter
this._importIncrementalVmSettings = { additionalVmTag, newMacAddresses, mapVdisSrs, useDifferentialRestore }
this._importIncrementalVmSettings = { additionnalVmTag, newMacAddresses, mapVdisSrs, useDifferentialRestore }
this._metadata = metadata
this._srUuid = srUuid
this._xapi = xapi
@@ -62,11 +61,11 @@ export class ImportVmBackup {
const { mapVdisSrs } = this._importIncrementalVmSettings
const { vbds, vhds, vifs, vm, vmSnapshot, vtpms } = metadata
const disks = {}
const metadataDir = dirname(metadata._filename)
const metdataDir = dirname(metadata._filename)
const vdis = ignoredVdis === undefined ? metadata.vdis : pickBy(metadata.vdis, vdi => !ignoredVdis.has(vdi.uuid))
for (const [vdiRef, vdi] of Object.entries(vdis)) {
const vhdPath = join(metadataDir, vhds[vdiRef])
const vhdPath = join(metdataDir, vhds[vdiRef])
let xapiDisk
try {
@@ -78,7 +77,7 @@ export class ImportVmBackup {
let snapshotCandidate, backupCandidate
if (xapiDisk !== undefined) {
debug('found disks, will search its snapshots', { snapshots: xapiDisk.snapshots })
debug('found disks, wlll search its snapshots', { snapshots: xapiDisk.snapshots })
for (const snapshotRef of xapiDisk.snapshots) {
const snapshot = await this._xapi.getRecord('VDI', snapshotRef)
@@ -97,7 +96,7 @@ export class ImportVmBackup {
// have a corresponding backup more recent than metadata ?
const pathToSnapshotData = await this.#getPathOfVdiSnapshot(snapshot.uuid)
if (pathToSnapshotData === undefined) {
debug('no backup linked to this snapshot')
debug('no backup linked to this snaphot')
continue
}
if (snapshot.$SR.uuid !== (mapVdisSrs[vdi.$snapshot_of$uuid] ?? this._srUuid)) {
@@ -113,7 +112,7 @@ export class ImportVmBackup {
}
let disk
const backupWithSnapshotPath = join(metadataDir, backupCandidate ?? '')
const backupWithSnapshotPath = join(metdataDir, backupCandidate ?? '')
if (vhdPath === backupWithSnapshotPath) {
// all the data are already on the host
debug('direct reuse of a snapshot')
@@ -195,7 +194,7 @@ export class ImportVmBackup {
}
async #decorateIncrementalVmMetadata() {
const { additionalVmTag, mapVdisSrs, useDifferentialRestore } = this._importIncrementalVmSettings
const { additionnalVmTag, mapVdisSrs, useDifferentialRestore } = this._importIncrementalVmSettings
const ignoredVdis = new Set(
Object.entries(mapVdisSrs)
@@ -212,8 +211,8 @@ export class ImportVmBackup {
const cache = new Map()
const mapVdisSrRefs = {}
if (additionalVmTag !== undefined) {
backup.vm.tags.push(additionalVmTag)
if (additionnalVmTag !== undefined) {
backup.vm.tags.push(additionnalVmTag)
}
for (const [vdiUuid, srUuid] of Object.entries(mapVdisSrs)) {
mapVdisSrRefs[vdiUuid] = await resolveUuid(xapi, cache, srUuid, 'SR')
@@ -271,7 +270,6 @@ export class ImportVmBackup {
`${metadata.vm.name_label} (${formatFilenameDate(metadata.timestamp)})`
),
xapi.call('VM.set_name_description', vmRef, desc),
resetVmOtherConfig(xapi, vmRef),
])
return {

View File

@@ -18,7 +18,7 @@ import groupBy from 'lodash/groupBy.js'
import pDefer from 'promise-toolbox/defer'
import pickBy from 'lodash/pickBy.js'
import reduce from 'lodash/reduce.js'
import * as tar from 'tar'
import tar from 'tar'
import zlib from 'zlib'
import { BACKUP_DIR } from './_getVmBackupDir.mjs'
@@ -27,11 +27,11 @@ import { formatFilenameDate } from './_filenameDate.mjs'
import { getTmpDir } from './_getTmpDir.mjs'
import { isMetadataFile } from './_backupType.mjs'
import { isValidXva } from './_isValidXva.mjs'
import { listPartitions, LVM_PARTITION_TYPE_MBR, LVM_PARTITION_TYPE_GPT } from './_listPartitions.mjs'
import { listPartitions, LVM_PARTITION_TYPE } from './_listPartitions.mjs'
import { lvs, pvs } from './_lvm.mjs'
import { watchStreamSize } from './_watchStreamSize.mjs'
import { RemoteVhdDisk } from './disks/RemoteVhdDisk.mjs'
import { RemoteVhd } from './disks/RemoteVhd.mjs'
import { openDiskChain } from './disks/openDiskChain.mjs'
import { toVhdStream, writeToVhdDirectory } from 'vhd-lib/disk-consumer/index.mjs'
import { ReadAhead } from '@xen-orchestra/disk-transform'
@@ -40,11 +40,11 @@ export const DIR_XO_CONFIG_BACKUPS = 'xo-config-backups'
export const DIR_XO_POOL_METADATA_BACKUPS = 'xo-pool-metadata-backups'
const IMMUTABILITY_METADATA_FILENAME = '/immutability.json'
const IMMUTABILTY_METADATA_FILENAME = '/immutability.json'
const { debug, warn } = createLogger('xo:backups:RemoteAdapter')
export const compareTimestamp = (a, b) => a.timestamp - b.timestamp
const compareTimestamp = (a, b) => a.timestamp - b.timestamp
const noop = Function.prototype
@@ -312,8 +312,8 @@ export class RemoteAdapter {
}
async deleteVmBackups(files) {
const metadata = await asyncMap(files, file => this.readVmBackupMetadata(file))
const { delta, full, ...others } = groupBy(metadata, 'mode')
const metadatas = await asyncMap(files, file => this.readVmBackupMetadata(file))
const { delta, full, ...others } = groupBy(metadatas, 'mode')
const unsupportedModes = Object.keys(others)
if (unsupportedModes.length !== 0) {
@@ -498,7 +498,7 @@ export class RemoteAdapter {
const results = []
await asyncMapSettled(partitions, partition =>
partition.type === LVM_PARTITION_TYPE_MBR || partition.type === LVM_PARTITION_TYPE_GPT
partition.type === LVM_PARTITION_TYPE
? this._listLvmLogicalVolumes(devicePath, partition, results)
: results.push(partition)
)
@@ -575,7 +575,7 @@ export class RemoteAdapter {
}
}
async #getCacheableDataListVmBackups(dir) {
async #getCachabledDataListVmBackups(dir) {
debug('generating cache', { path: dir })
const handler = this._handler
@@ -613,11 +613,6 @@ export class RemoteAdapter {
// if cache is missing or broken => regenerate it and return
async _readCacheListVmBackups(vmUuid) {
// immutable remote can't use any caching
// since the cache file may be non modifiable
if (this._handler.isImmutable()) {
return this.#getCacheableDataListVmBackups(`${BACKUP_DIR}/${vmUuid}`)
}
const path = this.#getVmBackupsCache(vmUuid)
const cache = await this._readCache(path)
@@ -627,7 +622,7 @@ export class RemoteAdapter {
}
// nothing cached, or cache unreadable => regenerate it
const backups = await this.#getCacheableDataListVmBackups(`${BACKUP_DIR}/${vmUuid}`)
const backups = await this.#getCachabledDataListVmBackups(`${BACKUP_DIR}/${vmUuid}`)
if (backups === undefined) {
return
}
@@ -714,7 +709,7 @@ export class RemoteAdapter {
})
} else {
const stream = await toVhdStream(disk)
await this.outputStream(path, stream, { validator, checksum: false })
await this.outputStream(path, stream, { validator })
await validator(path)
}
}
@@ -744,7 +739,7 @@ export class RemoteAdapter {
if (useChain) {
disk = await openDiskChain({ handler, path })
} else {
disk = new RemoteVhdDisk({ handler, path })
disk = new RemoteVhd({ handler, path })
await disk.init()
}
disk = new ReadAhead(disk)
@@ -784,7 +779,7 @@ export class RemoteAdapter {
// if the remote is immutable, check if this metadata is also immutable
try {
// this file is not encrypted
await this._handler._readFile(IMMUTABILITY_METADATA_FILENAME)
await this._handler._readFile(IMMUTABILTY_METADATA_FILENAME)
remoteIsImmutable = true
} catch (error) {
if (error.code !== 'ENOENT') {

View File

@@ -1,5 +1,4 @@
export const isMetadataFile = filename => filename.endsWith('.json')
export const isVhdFile = filename => filename.endsWith('.vhd')
export const isVhdSumFile = filename => filename.endsWith('.vhd.checksum')
export const isXvaFile = filename => filename.endsWith('.xva')
export const isXvaSumFile = filename => filename.endsWith('.xva.checksum')

View File

@@ -83,12 +83,12 @@ test('It remove broken vhd', async () => {
await handler.writeFile(`${basePath}/notReallyAVhd.vhd`, 'I AM NOT A VHD')
assert.equal((await handler.list(basePath)).length, 1)
let logged = ''
let loggued = ''
const logInfo = message => {
logged += message
loggued += message
}
await adapter.cleanVm(rootPath, { remove: false, logInfo, logWarn: logInfo, lock: false })
assert.equal(logged, `VHD check error`)
assert.equal(loggued, `VHD check error`)
// not removed
assert.deepEqual(await handler.list(basePath), ['notReallyAVhd.vhd'])
// really remove it
@@ -98,7 +98,7 @@ test('It remove broken vhd', async () => {
test('it remove vhd with missing or multiple ancestors', async () => {
// one with a broken parent, should be deleted
await generateVhd(`${basePath}/abandoned.vhd`, {
await generateVhd(`${basePath}/abandonned.vhd`, {
header: {
parentUnicodeName: 'gone.vhd',
parentUuid: uniqueIdBuffer(),
@@ -118,18 +118,18 @@ test('it remove vhd with missing or multiple ancestors', async () => {
`metadata.json`,
JSON.stringify({
mode: 'delta',
vhds: [`${basePath}/child.vhd`, `${basePath}/abandoned.vhd`],
vhds: [`${basePath}/child.vhd`, `${basePath}/abandonned.vhd`],
}),
{ flags: 'w' }
)
// clean
let logged = ''
let loggued = ''
const logInfo = message => {
logged += message + '\n'
loggued += message + '\n'
}
await adapter.cleanVm(rootPath, { remove: true, logInfo, logWarn: logInfo, lock: false })
const deletedOrphanVhd = logged.match(/deleting orphan VHD/g) || []
const deletedOrphanVhd = loggued.match(/deleting orphan VHD/g) || []
assert.equal(deletedOrphanVhd.length, 1) // only one vhd should have been deleted
// we don't test the file on disk, since they will all be marker as unused and deleted without a metadata.json file
@@ -144,12 +144,12 @@ test('it remove backup meta data referencing a missing vhd in delta backup', asy
vhds: [
`${relativePath}/orphan.vhd`,
`${relativePath}/child.vhd`,
// abandoned.json is not here
// abandonned.json is not here
],
})
)
await generateVhd(`${basePath}/abandoned.vhd`)
await generateVhd(`${basePath}/abandonned.vhd`)
// one orphan, which is a full vhd, no parent
const orphan = await generateVhd(`${basePath}/orphan.vhd`)
@@ -162,12 +162,12 @@ test('it remove backup meta data referencing a missing vhd in delta backup', asy
},
})
let logged = ''
let loggued = ''
const logInfo = message => {
logged += message + '\n'
loggued += message + '\n'
}
await adapter.cleanVm(rootPath, { remove: true, logInfo, logWarn: logInfo, lock: false })
let matched = logged.match(/deleting unused VHD/g) || []
let matched = loggued.match(/deleting unused VHD/g) || []
assert.equal(matched.length, 1) // only one vhd should have been deleted
// a missing vhd cause clean to remove all vhds
@@ -179,14 +179,14 @@ test('it remove backup meta data referencing a missing vhd in delta backup', asy
`deleted.vhd`, // in metadata but not in vhds
`orphan.vhd`,
`child.vhd`,
// abandoned.vhd is not here anymore
// abandonned.vhd is not here anymore
],
}),
{ flags: 'w' }
)
logged = ''
loggued = ''
await adapter.cleanVm(rootPath, { remove: true, logInfo, logWarn: () => {}, lock: false })
matched = logged.match(/deleting unused VHD/g) || []
matched = loggued.match(/deleting unused VHD/g) || []
assert.equal(matched.length, 2) // all vhds (orphan and child ) should have been deleted
})
@@ -221,21 +221,21 @@ test('it merges delta of non destroyed chain', async () => {
},
})
let logged = []
let loggued = []
const logInfo = message => {
logged.push(message)
loggued.push(message)
}
await adapter.cleanVm(rootPath, { remove: true, logInfo, logWarn: logInfo, lock: false })
assert.equal(logged[0], `unexpected number of entries in backup cache`)
assert.equal(loggued[0], `unexpected number of entries in backup cache`)
logged = []
loggued = []
await adapter.cleanVm(rootPath, { remove: true, merge: true, logInfo, logWarn: () => {}, lock: false })
const [merging] = logged
const [merging] = loggued
assert.equal(merging, `merging VHD chain`)
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, 104448)
assert.equal(metadata.size, 104960)
// 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
@@ -311,7 +311,7 @@ describe('tests multiple combination ', { concurrency: 1 }, () => {
// a vhd non referenced in metadata
await generateVhd(`${basePath}/nonreference.vhd`, { useAlias, mode: vhdMode })
// an abandoned delta vhd without its parent
await generateVhd(`${basePath}/abandoned.vhd`, {
await generateVhd(`${basePath}/abandonned.vhd`, {
useAlias,
mode: vhdMode,
header: {
@@ -402,12 +402,13 @@ describe('tests multiple combination ', { concurrency: 1 }, () => {
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, 4404224)
assert.deepEqual(metadata.size, vhdMode === 'file' ? 6502400 : 6501888)
// broken vhd, non referenced, abandoned should be deleted ( alias and data)
// ancestor and child should be merged
// grand child and clean vhd should not have changed
const survivors = await handler.list(basePath)
// console.log(survivors)
if (useAlias) {
const dataSurvivors = await handler.list(basePath + '/data')
// the goal of the alias : do not move a full folder

View File

@@ -4,11 +4,9 @@ import { asyncMap } from '@xen-orchestra/async-map'
import { Constants, openVhd, VhdAbstract, VhdFile } from 'vhd-lib'
import { isVhdAlias, resolveVhdAlias } from 'vhd-lib/aliases.js'
import { basename, dirname, resolve } from 'node:path'
import { isMetadataFile, isVhdFile, isVhdSumFile, isXvaFile, isXvaSumFile } from './_backupType.mjs'
import { isMetadataFile, isVhdFile, isXvaFile, isXvaSumFile } from './_backupType.mjs'
import { limitConcurrency } from 'limit-concurrency-decorator'
import { RemoteVhdDisk } from './disks/RemoteVhdDisk.mjs'
import { RemoteVhdDiskChain } from './disks/RemoteVhdDiskChain.mjs'
import { MergeRemoteDisk } from './disks/MergeRemoteDisk.mjs'
import { mergeVhdChain } from 'vhd-lib/merge.js'
import { Task } from './Task.mjs'
import { Disposable } from 'promise-toolbox'
@@ -53,15 +51,7 @@ async function _mergeVhdChain(handler, chain, { logInfo, remove, mergeBlockConcu
}
}, 10e3)
try {
const parentDisk = new RemoteVhdDisk({ handler, path: chain.shift() })
const childDisks = []
for (const path of chain) {
childDisks.push(new RemoteVhdDisk({ handler, path }))
}
const childDiskChain = new RemoteVhdDiskChain({ disks: childDisks })
const mergeRemoteDisk = new MergeRemoteDisk(handler, {
return await mergeVhdChain(handler, chain, {
logInfo,
mergeBlockConcurrency,
onProgress({ done: d, total: t }) {
@@ -70,14 +60,6 @@ async function _mergeVhdChain(handler, chain, { logInfo, remove, mergeBlockConcu
},
removeUnused: remove,
})
const isResumingMerge = await mergeRemoteDisk.isResuming(parentDisk)
await parentDisk.init({ force: isResumingMerge })
await childDiskChain.init({ force: isResumingMerge })
const result = await mergeRemoteDisk.merge(parentDisk, childDiskChain)
return result
} finally {
clearInterval(handle)
}
@@ -86,12 +68,10 @@ async function _mergeVhdChain(handler, chain, { logInfo, remove, mergeBlockConcu
const noop = Function.prototype
const INTERRUPTED_VHDS_REG = /^\.(.+)\.merge.json$/
const listVhds = async (handler, vmDir, logWarn) => {
const vhds = new Set()
const aliases = {}
const interruptedVhds = new Map()
const checksums = new Set()
await asyncMap(
await handler.list(`${vmDir}/vdis`, {
@@ -105,15 +85,11 @@ const listVhds = async (handler, vmDir, logWarn) => {
}),
async vdiDir => {
const list = await handler.list(vdiDir, {
filter: file => isVhdFile(file) || INTERRUPTED_VHDS_REG.test(file) || isVhdSumFile(file),
filter: file => isVhdFile(file) || INTERRUPTED_VHDS_REG.test(file),
})
aliases[vdiDir] = list.filter(vhd => isVhdAlias(vhd)).map(file => `${vdiDir}/${file}`)
await asyncMap(list, async file => {
if (isVhdSumFile(file)) {
checksums.add(`${vdiDir}/${file}`)
return
}
const res = INTERRUPTED_VHDS_REG.exec(file)
if (res === null) {
vhds.add(`${vdiDir}/${file}`)
@@ -135,7 +111,7 @@ const listVhds = async (handler, vmDir, logWarn) => {
)
)
return { vhds, interruptedVhds, aliases, checksums }
return { vhds, interruptedVhds, aliases }
}
export async function checkAliases(
@@ -252,16 +228,7 @@ export async function cleanVm(
const vhdParents = { __proto__: null }
const vhdChildren = { __proto__: null }
const { vhds, interruptedVhds, aliases, checksums } = await listVhds(handler, vmDir, logWarn)
// from 5.110 to 5.113 we computed checksum for vhd file
// but never used nor removed them
await asyncMap(checksums, async path => {
if (remove) {
logInfo('deleting checksum file ', { path })
return handler.unlink(path)
}
})
const { vhds, interruptedVhds, aliases } = await listVhds(handler, vmDir, logWarn)
// remove broken VHDs
await asyncMap(vhds, async path => {
@@ -539,14 +506,14 @@ export async function cleanVm(
const metadataWithMergedVhd = {}
const doMerge = async () => {
await asyncMap(toMerge, async chain => {
const { finalDiskSize } = await limitedMergeVhdChain(handler, chain, {
const { finalVhdSize } = await limitedMergeVhdChain(handler, chain, {
logInfo,
logWarn,
remove,
mergeBlockConcurrency,
})
const metadataPath = vhdsToJSons[chain[chain.length - 1]] // all the chain should have the same metadata file
metadataWithMergedVhd[metadataPath] = (metadataWithMergedVhd[metadataPath] ?? 0) + finalDiskSize
metadataWithMergedVhd[metadataPath] = (metadataWithMergedVhd[metadataPath] ?? 0) + finalVhdSize
})
}

View File

@@ -1,58 +1,5 @@
// @ts-check
import moment from 'moment-timezone'
import assert from 'node:assert'
/**
* @typedef {import('moment-timezone').Moment} Moment
*/
/**
* @typedef {Object} LTRSettings
* @property {number} [firstHourOfTheDay] - First hour of the day (for daily retention)
* @property {number} [firstDayOfWeek] - First day of the week (for weekly retention)
* @property {number} [firstDayOfMonth] - First day of the month (for monthly retention)
* @property {number} [firstDayOfYear] - First day of the year (for yearly retention)
*/
/**
* @typedef {Object} LTRConfig
* @property {number} retention - Number of time buckets to retain
* @property {LTRSettings} [settings] - Optional settings for the retention period
*/
/**
* @typedef {Object} LongTermRetention
* @property {LTRConfig} [daily] - Daily retention configuration
* @property {LTRConfig} [weekly] - Weekly retention configuration
* @property {LTRConfig} [monthly] - Monthly retention configuration
* @property {LTRConfig} [yearly] - Yearly retention configuration
*/
/**
* @typedef {Object} Entry
* @property {number | undefined} timestamp - Unix timestamp of the entry
* @property {string} id
* @property {*} [key] - Any other properties
*/
/**
* @typedef {Object} DateBucket
* @property {number} remaining - Number of remaining buckets to fill
* @property {string|null} lastMatchingBucket - Last bucket key that was matched
* @property {(date: Moment) => string} formatter - Function to format date into bucket key
* @property {Object.<string, Entry>} entries - Map of bucket keys to entries
*/
/**
* @typedef {Object} LTRDefinition
* @property {(options: {firstHourOfTheDay?: number, firstDayOfWeek?: number, firstDayOfMonth?: number, firstDayOfYear?: number, dateCreator: (date: Moment) => Moment}) => (date: Moment) => string} makeDateFormatter
* @property {string} [ancestor] - Name of the parent retention period
*/
/**
* Creates a function that converts dates to moment objects in a specific timezone
* @param {string|undefined} timezone - IANA timezone string (e.g., 'America/New_York')
* @returns {(date: Moment | number) => Moment} Function that creates timezoned moment objects
*/
function instantiateTimezonedDateCreator(timezone) {
return date => {
@@ -62,12 +9,9 @@ function instantiateTimezonedDateCreator(timezone) {
}
}
/**
* @type {Object.<string, LTRDefinition>}
*/
const LTR_DEFINITIONS = {
daily: {
makeDateFormatter: ({ firstHourOfTheDay = 0, dateCreator }) => {
makeDateFormatter: ({ firstHourOfTheDay = 0, dateCreator } = {}) => {
return date => {
const copy = dateCreator(date)
copy.hour(copy.hour() - firstHourOfTheDay)
@@ -76,11 +20,11 @@ const LTR_DEFINITIONS = {
},
},
weekly: {
makeDateFormatter: ({ firstDayOfWeek = 0 /* relative to timezone week start */, dateCreator }) => {
makeDateFormatter: ({ firstDayOfWeek = 0 /* relative to timezone week start */, dateCreator } = {}) => {
return date => {
const copy = dateCreator(date)
copy.date(copy.date() - firstDayOfWeek)
copy.date(date.date() - firstDayOfWeek)
// warning, the year in term of week may different from YYYY
// since the computation of the first week of a year is timezone dependent
return copy.format('gggg-ww')
@@ -89,7 +33,7 @@ const LTR_DEFINITIONS = {
ancestor: 'daily',
},
monthly: {
makeDateFormatter: ({ firstDayOfMonth = 0, dateCreator }) => {
makeDateFormatter: ({ firstDayOfMonth = 0, dateCreator } = {}) => {
return date => {
const copy = dateCreator(date)
copy.date(copy.date() - firstDayOfMonth)
@@ -99,7 +43,7 @@ const LTR_DEFINITIONS = {
ancestor: 'weekly',
},
yearly: {
makeDateFormatter: ({ firstDayOfYear = 0, dateCreator }) => {
makeDateFormatter: ({ firstDayOfYear = 0, dateCreator } = {}) => {
return date => {
const copy = dateCreator(date)
copy.date(copy.date() - firstDayOfYear)
@@ -109,23 +53,27 @@ const LTR_DEFINITIONS = {
ancestor: 'monthly',
},
}
/**
* Groups entries into date buckets based on long-term retention configuration
* @template {Entry} T
* @param {Array<T>} entries - Array of entries sorted in descending order by timestamp
* @param {LongTermRetention} longTermRetention - Configuration for retention periods
* @param {string | undefined} timezone - IANA timezone string
* @returns {Object.<string, DateBucket>} Map of retention period names to their date buckets
*/
export function getLtrEntries(entries, longTermRetention, timezone) {
/**
* @type {Object.<string, DateBucket>}
*/
// returns all entries but the last retention-th
/**
* return the entries too old to be kept
* if multiple entries are i the same time bucket : keep only the most recent one
* if an entry is valid in any of the bucket OR the minRetentionCount : keep it
* if a bucket is completely empty : it does not count as one, thus it may extend the retention
* @returns Array<Backup>
*/
export function getOldEntries(minRetentionCount, entries, { longTermRetention = {}, timezone } = {}) {
assert.strictEqual(
typeof minRetentionCount,
'number',
`minRetentionCount must be a number, got ${JSON.stringify(minRetentionCount)}`
)
assert.strictEqual(
minRetentionCount >= 0,
true,
`minRetentionCount must be a positive number, got ${JSON.stringify(minRetentionCount)}`
)
const dateBuckets = {}
if (!longTermRetention || Object.keys(longTermRetention).length === 0) {
return {}
}
const dateCreator = instantiateTimezonedDateCreator(timezone)
// only check buckets that have a retention set
for (const [duration, { retention, settings }] of Object.entries(longTermRetention)) {
@@ -133,7 +81,7 @@ export function getLtrEntries(entries, longTermRetention, timezone) {
assert.notStrictEqual(
timezone,
undefined,
`timezone must defined for ltr, got ${JSON.stringify({ longTermRetention, timezone })}`
`timezone must defined for ltr, got ${JSON.stringify({ minRetentionCount, longTermRetention, timezone })}`
)
assert.strictEqual(
typeof retention,
@@ -149,106 +97,40 @@ export function getLtrEntries(entries, longTermRetention, timezone) {
remaining: retention,
lastMatchingBucket: null,
formatter: LTR_DEFINITIONS[duration].makeDateFormatter({ ...settings, dateCreator }),
entries: {}, // bucket => entry id
}
}
const nb = entries.length
let previousTimestamp = -1
const oldEntries = []
for (let i = nb - 1; i >= 0; i--) {
const entry = entries[i]
// force it so the compiler is sure we have a timestamp
if (entry.timestamp === undefined) {
assert.notStrictEqual(
entry.timestamp,
undefined,
`Can't compute long term retention if entries don't have a timestamp`
)
continue
}
// we go through the entries from the last (most recent) to the first (oldest)
assert.ok(
previousTimestamp === -1 || entry.timestamp < previousTimestamp,
`entries must be sorted in desc order ${new Date(entry.timestamp)} , previous : > ${new Date(previousTimestamp)} `
)
previousTimestamp = entry.timestamp
const entryDate = dateCreator(entry.timestamp)
let shouldBeKept = false
for (const [duration, { remaining, lastMatchingBucket, formatter }] of Object.entries(dateBuckets)) {
if (remaining === 0) {
continue
}
const bucket = formatter(entryDate)
if (lastMatchingBucket !== bucket) {
if (remaining === 0) {
continue
if (lastMatchingBucket !== null) {
assert.strictEqual(
lastMatchingBucket > bucket,
true,
`entries must be sorted in asc order ${lastMatchingBucket} ${bucket}`
)
}
dateBuckets[duration].lastMatchingBucket = bucket
shouldBeKept = true
dateBuckets[duration].remaining -= 1
}
dateBuckets[duration].entries[bucket] = entry
}
}
return dateBuckets
}
/**
* return the status of an entry
* @param {Array<Entry>} entries
* @param {Entry} entry
* @param {LongTermRetention} longTermRetention - Configuration for retention periods
* @param {string | undefined} timezone - IANA timezone string
* @returns {Array<{duration: string, dateBucket:string}>}
*/
export function getEntryStatus(entries, entry, longTermRetention, timezone) {
const dateBuckets = getLtrEntries(entries, longTermRetention, timezone)
const entryBuckets = []
for (const [duration, { entries }] of Object.entries(dateBuckets)) {
for (const [dateBucket, bucketEntry] of Object.entries(entries)) {
if (entry.id === bucketEntry.id) {
entryBuckets.push({ duration, dateBucket })
dateBuckets[duration].lastMatchingBucket = bucket
}
}
}
return entryBuckets
}
/**
* return the entries too old to be kept
* if multiple entries are in the same time bucket: keep only the oldest one
* if an entry is valid in any of the bucket OR the minRetentionCount: keep it
* if a bucket is completely empty: it does not count as one, thus it may extend the retention
* if an entry is within the most recents minRetentionCount entries : keep it
*
* @param {number} minRetentionCount - Minimum number of most recent entries to always keep
* @param {Array<Entry>} entries - Array of entries sorted in descending order by timestamp
* @param {Object} options - Additional options
* @param {LongTermRetention} [options.longTermRetention={}] - Configuration for retention periods
* @param {string | undefined} [options.timezone] - IANA timezone string
* @returns {Array<Entry>} Array of entries that can be removed
*/
export function getOldEntries(minRetentionCount, entries, { longTermRetention = {}, timezone } = {}) {
assert.strictEqual(
typeof minRetentionCount,
'number',
`minRetentionCount must be a number, got ${JSON.stringify(minRetentionCount)}`
)
assert.ok(
minRetentionCount >= 0,
`minRetentionCount must be a positive number, got ${JSON.stringify(minRetentionCount)}`
)
const dateBuckets = getLtrEntries(entries, longTermRetention, timezone)
const kept = new Set(entries.filter((_, index) => index >= entries.length - minRetentionCount))
/**
* @type {Set<Entry>}
*/
for (const { entries } of Object.values(dateBuckets)) {
for (const entry of Object.values(entries)) {
kept.add(entry)
if (i >= nb - minRetentionCount) {
shouldBeKept = true
}
if (!shouldBeKept) {
oldEntries.push(entry)
}
}
// ensure order is the same as the source
const oldEntries = entries.filter((entry, index) => {
return !kept.has(entry)
})
return oldEntries
// we expect the entries to be in the right order
return oldEntries.reverse()
}

View File

@@ -10,28 +10,24 @@ describe('_getOldEntries() should succeed', () => {
1,
[
{ timestamp: 1, id: 1 },
{ timestamp: 2, id: 2 },
{ timestamp: 3, id: 3 },
{ timestamp: 3, id: 2 },
{ timestamp: 2, id: 3 },
],
],
expectedIds: [1, 2],
testLabel: 'should handle number based retention ',
},
{
args: [3, [{ id: 1 }, 4, new Date(), 'whatever']],
expectedIds: [1],
testLabel: 'should handle number based retention without timestamp ',
},
{
args: [
0,
[
{ timestamp: +new Date('2024-09-01 00:00:00'), id: 1 }, // too old
{ timestamp: +new Date('2024-09-01 00:01:00'), id: 2 }, // too old
{ timestamp: +new Date('2024-09-02 00:09:00'), id: 3 }, // oldest in same day
{ timestamp: +new Date('2024-09-01 00:01:00'), id: 1 }, // too old
{ timestamp: +new Date('2024-09-01 00:00:00'), id: 2 }, // too old
{ timestamp: +new Date('2024-09-02 00:09:00'), id: 3 }, // too old in same day
{ timestamp: +new Date('2024-09-02 00:10:00'), id: 4 },
{ timestamp: +new Date('2024-09-03 00:09:00'), id: 5 },
{ timestamp: +new Date('2024-09-04 00:09:00'), id: 6 }, // oldest in same day
{ timestamp: +new Date('2024-09-04 00:09:00'), id: 6 }, // too old in same day
{ timestamp: +new Date('2024-09-04 00:10:00'), id: 7 },
],
{
@@ -41,22 +37,22 @@ describe('_getOldEntries() should succeed', () => {
timezone: 'Europe/Paris',
},
],
expectedIds: [1, 2, 4, 7],
expectedIds: [1, 2, 3, 6],
testLabel: 'should handle day based retention ',
},
{
args: [
0,
[
{ timestamp: +new Date('2024-08-30 00:01:00'), id: 1 }, // week n-3 too old
{ timestamp: +new Date('2024-08-31 00:00:00'), id: 2 }, // week n-3 too old
{ timestamp: +new Date('2024-09-03 00:09:00'), id: 3 }, // week n-2, oldest
{ timestamp: +new Date('2024-09-01 00:01:00'), id: 1 }, // week n-3 too old
{ timestamp: +new Date('2024-09-02 00:00:00'), id: 2 }, // week n-3 too old
{ timestamp: +new Date('2024-09-03 00:09:00'), id: 3 }, // week n-2
{ timestamp: +new Date('2024-09-04 00:09:00'), id: 4 }, // week n-2
{ timestamp: +new Date('2024-09-05 00:09:00'), id: 5 }, // week n-2
{ timestamp: +new Date('2024-09-06 00:09:00'), id: 6 }, // week n-2
{ timestamp: +new Date('2024-09-07 00:09:00'), id: 7 }, // week n-2
{ timestamp: +new Date('2024-09-15 00:09:00'), id: 8 }, // week n-1, oldest
{ timestamp: +new Date('2024-09-21 00:09:00'), id: 9 }, // week n-1 most recent
{ timestamp: +new Date('2024-09-07 00:09:00'), id: 7 }, // week n-2, most recent kept
{ timestamp: +new Date('2024-09-09 00:09:00'), id: 8 }, // week n-1, too old
{ timestamp: +new Date('2024-09-15 00:09:00'), id: 9 }, // week n-1 kept
{ timestamp: +new Date('2024-09-22 00:09:00'), id: 10 }, // week n kept
],
{
@@ -66,7 +62,7 @@ describe('_getOldEntries() should succeed', () => {
timezone: 'Europe/Paris',
},
],
expectedIds: [1, 2, 4, 5, 6, 7, 9],
expectedIds: [1, 2, 3, 4, 5, 6, 8],
testLabel: 'should handle week based retention ',
},
{
@@ -89,26 +85,26 @@ describe('_getOldEntries() should succeed', () => {
timezone: 'Europe/Paris',
},
],
expectedIds: [1, 4, 5, 7, 8],
expectedIds: [1, 3, 4, 6, 7],
testLabel: 'should handle month based retention',
},
{
args: [
2,
0,
[
{ timestamp: +new Date('2023-05-18 00:09:00'), id: 1 }, //
{ timestamp: +new Date('2024-06-15 00:09:00'), id: 2 }, // year n -1
{ timestamp: +new Date('2024-07-04 00:09:00'), id: 3 }, //
{ timestamp: +new Date('2024-08-12 00:09:00'), id: 4 }, //
{ timestamp: +new Date('2024-09-05 00:09:00'), id: 5 }, //
{ timestamp: +new Date('2024-10-02 00:09:00'), id: 6 }, // month n-4
{ timestamp: +new Date('2024-11-01 00:09:00'), id: 7 }, // month n-3
{ timestamp: +new Date('2024-12-17 00:09:00'), id: 8 }, // week n-3
{ timestamp: +new Date('2024-12-24 00:09:00'), id: 9 }, // week n-2, month n-2,
{ timestamp: +new Date('2025-01-01 00:09:00'), id: 10 }, // week n-1, year n
{ timestamp: +new Date('2025-01-02 00:10:00'), id: 11 }, // day n-1, month n-1,
{ timestamp: +new Date('2025-12-31 00:09:00'), id: 12 }, // day n , week n , month n
{ timestamp: +new Date('2025-12-31 10:09:00'), id: 13 }, // min retention
{ timestamp: +new Date('2023-05-18 00:09:00'), id: 1 }, // too old
{ timestamp: +new Date('2024-06-15 00:09:00'), id: 2 }, // too old in same year
{ timestamp: +new Date('2024-07-04 00:09:00'), id: 3 }, // too old
{ timestamp: +new Date('2024-08-12 00:09:00'), id: 4 }, // too old
{ timestamp: +new Date('2024-09-05 00:09:00'), id: 5 }, // too old
{ timestamp: +new Date('2024-10-02 00:09:00'), id: 6 }, // new month,
{ timestamp: +new Date('2024-11-01 00:09:00'), id: 7 }, // new month , week reached retention
{ timestamp: +new Date('2024-12-17 00:09:00'), id: 8 }, // new week
{ timestamp: +new Date('2024-12-24 00:09:00'), id: 9 }, // new week/month / year daily reach retention
{ timestamp: +new Date('2025-01-01 00:09:00'), id: 10 }, // same day/week/month/year
{ timestamp: +new Date('2025-01-01 00:10:00'), id: 11 }, // new day / week / month
{ timestamp: +new Date('2025-12-31 00:09:00'), id: 12 }, // same day/week/month/year
{ timestamp: +new Date('2025-12-31 00:09:00'), id: 13 }, // new month /year
],
{
longTermRetention: {
@@ -120,18 +116,18 @@ describe('_getOldEntries() should succeed', () => {
timezone: 'Europe/Paris', // use a time zone here because week definition is timezone bound
},
],
expectedIds: [1, 3, 4, 5],
expectedIds: [1, 2, 3, 4, 5, 10, 12],
testLabel: 'complete test ',
},
{
args: [
0,
[
{ timestamp: +new Date('2024-08-31 09:01:00'), id: 1 }, // 4th day too old
{ timestamp: +new Date('2024-09-01 00:10:00'), id: 2 }, // third day
{ timestamp: +new Date('2024-09-01 14:20:00'), id: 3 }, // second day, oldest
{ timestamp: +new Date('2024-09-02 00:22:00'), id: 4 }, // second day
{ timestamp: +new Date('2024-09-03 14:00:00'), id: 5 }, // same day oldest
{ timestamp: +new Date('2024-09-01 00:01:00'), id: 1 }, // thrid day too old
{ timestamp: +new Date('2024-09-01 00:10:00'), id: 2 }, // thrid day
{ timestamp: +new Date('2024-09-01 00:20:00'), id: 3 }, // second day, too old
{ timestamp: +new Date('2024-09-02 00:22:00'), id: 4 }, // second day too old
{ timestamp: +new Date('2024-09-03 00:20:00'), id: 5 }, // second day in NZ
{ timestamp: +new Date('2024-09-04 00:09:00'), id: 6 }, // same day in NZ
{ timestamp: +new Date('2024-09-04 00:10:00'), id: 7 }, // most recent
],
@@ -139,10 +135,10 @@ describe('_getOldEntries() should succeed', () => {
longTermRetention: {
daily: { retention: 3 },
},
timezone: 'Pacific/Auckland', // GMT +13
timezone: 'Pacific/Auckland', // GMT +6
},
],
expectedIds: [1, 4, 6, 7],
expectedIds: [1, 2, 3, 6],
testLabel: 'should handle timezone ',
},
]
@@ -153,20 +149,13 @@ describe('_getOldEntries() should succeed', () => {
assert.strictEqual(
oldEntries.length,
expectedIds.length,
`different length , ${JSON.stringify({ expectedIds, oldEntries: oldEntries.map(({ id }) => id) })}`
`different length , ${JSON.stringify({ oldEntries, expectedIds })}`
)
for (let i = 0; i < expectedIds.length; i++) {
if (i > 0) {
assert.strictEqual(
expectedIds[i - 1] < expectedIds[i],
true,
`expect ids in ascending order ${expectedIds[i - 1]} ${expectedIds[i]}`
)
}
assert.strictEqual(
oldEntries[i].id,
expectedIds[i],
`different id , ${JSON.stringify({ i, expectedIds, oldEntries: oldEntries.map(({ id }) => id) })}`
`different id , ${JSON.stringify({ i, expectedIds, oldEntries })}`
)
}
})
@@ -283,19 +272,6 @@ describe('_getOldEntries() should fail when called incorrectly', () => {
],
testLabel: 'broken date ',
},
{
args: [
1,
[{ obj: 1 }, 'toto', Date.now()],
{
longTermRetention: {
daily: { retention: 5 },
},
timezone: 'Europe/Paris',
},
],
testLabel: 'should fail if LTR without timestamp',
},
]
for (const { args, testLabel } of tests) {

View File

@@ -10,9 +10,10 @@ import { Task } from './Task.mjs'
import pick from 'lodash/pick.js'
import { BASE_DELTA_VDI, COPY_OF, VM_UUID } from './_otherConfig.mjs'
import { VHD_MAX_SIZE, XapiDiskSource } from '@xen-orchestra/xapi'
import { XapiDiskSource } from '@xen-orchestra/xapi'
import { toVhdStream } from 'vhd-lib/disk-consumer/index.mjs'
import { toQcow2Stream } from '@xen-orchestra/qcow2'
import { VHD_MAX_SIZE } from '@xen-orchestra/xapi/disks/Xapi.mjs'
const ensureArray = value => (value === undefined ? [] : Array.isArray(value) ? value : [value])
@@ -93,13 +94,11 @@ export async function exportIncrementalVm(
}
})
// Get a fresh list of VM's VTPM to avoid `vm.VTPMs: [undefined]`
const vmVtpms = await vm.$xapi.getField('VM', vm.$ref, 'VTPMs')
const vtpms = await Promise.all(
vmVtpms.map(async vtpmRef => {
vm.$VTPMs.map(async vtpm => {
let content
try {
content = await vm.$xapi.call('VTPM.get_contents', vtpmRef)
content = await vm.$xapi.call('VTPM.get_contents', vtpm.$ref)
} catch (err) {
console.error(err)
}
@@ -291,16 +290,10 @@ export const importIncrementalVm = defer(async function importIncrementalVm(
await xapi.VTPM_create({ VM: vmRef, contents })
})
)
const vm = await xapi.getRecord('VM', vmRef)
await Promise.all([
vmRecord.ha_always_run && xapi.setField('VM', vmRef, 'ha_always_run', true),
xapi.setField('VM', vmRef, 'name_label', vmRecord.name_label),
// correctly unlock the VM and reapply the target blocked operations
vm.update_blocked_operations({
start: null,
start_on: null,
...vmRecord.blocked_operations,
}),
incrementalVm.vm.ha_always_run && xapi.setField('VM', vmRef, 'ha_always_run', true),
xapi.setField('VM', vmRef, 'name_label', incrementalVm.vm.name_label),
])
return vmRef

View File

@@ -20,31 +20,13 @@ const IGNORED_PARTITION_TYPES = {
0xd5: true,
0x82: true, // swap
// GPT Linux swap GUID
'0657fd6d-a4ab-43c4-84e5-0933c84b4f4f': true,
}
// MBR LVM type
export const LVM_PARTITION_TYPE_MBR = 0x8e
// GPT LVM type
export const LVM_PARTITION_TYPE_GPT = 'e6d6d379-f507-44c2-a23c-238f2a3df928'
export const LVM_PARTITION_TYPE = 0x8e
const parsePartxLine = createParser({
keyTransform: key => (key === 'UUID' ? 'id' : key.toLowerCase()),
valueTransform: (value, key) => {
if (key === 'start' || key === 'size') {
return +value
}
// For GPT partitions, type is a UUID string
if (key === 'type' && !value.startsWith('0x')) {
return value.toLowerCase()
}
// For MBR partitions, type is a hex number as string (e.g., "0x8e")
if (key === 'type' && value.startsWith('0x')) {
return parseInt(value, 16)
}
return value
},
valueTransform: (value, key) => (key === 'start' || key === 'size' || key === 'type' ? +value : value),
})
// returns an empty array in case of a non-partitioned disk

View File

@@ -70,8 +70,7 @@ export async function getVmDeltaChainLength(xapi, vmRef) {
/**
*
* Reset the other_config field related to backups of a VM and its VDIs
*
* Reset the other_config field of a VM and its VDIs
*
* @param {Xapi} xapi
* @param {String} vmRef
@@ -91,6 +90,39 @@ export function resetVmOtherConfig(xapi, vmRef) {
})
}
/**
*
* used to ensure compatibility with the previous snapshots that were having the config stored only into VM
*
* @param {Xapi} xapi
* @param {String} vmRef
* @returns {Promise}
*/
export async function populateVdisOtherConfig(xapi, vmRef) {
const otherConfig = await xapi.getField('VM', vmRef, 'other_config')
const {
[DATETIME]: datetime,
[DELTA_CHAIN_LENGTH]: chainLength,
[EXPORTED_SUCCESSFULLY]: successfully,
[JOB_ID]: jobId,
[REPLICATED_TO_SR_UUID]: replicatedTo,
[SCHEDULE_ID]: scheduleId,
[VM_UUID]: vmUuid,
} = otherConfig
return applyToVmAndVdis(xapi, vmRef, (type, ref) =>
xapi.setFieldEntries(type, ref, 'other_config', {
[DATETIME]: datetime,
[DELTA_CHAIN_LENGTH]: chainLength,
[EXPORTED_SUCCESSFULLY]: successfully,
[JOB_ID]: jobId,
[REPLICATED_TO_SR_UUID]: replicatedTo,
[SCHEDULE_ID]: scheduleId,
[VM_UUID]: vmUuid,
})
)
}
/**
*
* set the other_config key related to a backup of a VM and its associated VDIs

View File

@@ -9,7 +9,6 @@ import { getAdaptersByRemote } from './_getAdaptersByRemote.mjs'
import { FullRemote } from './_vmRunners/FullRemote.mjs'
import { IncrementalRemote } from './_vmRunners/IncrementalRemote.mjs'
import { Throttle } from '@vates/generator-toolbox'
import createStreamThrottle from './_createStreamThrottle.mjs'
const noop = Function.prototype
@@ -42,8 +41,7 @@ export const VmsRemote = class RemoteVmsBackupRunner extends Abstract {
const schedule = this._schedule
const settings = this._settings
const throttleGenerator = new Throttle(settings.maxExportRate)
const throttleStream = createStreamThrottle(settings.maxExportRate)
const throttleGenerator = new Throttle()
const config = this._config
@@ -91,8 +89,7 @@ export const VmsRemote = class RemoteVmsBackupRunner extends Abstract {
schedule,
settings: vmSettings,
sourceRemoteAdapter,
throttleGenerator, // for incrementals
throttleStream, // for full
throttleGenerator,
vmUuid,
}
let vmBackup

View File

@@ -10,7 +10,6 @@ import { getAdaptersByRemote } from './_getAdaptersByRemote.mjs'
import { IncrementalXapi } from './_vmRunners/IncrementalXapi.mjs'
import { FullXapi } from './_vmRunners/FullXapi.mjs'
import { Throttle } from '@vates/generator-toolbox'
import createStreamThrottle from './_createStreamThrottle.mjs'
const noop = Function.prototype
@@ -56,8 +55,7 @@ export const VmsXapi = class VmsXapiBackupRunner extends Abstract {
const schedule = this._schedule
const settings = this._settings
const throttleGenerator = new Throttle(settings.maxExportRate)
const throttleStream = createStreamThrottle(settings.maxExportRate)
const throttleGenerator = new Throttle()
const config = this._config
@@ -150,7 +148,6 @@ export const VmsXapi = class VmsXapiBackupRunner extends Abstract {
settings: vmSettings,
srs,
throttleGenerator,
throttleStream,
vm,
}

View File

@@ -2,11 +2,10 @@ import { AbstractRemote } from './_AbstractRemote.mjs'
import { FullRemoteWriter } from '../_writers/FullRemoteWriter.mjs'
import { forkStreamUnpipe } from '../_forkStreamUnpipe.mjs'
import { watchStreamSize } from '../../_watchStreamSize.mjs'
import { AggregatedFullRemoteWriter } from '../_writers/AggregatedFullRemoteWriter.mjs'
export const FullRemote = class FullRemoteVmBackupRunner extends AbstractRemote {
_getRemoteWriters() {
return [FullRemoteWriter, AggregatedFullRemoteWriter]
_getRemoteWriter() {
return FullRemoteWriter
}
_filterTransferList(transferList) {
@@ -17,7 +16,7 @@ export const FullRemote = class FullRemoteVmBackupRunner extends AbstractRemote
const transferList = await this._computeTransferList(({ mode }) => mode === 'full')
for (const metadata of transferList) {
const stream = this._throttleStream(await this._sourceRemoteAdapter.readFullVmBackup(metadata))
const stream = await this._sourceRemoteAdapter.readFullVmBackup(metadata)
const sizeContainer = watchStreamSize(stream)
// @todo shouldn't transfer backup if it will be deleted by retention policy (higher retention on source than destination)
@@ -38,6 +37,5 @@ export const FullRemote = class FullRemoteVmBackupRunner extends AbstractRemote
// for healthcheck
this._tags = metadata.vm.tags
}
this._hasTransferredData = transferList.length > 0
}
}

View File

@@ -5,14 +5,12 @@ import { FullRemoteWriter } from '../_writers/FullRemoteWriter.mjs'
import { FullXapiWriter } from '../_writers/FullXapiWriter.mjs'
import { watchStreamSize } from '../../_watchStreamSize.mjs'
import { AbstractXapi } from './_AbstractXapi.mjs'
import { AggregatedFullRemoteWriter } from '../_writers/AggregatedFullRemoteWriter.mjs'
import { AggregatedFullXapiWriter } from '../_writers/AggregatedFullXapiWriter.mjs'
const { debug } = createLogger('xo:backups:FullXapiVmBackup')
export const FullXapi = class FullXapiVmBackupRunner extends AbstractXapi {
_getWriters() {
return [FullRemoteWriter, FullXapiWriter, AggregatedFullRemoteWriter, AggregatedFullXapiWriter]
return [FullRemoteWriter, FullXapiWriter]
}
async _mustDoSnapshot() {
@@ -51,14 +49,16 @@ export const FullXapi = class FullXapiVmBackupRunner extends AbstractXapi {
const { compression } = this.job
const vm = this._vm
const exportedVm = this._exportedVm
const stream = this._throttleStream(
// @todo put back throttle for full backup/Replication
const stream =
/* this._throttleStream( */
(
await this._xapi.VM_export(exportedVm.$ref, {
compress: Boolean(compression) && (compression === 'native' ? 'gzip' : 'zstd'),
useSnapshot: false,
})
).body
)
/* ) */
const vdis = await exportedVm.$getDisks()
let maxStreamLength = 1024 * 1024 // Ovf file and tar headers are a few KB, let's stay safe
@@ -66,16 +66,9 @@ export const FullXapi = class FullXapiVmBackupRunner extends AbstractXapi {
const vdi = await this._xapi.getRecord('VDI', vdiRef)
// the size a of fully allocated vdi will be virtual_size exactly, it's a gross over evaluation
// of the real stream size in general, since a disk is rarely completely full
// of the real stream size in general, since a disk is never completely full
// vdi.physical_size seems to underevaluate a lot the real disk usage of a VDI, as of 2023-10-30
// xva files are tar archive with data cut in 1MB blocks
// each block is signed with a hash (in xxhash format)
// each of these blocks + hash add one tar header entry in the file
const XVA_BLOCK_SIZE = 1024 * 1024
const nbBlocks = Math.ceil(vdi.virtual_size / XVA_BLOCK_SIZE)
const headersSize = nbBlocks * (512 /* file header */ + 512 /* xxhash header */ + 512) /* xhxhash size */
maxStreamLength += XVA_BLOCK_SIZE * nbBlocks + headersSize
maxStreamLength += vdi.virtual_size
}
const sizeContainer = watchStreamSize(stream)

View File

@@ -10,13 +10,12 @@ import { IncrementalRemoteWriter } from '../_writers/IncrementalRemoteWriter.mjs
import { Disposable } from 'promise-toolbox'
import { openVhd } from 'vhd-lib'
import { getVmBackupDir } from '../../_getVmBackupDir.mjs'
import { SynchronizedDisk, ThrottledDisk } from '@xen-orchestra/disk-transform'
import { AggregatedIncrementalRemoteWriter } from '../_writers/AggregatedIncrementalRemoteWriter.mjs'
import { SynchronizedDisk } from '@xen-orchestra/disk-transform'
const { warn } = createLogger('xo:backups:Incrementalremote')
class IncrementalRemoteVmBackupRunner extends AbstractRemote {
_getRemoteWriters() {
return [IncrementalRemoteWriter, AggregatedIncrementalRemoteWriter]
_getRemoteWriter() {
return IncrementalRemoteWriter
}
// we'll transfer the full list if at least one backup should be transferred
@@ -72,9 +71,8 @@ class IncrementalRemoteVmBackupRunner extends AbstractRemote {
const isVhdDifferencing = {}
for (const key in incrementalExport.disks) {
let disk = incrementalExport.disks[key]
const disk = incrementalExport.disks[key]
isVhdDifferencing[key] = disk.isDifferencing()
disk = new ThrottledDisk(disk, this._throttleGenerator)
incrementalExport.disks[key] = new SynchronizedDisk(disk)
}
@@ -117,7 +115,6 @@ class IncrementalRemoteVmBackupRunner extends AbstractRemote {
// for healthcheck
this._tags = metadata.vm.tags
}
this._hasTransferredData = transferList.length > 0
}
}

View File

@@ -14,20 +14,13 @@ import {
setVmDeltaChainLength,
markExportSuccessfull,
} from '../../_otherConfig.mjs'
import { ThrottledDisk, SynchronizedDisk } from '@xen-orchestra/disk-transform'
import { AggregatedIncrementalRemoteWriter } from '../_writers/AggregatedIncrementalRemoteWriter.mjs'
import { AggregatedIncrementalXapiWriter } from '../_writers/AggregatedIncrementalXapiWriter.mjs'
import { SynchronizedDisk } from '@xen-orchestra/disk-transform'
const { debug } = createLogger('xo:backups:IncrementalXapiVmBackup')
export const IncrementalXapi = class IncrementalXapiVmBackupRunner extends AbstractXapi {
_getWriters() {
return [
IncrementalRemoteWriter,
IncrementalXapiWriter,
AggregatedIncrementalRemoteWriter,
AggregatedIncrementalXapiWriter,
]
return [IncrementalRemoteWriter, IncrementalXapiWriter]
}
async _mustDoSnapshot() {
@@ -50,14 +43,10 @@ export const IncrementalXapi = class IncrementalXapiVmBackupRunner extends Abstr
const isVhdDifferencing = {}
let useNbd = false
for (const key in deltaExport.disks) {
let disk = deltaExport.disks[key]
const disk = deltaExport.disks[key]
isVhdDifferencing[key] = disk.isDifferencing()
if (!isFull && !isVhdDifferencing[key] && key !== exportedVm.$suspend_VDI?.$ref) {
Task.warning('Backup fell back to a full')
}
useNbd = useNbd || disk.useNbd()
disk = new ThrottledDisk(disk, this._throttleGenerator)
deltaExport.disks[key] = new SynchronizedDisk(disk)
useNbd = useNbd || disk.useNbd()
}
if (useNbd) {
Task.info('Transfer data using NBD')

View File

@@ -13,8 +13,6 @@ import { Task } from '../../Task.mjs'
export const AbstractRemote = class AbstractRemoteVmBackupRunner extends Abstract {
_filterPredicate
_hasTransferredData
constructor({
config,
job,
@@ -24,7 +22,6 @@ export const AbstractRemote = class AbstractRemoteVmBackupRunner extends Abstrac
settings,
sourceRemoteAdapter,
throttleGenerator,
throttleStream,
vmUuid,
}) {
super()
@@ -38,48 +35,32 @@ export const AbstractRemote = class AbstractRemoteVmBackupRunner extends Abstrac
this._healthCheckSr = healthCheckSr
this._sourceRemoteAdapter = sourceRemoteAdapter
this._throttleGenerator = throttleGenerator
this._throttleStream = throttleStream
this._vmUuid = vmUuid
const allSettings = job.settings
const writers = new Set()
this._writers = writers
const [BackupWriter, AggregratedBackupWriter] = this._getRemoteWriters()
if (settings.distributeBackups) {
const RemoteWriter = this._getRemoteWriter()
extractIdsFromSimplePattern(job.remotes).forEach(remoteId => {
const adapter = remoteAdapters[remoteId]
const targetSettings = {
...settings,
...allSettings[remoteId],
}
writers.add(
new AggregratedBackupWriter({
adapters: remoteAdapters,
BackupWriter,
new RemoteWriter({
adapter,
config,
healthCheckSr,
job,
scheduleId: schedule.id,
vmUuid,
settings,
remoteId,
settings: targetSettings,
})
)
} else {
extractIdsFromSimplePattern(job.remotes).forEach(remoteId => {
const adapter = remoteAdapters[remoteId]
const targetSettings = {
...settings,
...allSettings[remoteId],
}
writers.add(
new BackupWriter({
adapter,
config,
healthCheckSr,
job,
scheduleId: schedule.id,
vmUuid,
remoteId,
settings: targetSettings,
})
)
})
}
})
const { filter } = job
if (filter === undefined) {
this._filterPredicate = () => true
@@ -89,28 +70,28 @@ export const AbstractRemote = class AbstractRemoteVmBackupRunner extends Abstrac
}
async #computeTransferListPerJob(sourceBackups, remotesBackups) {
const localMetadata = new Map()
const localMetada = new Map()
sourceBackups.forEach(metadata => {
const timestamp = metadata.timestamp
localMetadata.set(timestamp, metadata)
localMetada.set(timestamp, metadata)
})
const nbRemotes = remotesBackups.length
const remoteMetadata = {}
const remoteMetadatas = {}
remotesBackups.forEach(async remoteBackups => {
remoteBackups.forEach(metadata => {
const timestamp = metadata.timestamp
remoteMetadata[timestamp] = (remoteMetadata[timestamp] ?? 0) + 1
remoteMetadatas[timestamp] = (remoteMetadatas[timestamp] ?? 0) + 1
})
})
let transferList = []
const timestamps = [...localMetadata.keys()]
const timestamps = [...localMetada.keys()]
timestamps.sort()
for (const timestamp of timestamps) {
if (remoteMetadata[timestamp] !== nbRemotes) {
if (remoteMetadatas[timestamp] !== nbRemotes) {
// this backup is not present in all the remote
// should be retransferred if not found later
transferList.push(localMetadata.get(timestamp))
transferList.push(localMetada.get(timestamp))
} else {
// backup is present in local and remote : the chain has already been transferred
transferList = []
@@ -118,10 +99,17 @@ export const AbstractRemote = class AbstractRemoteVmBackupRunner extends Abstrac
}
if (transferList.length > 0) {
const filteredTransferList = this._filterTransferList(transferList)
return { transferList: filteredTransferList, filtered: true }
if (filteredTransferList.length > 0) {
return filteredTransferList
} else {
Task.info('This VM is excluded by the job filter')
return []
}
} else {
return { transferList, filtered: false }
Task.info('No new data to upload for this VM')
}
return []
}
/**
@@ -135,21 +123,12 @@ export const AbstractRemote = class AbstractRemoteVmBackupRunner extends Abstrac
Object.values(this.remoteAdapters).map(remoteAdapter => remoteAdapter.listVmBackups(this._vmUuid, vmPredicate))
)
const sourceBackupByJobId = groupBy(sourceBackups, 'jobId')
const transferObjectsList = await Promise.all(
const transferByJobs = await Promise.all(
Object.values(sourceBackupByJobId).map(vmBackupsByJob =>
this.#computeTransferListPerJob(vmBackupsByJob, remotesBackups)
)
)
const transferList = transferObjectsList.map(transferObject => transferObject.transferList).flat(1)
if (transferList.length === 0 && Object.values(sourceBackupByJobId).length > 0) {
if (transferObjectsList.some(transferObject => transferObject.filtered)) {
// Happens if any job transfer list wasn't empty before filter and is empty after filter.
Task.info('This VM is excluded by the job filter')
} else {
Task.info('No new data to upload for this VM')
}
}
return transferList
return transferByJobs.flat(1)
}
async run($defer) {
@@ -162,16 +141,7 @@ export const AbstractRemote = class AbstractRemoteVmBackupRunner extends Abstrac
})
}, 'writer.beforeBackup()')
await this._run()
if (this._hasTransferredData === undefined) {
throw new Error('Missing tag to check there are some transferred data')
}
if (this._hasTransferredData) {
await this._healthCheck()
} else {
Task.info(`No healthCheck needed because no data was transferred.`)
}
await this._healthCheck()
})
}
}

View File

@@ -1,20 +1,21 @@
import assert from 'node:assert'
import groupBy from 'lodash/groupBy.js'
import { createLogger } from '@xen-orchestra/log'
import ignoreErrors from 'promise-toolbox/ignoreErrors'
import { asyncMap } from '@xen-orchestra/async-map'
import { asyncEach } from '@vates/async-each'
import { decorateMethodsWith } from '@vates/decorate-with'
import { defer } from 'golike-defer'
import { getOldEntries } from '../../_getOldEntries.mjs'
import { Task } from '../../Task.mjs'
import { Abstract } from './_Abstract.mjs'
import { DATETIME, JOB_ID, SCHEDULE_ID, VM_UUID, resetVmOtherConfig, setVmOtherConfig } from '../../_otherConfig.mjs'
const { warn, info } = createLogger('xo:backups:AbstractXapi')
const TEMP_SNAPSHOT_NAME = 'xo-backup-temp-snapshot-name'
import {
DATETIME,
JOB_ID,
SCHEDULE_ID,
populateVdisOtherConfig,
resetVmOtherConfig,
setVmOtherConfig,
} from '../../_otherConfig.mjs'
export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
constructor({
@@ -28,7 +29,6 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
settings,
srs,
throttleGenerator,
throttleStream,
vm,
}) {
super()
@@ -63,7 +63,6 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
this._jobId = job.id
this._jobSnapshotVdis = undefined
this._throttleGenerator = throttleGenerator
this._throttleStream = throttleStream
this._xapi = vm.$xapi
// Base VM for the export
@@ -82,84 +81,48 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
const writers = new Set()
this._writers = writers
const [BackupWriter, ReplicationWriter, AggregratedBackupWriter, AggregratedReplicationWriter] =
this._getWriters()
const [BackupWriter, ReplicationWriter] = this._getWriters()
const allSettings = job.settings
if (settings.exportRetention > 0) {
if (settings.distributeBackups) {
Object.entries(remoteAdapters).forEach(([remoteId, adapter]) => {
const targetSettings = {
...settings,
...allSettings[remoteId],
}
if (targetSettings.exportRetention !== 0) {
writers.add(
new AggregratedBackupWriter({
adapters: remoteAdapters,
BackupWriter,
new BackupWriter({
adapter,
config,
healthCheckSr,
job,
scheduleId: schedule.id,
vmUuid: vm.uuid,
settings,
remoteId,
settings: targetSettings,
})
)
} else {
Object.entries(remoteAdapters).forEach(([remoteId, adapter]) => {
const targetSettings = {
...settings,
...allSettings[remoteId],
}
if (targetSettings.exportRetention !== 0) {
writers.add(
new BackupWriter({
adapter,
config,
healthCheckSr,
job,
scheduleId: schedule.id,
vmUuid: vm.uuid,
remoteId,
settings: targetSettings,
})
)
}
})
}
}
if (settings.copyRetention) {
if (settings.distributeReplications) {
})
srs.forEach(sr => {
const targetSettings = {
...settings,
...allSettings[sr.uuid],
}
if (targetSettings.copyRetention !== 0) {
writers.add(
new AggregratedReplicationWriter({
new ReplicationWriter({
config,
healthCheckSr,
job,
ReplicationWriter,
scheduleId: schedule.id,
vmUuid: vm.uuid,
srs,
settings,
sr,
settings: targetSettings,
})
)
} else {
srs.forEach(sr => {
const targetSettings = {
...settings,
...allSettings[sr.uuid],
}
if (targetSettings.copyRetention !== 0) {
writers.add(
new ReplicationWriter({
config,
healthCheckSr,
job,
scheduleId: schedule.id,
vmUuid: vm.uuid,
sr,
settings: targetSettings,
})
)
}
})
}
}
})
}
}
@@ -195,7 +158,7 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
const snapshotRef = await vm[settings.checkpointSnapshot ? '$checkpoint' : '$snapshot']({
ignoredVdisTag: '[NOBAK]',
name_label: TEMP_SNAPSHOT_NAME,
name_label: this._getSnapshotNameLabel(vm),
unplugVusbs: true,
})
this.timestamp = Date.now()
@@ -205,9 +168,6 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
scheduleId: this.scheduleId,
vmUuid: vm.uuid,
})
const snapshot = await xapi.getRecord('VM', snapshotRef)
await snapshot.set_name_label(this._getSnapshotNameLabel(vm))
// reload data to ensure it is up to date with the new name label
this._exportedVm = await xapi.getRecord('VM', snapshotRef)
return this._exportedVm.uuid
})
@@ -217,113 +177,43 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
}
}
// handle snapshot by VDI since snapshot of cbtDestroySnapshotData jobs
// aren't attached to any VM
// look at all the vdi snapshots ( snapshot_of not empty )
// with the same vm_uuid and job_uuid
// for cbt_metadata list them unconditionnaly to remove older one
// for other: only list them if they are attached to a VM snapshot
// and if this vm snapshot is also part of the backup
// ensure they are attached to only one vm snapshot
// ensure any VM-snapshot harvested by this has all its disk harvested (no mix of vdi snapshot from this job and not)
async _fetchJobSnapshots() {
const jobId = this._jobId
const vmRef = this._vm.$ref
const xapi = this._xapi
const vdiCandidates = {}
// to ensure compatibility with snapshots older than CBT implementation
// update vdi data to ensure the vdi are correctly fetched in _jobSnapshotVdis
// remove by then end of 2024
const vmSnapshotsRef = await xapi.getField('VM', vmRef, 'snapshots')
const vmSnapshotsOtherConfig = await asyncMap(vmSnapshotsRef, ref => xapi.getField('VM', ref, 'other_config'))
Object.values(xapi.objects.indexes.type.VDI)
.filter(_ => !!_) // filter nullish
.filter(({ other_config, $snapshot_of }) => {
return $snapshot_of !== undefined && other_config[JOB_ID] === jobId && other_config[VM_UUID] === this._vm.uuid
})
.forEach(vdi => {
vdiCandidates[vdi.uuid] = vdi
})
// check that user snapshots are clean
for (const vdi of Object.values(vdiCandidates)) {
// cbt metadata are always considered linked to a backup job
// if they have the right other_config
if (vdi.type === 'cbt_metadata') {
continue
}
const vbds = vdi.$VBDs
.filter(({ $VM }) => !!$VM) // filter empty VMs
.filter(({ $VM }) => $VM.is_control_domain === false) // do not handle control domain
if (vbds.length === 0) {
// orphan vdi snapshot
info(
`disk snapshot ${vdi.name_label} is orphan or attached only to control domain,
it will be removed at the end of a successful backup run`,
{ vdi, attachedto: vdi.$VBDs.map(vbd => vbd?.$VM) }
)
continue
}
const userVms = vbds.map(({ $VM }) => $VM)
if (vbds.length > 1) {
warn(
`vdi ${vdi.name_label} (${vdi.uuid}) is linked to multipe vms : ${userVms.map(({ name_label, uuid }) => `${name_label} ${uuid}`).join(', ')}.
This disk snapshot will be excluded from the backup cleaning`,
{ vdi, userVms }
)
delete vdiCandidates[vdi.uuid]
continue
const vmSnapshots = []
vmSnapshotsOtherConfig.forEach((other_config, i) => {
if (other_config[JOB_ID] === jobId) {
vmSnapshots.push({ other_config, $ref: vmSnapshotsRef[i] })
}
})
await Promise.all(vmSnapshots.map(snapshot => populateVdisOtherConfig(xapi, snapshot.$ref)))
// end of compatibility handling
const vm = vbds[0].$VM
// xapi has some issue regarding vdi snapshot attached to non snapshot VM
// it can also be some user action forcibely linking a vdi snapshot to a vm
// => we exclude these from the backup processing
if (vm.$snapshot_of === undefined) {
warn(
`vdi ${vdi.name_label} (${vdi.uuid}) is a snapshot linked to a non snapshot vm ${vm.name_label} ${vm.uuid}.
This disk snapshot will be excluded from the backup cleaning`,
{ vdi, vm }
)
delete vdiCandidates[vdi.uuid]
continue
// handle snapshot by VDI
this._jobSnapshotVdis = []
const srcVdis = await xapi.getRecords('VDI', await this._vm.$getDisks())
for (const srcVdi of srcVdis) {
const snapshots = await xapi.getRecords('VDI', srcVdi.snapshots)
for (const snapshot of snapshots) {
// only keep the snapshot related to this backup job
// and only if the job is still using purge snapshot data or if the disk
// is not a cbt metadata disk ( expect a type: user for normal disks)
if (
snapshot.other_config[JOB_ID] === jobId &&
(this._settings.cbtDestroySnapshotData || snapshot.type !== 'cbt_metadata')
) {
this._jobSnapshotVdis.push(snapshot)
}
}
// vdi is attached only to a snapshot that is not a backup snapshot
// we don't check scheduleId since we are looking for all the snapshot of this job
// => excludes from the list to be cleared
if (
vm.other_config[DATETIME] !== vdi.other_config[DATETIME] ||
vm.other_config[JOB_ID] !== vdi.other_config[JOB_ID] ||
vm.other_config[VM_UUID] !== vdi.other_config[VM_UUID]
) {
warn(
`vdi ${vdi.name_label} (${vdi.uuid}) is a snapshot linked to a snapshot vm ${vm.name_label} ${vm.uuid} out of this backup job scope.
This disk snapshot will be excluded from the backup cleaning`,
{ vdi, vm }
)
delete vdiCandidates[vdi.uuid]
continue
}
// check if all the disks of these VM snapshot have been harvested
// if not => remove it from the list to ensure we won't half destroy VM later
vm.$VBDs
.filter(({ $VDI }) => !!$VDI) // filter missing keys
.filter(({ $VDI }) => $VDI && vdiCandidates[$VDI.uuid] === undefined)
.forEach(({ $VDI: outOfSnapshotsVdi, ...other }) => {
warn(
`vdi ${vdi.name_label} ${vdi.uuid} is recognized as a snapshot of the backup job,
linked to vm ${vm.name_label} ${vm.uuid} but vdi ${outOfSnapshotsVdi.name_label} ${outOfSnapshotsVdi.uuid}
is not linked to the job. This disk snapshot will be excluded from the backup cleaning`,
{ vdi, vm, vbds, outOfSnapshotsVdi }
)
// this will be called multiple time but it is not really an issue
delete vdiCandidates[vdi.uuid]
})
}
this._jobSnapshotVdis = Object.values(vdiCandidates)
}
async _removeUnusedSnapshots() {
@@ -363,47 +253,28 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
return
}
const vdis = snapshotPerDatetime[datetime]
let vm
let vmRef
// if there is an attached VM => destroy the VM (Non CBT backups)
for (const vdi of vdis) {
const vbds = vdi.$VBDs.filter(({ $VM }) => $VM.is_control_domain === false)
if (vbds.length > 0) {
// only one VM linked to this vdi
// this will throw error for VDI still attached to control domain
// since we won't be able to remove an attached VDI
assert.strictEqual(vbds.length, 1, 'VDI must be free or attached to exactly one VM')
const vdiVm = vbds[0].$VM
if (vdiVm.$snapshot_of === undefined) {
// don't delete a VM (especially a control domain)
warn(
`VM ${vdiVm.uuid} (${vdiVm.name_label}) linked to VDI ${vdi.uuid} (${vdi.name_label}) should be a snapshot`
)
throw new Error(`VM must be a snapshot`)
}
if (vm !== undefined && vm.$ref !== vdiVm.$ref) {
// this VDI is attached to another VM than the other vdi of
// this batch
// in doubt, do not delete anything
warn("_removeUnusedSnapshots don't handle vdi related to multiple VMs ", {
vm1: {
label: vm.name_label,
id: vm.$id,
},
vm2: {
label: vdiVm.name_label,
id: vdiVm.$id,
},
vdis: vdis.map(({ name_label, $id }) => ({ name_label, $id })),
})
throw new Error(
`_removeUnusedSnapshots don't handle vdi related to multiple VMs ${vm.name_label} and ${vdiVm.name_label}`
)
}
vm = vdiVm
const vm = vbds[0].$VM
assert.strictEqual(vm.is_a_snapshot, true, `VM must be a snapshot`) // don't delete a VM (especially a control domain)
const vmRefVdi = vm.$ref
// same vm than other vdi of the same batch
assert.ok(
vmRef === undefined || vmRef === vmRefVdi,
'_removeUnusedSnapshots don t handle vdi related to multiple VMs '
)
vmRef = vmRefVdi
}
}
if (vm?.$ref !== undefined) {
return xapi.VM_destroy(vm.$ref)
if (vmRef !== undefined) {
return xapi.VM_destroy(vmRef)
} else {
return asyncMap(
vdis.map(async ({ $ref }) => {
@@ -413,11 +284,6 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
}
})
})
// list and remove the snapshot were the jobs failed between
// makesnapshot and update_other_config
const snapshots = this._vm.$snapshots.filter(_ => !!_).filter(({ name_label }) => name_label === TEMP_SNAPSHOT_NAME)
await asyncEach(snapshots, snapshot => snapshot.$destroy())
}
async _removeSnapshotData() {
@@ -425,9 +291,8 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
// going back to a previous version of XO not supporting CBT will create a full backup
// this will only do something after snapshot and transfer
if (
this._exportedVm !== undefined &&
// don't modify the VM
this._exportedVm.$snapshot_of !== undefined &&
this._exportedVm?.is_a_snapshot &&
// user don't want to keep the snapshot data
this._settings.snapshotRetention === 0 &&
// preferNbd is not a guarantee that the backup used NBD, depending on the network configuration,

View File

@@ -1,38 +0,0 @@
import { AbstractAggregatedRemoteWriter } from './_AbstractAggregatedRemoteWriter.mjs'
export class AggregatedFullRemoteWriter extends AbstractAggregatedRemoteWriter {
async deleteOldBackupsOnAdapter(adapter, backups) {
await adapter.deleteFullVmBackups(backups)
}
// take the lock on every adapters with this VM
// cleanup if deleteFirst is selected
async beforeBackup() {
await this.setupWriters()
await Promise.all(this.writers.map(writer => writer.beforeBackup()))
await this.setOldBackups()
if (this.props.settings.deleteFirst) {
await this.deleteOldBackups()
}
}
async run(props) {
const mainAdapter = await this.computeAdapterCandidate()
this.mainWriter = this.getWriterByAdapter(mainAdapter)
return this.mainWriter.run(props)
}
// cleanup if deleteFirst is NOT selected
// release the lock on every adapters with this VM
async afterBackup() {
if (!this.props.settings.deleteFirst) {
await this.deleteOldBackups()
}
await Promise.all(this.writers.map(writer => writer.afterBackup()))
}
healthCheck() {
return this.mainWriter.healthCheck()
}
}

View File

@@ -1,31 +0,0 @@
import { AbstractAggregatedXapiWriter } from './_AbstractAggregatedXapiWriter.mjs'
export class AggregatedFullXapiWriter extends AbstractAggregatedXapiWriter {
// delete replica if deleteFirst is selected
async beforeBackup() {
await this.setupWriters()
await Promise.all(this.writers.map(writer => writer.beforeBackup()))
this.setOldReplicaList()
if (this.props.settings.deleteFirst) {
await this.deleteOldReplicas()
}
}
async run(props) {
const mainSr = await this.computeSRCandidate()
this.mainWriter = this.getWriterBySr(mainSr)
await this.mainWriter.run(props)
}
// delete replica if not using deleteFirst
async afterBackup() {
if (!this.props.settings.deleteFirst) {
await this.deleteOldReplicas()
}
await Promise.all(this.writers.map(writer => writer.afterBackup()))
}
healthCheck() {
return this.mainWriter.healthCheck()
}
}

View File

@@ -1,78 +0,0 @@
import { AbstractAggregatedRemoteWriter } from './_AbstractAggregatedRemoteWriter.mjs'
export class AggregatedIncrementalRemoteWriter extends AbstractAggregatedRemoteWriter {
async deleteOldBackupsOnAdapter(adapter, backups) {
await adapter.deleteDeltaVmBackups(backups)
}
/**
*
* @param {Map<string,string>} baseUuidToSrcVdi
*/
async checkBaseVdis(baseUuidToSrcVdi) {
let selectedCopy = new Map()
for (const writer of this.writers) {
const copy = new Map(baseUuidToSrcVdi)
await writer.checkBaseVdis(copy)
if (copy.size > 0) {
// there can be multiple candidates
// we use the last one in this case
this.mainWriter = writer
selectedCopy = copy
}
}
// update the parameter with our best candidate
// that can be an empty map
baseUuidToSrcVdi.forEach(key => {
if (!selectedCopy.has(key)) {
baseUuidToSrcVdi.delete(key)
}
})
}
// take the lock on every adapters with this VM
// cleanup if deleteFirst is selected
async beforeBackup() {
await this.setupWriters()
await Promise.all(this.writers.map(writer => writer.beforeBackup()))
await this.setOldBackups()
if (this.props.settings.deleteFirst) {
await this.deleteOldBackups()
}
}
async prepare({ isFull }) {
if (this.mainWriter === undefined) {
// use the remote with the most empty space for starting a new chain
const mainAdapter = await this.computeAdapterCandidate()
this.mainWriter = this.getWriterByAdapter(mainAdapter)
}
await Promise.all(this.writers.map(writer => writer.prepare({ isFull })))
}
// write only on the main writer
transfer({ isVhdDifferencing, timestamp, deltaExport, vm, vmSnapshot }) {
return this.mainWriter.transfer({ isVhdDifferencing, timestamp, deltaExport, vm, vmSnapshot })
}
// chain only on the main writer
updateUuidAndChain({ isVhdDifferencing, vdis }) {
return this.mainWriter.updateUuidAndChain({ isVhdDifferencing, vdis })
}
// remove the backups and remove the entries
async cleanup() {
if (!this.props.settings.deleteFirst) {
await this.deleteOldBackups()
}
await Promise.all(this.writers.map(writer => writer.cleanup()))
}
// cleanVM on all, since we may want to delete a chani
// that is not on the main writer
async afterBackup() {
await Promise.all(this.writers.map(writer => writer.afterBackup()))
}
healthCheck() {
return this.mainWriter.healthCheck()
}
}

View File

@@ -1,85 +0,0 @@
import { AbstractAggregatedXapiWriter } from './_AbstractAggregatedXapiWriter.mjs'
import { createLogger } from '@xen-orchestra/log'
const { debug } = createLogger('xo:backups:AggregatedIncrementalXapiWriter')
export class AggregatedIncrementalXapiWriter extends AbstractAggregatedXapiWriter {
/**
*
* @param {Map<string,string>} baseUuidToSrcVdi
*/
async checkBaseVdis(baseUuidToSrcVdi) {
debug('checkBaseVdis', { baseUuidToSrcVdi })
let selectedCopy = new Map()
for (const writer of this.writers) {
const copy = new Map(baseUuidToSrcVdi)
await writer.checkBaseVdis(copy)
if (copy.size > 0) {
debug('checkBaseVdis found a mainwriter candidate ', writer._sr.name_label)
// there can be multiple candidates
// we use the last one in this case
this.mainWriter = writer
selectedCopy = copy
} else {
debug(writer._sr.name_label, 'is not a delta candidate')
}
}
// update the parameter with our best candidate
// that can be an empty map
baseUuidToSrcVdi.forEach(key => {
if (!selectedCopy.has(key)) {
baseUuidToSrcVdi.delete(key)
}
})
debug('checkBaseVdis', { baseUuidToSrcVdi })
}
// take the lock on every adapters with this VM
// cleanup if deleteFirst is selected
async beforeBackup() {
await this.setupWriters()
await Promise.all(this.writers.map(writer => writer.beforeBackup()))
this.setOldReplicaList()
if (this.props.settings.deleteFirst) {
await this.deleteOldReplicas()
}
}
async prepare(args) {
if (this.mainWriter === undefined) {
debug('no mainwriter found, fallback to a new SR')
// use the SR with the most empty space for starting a new chain
const mainSr = await this.computeSRCandidate()
this.mainWriter = this.getWriterBySr(mainSr)
}
await Promise.all(this.writers.map(writer => writer.prepare(args)))
}
// write only on the main writer
transfer(args) {
return this.mainWriter.transfer(args)
}
// chain only on the main writer
updateUuidAndChain(args) {
return this.mainWriter.updateUuidAndChain(args)
}
// remove the backups and remove the entries
async cleanup() {
debug('cleanup')
if (!this.props.settings.deleteFirst) {
await this.deleteOldReplicas()
}
await Promise.all(this.writers.map(writer => writer.cleanup()))
}
// cleanVM on all, since we may want to delete a chani
// that is not on the main writer
async afterBackup() {
await Promise.all(this.writers.map(writer => writer.afterBackup()))
}
healthCheck() {
return this.mainWriter.healthCheck()
}
}

View File

@@ -33,7 +33,7 @@ export class FullRemoteWriter extends MixinRemoteWriter(AbstractFullWriter) {
let metadata = await this._isAlreadyTransferred(timestamp)
if (metadata !== undefined) {
// @todo : should skip backup while being vigilant to not stuck the forked stream
Task.info('This backup has already been transferred')
Task.info('This backup has already been transfered')
}
const oldBackups = getOldEntries(
@@ -59,8 +59,8 @@ export class FullRemoteWriter extends MixinRemoteWriter(AbstractFullWriter) {
xva: './' + dataBasename,
}
const { skipDeleteOldEntries, deleteFirst } = settings
if (!skipDeleteOldEntries && deleteFirst) {
const { deleteFirst } = settings
if (deleteFirst) {
await deleteOldBackups()
}
@@ -73,10 +73,9 @@ export class FullRemoteWriter extends MixinRemoteWriter(AbstractFullWriter) {
return { size: sizeContainer.size }
})
metadata.size = sizeContainer.size
metadata.tags = await this.getLongTermRetentionTags(metadata)
this._metadataFileName = await adapter.writeVmBackupMetadata(vm.uuid, metadata)
if (!skipDeleteOldEntries && !deleteFirst) {
if (!deleteFirst) {
await deleteOldBackups()
}

View File

@@ -46,8 +46,8 @@ export class FullXapiWriter extends MixinXapiWriter(AbstractFullWriter) {
const oldVms = getOldEntries(settings.copyRetention - 1, listReplicatedVms(xapi, scheduleId, srUuid, vm.uuid))
const deleteOldBackups = () => asyncMapSettled(oldVms, vm => xapi.VM_destroy(vm.$ref))
const { deleteFirst, skipDeleteOldEntries, _warmMigration } = settings
if (!skipDeleteOldEntries && deleteFirst) {
const { deleteFirst, _warmMigration } = settings
if (deleteFirst) {
await deleteOldBackups()
}
@@ -85,7 +85,7 @@ export class FullXapiWriter extends MixinXapiWriter(AbstractFullWriter) {
}),
])
if (!skipDeleteOldEntries && !deleteFirst) {
if (!deleteFirst) {
await deleteOldBackups()
}
}

View File

@@ -114,13 +114,13 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
oldEntries.length = maxMergedDeltasPerRun
}
if (settings.deleteFirst && !settings.skipDeleteOldEntries) {
if (settings.deleteFirst) {
await this._deleteOldEntries()
}
}
async cleanup() {
if (!this._settings.deleteFirst && !this._settings.skipDeleteOldEntries) {
if (!this._settings.deleteFirst) {
await this._deleteOldEntries()
}
}
@@ -244,7 +244,6 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
return { size }
})
metadataContent.tags = await this.getLongTermRetentionTags(metadataContent)
metadataContent.size = size // @todo return exactly the size written by this writer
this._metadataFileName = await adapter.writeVmBackupMetadata(vm.uuid, metadataContent)

View File

@@ -1,6 +1,7 @@
import { asyncMapSettled } from '@xen-orchestra/async-map'
import { asyncMap, asyncMapSettled } from '@xen-orchestra/async-map'
import ignoreErrors from 'promise-toolbox/ignoreErrors'
import { formatFilenameDate } from '../../_filenameDate.mjs'
import { getOldEntries } from '../../_getOldEntries.mjs'
import { importIncrementalVm } from '../../_incrementalVm.mjs'
import { Task } from '../../Task.mjs'
@@ -8,18 +9,7 @@ import { Task } from '../../Task.mjs'
import { AbstractIncrementalWriter } from './_AbstractIncrementalWriter.mjs'
import { MixinXapiWriter } from './_MixinXapiWriter.mjs'
import { listReplicatedVms } from './_listReplicatedVms.mjs'
import {
COPY_OF,
setVmOtherConfig,
BASE_DELTA_VDI,
JOB_ID,
SCHEDULE_ID,
REPLICATED_TO_SR_UUID,
DATETIME,
VM_UUID,
} from '../../_otherConfig.mjs'
import assert from 'node:assert'
import { formatFilenameDate } from '../../_filenameDate.mjs'
import { COPY_OF, setVmOtherConfig, BASE_DELTA_VDI } from '../../_otherConfig.mjs'
export class IncrementalXapiWriter extends MixinXapiWriter(AbstractIncrementalWriter) {
async checkBaseVdis(baseUuidToSrcVdi) {
@@ -35,11 +25,7 @@ export class IncrementalXapiWriter extends MixinXapiWriter(AbstractIncrementalWr
const replicatedVdis = sr.$VDIs
.filter(vdi => {
// REPLICATED_TO_SR_UUID is not used here since we are already filtering from sr.$VDIs
return (
vdi?.managed &&
!vdi?.is_a_snapshot /* only look for real vdi */ &&
baseUuidToSrcVdi.has(vdi?.other_config[COPY_OF])
)
return baseUuidToSrcVdi.has(vdi?.other_config[COPY_OF])
})
.map(({ other_config }) => other_config?.[COPY_OF])
.filter(_ => !!_)
@@ -83,7 +69,7 @@ export class IncrementalXapiWriter extends MixinXapiWriter(AbstractIncrementalWr
this._oldEntries = getOldEntries(settings.copyRetention - 1, listReplicatedVms(xapi, scheduleId, srUuid, vmUuid))
if (settings.deleteFirst && settings.skipDeleteOldEntries) {
if (settings.deleteFirst) {
// we want to keep the baseVM when copying a delta
// even if we want to keep only one after
let mostRecentEntry
@@ -96,37 +82,19 @@ export class IncrementalXapiWriter extends MixinXapiWriter(AbstractIncrementalWr
}
async cleanup() {
if (!this._settings.skipDeleteOldEntries) {
await this._deleteOldEntries()
}
await this._deleteOldEntries()
}
async _deleteOldEntries() {
return asyncMapSettled(this._oldEntries, vm => vm.$destroy({ bypassBlockedOperation: true }))
return asyncMapSettled(this._oldEntries, vm => vm.$destroy())
}
#decorateVmMetadata(backup, timestamp) {
#decorateVmMetadata(backup) {
const { _warmMigration } = this._settings
const sr = this._sr
const vm = backup.vm
const job = this._job
const scheduleId = this._scheduleId
vm.name_label = `${vm.name_label} - ${job.name} - (${formatFilenameDate(timestamp)})`
// update other_config data as soon as possible to ensure the next job
// will be able to detect any partial transfer and lean them
vm.other_config[COPY_OF] = vm.uuid
vm.other_config[JOB_ID] = job.id
vm.other_config[SCHEDULE_ID] = scheduleId
vm.other_config[REPLICATED_TO_SR_UUID] = sr.uuid
// set the timestamp in the past to ensure any incomplete VM will be deleted on next run
vm.other_config[DATETIME] = formatFilenameDate(0)
vm.blocked_operations = {
start: 'Start operation for this vm is blocked, clone it if you want to use it.',
start_on: 'Start operation for this vm is blocked, clone it if you want to use it.',
}
if (!_warmMigration) {
vm.tags.push('Continuous Replication')
}
@@ -140,26 +108,17 @@ export class IncrementalXapiWriter extends MixinXapiWriter(AbstractIncrementalWr
const replicatedVdis = sr.$VDIs.filter(vdi => {
// REPLICATED_TO_SR_UUID is not used here since we are already filtering from sr.$VDIs
return vdi?.managed && !vdi?.is_a_snapshot && sourceVdiUuids.includes(vdi?.other_config[COPY_OF])
return sourceVdiUuids.includes(vdi?.other_config[COPY_OF])
})
Object.values(backup.vdis).forEach(vdi => {
vdi.other_config[COPY_OF] = vdi.uuid
vdi.other_config[JOB_ID] = job.id
vdi.other_config[SCHEDULE_ID] = scheduleId
vdi.other_config[REPLICATED_TO_SR_UUID] = sr.uuid
vdi.other_config[VM_UUID] = vm.uuid
if (sourceVdiUuids.length > 0) {
const baseReplicatedTo = replicatedVdis.filter(
const baseReplicatedTo = replicatedVdis.find(
replicatedVdi => replicatedVdi.other_config[COPY_OF] === vdi.other_config[BASE_DELTA_VDI]
)
assert.ok(
baseReplicatedTo.length <= 1,
`Target of a replication must be unique, got ${baseReplicatedTo.length} candidates`
)
// baseReplicatedTo can be undefined if a new disk is added and other are already replicated
vdi.baseVdi = baseReplicatedTo[0]
vdi.baseVdi = baseReplicatedTo
} else {
// first replication of this disk
vdi.baseVdi = undefined
@@ -176,11 +135,12 @@ export class IncrementalXapiWriter extends MixinXapiWriter(AbstractIncrementalWr
const sr = this._sr
const job = this._job
const scheduleId = this._scheduleId
const { uuid: srUuid, $xapi: xapi } = sr
let targetVmRef
await Task.run({ name: 'transfer' }, async () => {
targetVmRef = await importIncrementalVm(this.#decorateVmMetadata(deltaExport, timestamp), sr)
targetVmRef = await importIncrementalVm(this.#decorateVmMetadata(deltaExport), sr)
// size is mandatory to ensure the task have the right data
return {
size: Object.values(deltaExport.disks).reduce(
@@ -197,8 +157,15 @@ export class IncrementalXapiWriter extends MixinXapiWriter(AbstractIncrementalWr
!_warmMigration &&
targetVm.ha_restart_priority !== '' &&
Promise.all([targetVm.set_ha_restart_priority(''), targetVm.add_tags('HA disabled')]),
targetVm.set_name_label(`${vm.name_label} - ${job.name} - (${formatFilenameDate(timestamp)})`),
asyncMap(['start', 'start_on'], op =>
targetVm.update_blocked_operations(
op,
'Start operation for this vm is blocked, clone it if you want to use it.'
)
),
setVmOtherConfig(xapi, targetVmRef, {
timestamp, // updated at the end to mark the transfer as complete
timestamp,
jobId: job.id,
scheduleId,
vmUuid: vm.uuid,

View File

@@ -1,157 +0,0 @@
import { asyncEach } from '@vates/async-each'
import { getOldEntries } from '../../_getOldEntries.mjs'
import { compareTimestamp } from '../../RemoteAdapter.mjs'
import { createLogger } from '@xen-orchestra/log'
const { debug } = createLogger('xo:backups:AbstractAggregatedRemoteWriter')
export const DEFAULT_AGGREGATED_REMOTE_DELETE_CONCURRENCY = 2
export class AbstractAggregatedRemoteWriter {
#BackupWriter
#adapters
get adapters() {
return this.#adapters
}
mainWriter
#props
get props() {
return this.#props
}
#oldBackups
#writers = []
get writers() {
return this.#writers
}
constructor({ adapters, BackupWriter, ...props }) {
debug('instantiate AggregatedFullRemoteWriter')
if (Object.keys(adapters).length < 1) {
throw new Error('AggregatedRemoteWriter need at least one backup repository to work ')
}
this.#props = props
this.#adapters = adapters
this.#BackupWriter = BackupWriter
}
getWriterByAdapter(adapter) {
for (const writer of this.#writers) {
if (writer._adapter === adapter) {
return writer
}
}
throw new Error("Can't find writer for adapter")
}
/**
* select the best adapter candidate to write this backup
* if all the adapter infos expose an available info use the one with the more free space
* if none of the adapter exposes this info : choose at random
* if mixed : throw an error
* @returns {RemoteAdapter}
*/
async computeAdapterCandidate() {
const adapters = Object.values(this.#adapters)
const infos = await Promise.all(
adapters.map(async adapter => {
const infos = await adapter._handler.getInfo()
return { adapter, infos }
})
)
const withLimit = infos.filter(({ infos: { available } }) => available > 0).length
if (withLimit !== 0 && withLimit !== infos.length) {
throw new Error(`an Aggregate remote can't use a mix of limited and unlimited storages`)
}
let candidates
if (withLimit === 0) {
debug('no storage limit , choose at random')
candidates = Object.values(this.adapters)
} else {
debug('storage limit , choose at random between those with the max space avilable')
let maxSpace = 0
infos.forEach(({ infos: { available } }) => {
if (available > maxSpace) {
maxSpace = available
}
})
// candidates are the adapter with the same free space , equal to the max free space
candidates = infos.filter(({ infos }) => infos.available === maxSpace).map(({ adapter }) => adapter)
}
const adapterCandidate = candidates[Math.floor(Math.random() * candidates.length)]
debug('adapter candidate is selected ', adapterCandidate._handler._remote.id)
return adapterCandidate
}
async setupWriters() {
debug('Setup writers ')
const settings = this.#props.settings
const allSettings = this.#props.job.settings
Object.entries(this.#adapters).forEach(([remoteId, adapter]) => {
const targetSettings = {
...settings,
...allSettings[remoteId],
skipDeleteOldEntries: true, // delete is handled globally
}
if (targetSettings.exportRetention !== 0) {
const writer = new this.#BackupWriter({
...this.#props,
adapter,
remoteId,
settings: targetSettings,
})
this.#writers.push(writer)
}
})
}
async getEntriesPerAdapter(adapter) {
const scheduleId = this.#props.scheduleId
const vmUuid = this.#props.vmUuid
return (await adapter.listVmBackups(vmUuid, _ => _.scheduleId === scheduleId)).map(entry => ({
...entry,
adapter,
}))
}
async setOldBackups() {
const entriesPerAdapter = await Promise.all(
Object.values(this.#adapters).map(adapter => this.getEntriesPerAdapter(adapter))
)
const entries = entriesPerAdapter
.flat(1)
.filter(_ => !!_)
.sort(compareTimestamp)
const settings = this.#props.settings
this.#oldBackups = getOldEntries(settings.exportRetention - 1, entries, {
longTermRetention: settings.longTermRetention,
timezone: settings.timezone,
})
debug(`got ${this.#oldBackups.length} old backup(s) to delete `)
}
async deleteOldBackupsOnAdapter(adapter, backup) {
throw new Error('not implemented')
}
async deleteOldBackups() {
const byAdapters = new Map()
this.#oldBackups.forEach(({ adapter, ...backup }) => {
const current = byAdapters.has(adapter) ? byAdapters.get(adapter) : []
current.push(backup)
byAdapters.set(adapter, current)
})
await asyncEach(
byAdapters.entries(),
async ([adapter, backups]) => {
debug(`delete ${backups.length} old backup(s) to delete from ${adapter._handler._remote.id}`)
await this.deleteOldBackupsOnAdapter(adapter, backups)
},
{
concurrency: this.#props.deleteConcurrency ?? DEFAULT_AGGREGATED_REMOTE_DELETE_CONCURRENCY,
}
)
}
}

View File

@@ -1,114 +0,0 @@
import { getOldEntries } from '../../_getOldEntries.mjs'
import { createLogger } from '@xen-orchestra/log'
import { compareReplicatedVmDatetime, listReplicatedVms } from './_listReplicatedVms.mjs'
import { asyncMapSettled } from '@xen-orchestra/async-map'
const { debug } = createLogger('xo:backups:AbstractAggregatedXapiWriter')
export class AbstractAggregatedXapiWriter {
#ReplicationWriter
#storageRepositories
#writers = []
get writers() {
return this.#writers
}
mainWriter
#props
get props() {
return this.#props
}
#oldVmReplicaList = []
constructor({ srs, ReplicationWriter, ...props }) {
debug('instantiate AbstractAggregatedXapiWriter')
if (srs.length < 1) {
throw new Error('AggregatedXapiWriter need at least one storage repository to work ')
}
this.#props = props
this.#ReplicationWriter = ReplicationWriter
this.#storageRepositories = srs
}
getWriterBySr(storageRepository) {
for (const writer of this.#writers) {
if (writer._sr === storageRepository) {
return writer
}
}
throw new Error("Can't find writer for storage repository")
}
async computeSRCandidate() {
let maxSpace = 0
this.#storageRepositories.forEach(({ physical_utilisation, physical_size }) => {
if (physical_size - physical_utilisation > maxSpace) {
maxSpace = physical_size - physical_utilisation
}
})
debug(`computeSRCandidate found the max free space ${maxSpace} for vm${this.#props.vmUuid}`)
const srCandidates = this.#storageRepositories.filter(
({ physical_utilisation, physical_size }) => maxSpace === physical_size - physical_utilisation
)
// one at random from the sr with the most free space
const candidate = srCandidates[Math.floor(Math.random() * srCandidates.length)]
debug(
`computeSRCandidate found ${srCandidates.length} sr with ${maxSpace} free size, and chose ${candidate.name_label} for vm${this.#props.vmUuid}`
)
return candidate
}
setOldReplicaList() {
debug(`setOldReplicaList for vm ${this.#props.vmUuid}`)
const scheduleId = this.#props.scheduleId
const vmUuid = this.#props.vmUuid
const settings = this.#props.settings
const replicatedVms = this.#storageRepositories
.map(sr => {
return listReplicatedVms(sr.$xapi, scheduleId, sr.uuid, vmUuid)
})
.flat(1)
.filter(_ => !!_)
.sort(compareReplicatedVmDatetime)
this.#oldVmReplicaList = getOldEntries(settings.copyRetention - 1, replicatedVms)
debug(
`setOldReplicaList found ${replicatedVms.length} replica, and will delete ${this.#oldVmReplicaList.length} (retention ${settings.copyRetention}) for vm ${this.#props.vmUuid}`
)
}
async deleteOldReplicas() {
debug(`deleteOldReplicas will delete ${this.#oldVmReplicaList.length} replicated vms for vm ${this.#props.vmUuid}`)
// destroy the VM on the right xapi
await asyncMapSettled(this.#oldVmReplicaList, async vm => {
debug('will delete old replica', vm.name_label)
await vm.$xapi.VM_destroy(vm.$ref)
})
debug(`deleteOldReplicas deleted ${this.#oldVmReplicaList.length} replicated vms for vm ${this.#props.vmUuid}`)
}
async setupWriters() {
debug('Setup writers ')
const settings = this.#props.settings
const allSettings = this.#props.job.settings
this.#storageRepositories.forEach(storageRepository => {
const targetSettings = {
...settings,
...allSettings[storageRepository.uuid],
skipDeleteOldEntries: true, // delete is handled globally
}
if (targetSettings.copyRetention !== 0) {
const writer = new this.#ReplicationWriter({
...this.#props,
sr: storageRepository,
settings: targetSettings,
})
this.#writers.push(writer)
}
})
}
}

View File

@@ -1,3 +1,6 @@
import { formatFilenameDate } from '../../_filenameDate.mjs'
import { getVmBackupDir } from '../../_getVmBackupDir.mjs'
export class AbstractWriter {
constructor({ config, healthCheckSr, job, vmUuid, scheduleId, settings }) {
this._config = config
@@ -13,4 +16,14 @@ export class AbstractWriter {
afterBackup() {}
healthCheck(sr) {}
_isAlreadyTransferred(timestamp) {
const vmUuid = this._vmUuid
const adapter = this._adapter
const backupDir = getVmBackupDir(vmUuid)
try {
const actualMetadata = JSON.parse(adapter._handler.readFile(`${backupDir}/${formatFilenameDate(timestamp)}.json`))
return actualMetadata
} catch (error) {}
}
}

View File

@@ -9,7 +9,6 @@ import { ImportVmBackup } from '../../ImportVmBackup.mjs'
import { Task } from '../../Task.mjs'
import * as MergeWorker from '../../merge-worker/index.mjs'
import ms from 'ms'
import { getEntryStatus } from '../../_getOldEntries.mjs'
const { info, warn } = createLogger('xo:backups:MixinBackupWriter')
@@ -48,19 +47,6 @@ export const MixinRemoteWriter = (BaseClass = Object) =>
}
}
async getLongTermRetentionTags(currentEntry) {
const settings = this._settings
const scheduleId = this._scheduleId
const vmUuid = this._vmUuid
const adapter = this._adapter
const entries = await adapter.listVmBackups(vmUuid, _ => _.scheduleId === scheduleId)
entries.push(currentEntry)
const buckets = getEntryStatus(entries, currentEntry, settings.longTermRetention, settings.timezone)
return buckets.map(({ duration, dateBucket }) => `${duration}=${dateBucket}`)
}
async beforeBackup() {
const { handler } = this._adapter
const vmBackupDir = this._vmBackupDir
@@ -113,7 +99,7 @@ export const MixinRemoteWriter = (BaseClass = Object) =>
srUuid,
xapi,
settings: {
additionalVmTag: 'xo:no-bak=Health Check',
additionnalVmTag: 'xo:no-bak=Health Check',
},
}).run()
let restoredVm
@@ -130,7 +116,7 @@ export const MixinRemoteWriter = (BaseClass = Object) =>
xapi,
}).run()
} finally {
await xapi.VM_destroy(restoredVm.$ref, { bypassBlockedOperation: true })
await xapi.VM_destroy(restoredVm.$ref)
}
}
)

View File

@@ -29,7 +29,7 @@ export const MixinXapiWriter = (BaseClass = Object) =>
// the SR that the VM has been replicated on
const sr = this._sr
assert.notStrictEqual(sr, undefined, 'SR should be defined before making a health check')
assert.notEqual(this._targetVmRef, undefined, 'A vm should have been transferred to be health checked')
assert.notEqual(this._targetVmRef, undefined, 'A vm should have been transfered to be health checked')
// copy VM
return Task.run(
{
@@ -72,7 +72,7 @@ export const MixinXapiWriter = (BaseClass = Object) =>
xapi,
}).run()
} finally {
healthCheckVmRef && (await xapi.VM_destroy(healthCheckVmRef, { bypassBlockedOperation: true }))
healthCheckVmRef && (await xapi.VM_destroy(healthCheckVmRef))
}
}
)

View File

@@ -5,18 +5,10 @@ const getReplicatedVmDatetime = vm => {
return datetime
}
export const compareReplicatedVmDatetime = (a, b) => (getReplicatedVmDatetime(a) < getReplicatedVmDatetime(b) ? -1 : 1)
const compareReplicatedVmDatetime = (a, b) => (getReplicatedVmDatetime(a) < getReplicatedVmDatetime(b) ? -1 : 1)
/**
*
* @param {Xapi} xapi
* @param {string} scheduleOrJobId
* @param {string} srUuid
* @param {string} vmUuid
* @returns {Array<XoVm>}
*/
export function listReplicatedVms(xapi, scheduleOrJobId, srUuid, vmUuid) {
const all = xapi.objects.indexes.type.VM
const { all } = xapi.objects
const vms = {}
for (const key in all) {
const object = all[key]
@@ -28,7 +20,9 @@ export function listReplicatedVms(xapi, scheduleOrJobId, srUuid, vmUuid) {
'start' in object.blocked_operations &&
(oc[JOB_ID] === scheduleOrJobId || oc[SCHEDULE_ID] === scheduleOrJobId) &&
oc[REPLICATED_TO_SR_UUID] === srUuid &&
oc[VM_UUID] === vmUuid
(oc[VM_UUID] === vmUuid ||
// 2018-03-28, JFT: to catch VMs replicated before this fix
oc[VM_UUID] === undefined)
) {
vms[object.$id] = object
}

View File

@@ -1,317 +0,0 @@
// @ts-check
/**
* @typedef {import('./RemoteDisk.mjs').RemoteDisk} RemoteDisk
* @typedef {import('@xen-orchestra/disk-transform').FileAccessor} FileAccessor
*/
import assert from 'assert'
import { createLogger } from '@xen-orchestra/log'
import { basename, dirname } from 'path'
import { asyncEach } from '@vates/async-each'
// @ts-ignore
const { warn } = createLogger('remote-disk:merge')
/**
* @typedef {Object} MergeState
* @property {{ uuid: string }} child
* @property {{ uuid: string }} parent
* @property {number} currentBlock
* @property {number} mergedDataSize
* @property {'mergeBlocks' | 'cleanup'} step
* @property {number} diskSize
*/
export class MergeRemoteDisk {
/**
* @type {MergeState}
*/
#state = {
child: { uuid: '0' },
parent: { uuid: '0' },
currentBlock: 0,
mergedDataSize: 0,
step: 'mergeBlocks',
diskSize: 0,
}
/**
* @type {string}
*/
#statePath = ''
/**
* @type {boolean}
*/
#isResuming
/**
* @type {Logger | Function}
*/
#logInfo
/**
* @type {number}
*/
#mergeBlockConcurrency
/**
* @type {Function}
*/
#onProgress
/**
* @type {boolean}
*/
#removeUnused
/**
* @type {number}
*/
#writeStateDelay
/**
* @type {number}
*/
#lastStateWrittenAt
/**
* @type {FileAccessor}
*/
#handler
/**
* @param {FileAccessor} handler
* @param {Object} params
* @param {Function} params.onProgress
* @param {Logger | Function} params.logInfo
* @param {boolean} params.removeUnused
* @param {number} params.mergeBlockConcurrency
* @param {number} params.writeStateDelay
*/
constructor(
handler,
{
onProgress = () => {},
logInfo = () => {},
removeUnused = false,
mergeBlockConcurrency = 2,
writeStateDelay = 10e3,
}
) {
this.#handler = handler
this.#logInfo = logInfo
this.#onProgress = onProgress
this.#removeUnused = removeUnused
this.#mergeBlockConcurrency = mergeBlockConcurrency
this.#writeStateDelay = writeStateDelay
this.#isResuming = false
this.#lastStateWrittenAt = 0
}
/**
* @param {RemoteDisk} parentDisk
* @returns {Promise<boolean>} isResuming
*/
async isResuming(parentDisk) {
try {
await this.#handler.readFile(
dirname(parentDisk.getPath()) + '/.' + basename(parentDisk.getPath()) + '.merge.json'
)
return true
} catch (error) {
return false
}
}
/**
* @param {RemoteDisk} parentDisk
* @param {RemoteDisk} childDisk
*/
async merge(parentDisk, childDisk) {
this.#statePath = dirname(parentDisk.getPath()) + '/.' + basename(parentDisk.getPath()) + '.merge.json'
try {
const mergeStateContent = await this.#handler.readFile(this.#statePath)
this.#state = JSON.parse(mergeStateContent)
// work-around a bug introduce in 97d94b795
//
// currentBlock could be `null` due to the JSON.stringify of a `NaN` value
if (this.#state?.currentBlock === null) this.#state.currentBlock = 0
this.#isResuming = true
} catch (error) {
// @ts-ignore
if (error.code !== 'ENOENT') {
warn('problem while checking the merge state', { error })
}
}
try {
/* eslint-disable no-fallthrough */
switch (this.#state?.step ?? 'mergeBlocks') {
case 'mergeBlocks':
await this.#step_mergeBlocks(parentDisk, childDisk)
case 'cleanup':
await this.#step_cleanup(parentDisk, childDisk)
return this.#cleanup(parentDisk, childDisk, true)
default:
warn(`Step ${this.#state?.step} is unknown`, { state: this.#state })
}
/* eslint-enable no-fallthrough */
} catch (error) {
await this.#cleanup(parentDisk, childDisk, false)
throw error
}
}
async #writeState() {
try {
await this.#handler.writeFile(this.#statePath, JSON.stringify(this.#state), { flags: 'w' })
} catch (err) {
warn('failed to write merge state', { error: err })
}
}
async #writeStateThrottled() {
const now = Date.now()
if (now - this.#lastStateWrittenAt > this.#writeStateDelay) {
this.#lastStateWrittenAt = now
await this.#writeState()
}
}
/**
* @param {RemoteDisk} parentDisk
* @param {RemoteDisk} childDisk
*/
async #step_mergeBlocks(parentDisk, childDisk) {
const getMaxBlockCount = childDisk.getMaxBlockCount()
if (this.#isResuming) {
const alreadyMergedBlocks = []
for (let blockId = 0; blockId < this.#state.currentBlock; blockId++) {
if (childDisk.hasBlock(blockId)) {
alreadyMergedBlocks.push(blockId)
}
}
parentDisk.setAllocatedBlocks(alreadyMergedBlocks)
} else {
this.#state.child = { uuid: childDisk.getUuid() ?? 0 }
this.#state.parent = { uuid: parentDisk.getUuid() ?? 0 }
// Finds first allocated block for the 2 following loops
while (this.#state.currentBlock < getMaxBlockCount && !childDisk.hasBlock(this.#state.currentBlock)) {
++this.#state.currentBlock
}
await this.#writeState()
}
await this.#mergeBlocks(parentDisk, childDisk)
await parentDisk.flushMetadata(childDisk)
parentDisk.mergeMetadata(childDisk)
}
/**
* @param {RemoteDisk} parentDisk
* @param {RemoteDisk} childDisk
*/
async #mergeBlocks(parentDisk, childDisk) {
this.#mergeBlockConcurrency =
(await parentDisk.canMergeConcurently()) && (await childDisk.canMergeConcurently())
? this.#mergeBlockConcurrency
: 1
const toMerge = []
for (let block = this.#state.currentBlock; block < childDisk.getMaxBlockCount(); block++) {
if (childDisk.hasBlock(block)) {
toMerge.push(block)
}
}
const nBlocks = toMerge.length
this.#onProgress({ total: nBlocks, done: 0 })
const merging = new Set()
let counter = 0
await asyncEach(
toMerge,
async blockId => {
merging.add(blockId)
const blockSize = await parentDisk.mergeBlock(childDisk, blockId, this.#isResuming)
this.#state.mergedDataSize += blockSize
this.#state.currentBlock = Math.min(...merging) - 1
merging.delete(blockId)
this.#onProgress({ total: nBlocks, done: counter + 1 })
counter++
await this.#writeStateThrottled()
},
{ concurrency: this.#mergeBlockConcurrency }
)
await this.#writeState()
this.#state.diskSize = childDisk.getSizeOnDisk()
this.#onProgress({ total: nBlocks, done: nBlocks })
}
/**
* @param {RemoteDisk} parentDisk
* @param {RemoteDisk} childDisk
*/
async #step_cleanup(parentDisk, childDisk) {
assert.notEqual(this.#state, undefined)
this.#state.step = 'cleanup'
await this.#writeState()
const mergeTargetPath = childDisk.getPath()
// delete intermediate children if needed
if (this.#removeUnused) {
await childDisk.unlink()
}
try {
await parentDisk.rename(mergeTargetPath)
} catch (error) {
// @ts-ignore
if (error.code === 'ENOENT' && this.#isResuming) {
// @ts-ignore
this.#logInfo(`the parent disk was already renamed`, {
parent: parentDisk.getPath(),
mergeTarget: mergeTargetPath,
})
} else {
throw error
}
}
}
/**
* @param {RemoteDisk} parentDisk
* @param {RemoteDisk} childDisk
* @param {boolean} cleanStateFile
*
* @returns {Promise<{mergedDataSize: number, finalDiskSize: number}>} result
*/
async #cleanup(parentDisk, childDisk, cleanStateFile) {
const finalDiskSize = this.#state?.diskSize ?? 0
const mergedDataSize = this.#state?.mergedDataSize ?? 0
await parentDisk.close().catch(warn)
await childDisk.close().catch(warn)
if (cleanStateFile) {
await this.#handler.unlink(this.#statePath).catch(warn)
}
return { mergedDataSize, finalDiskSize }
}
}

View File

@@ -1,204 +0,0 @@
// @ts-check
/**
* @typedef {import('@xen-orchestra/disk-transform').DiskBlock} DiskBlock
*/
import { RandomAccessDisk } from '@xen-orchestra/disk-transform'
export class RemoteDisk extends RandomAccessDisk {
/**
* Abstract
* @param {Object} options
* @param {boolean} options.force
* @returns {Promise<void>}
*/
async init(options = { force: false }) {
throw new Error(`init must be implemented`)
}
/**
* Abstract
* @returns {Promise<void>}
*/
async close() {
throw new Error(`close must be implemented`)
}
/**
* Abstract
* @returns {number}
*/
getVirtualSize() {
throw new Error(`getVirtualSize must be implemented`)
}
/**
* Abstract
* @returns {number} size
*/
getSizeOnDisk() {
throw new Error(`getSizeOnDisk must be implemented`)
}
/**
* @returns {number}
*/
getBlockSize() {
throw new Error(`getBlockSize must be implemented`)
}
/**
* Abstract
* @returns {string}
*/
getPath() {
throw new Error(`getPath must be implemented`)
}
/**
* Abstract
* @returns {string}
*/
getUuid() {
throw new Error(`getUuid must be implemented`)
}
/**
* Abstract
* @returns {Promise<boolean>} canMergeConcurently
*/
async canMergeConcurently() {
throw new Error(`canMergeConcurently must be implemented`)
}
/**
* Abstract
* @returns {number} getMaxBlockCount
*/
getMaxBlockCount() {
throw new Error(`getMaxBlockCount must be implemented`)
}
/**
* Checks if the VHD contains a specific block.
* @param {number} index
* @returns {boolean}
*/
hasBlock(index) {
throw new Error(`hasBlock must be implemented`)
}
/**
* Abstract
* Gets the indexes of all blocks in the VHD.
* @returns {Array<number>}
*/
getBlockIndexes() {
throw new Error(`getBlockIndexes must be implemented`)
}
/**
* Abstract
* Returns the parent non inizialized instance
* @returns {RemoteDisk}
*/
instantiateParent() {
throw new Error(`instantiateParent must be implemented`)
}
/**
* Abstract
* Writes a full block.
* @param {DiskBlock} diskBlock
* @return {Promise<number>} blockSize
*/
async writeBlock(diskBlock) {
throw new Error(`writeBlock must be implemented`)
}
/**
* Abstract
* Reads a specific block from the VHD.
* @param {number} index
* @returns {Promise<DiskBlock>} diskBlock
*/
async readBlock(index) {
throw new Error(`readBlock must be implemented`)
}
/**
* Abstract
* Reads a specific block from the child disk to copy/move it to this disk.
* @param {RemoteDisk} childDisk
* @param {number} index
* @param {boolean} isResumingMerge
* @returns {Promise<number>} blockSize
*/
async mergeBlock(childDisk, index, isResumingMerge) {
throw new Error(`mergeBlock must be implemented`)
}
/**
* Abstract
* Manually set the disk allocated blocks.
* @param {Array<number>} blockIds
* @returns {Promise<void>}
*/
async setAllocatedBlocks(blockIds) {
throw new Error(`setAllocatedBlocks must be implemented`)
}
/**
* Abstract
* @param {RemoteDisk} childDisk
* @returns {Promise<void>}
*/
async flushMetadata(childDisk) {
throw new Error(`flushMetadata must be implemented`)
}
/**
* Abstract
* @param {RemoteDisk} childDisk
*/
mergeMetadata(childDisk) {
throw new Error(`mergeMetadata must be implemented`)
}
/**
* Abstract
* Checks if the VHD is a differencing disk.
* @returns {boolean}
*/
isDifferencing() {
throw new Error(`isDifferencing must be implemented`)
}
/**
* Abstract
* Rename alias/disk
* @param {string} newPath
*/
async rename(newPath) {
throw new Error(`rename must be implemented`)
}
/**
* Abstract
* Deletes alias/disk/disks
*/
async unlink() {
throw new Error(`unlink must be implemented`)
}
/**
* @returns {Promise<RemoteDisk>}
*/
async openParent() {
const parent = await super.openParent()
if (!(parent instanceof RemoteDisk)) {
throw new Error('parent of a RemoteDisk must be also a RemoteDisk')
}
return parent
}
}

View File

@@ -1,894 +0,0 @@
import { test } from 'node:test'
import { strict as assert } from 'node:assert'
import tmp from 'tmp'
import fs from 'fs-extra'
import * as uuid from 'uuid'
import { getHandler } from '@xen-orchestra/fs'
import { pFromCallback } from 'promise-toolbox'
import { VHDFOOTER, VHDHEADER } from '../tests.fixtures.mjs'
import { VhdFile, Constants, VhdDirectory, VhdAbstract } from 'vhd-lib'
import { RemoteVhdDisk } from './RemoteVhdDisk.mjs'
import { RemoteVhdDiskChain } from './RemoteVhdDiskChain.mjs'
import { dirname, basename } from 'node:path'
import { rimraf } from 'rimraf'
import { MergeRemoteDisk } from './MergeRemoteDisk.mjs'
const { beforeEach, afterEach, describe } = test
let tempDir, handler, jobId, vdiId, basePath, relativePath
const rootPath = 'xo-vm-backups/VMUUID'
beforeEach(async () => {
tempDir = await pFromCallback(cb => tmp.dir(cb))
handler = getHandler({ url: `file://${tempDir}` })
await handler.sync()
jobId = uniqueId()
vdiId = uniqueId()
relativePath = `vdis/${jobId}/${vdiId}`
basePath = `${rootPath}/${relativePath}`
await fs.mkdirp(`${tempDir}/${basePath}`)
})
afterEach(async () => {
await rimraf(tempDir)
await handler.forget()
})
const uniqueId = () => uuid.v1()
const uniqueIdBuffer = () => uuid.v1({}, Buffer.alloc(16))
async function generateVhd(path, opts = {}) {
let vhd
let dataPath = path
if (opts.useAlias) {
await handler.mkdir(dirname(path) + '/data/')
dataPath = dirname(path) + '/data/' + basename(path)
}
if (opts.mode === 'directory') {
await handler.mkdir(dataPath)
vhd = new VhdDirectory(handler, dataPath)
} else {
const fd = await handler.openFile(dataPath, 'wx')
vhd = new VhdFile(handler, fd)
}
vhd.header = { ...VHDHEADER, ...opts.header }
vhd.footer = { ...VHDFOOTER, ...opts.footer, uuid: uniqueIdBuffer() }
if (vhd.header.parentUuid) {
vhd.footer.diskType = Constants.DISK_TYPES.DIFFERENCING
} else {
vhd.footer.diskType = Constants.DISK_TYPES.DYNAMIC
}
if (opts.useAlias === true) {
await VhdAbstract.createAlias(handler, path + '.alias.vhd', dataPath)
}
if (opts.blocks) {
for (const blockId of opts.blocks) {
await vhd.writeEntireBlock({ id: blockId, buffer: Buffer.alloc(2 * 1024 * 1024 + 512, blockId) })
}
}
await vhd.writeBlockAllocationTable()
await vhd.writeHeader()
await vhd.writeFooter()
return vhd
}
/**
* RemoteVhdDisk
*/
describe('tests RemoteVhdDisk', { concurrency: 1 }, () => {
test('RemoteVhdDisk should read block', async () => {
// Create VHD disk
await generateVhd(`${basePath}/disk.vhd`, { blocks: [0, 1] })
const disk = new RemoteVhdDisk({ handler, path: `${basePath}/disk.vhd` })
await disk.init({ force: false })
const readBlock = await disk.readBlock(1)
assert.equal(readBlock.data.length, 2097152, 'block should be readable')
})
test('RemoteVhdDisk should write block', async () => {
// Create VHD disk
await generateVhd(`${basePath}/disk.vhd`, { blocks: [0, 1] })
const disk = new RemoteVhdDisk({ handler, path: `${basePath}/disk.vhd` })
await disk.init({ force: false })
const blockId = 2
await disk.writeBlock({ index: blockId, data: Buffer.alloc(2 * 1024 * 1024, blockId) })
const readBlock = await disk.readBlock(blockId)
assert.equal(readBlock.data.length, 2097152, 'block should be readable')
})
test('RemoteVhdDisk should read block on VHD directory', async () => {
// Create VHD disk
await generateVhd(`${basePath}/directory.vhd`, { blocks: [0, 1], mode: 'directory', useAlias: true })
const directory = new RemoteVhdDisk({ handler, path: `${basePath}/directory.vhd.alias.vhd` })
await directory.init({ force: false })
const readBlock = await directory.readBlock(1)
assert.equal(readBlock.data.length, 2097152, 'block should be readable')
})
test('RemoteVhdDisk should write block on VHD directory', async () => {
// Create VHD disk
await generateVhd(`${basePath}/directory.vhd`, { blocks: [0, 1], mode: 'directory', useAlias: true })
const directory = new RemoteVhdDisk({ handler, path: `${basePath}/directory.vhd.alias.vhd` })
await directory.init({ force: false })
const blockId = 2
await directory.writeBlock({ index: blockId, data: Buffer.alloc(2 * 1024 * 1024, blockId) })
const readBlock = await directory.readBlock(blockId)
assert.equal(readBlock.data.length, 2097152, 'block should be readable')
})
test('RemoteVhdDisk should not support non alias VHD directory', async () => {
// Create VHD directory
await generateVhd(`${basePath}/directory.vhd`, { blocks: [0, 1], mode: 'directory' })
const directory = new RemoteVhdDisk({ handler, path: `${basePath}/directory.vhd` })
try {
await directory.init({ force: true })
} catch (err) {
assert.strictEqual(
err.code,
'NOT_SUPPORTED',
'Initializing a vhd directory without using alias should raise a not supported error'
)
return
}
assert.strictEqual(
true,
false,
'Initializing a vhd directory without using alias should raise a not supported error'
)
})
test('RemoteVhdDisk closes disk on init error', async () => {
// Create VHD disk
await generateVhd(`${basePath}/disk.vhd`, { blocks: [0] })
const disk = new RemoteVhdDisk({ handler, path: `${basePath}/disk.vhd` })
// Override the disk close method to monitor its execution
let diskClosed = false
const originalClose = disk.close.bind(disk)
disk.close = async () => {
diskClosed = true
await originalClose()
}
// Make isDirectory throw an error to simulate init failure
disk.isDirectory = async () => {
throw new Error('simulated write error')
}
// Run init and expect it to throw
let threw = false
try {
await disk.init()
} catch (err) {
threw = true
assert.equal(err.message, 'simulated write error')
}
assert.equal(threw, true, 'merge should throw')
assert.equal(diskClosed, true, 'disk disk should be closed on error')
})
})
/**
* RemoteVhdDiskChain
*/
describe('tests RemoteVhdDiskChain', { concurrency: 1 }, () => {
test('RemoteVhdDiskChain should read block', async () => {
// Create parent and child VHDs
const chainParent = await generateVhd(`${basePath}/parent.vhd`, { blocks: [0] })
const chainChild = await generateVhd(`${basePath}/child.vhd`, {
header: {
parentUnicodeName: 'parent.vhd',
parentUuid: chainParent.footer.uuid,
},
blocks: [1],
})
await generateVhd(`${basePath}/child_2.vhd`, {
header: {
parentUnicodeName: 'child.vhd',
parentUuid: chainChild.footer.uuid,
},
blocks: [1],
})
const parent = new RemoteVhdDisk({ handler, path: `${basePath}/parent.vhd` })
const child = new RemoteVhdDisk({ handler, path: `${basePath}/child.vhd` })
const child_2 = new RemoteVhdDisk({ handler, path: `${basePath}/child_2.vhd` })
const diskChain = new RemoteVhdDiskChain({ disks: [parent, child, child_2] })
await diskChain.init({ force: false })
const readBlock = await diskChain.readBlock(1)
assert.equal(readBlock.data.length, 2097152, 'block should be readable')
})
test('RemoteVhdDiskChain should read block on VHD directory', async () => {
// Create parent and child VHD directories
const chainParent = await generateVhd(`${basePath}/parent.vhd`, { blocks: [0], mode: 'directory', useAlias: true })
await generateVhd(`${basePath}/child.vhd`, {
header: {
parentUnicodeName: 'parent.vhd',
parentUuid: chainParent.footer.uuid,
},
blocks: [1],
mode: 'directory',
useAlias: true,
})
const parent = new RemoteVhdDisk({ handler, path: `${basePath}/parent.vhd.alias.vhd` })
const child = new RemoteVhdDisk({ handler, path: `${basePath}/child.vhd.alias.vhd` })
const directoryChain = new RemoteVhdDiskChain({ disks: [parent, child] })
await directoryChain.init({ force: false })
const readBlock = await directoryChain.readBlock(1)
assert.equal(readBlock.data.length, 2097152, 'block should be readable')
})
test('RemoteVhdDiskChain should closes disks on init error', async () => {
// Create parent and child VHDs
const chainParent = await generateVhd(`${basePath}/parent.vhd`, { blocks: [0] })
await generateVhd(`${basePath}/child.vhd`, {
header: {
parentUnicodeName: 'parent.vhd',
parentUuid: chainParent.footer.uuid,
},
blocks: [1],
})
const parent = new RemoteVhdDisk({ handler, path: `${basePath}/parent.vhd` })
const child = new RemoteVhdDisk({ handler, path: `${basePath}/child.vhd` })
const diskChain = new RemoteVhdDiskChain({ disks: [parent, child] })
// Override the disks close method to monitor their execution
let parentClosed = false
const originalParentClose = parent.close.bind(parent)
parent.close = async () => {
parentClosed = true
await originalParentClose()
}
let childClosed = false
const originalChildClose = child.close.bind(child)
child.close = async () => {
childClosed = true
await originalChildClose()
}
// Make isDifferencing throw an error to simulate init failure of the child disk
child.isDifferencing = () => {
throw new Error('simulated write error')
}
// Run init and expect it to throw
let threw = false
try {
await diskChain.init({ force: false })
} catch (err) {
threw = true
assert.equal(err.message, 'simulated write error')
}
assert.equal(threw, true, 'merge should throw')
assert.equal(parentClosed, true, 'parent disk should be closed on error')
assert.equal(childClosed, true, 'child disk should be closed on error')
})
test('RemoteVhdDiskChain should not support non differencing VHD chain children', async () => {
// Create VHD chain
await generateVhd(`${basePath}/disk_1.vhd`, { blocks: [2] })
await generateVhd(`${basePath}/disk_2.vhd`, { blocks: [3] })
const disk1 = new RemoteVhdDisk({ handler, path: `${basePath}/disk_1.vhd` })
const disk2 = new RemoteVhdDisk({ handler, path: `${basePath}/disk_2.vhd` })
const diskChain = new RemoteVhdDiskChain({ disks: [disk1, disk2] })
try {
await diskChain.init({ force: true })
} catch (err) {
assert.strictEqual(err.code, 'NOT_SUPPORTED', "Can't init vhd directory with non differencing child disks")
return
}
assert.strictEqual(true, false, "Can't init vhd directory with non differencing child disks")
})
})
/**
* MergeVhdChain
*/
describe('tests MergeVhdChain', { concurrency: 1 }, () => {
test('mergeVhdChain merges a simple ancestor VHD + child VHD', async () => {
let progressCalls = 0
const onProgress = () => {
progressCalls++
}
// Create ancestor and child VHDs
await generateVhd(`${basePath}/ancestor.vhd`, { 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, { onProgress, removeUnused: true })
const isResumingMerge = await mergeRemoteDisk.isResuming(parent)
assert.ok(!isResumingMerge, 'merge is not resuming')
await parent.init({ force: isResumingMerge })
await child.init({ force: isResumingMerge })
const expectedIndexes = parent.getBlockIndexes().concat(child.getBlockIndexes())
const result = await mergeRemoteDisk.merge(parent, child)
assert.ok(result.finalDiskSize > 0, 'merged disks should have non-zero size')
assert.ok(result.mergedDataSize > 0, 'merged data size should be > 0')
assert.ok(progressCalls > 0, 'onProgress should have been called')
// Check that ancestor was renamed to child
const remainingDisks = await handler.list(basePath)
assert.deepEqual(remainingDisks, ['child.vhd'])
const parentIndexes = parent.getBlockIndexes()
assert.deepEqual(parentIndexes, expectedIndexes, 'all child blocks should be merged into parent')
})
test('mergeVhdChain merges a simple ancestor VHD + child VHD chain', async () => {
let progressCalls = 0
const onProgress = () => {
progressCalls++
}
// Create ancestor and children VHDs
await generateVhd(`${basePath}/ancestor.vhd`, { blocks: [0, 1] })
const chainChild1 = await generateVhd(`${basePath}/child_1.vhd`, { blocks: [2] })
const chainChild2 = await generateVhd(`${basePath}/child_2.vhd`, {
header: {
parentUnicodeName: 'child_1.vhd',
parentUuid: chainChild1.footer.uuid,
},
blocks: [3],
})
await generateVhd(`${basePath}/child_3.vhd`, {
header: {
parentUnicodeName: 'child_2.vhd',
parentUuid: chainChild2.footer.uuid,
},
blocks: [4],
})
const parent = new RemoteVhdDisk({ handler, path: `${basePath}/ancestor.vhd` })
const child1 = new RemoteVhdDisk({ handler, path: `${basePath}/child_1.vhd` })
const child2 = new RemoteVhdDisk({ handler, path: `${basePath}/child_2.vhd` })
const child3 = new RemoteVhdDisk({ handler, path: `${basePath}/child_3.vhd` })
const childDiskChain = new RemoteVhdDiskChain({ disks: [child1, child2, child3] })
const mergeRemoteDisk = new MergeRemoteDisk(handler, { onProgress, removeUnused: true })
const isResumingMerge = await mergeRemoteDisk.isResuming(parent)
assert.ok(!isResumingMerge, 'merge is not resuming')
await parent.init({ force: isResumingMerge })
await child1.init({ force: isResumingMerge })
await child2.init({ force: isResumingMerge })
await child3.init({ force: isResumingMerge })
await childDiskChain.init({ force: isResumingMerge })
const expectedIndexes = parent
.getBlockIndexes()
.concat(child1.getBlockIndexes())
.concat(child2.getBlockIndexes())
.concat(child3.getBlockIndexes())
const result = await mergeRemoteDisk.merge(parent, childDiskChain)
assert.ok(result.finalDiskSize > 0, 'merged disks should have non-zero size')
assert.ok(result.mergedDataSize > 0, 'merged data size should be > 0')
assert.ok(progressCalls > 0, 'onProgress should have been called')
// Check that ancestor was renamed to child
const remainingDisks = await handler.list(basePath)
assert.deepEqual(remainingDisks, ['child_3.vhd']) // TODO: Check that it's the correct child that is remaining.
const parentIndexes = parent.getBlockIndexes()
assert.deepEqual(parentIndexes, expectedIndexes, 'all child blocks should be merged into parent')
})
test('mergeVhdChain merges an alias ancestor VHD + alias child VHD', async () => {
let progressCalls = 0
const onProgress = () => {
progressCalls++
}
// Create ancestor and child VHDs
await generateVhd(`${basePath}/ancestor.vhd`, { blocks: [0, 1], useAlias: true })
await generateVhd(`${basePath}/child.vhd`, { blocks: [2, 3], 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, { onProgress, removeUnused: true })
const isResumingMerge = await mergeRemoteDisk.isResuming(parent)
assert.ok(!isResumingMerge, 'merge is not resuming')
await parent.init({ force: true })
await child.init({ force: true })
const expectedIndexes = parent.getBlockIndexes().concat(child.getBlockIndexes())
const result = await mergeRemoteDisk.merge(parent, child)
assert.ok(result.finalDiskSize > 0, 'merged disks should have non-zero size')
assert.ok(result.mergedDataSize > 0, 'merged data size should be > 0')
assert.ok(progressCalls > 0, 'onProgress should have been called')
// Check that ancestor was renamed to child
const remainingDisks = await handler.list(basePath)
assert.deepEqual(remainingDisks, ['child.vhd.alias.vhd', 'data'])
const remainingDatas = await handler.list(basePath + '/data')
assert.deepEqual(remainingDatas, ['ancestor.vhd'])
const parentIndexes = parent.getBlockIndexes()
assert.deepEqual(parentIndexes, expectedIndexes, 'all child blocks should be merged into parent')
})
test('mergeVhdChain merges an alias ancestor VHD + alias child VHD chain', async () => {
let progressCalls = 0
const onProgress = () => {
progressCalls++
}
// Create ancestor VHD
await generateVhd(`${basePath}/ancestor.vhd`, { blocks: [0, 1], useAlias: true })
// Create child VHD chain
const chainParent = await generateVhd(`${basePath}/child_1.vhd`, { blocks: [2], useAlias: true })
await generateVhd(`${basePath}/child_2.vhd`, {
header: {
parentUnicodeName: 'child_1.vhd',
parentUuid: chainParent.footer.uuid,
},
blocks: [3],
useAlias: true,
})
const parent = new RemoteVhdDisk({ handler, path: `${basePath}/ancestor.vhd.alias.vhd` })
const child1 = new RemoteVhdDisk({ handler, path: `${basePath}/child_1.vhd.alias.vhd` })
const child2 = new RemoteVhdDisk({ handler, path: `${basePath}/child_2.vhd.alias.vhd` })
const childDiskChain = new RemoteVhdDiskChain({ disks: [child1, child2] })
const mergeRemoteDisk = new MergeRemoteDisk(handler, { onProgress, removeUnused: true })
const isResumingMerge = await mergeRemoteDisk.isResuming(parent)
assert.ok(!isResumingMerge, 'merge is not resuming')
await parent.init({ force: isResumingMerge })
await child1.init({ force: isResumingMerge })
await child2.init({ force: isResumingMerge })
await childDiskChain.init({ force: isResumingMerge })
const expectedIndexes = parent.getBlockIndexes().concat(child1.getBlockIndexes()).concat(child2.getBlockIndexes())
const result = await mergeRemoteDisk.merge(parent, childDiskChain)
assert.ok(result.finalDiskSize > 0, 'merged disks should have non-zero size')
assert.ok(result.mergedDataSize > 0, 'merged data size should be > 0')
assert.ok(progressCalls > 0, 'onProgress should have been called')
// Check that ancestor was renamed to child
const remainingDisks = await handler.list(basePath)
assert.deepEqual(remainingDisks, ['child_2.vhd.alias.vhd', 'data'])
const remainingDatas = await handler.list(basePath + '/data')
assert.deepEqual(remainingDatas, ['ancestor.vhd'])
const parentIndexes = parent.getBlockIndexes()
assert.deepEqual(parentIndexes, expectedIndexes, 'all child blocks should be merged into parent')
})
test('mergeVhdChain merges an alias ancestor VHD + child VHD', async () => {
let progressCalls = 0
const onProgress = () => {
progressCalls++
}
// Create ancestor and child VHDs
await generateVhd(`${basePath}/ancestor.vhd`, { blocks: [0, 1], useAlias: true })
await generateVhd(`${basePath}/child.vhd`, { blocks: [2, 3] })
const parent = new RemoteVhdDisk({ handler, path: `${basePath}/ancestor.vhd.alias.vhd` })
const child = new RemoteVhdDisk({ handler, path: `${basePath}/child.vhd` })
const mergeRemoteDisk = new MergeRemoteDisk(handler, { onProgress, removeUnused: true })
const isResumingMerge = await mergeRemoteDisk.isResuming(parent)
assert.ok(!isResumingMerge, 'merge is not resuming')
await parent.init({ force: isResumingMerge })
await child.init({ force: isResumingMerge })
const expectedIndexes = parent.getBlockIndexes().concat(child.getBlockIndexes())
const result = await mergeRemoteDisk.merge(parent, child)
assert.ok(result.finalDiskSize > 0, 'merged disks should have non-zero size')
assert.ok(result.mergedDataSize > 0, 'merged data size should be > 0')
assert.ok(progressCalls > 0, 'onProgress should have been called')
// Check that ancestor was renamed to child
const remainingDisks = await handler.list(basePath)
assert.deepEqual(remainingDisks, ['child.vhd', 'data'])
const remainingDatas = await handler.list(basePath + '/data')
assert.deepEqual(remainingDatas, ['ancestor.vhd'])
const parentIndexes = parent.getBlockIndexes()
assert.deepEqual(parentIndexes, expectedIndexes, 'all child blocks should be merged into parent')
})
test('mergeVhdChain merges an ancestor VHD + alias child VHD', async () => {
let progressCalls = 0
const onProgress = () => {
progressCalls++
}
// Create ancestor and child VHDs
await generateVhd(`${basePath}/ancestor.vhd`, { blocks: [0, 1] })
await generateVhd(`${basePath}/child.vhd`, { blocks: [2, 3], useAlias: true })
const parent = new RemoteVhdDisk({ handler, path: `${basePath}/ancestor.vhd` })
const child = new RemoteVhdDisk({ handler, path: `${basePath}/child.vhd.alias.vhd` })
const mergeRemoteDisk = new MergeRemoteDisk(handler, { onProgress, removeUnused: true })
const isResumingMerge = await mergeRemoteDisk.isResuming(parent)
assert.ok(!isResumingMerge, 'merge is not resuming')
await parent.init({ force: isResumingMerge })
await child.init({ force: isResumingMerge })
const expectedIndexes = parent.getBlockIndexes().concat(child.getBlockIndexes())
const result = await mergeRemoteDisk.merge(parent, child)
assert.ok(result.finalDiskSize > 0, 'merged disks should have non-zero size')
assert.ok(result.mergedDataSize > 0, 'merged data size should be > 0')
assert.ok(progressCalls > 0, 'onProgress should have been called')
// Check that ancestor was renamed to child
const remainingDisks = await handler.list(basePath)
assert.deepEqual(remainingDisks, ['child.vhd.alias.vhd', 'data'])
const remainingDatas = await handler.list(basePath + '/data')
assert.deepEqual(remainingDatas, [])
const parentIndexes = parent.getBlockIndexes()
assert.deepEqual(parentIndexes, expectedIndexes, 'all child blocks should be merged into parent')
})
test('mergeVhdChain merges a alias ancestor VHD directory + alias child VHD directory', async () => {
let progressCalls = 0
const onProgress = () => {
progressCalls++
}
// Create ancestor and child VHD directories
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, { onProgress, removeUnused: true })
const isResumingMerge = await mergeRemoteDisk.isResuming(parent)
assert.ok(!isResumingMerge, 'merge is not resuming')
await parent.init({ force: isResumingMerge })
await child.init({ force: isResumingMerge })
const expectedIndexes = parent.getBlockIndexes().concat(child.getBlockIndexes())
const result = await mergeRemoteDisk.merge(parent, child)
assert.ok(result.finalDiskSize > 0, 'merged disks should have non-zero size')
assert.ok(result.mergedDataSize > 0, 'merged data size should be > 0')
assert.ok(progressCalls > 0, 'onProgress should have been called')
// Check that ancestor was renamed to child
const remainingDisks = await handler.list(basePath)
assert.deepEqual(remainingDisks, ['child.vhd.alias.vhd', 'data'])
const remainingDatas = await handler.list(basePath + '/data')
assert.deepEqual(remainingDatas, ['ancestor.vhd'])
const parentIndexes = parent.getBlockIndexes()
assert.deepEqual(parentIndexes, expectedIndexes, 'all child blocks should be merged into parent')
const ancestorData = await handler.list(`${basePath}/data/ancestor.vhd`)
assert.ok(ancestorData.length > 0, 'ancestor.vhd directory should contain blocks')
})
test('mergeVhdChain closes disks on error', async () => {
// Create parent and child VHDs
await generateVhd(`${basePath}/ancestor.vhd`, { blocks: [0] })
await generateVhd(`${basePath}/child.vhd`, { blocks: [1] })
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 })
const isResumingMerge = await mergeRemoteDisk.isResuming(parent)
assert.ok(!isResumingMerge, 'merge is not resuming')
await parent.init({ force: isResumingMerge })
await child.init({ force: isResumingMerge })
// Override the disks close method to monitor their execution
let parentClosed = false
let childClosed = false
const originalParentClose = parent.close.bind(parent)
parent.close = async () => {
parentClosed = true
await originalParentClose()
}
const originalChildClose = child.close.bind(child)
child.close = async () => {
childClosed = true
await originalChildClose()
}
// Make writeBlock throw an error to simulate failure
parent.writeBlock = async () => {
throw new Error('simulated write error')
}
// Run merge and expect it to throw
let threw = false
try {
await mergeRemoteDisk.merge(parent, child)
} catch (err) {
threw = true
assert.equal(err.message, 'simulated write error')
}
assert.equal(threw, true, 'merge should throw')
assert.equal(parentClosed, true, 'parent disk should be closed on error')
assert.equal(childClosed, true, 'child disk should be closed on error')
})
test('mergeRemoteDisk resumes after interruption', async () => {
// Create parent and child VHDs
await generateVhd(`${basePath}/ancestor.vhd`, { blocks: [0, 1] })
await generateVhd(`${basePath}/child.vhd`, { blocks: [2, 3, 4, 5, 6, 7, 8, 9, 10] })
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, writeStateDelay: 0 })
let isResumingMerge = await mergeRemoteDisk.isResuming(parent)
assert.ok(!isResumingMerge, 'merge is not resuming')
await parent.init({ force: isResumingMerge })
await child.init({ force: isResumingMerge })
const expectedIndexes = parent.getBlockIndexes().concat(child.getBlockIndexes())
// Track write progress
let blocksWritten = 0
const originalWriteBlock = parent.writeBlock.bind(parent)
// Make writeBlock fail on the second block
parent.writeBlock = async diskBlock => {
if (blocksWritten === 5) {
throw new Error('simulated interruption')
}
blocksWritten++
return originalWriteBlock(diskBlock)
}
// 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` })
const child2 = new RemoteVhdDisk({ handler, path: `${basePath}/child.vhd` })
isResumingMerge = await mergeRemoteDisk.isResuming(parent)
assert.ok(isResumingMerge, 'merge is resuming')
await parent2.init({ force: isResumingMerge })
await child2.init({ force: isResumingMerge })
const originalWriteBlock2 = parent2.writeBlock.bind(parent2)
// Make writeBlock fail on the second block
parent2.writeBlock = async diskBlock => {
blocksWritten++
return originalWriteBlock2(diskBlock)
}
// Resume merge
const result = await mergeRemoteDisk.merge(parent2, child2)
// Verify merge completed
assert.ok(result.finalDiskSize > 0, 'final disk size should be > 0')
assert.ok(result.mergedDataSize > 0, 'merged data size should be > 0')
// Verify state file removed after successful resume
assert.equal(
(await handler.list(dirname(parent2.getPath()))).includes(`.${basename(parent2.getPath())}.merge.json`),
false,
'merge state file should be removed after successful resume'
)
// Verify all blocks present in parent
const parentIndexes = parent2.getBlockIndexes()
assert.deepEqual(parentIndexes, expectedIndexes, 'all child blocks should be merged into parent')
})
test('mergeRemoteDisk resumes after interruption with VHD directory', async () => {
// Track write progress
let blocksWritten = 0
// Create parent and child VHDs
await generateVhd(`${basePath}/ancestor.vhd`, { blocks: [0, 1], useAlias: true, mode: 'directory' })
await generateVhd(`${basePath}/child.vhd`, {
blocks: [2, 3, 4, 5, 6, 7, 8, 9, 10],
useAlias: true,
mode: 'directory',
})
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,
mergeBlockConcurrency: 4,
})
let isResumingMerge = await mergeRemoteDisk.isResuming(parent)
assert.ok(!isResumingMerge, 'merge is not resuming')
await parent.init({ force: isResumingMerge })
await child.init({ force: isResumingMerge })
const expectedIndexes = parent.getBlockIndexes().concat(child.getBlockIndexes())
const originalMergeBlock = parent.mergeBlock.bind(parent)
// Make writeBlock fail on the second block
parent.mergeBlock = async (disk, index, isResumingMerge) => {
if (blocksWritten === 4) {
throw new Error('simulated interruption')
}
blocksWritten++
return originalMergeBlock(disk, 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` })
isResumingMerge = await mergeRemoteDisk.isResuming(parent)
assert.ok(isResumingMerge, 'merge is resuming')
await parent2.init({ force: isResumingMerge })
await child2.init({ force: isResumingMerge })
const originalWriteBlock2 = parent2.writeBlock.bind(parent2)
// Make writeBlock fail on the second block
parent2.writeBlock = async diskBlock => {
blocksWritten++
return originalWriteBlock2(diskBlock)
}
// Resume merge
const result = await mergeRemoteDisk.merge(parent2, child2)
// Verify merge completed
assert.ok(result.finalDiskSize > 0, 'final disk size should be > 0')
assert.ok(result.mergedDataSize > 0, 'merged data size should be > 0')
// Verify state file removed after successful resume
assert.equal(
(await handler.list(dirname(parent2.getPath()))).includes(`.${basename(parent2.getPath())}.merge.json`),
false,
'merge state file should be removed after successful resume'
)
// Verify all blocks present in parent BAT
const parentIndexes = parent2.getBlockIndexes()
assert.deepEqual(parentIndexes, expectedIndexes, 'all child blocks should be merged into parent')
// Verify all blocks actually present in parent
for (const index of expectedIndexes) {
const parentBlockPath = parent2.getBlockPath(index)
let size
try {
size = await handler.getSize(parentBlockPath)
} catch {
assert.fail(`block ${index} is missing from parent directory`)
}
assert.ok(size >= parent2.getBlockSize(), `block ${index} complete`)
}
})
})

View File

@@ -0,0 +1,185 @@
// @ts-check
/**
* @typedef {import('@xen-orchestra/disk-transform').FileAccessor} FileAccessor
* @typedef {import('@xen-orchestra/disk-transform').DiskBlock} DiskBlock
* @typedef {import('@xen-orchestra/disk-transform').Disk} Disk
* @typedef {import('vhd-lib/Vhd/VhdDirectory.js').VhdDirectory} VhdDirectory
* @typedef {import('vhd-lib/Vhd/VhdFile.js').VhdFile} VhdFile
*/
import { openVhd } from 'vhd-lib'
import { DISK_TYPES } from 'vhd-lib/_constants.js'
import { dirname, join } from 'node:path'
import { RandomAccessDisk, ReadAhead } from '@xen-orchestra/disk-transform'
import { getHandler } from '@xen-orchestra/fs'
import { asyncEach } from '@vates/async-each'
/**
* Represents a remote VHD (Virtual Hard Disk) that extends RandomAccessDisk.
*/
export class RemoteVhd extends RandomAccessDisk {
/**
* @type {string}
*/
#path
/**
* @type {FileAccessor}
*/
#handler
/**
* @type {VhdFile | VhdDirectory | undefined}
*/
#vhd
/**
* @type {boolean | undefined}
*/
#isDifferencing
/**
* @type {() => any}
*/
#dispose = () => {}
/**
* @returns {string}
*/
get path() {
return this.#path
}
/**
* @param {Object} params
* @param {FileAccessor} params.handler
* @param {string} params.path
*/
constructor({ handler, path }) {
super()
// @todo : ensure this is the full path from the root of the remote
this.#path = path
this.#handler = handler
}
/**
* @returns {number}
*/
getVirtualSize() {
if (this.#vhd === undefined) {
throw new Error(`can't call getvirtualsize of a RemoteVhd before init`)
}
return this.#vhd.footer.currentSize
}
/**
* @returns {number}
*/
getBlockSize() {
return 2 * 1024 * 1024
}
/**
* Initializes the VHD.
* @returns {Promise<void>}
*/
async init() {
const { value, dispose } = await openVhd(this.#handler, this.#path)
this.#vhd = value
this.#dispose = dispose
await this.#vhd.readBlockAllocationTable()
this.#isDifferencing = value.footer.diskType === DISK_TYPES.DIFFERENCING
}
/**
* Closes the VHD.
* @returns {Promise<void>}
*/
async close() {
await this.#dispose()
}
/**
* Checks if the VHD contains a specific block.
* @param {number} index
* @returns {boolean}
*/
hasBlock(index) {
if (this.#vhd === undefined) {
throw new Error(`can't call hasblock of a RemoteVhd before init`)
}
return this.#vhd.containsBlock(index)
}
/**
* Gets the indexes of all blocks in the VHD.
* @returns {Array<number>}
*/
getBlockIndexes() {
if (this.#vhd === undefined) {
throw new Error(`can't call getBlockIndexes of a RemoteVhd before init`)
}
const index = []
for (let blockIndex = 0; blockIndex < this.#vhd.header.maxTableEntries; blockIndex++) {
if (this.hasBlock(blockIndex)) {
index.push(blockIndex)
}
}
console.log('BLOCK INDEX ',{index})
return index
}
/**
* Reads a specific block from the VHD.
* @param {number} index
* @returns {Promise<DiskBlock>}
*/
async readBlock(index) {
if (this.#vhd === undefined) {
throw new Error(`can't call readBlock of a RemoteVhd before init`)
}
const { data } = await this.#vhd.readBlock(index)
return {
index,
data,
}
}
/**
*
* @returns {RandomAccessDisk}
*/
instantiateParent() {
if (this.#vhd === undefined) {
throw new Error(`can't call openParent of a RemoteVhd before init`)
}
const parentPath = this.#vhd.header.parentUnicodeName
const fullParentPath = join(dirname(this.#path), parentPath)
if (!parentPath) {
throw new Error(`Disk ${this.#path} doesn't have parents`)
}
const parent = new RemoteVhd({ handler: this.#handler, path: fullParentPath })
return parent
}
/**
* Checks if the VHD is a differencing disk.
* @returns {boolean}
*/
isDifferencing() {
if (this.#isDifferencing === undefined) {
throw new Error(`can't call isDifferencing of a RemoteVhd before init`)
}
return this.#isDifferencing
}
}
/*
const handler = getHandler({url:'file:///mnt/hosts/'})
await handler.sync()
const disk = new RemoteVhd({handler, path: '/fba0e581-8d94-4741-b1a0-02ec8ce5842a.vhd'})
await disk.init()
const start = Date.now()
await asyncEach(disk.diskBlocks(),async block=>process.stdout.write('.'))
console.log(' duration ', (Date.now() - start)/1000 )*/

View File

@@ -1,459 +0,0 @@
// @ts-check
/**
* @typedef {import('vhd-lib/Vhd/VhdDirectory.js').VhdDirectory} VhdDirectory
* @typedef {import('vhd-lib/Vhd/VhdFile.js').VhdFile} VhdFile
* @typedef {import('vhd-lib/_createFooterHeader').VhdFooter} VhdFooter
* @typedef {import('@xen-orchestra/disk-transform').DiskBlock} DiskBlock
* @typedef {import('@xen-orchestra/disk-transform').FileAccessor} FileAccessor
*
*/
import { openVhd, VhdAbstract, VhdDirectory } from 'vhd-lib'
import { RemoteDisk } from './RemoteDisk.mjs'
import { DISK_TYPES } from 'vhd-lib/_constants.js'
import { isVhdAlias, resolveVhdAlias } from 'vhd-lib/aliases.js'
// import { set as setBitmap } from 'vhd-lib/_bitmap.js'
import { stringify } from 'uuid'
import { dirname, join } from 'node:path'
export class RemoteVhdDisk extends RemoteDisk {
/**
* @type {string}
*/
#path
/**
* @type {FileAccessor}
*/
#handler
/**
* @type {VhdFile | VhdDirectory | undefined}
*/
#vhd
/**
* @type {boolean | undefined}
*/
#isDifferencing
/**
* @type {number}
*/
#blockSize = 2 * 1024 * 1024
/**
* @type {number}
*/
#bitmapSize = 512
/**
* @type {() => any}
*/
#dispose = () => {}
/**
* @param {Object} params
* @param {FileAccessor} params.handler
* @param {string} params.path
*/
constructor({ handler, path }) {
super()
// @todo : ensure this is the full path from the root of the remote
this.#path = path
this.#handler = handler
}
/**
* @param {Object} [options]
* @param {boolean} [options.force=false]
* @returns {Promise<void>}
*/
async init(options = {}) {
if (this.#vhd === undefined) {
try {
const { value, dispose } = await openVhd(this.#handler, await resolveVhdAlias(this.#handler, this.#path), {
checkSecondFooter: !options.force,
})
this.#vhd = value
if ((await this.isDirectory()) && !isVhdAlias(this.#path)) {
this.#vhd = undefined
throw Object.assign(new Error("Can't init vhd directory without using alias"), { code: 'NOT_SUPPORTED' })
}
this.#dispose = dispose
await this.#vhd.readBlockAllocationTable()
this.#isDifferencing = value.footer.diskType === DISK_TYPES.DIFFERENCING
} catch (error) {
await this.close()
throw error
}
}
}
/**
* Closes the VHD.
* @returns {Promise<void>}
*/
async close() {
await this.#dispose()
}
/**
* @returns {number}
*/
getVirtualSize() {
if (this.#vhd === undefined) {
throw new Error(`can't call getVirtualSize of a RemoteVhdDisk before init`)
}
return this.#vhd.footer.currentSize
}
/**
* @returns {number} size
*/
getSizeOnDisk() {
if (this.#vhd === undefined) {
throw new Error(`can't call getVirtualSize of a RemoteVhdDisk before init`)
}
return this.#vhd.streamSize()
}
/**
* @returns {number}
*/
getBlockSize() {
return this.#blockSize
}
/**
* @returns {string}
*/
getPath() {
return this.#path
}
/**
* @returns {string}
*/
getUuid() {
if (this.#vhd === undefined) {
throw new Error(`can't call getUid of a RemoteVhdDisk before init`)
}
return stringify(this.#vhd.footer.uuid)
}
/**
* @returns {string}
*/
getParentUuid() {
if (this.#vhd === undefined) {
throw new Error(`can't call getParentUid of a RemoteVhdDisk before init`)
}
return stringify(this.#vhd.header.parentUuid)
}
/**
* @returns {Promise<boolean>} canMergeConcurently
*/
async canMergeConcurently() {
return await this.isDirectory()
}
/**
* @returns {number} getMaxBlockCount
*/
getMaxBlockCount() {
if (this.#vhd === undefined) {
throw new Error(`can't call getMaxBlockCount of a RemoteVhdDisk before init`)
}
return this.#vhd.header.maxTableEntries
}
/**
* Checks if the VHD contains a specific block.
* @param {number} index
* @returns {boolean}
*/
hasBlock(index) {
if (this.#vhd === undefined) {
throw new Error(`can't call hasblock of a RemoteVhdDisk before init`)
}
return this.#vhd.containsBlock(index)
}
/**
* Gets the indexes of all blocks in the VHD.
* @returns {Array<number>}
*/
getBlockIndexes() {
if (this.#vhd === undefined) {
throw new Error(`can't call getBlockIndexes of a RemoteVhdDisk before init`)
}
const indexes = []
for (let blockIndex = 0; blockIndex < this.#vhd.header.maxTableEntries; blockIndex++) {
if (this.hasBlock(blockIndex)) {
indexes.push(blockIndex)
}
}
return indexes
}
/**
* Returns the parent non inizialized instance
* @returns {RemoteDisk}
*/
instantiateParent() {
if (this.#vhd === undefined) {
throw new Error(`can't call instantiateParent of a RemoteVhdDisk before init`)
}
const parentPath = this.#vhd.header.parentUnicodeName
const fullParentPath = join(dirname(this.#path), parentPath)
if (!parentPath) {
throw new Error(`disk ${this.#path} doesn't have parents`)
}
const parent = new RemoteVhdDisk({ handler: this.#handler, path: fullParentPath })
return parent
}
/**
* Writes a full block into this VHD.
* @param {DiskBlock} diskBlock
* @return {Promise<number>} blockSize
*/
async writeBlock(diskBlock) {
if (this.#vhd === undefined) {
throw new Error(`can't call readBlock of a RemoteVhdDisk before init`)
}
await this.#vhd.writeEntireBlock({
id: diskBlock.index,
buffer: Buffer.concat([Buffer.alloc(this.#bitmapSize, 255), diskBlock.data]),
})
return this.getBlockSize()
}
/**
* Reads a specific block from the VHD.
* @param {number} index
* @returns {Promise<DiskBlock>} diskBlock
*/
async readBlock(index) {
if (this.#vhd === undefined) {
throw new Error(`can't call readBlock of a RemoteVhdDisk before init`)
}
const { data } = await this.#vhd.readBlock(index)
return {
index,
data,
}
}
/**
* Reads a specific block from the child disk to copy/move it to this disk.
* @param {RemoteDisk} childDisk
* @param {number} index
* @param {boolean} isResumingMerge
* @returns {Promise<number>} blockSize
*/
async mergeBlock(childDisk, index, isResumingMerge) {
if ((await this.isDirectory()) && childDisk instanceof RemoteVhdDisk && (await childDisk.isDirectory())) {
try {
await this.#handler.rename(childDisk.getBlockPath(index), this.getBlockPath(index))
this.setAllocatedBlocks([index])
} catch (error) {
// @ts-ignore
if (error.code === 'ENOENT' && isResumingMerge === true) {
// when resuming, the blocks moved since the last merge state write are
// not in the child anymore but it should be ok
// 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
} else {
this.setAllocatedBlocks([index])
}
} else {
throw error
}
}
return this.getBlockSize()
} else {
return this.writeBlock(await childDisk.readBlock(index))
}
}
/**
* Gets a specific block path from the VHD directory.
* @param {number} index
* @returns {string} blockPath
*/
getBlockPath(index) {
if (this.#vhd === undefined) {
throw new Error(`can't call readBlock of a RemoteVhdDisk before init`)
}
if (this.#vhd instanceof VhdDirectory) {
return this.#vhd.getFullBlockPath(index)
} else {
throw new Error(`can't call getBlockPath of non directory VHD`)
}
}
/**
* Manually set the disk allocated blocks.
* @param {Array<number>} blockIds
* @returns {Promise<void>}
*/
async setAllocatedBlocks(blockIds) {
if (this.#vhd instanceof VhdDirectory) {
this.#vhd.setAllocatedBlocks(blockIds)
}
}
/**
* Writes Block Allocation Table
* @param {RemoteDisk} childDisk
* @returns {Promise<void>}
*/
async flushMetadata(childDisk) {
if (this.#vhd === undefined) {
throw new Error(`can't call flushMetadata of a RemoteVhdDisk before init`)
}
await this.#vhd.writeBlockAllocationTable()
}
/**
* @returns {VhdFooter}
*/
getMetadata() {
if (this.#vhd === undefined) {
throw new Error(`can't call getMetadata of a RemoteVhdDisk before init`)
}
return this.#vhd.footer
}
/**
* @param {RemoteVhdDisk} childDisk
*/
async mergeMetadata(childDisk) {
const childDiskMetadata = childDisk.getMetadata()
if (this.#vhd === undefined) {
throw new Error(`can't call mergeMetadata of a RemoteVhdDisk before init`)
}
// @ts-ignore
this.#vhd.footer.currentSize = childDiskMetadata.currentSize
// @ts-ignore
this.#vhd.footer.diskGeometry = { ...childDiskMetadata.diskGeometry }
// @ts-ignore
this.#vhd.footer.originalSize = childDiskMetadata.originalSize
// @ts-ignore
this.#vhd.footer.timestamp = childDiskMetadata.timestamp
// @ts-ignore
this.#vhd.footer.uuid = childDiskMetadata.uuid
await this.#vhd.writeFooter()
}
/**
* Checks if the VHD is a differencing disk.
* @returns {boolean}
*/
isDifferencing() {
if (this.#isDifferencing === undefined) {
throw new Error(`can't call isDifferencing of a RemoteVhdDisk before init`)
}
return this.#isDifferencing
}
/**
* Rename alias/disk
* @param {string} newPath
*/
async rename(newPath) {
if (isVhdAlias(newPath)) {
const dataPath = await resolveVhdAlias(this.#handler, this.#path)
await this.#handler.unlink(this.#path)
await this.#handler.unlink(newPath)
await VhdAbstract.createAlias(this.#handler, newPath, dataPath)
this.#path = newPath
} else {
try {
await this.#handler.unlink(newPath)
} catch (err) {
if (err && typeof err === 'object' && 'code' in err && err.code === 'EISDIR') {
await this.#handler.rmtree(newPath).catch(() => {})
}
}
await this.#handler.rename(this.#path, newPath)
this.#path = newPath
}
}
/**
* Deletes disk
*/
async unlink() {
if (this.#vhd === undefined) {
throw new Error(`can't call unlink of a RemoteVhdDisk before init`)
}
await this.close()
if (isVhdAlias(this.#path)) {
try {
await this.#handler.unlink(await resolveVhdAlias(this.#handler, this.#path))
} catch (err) {
if (err && typeof err === 'object' && 'code' in err && err.code === 'EISDIR') {
await this.#handler.rmtree(await resolveVhdAlias(this.#handler, this.#path)).catch(() => {})
}
}
}
try {
await this.#handler.unlink(this.#path)
} catch (err) {
if (err && typeof err === 'object' && 'code' in err && err.code === 'EISDIR') {
await this.#handler.rmtree(this.#path).catch(() => {})
}
}
}
/**
* Check if the disk is a VHD directory.
* @returns {Promise<boolean>}
*/
async isDirectory() {
if (this.#vhd === undefined) {
throw new Error(`can't call isDirectory of a RemoteVhdDisk before init`)
}
return this.#vhd instanceof VhdDirectory
}
}

View File

@@ -1,271 +0,0 @@
// @ts-check
/**
* @typedef {import('./RemoteVhdDisk.mjs').VhdFooter} VhdFooter
* @typedef {import('./RemoteVhdDisk.mjs').RemoteVhdDisk} RemoteVhdDisk
* @typedef {import('@xen-orchestra/disk-transform').DiskBlock} DiskBlock
* @typedef {import('@xen-orchestra/disk-transform').FileAccessor} FileAccessor
*/
import { RemoteDisk } from './RemoteDisk.mjs'
export class RemoteVhdDiskChain extends RemoteDisk {
/**
* @type {RemoteVhdDisk[]}
*/
#disks
/**
* @type {number}
*/
#blockSize = 2 * 1024 * 1024
/**
* @type {number}
*/
#headerSize = 1024
/**
* @type {number}
*/
#footerSize = 512
/**
* @type {number}
*/
#bitmapSize = 512
/**
* @param {Object} params
* @param {FileAccessor} params.handler
* @param {RemoteVhdDisk[]} params.disks
*/
constructor({ disks }) {
super()
this.#disks = disks
}
/**
* Initializes the VHD chain
* @param {Object} options
* @param {boolean} options.force
* @returns {Promise<void>}
*/
async init(options) {
try {
await Promise.all(this.#disks.map(disk => disk.init(options)))
let parentUuid = ''
for (const [index, disk] of this.#disks.entries()) {
if (index !== 0) {
if (!disk.isDifferencing()) {
throw Object.assign(new Error("Can't init vhd directory with non differencing child disks"), {
code: 'NOT_SUPPORTED',
})
}
if (disk.getParentUuid() !== parentUuid) {
throw Object.assign(new Error("Can't init vhd directory with incorrect parentage"), {
code: 'NOT_SUPPORTED',
})
}
}
parentUuid = disk.getUuid()
}
} catch (error) {
await this.close()
throw error
}
}
/**
* Closes the VHD.
* @returns {Promise<void>}
*/
async close() {
await Promise.all(this.#disks.map(disk => disk.close()))
}
/**
* @returns {number}
*/
getVirtualSize() {
return this.#disks[this.#disks.length - 1].getVirtualSize()
}
/**
* @returns {number} size
*/
getSizeOnDisk() {
const batEntrySize = 4
const sectorSize = 512
const batSize = Math.ceil((this.getMaxBlockCount() * batEntrySize) / sectorSize) * sectorSize
return (
this.#footerSize +
this.#headerSize +
batSize +
this.getBlockIndexes().length * (this.#blockSize + this.#bitmapSize) +
this.#footerSize
)
}
/**
* @returns {number}
*/
getBlockSize() {
return this.#disks[this.#disks.length - 1].getBlockSize()
}
/**
* @returns {string}
*/
getPath() {
return this.#disks[this.#disks.length - 1].getPath()
}
/**
* @returns {string}
*/
getUuid() {
return this.#disks[this.#disks.length - 1].getUuid()
}
/**
* @returns {Promise<boolean>} canMergeConcurently
*/
async canMergeConcurently() {
for (const disk of this.#disks) {
if (!(await disk.isDirectory())) {
return true
}
}
return false
}
/**
* @returns {number} getMaxBlockCount
*/
getMaxBlockCount() {
return this.#disks[this.#disks.length - 1].getMaxBlockCount()
}
/**
* Checks if the VHD contains a specific block.
* @param {number} index
* @returns {boolean}
*/
hasBlock(index) {
for (const disk of this.#disks) {
if (disk.hasBlock(index)) {
return true
}
}
return false
}
/**
* Gets the indexes of all blocks in the VHD.
* @returns {Array<number>}
*/
getBlockIndexes() {
const indexes = new Set()
for (const disk of this.#disks) {
for (const index of disk.getBlockIndexes()) {
indexes.add(index)
}
}
return [...indexes]
}
/**
* Returns the parent non inizialized instance
* @returns {RemoteDisk}
*/
instantiateParent() {
return this.#disks[0].instantiateParent()
}
/**
* Writes a full block into this VHD.
* @param {DiskBlock} diskBlock
* @return {Promise<number>} blockSize
*/
async writeBlock(diskBlock) {
throw new Error(`Can't write blocks into a disk chain`)
}
/**
* Reads a specific block from the VHD.
* @param {number} index
* @returns {Promise<DiskBlock>} diskBlock
*/
async readBlock(index) {
const reversedDisks = this.#disks.slice().reverse()
for (const disk of reversedDisks) {
if (disk.hasBlock(index)) {
return disk.readBlock(index)
}
}
throw new Error(`Block ${index} not found in chain `)
}
/**
* Reads a specific block from the child disk to copy/move it to this disk.
* @param {RemoteDisk} childDisk
* @param {number} index
* @param {boolean} isResumingMerge
* @returns {Promise<number>} blockSize
*/
async mergeBlock(childDisk, index, isResumingMerge) {
throw new Error(`Can't merge block into a disk chain`)
}
/**
* @returns {VhdFooter}
*/
getMetadata() {
return this.#disks[this.#disks.length - 1].getMetadata()
}
/**
* @param {RemoteVhdDisk} childDisk
* @returns {Promise<void>}
*/
async flushMetadata(childDisk) {
throw new Error(`Can't flush metadata on a disk chain`)
}
/**
* @param {RemoteVhdDisk} childDisk
*/
mergeMetadata(childDisk) {
throw new Error(`Can't merge metadata on a disk chain`)
}
/**
* Checks if the VHD is a differencing disk.
* @returns {boolean}
*/
isDifferencing() {
return this.#disks[0].isDifferencing()
}
/**
* Abstract
* Rename alias/disk
* @param {string} newPath
*/
async rename(newPath) {
throw new Error(`Can't rename a disk chain`)
}
/**
* Deletes all the disks
*/
async unlink() {
for (const disk of this.#disks) {
await disk.unlink()
}
}
}

View File

@@ -2,14 +2,12 @@
/**
*
* @typedef {import('../../disk-transform/src/FileAccessor.mjs').FileAccessor} FileAccessor
* @typedef {import('./RemoteDisk.mjs').RemoteDisk} RemoteDisk
*/
import { DiskChain } from '@xen-orchestra/disk-transform'
import { RemoteVhdDisk } from './RemoteVhdDisk.mjs'
import { RemoteVhd } from './RemoteVhd.mjs'
import { defer } from 'golike-defer'
/**
* @param {any} $defer
* @param {Object} params
* @param {FileAccessor} params.handler
* @param {string} params.path
@@ -17,18 +15,15 @@ import { defer } from 'golike-defer'
*/
async function _openDiskChain($defer, { handler, path, until }) {
let disk
/**
* @type {Array<RemoteDisk>}
*/
const disks = []
$defer.onFailure(() => Promise.all(disks.map(disk => disk.close())))
disk = new RemoteVhdDisk({ handler, path })
disk = new RemoteVhd({ handler, path })
await disk.init()
disks.push(disk)
while (disk.isDifferencing()) {
disk = await disk.openParent()
if (disk.getPath() === until) {
if (disk.path === until) {
break
}
disks.unshift(disk)

View File

@@ -18,8 +18,6 @@ function formatVmBackup(backup) {
}
}
return {
type: 'xo-vm-backup',
backupRepository: backup.backupRepositoryId,
disks:
backup.vhds === undefined
? []
@@ -40,24 +38,17 @@ function formatVmBackup(backup) {
size: backup.size,
timestamp: backup.timestamp,
vm: {
uuid: backup.vm.uuid,
name_description: backup.vm.name_description,
name_label: backup.vm.name_label,
tags: backup.vm.tags,
},
tags: backup.tags ?? [],
differencingVhds,
dynamicVhds,
withMemory,
}
}
/**
* format all backups as returned by RemoteAdapter#listAllVmBackups()
* @param {Record<string, object[]>} backupsByVM
* @param {string} backupRepositoryId
* @returns {Record<string, object[]>}
*/
export function formatVmBackups(backupsByVM, backupRepositoryId) {
return mapValues(backupsByVM, backups => backups.map(backup => formatVmBackup({ ...backup, backupRepositoryId })))
// format all backups as returned by RemoteAdapter#listAllVmBackups()
export function formatVmBackups(backupsByVM) {
return mapValues(backupsByVM, backups => backups.map(formatVmBackup))
}

View File

@@ -8,7 +8,7 @@
"type": "git",
"url": "https://github.com/vatesfr/xen-orchestra.git"
},
"version": "0.68.2",
"version": "0.63.0",
"engines": {
"node": ">=14.18"
},
@@ -19,20 +19,20 @@
"dependencies": {
"@iarna/toml": "^2.2.5",
"@kldzj/stream-throttle": "^1.1.1",
"@vates/async-each": "^1.0.1",
"@vates/async-each": "^1.0.0",
"@vates/cached-dns.lookup": "^1.0.0",
"@vates/compose": "^2.1.0",
"@vates/decorate-with": "^2.1.0",
"@vates/disposable": "^0.1.6",
"@vates/fuse-vhd": "^2.1.2",
"@vates/generator-toolbox": "^1.1.0",
"@vates/nbd-client": "^3.2.3",
"@vates/generator-toolbox": "^1.0.4",
"@vates/nbd-client": "^3.1.4",
"@vates/parse-duration": "^0.1.1",
"@xen-orchestra/async-map": "^0.1.2",
"@xen-orchestra/disk-transform": "^1.2.1",
"@xen-orchestra/fs": "^4.6.6",
"@xen-orchestra/disk-transform": "^1.1.0",
"@xen-orchestra/fs": "^4.6.2",
"@xen-orchestra/log": "^0.7.1",
"@xen-orchestra/qcow2": "^1.1.2",
"@xen-orchestra/qcow2": "^1.0.0",
"@xen-orchestra/template": "^0.1.0",
"app-conf": "^3.0.0",
"compare-versions": "^6.0.0",
@@ -48,21 +48,21 @@
"parse-pairs": "^2.0.0",
"promise-toolbox": "^0.21.0",
"proper-lockfile": "^4.1.2",
"tar": "^7.5.3",
"tar": "^6.1.15",
"uuid": "^9.0.0",
"value-matcher": "^0.2.0",
"vhd-lib": "^4.14.7",
"xen-api": "^4.7.6",
"vhd-lib": "^4.14.0",
"xen-api": "^4.7.3",
"yazl": "^2.5.1"
},
"devDependencies": {
"fs-extra": "^11.1.0",
"rimraf": "^6.0.1",
"rimraf": "^5.0.1",
"sinon": "^18.0.0",
"tmp": "^0.2.1"
},
"peerDependencies": {
"@xen-orchestra/xapi": "^8.6.6"
"@xen-orchestra/xapi": "^8.3.3"
},
"license": "AGPL-3.0-or-later",
"author": {

View File

@@ -18,7 +18,7 @@
"preferGlobal": true,
"dependencies": {
"golike-defer": "^0.5.1",
"xen-api": "^4.7.6"
"xen-api": "^4.7.3"
},
"scripts": {
"postversion": "npm publish"

View File

@@ -1,13 +1,13 @@
{
"name": "@xen-orchestra/disk-transform",
"version": "1.2.1",
"version": "1.1.0",
"main": "./dist/index.mjs",
"license": "MIT",
"private": false,
"type": "module",
"devDependencies": {
"@eslint/js": "^9.19.0",
"rimraf": "^6.0.1",
"rimraf": "^5.0.1",
"@types/node": "^22.3.0",
"typescript": "~5.6",
"typescript-eslint": "^8.23.0"
@@ -34,7 +34,7 @@
"node": ">=20.17"
},
"dependencies": {
"vhd-lib": "^4.14.7",
"@vates/generator-toolbox": "^1.1.0"
"vhd-lib": "^4.14.0",
"@vates/generator-toolbox": "^1.0.4"
}
}

View File

@@ -6,8 +6,6 @@ export class DiskSmallerBlock extends DiskPassthrough {
#blockSize
#generatedDiskBlocks = 0
#blockCache?: DiskBlock
#blockRatio: number
#maxBlockIndex: number
constructor(source: Disk, blockSize: number) {
super(source)
@@ -19,11 +17,9 @@ export class DiskSmallerBlock extends DiskPassthrough {
assert.strictEqual(
source.getBlockSize() % blockSize,
0,
`source block size ${blockSize} must be a multiple of the target block size ${source.getBlockSize()} `
`target block size ${blockSize} must be a multiple of the source block size ${source.getBlockSize()} `
)
this.#blockSize = blockSize
this.#blockRatio = source.getBlockSize() / blockSize
this.#maxBlockIndex = Math.ceil(this.getVirtualSize() / this.getBlockSize())
}
openSource(): Promise<Disk> {
@@ -39,19 +35,13 @@ export class DiskSmallerBlock extends DiskPassthrough {
try {
const blockRatio = this.source.getBlockSize() / this.#blockSize
const sourceGenerator = this.source.diskBlocks()
// we don't reuse getBlockIndexes here since we want don't want to force
// a use of source.readblock that would limit the use of this class to RandomeAccessDisk
// thus we generate block based on the source block generator
for await (const { data: sourceData, index: sourceIndex } of sourceGenerator) {
for (let i = 0; i < blockRatio; i++) {
this.#generatedDiskBlocks++
const data = sourceData.subarray(i * this.#blockSize, (i + 1) * this.#blockSize)
const index = sourceIndex * blockRatio + i
if (this.#isBlockBeforeEnd(index)) {
yield {
index,
data,
}
yield {
index: sourceIndex * blockRatio + i,
data,
}
}
}
@@ -64,22 +54,15 @@ export class DiskSmallerBlock extends DiskPassthrough {
getBlockSize(): number {
return this.#blockSize
}
// changing the block size can lead
// to the last block being incomplete
// for example going for a block size of 1024 to 512
// and a virtual size of 1200 means 2 blocks in source,
// but 3 here
#isBlockBeforeEnd(blockIndex: number): boolean {
return blockIndex < this.#maxBlockIndex
}
getBlockIndexes(): Array<number> {
const blockRatio = this.source.getBlockSize() / this.getBlockSize()
const sourceIndexes = this.source.getBlockIndexes()
const indexes: Array<number> = []
const maxIndex = Math.ceil(this.getVirtualSize() / this.getBlockSize())
for (const sourceIndex of sourceIndexes) {
for (let i = 0; i < blockRatio; i++) {
const index = sourceIndex * blockRatio + i
if (this.#isBlockBeforeEnd(index)) {
if (index < maxIndex) {
indexes.push(index)
}
}
@@ -88,28 +71,13 @@ export class DiskSmallerBlock extends DiskPassthrough {
}
hasBlock(index: number): boolean {
// asking for a block after the end of the smaller disk => false
if (!this.#isBlockBeforeEnd(index)) {
return false
}
const blockRatio = this.source.getBlockSize() / this.getBlockSize()
const sourceIndex = Math.floor(index / blockRatio)
return this.source.hasBlock(sourceIndex)
}
/**
* handle gracefully readblock if the source is a RandomAccessDisk
* @param index
* @returns Promise<DiskBlock>
*/
async readBlock(index: number): Promise<DiskBlock> {
if (this.source instanceof RandomAccessDisk) {
if (!this.#isBlockBeforeEnd(index)) {
throw new Error(
`Read after the end, asking for ${index}, last block is ${this.#maxBlockIndex - 1}, vitual size is ${this.getVirtualSize()}, blockSize : ${this.getBlockSize()}`
)
}
const blockRatio = this.source.getBlockSize() / this.getBlockSize()
const sourceBlockIndex = Math.floor(index / blockRatio)
const indexInblock = index % blockRatio

View File

@@ -160,8 +160,8 @@ test('hasBlock behavior', async () => {
test('getBlockIndexes', async () => {
const source = new MockDisk(512, 2048, [
[0, Buffer.alloc(2048)],
[2, Buffer.alloc(2048)],
[0, Buffer.alloc(512)],
[2, Buffer.alloc(512)],
])
await source.init()
@@ -182,28 +182,3 @@ test('close propagation', async () => {
await disk.close()
assert(source.closed)
})
test('unaligned END ', async () => {
const source = new MockDisk(1024, 2048 + 256, [
[0, Buffer.alloc(1024)],
[2, Buffer.alloc(1024)],
])
await source.init()
const disk = new DiskSmallerBlock(source, 256)
await disk.init()
assert.strictEqual(source.getVirtualSize(), disk.getVirtualSize())
const indexes = disk.getBlockIndexes()
const expecteBlockIndex = [0, 1, 2, 3, 8]
assert.deepStrictEqual(indexes, expecteBlockIndex)
assert.strictEqual(disk.hasBlock(8), true)
assert.strictEqual(disk.hasBlock(9), false) //After the end of small block disk
assert.strictEqual(disk.hasBlock(12), false) //After the end of source disk
// ensure disk blocks also handle the unaligned part
for await (const { index, data } of disk.diskBlocks()) {
assert.ok(expecteBlockIndex.includes(index))
assert.equal(data.length, 256)
}
})

View File

@@ -18,12 +18,9 @@ export interface FileAccessor {
buffer: Buffer | DataView,
position: number
): Promise<{ bytesRead: number; buffer: Buffer | DataView }>
readFile(path: string): Promise<string>
writeFile(path: string, content: string, opts?: unknown): Promise<void>
getSize(path: string): Promise<number>
mktree(path: string): Promise<void>
rmtree(path: string): Promise<void>
unlink(path: string): Promise<void>
outputStream(stream: Readable): Promise<void>
rename(path: string, newPath: string): Promise<void>
}

View File

@@ -1,26 +0,0 @@
import { Throttle } from '@vates/generator-toolbox'
import { Disk, DiskBlock } from './Disk.mjs'
import { DiskPassthrough } from './DiskPassthrough.mjs'
export class ThrottledDisk extends DiskPassthrough {
#throttle: Throttle
constructor(source: Disk, throttle: Throttle) {
super(source)
this.#throttle = throttle
}
async buildDiskBlockGenerator(): Promise<AsyncGenerator<DiskBlock>> {
const generator = await this.source.buildDiskBlockGenerator()
//throttle want to be able to know the length of the data
async function* generatorWithLength() {
for await (const { index, data } of generator) {
yield {
index,
data,
length: data.length,
}
}
}
const throttledGenerator = this.#throttle.createThrottledGenerator(generatorWithLength())
return throttledGenerator as AsyncGenerator<DiskBlock>
}
}

View File

@@ -1,16 +0,0 @@
import { Timeout } from '@vates/generator-toolbox'
import { Disk, DiskBlock } from './Disk.mjs'
import { DiskPassthrough } from './DiskPassthrough.mjs'
export class TimeoutDisk extends DiskPassthrough {
#timeout: number
constructor(source: Disk, timeout: number) {
super(source)
this.#timeout = timeout
}
async buildDiskBlockGenerator(): Promise<AsyncGenerator<DiskBlock>> {
const generator = await this.source.buildDiskBlockGenerator()
const timeoutedGenerator = new Timeout(generator, this.#timeout)
return timeoutedGenerator
}
}

View File

@@ -8,6 +8,4 @@ export { DiskPassthrough, RandomDiskPassthrough } from './DiskPassthrough.mjs'
export { RawDisk } from './RawDisk.mjs'
export { ReadAhead } from './ReadAhead.mjs'
export { SynchronizedDisk } from './SynchronizedDisk.mjs'
export { TimeoutDisk } from './Timeout.mjs'
export { ThrottledDisk } from './Throttled.mjs'
export { ProgressHandler } from './ProgressHandler.mjs'

View File

@@ -8,7 +8,6 @@
"moduleResolution": "bundler",
"target": "es2022",
"skipLibCheck": true,
"types": ["node"], // Only use types from Node.js and packages that are explicitly imported
"declaration": true // Generates `.d.ts` files for type safety
},
"include": ["./src/**/*"],

View File

@@ -1,7 +1,7 @@
{
"private": false,
"name": "@xen-orchestra/fs",
"version": "4.6.6",
"version": "4.6.2",
"license": "AGPL-3.0-or-later",
"description": "The File System for Xen Orchestra backups.",
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/@xen-orchestra/fs",
@@ -26,10 +26,10 @@
"@aws-sdk/middleware-apply-body-checksum": "^3.58.0",
"@aws-sdk/node-http-handler": "^3.54.0",
"@azure/storage-blob": "^12.26.0",
"@vates/async-each": "^1.0.1",
"@vates/async-each": "^1.0.0",
"@vates/coalesce-calls": "^0.1.0",
"@vates/decorate-with": "^2.1.0",
"@vates/read-chunk": "^1.2.1",
"@vates/read-chunk": "^1.2.0",
"@xen-orchestra/log": "^0.7.1",
"bind-property-descriptor": "^2.0.0",
"decorator-synchronized": "^0.6.0",
@@ -52,7 +52,7 @@
"@babel/preset-env": "^7.8.0",
"cross-env": "^7.0.2",
"dotenv": "^16.0.0",
"rimraf": "^6.0.1",
"rimraf": "^5.0.1",
"sinon": "^18.0.0",
"tmp": "^0.2.1"
},

View File

@@ -23,7 +23,7 @@ const computeRate = (hrtime, size) => {
return size / seconds
}
const DEFAULT_TIMEOUT = 12e5 // 20 min
const DEFAULT_TIMEOUT = 6e5 // 10 min
const DEFAULT_MAX_PARALLEL_OPERATIONS = 10
const ENCRYPTION_DESC_FILENAME = 'encryption.json'
@@ -48,31 +48,24 @@ const WITH_LIMIT = [
'writeFile',
]
const WITH_RETRY = {
_closeFile: {},
_copy: {},
_getInfo: {},
_getSize: {},
_list: {},
_mkdir: {},
_openFile: {},
_read: {},
_readFile: {},
_rename: {},
_rmdir: {},
_truncate: {},
_unlink: {},
_write: {},
_writeFile: {
updateArguments(error, [file, data, options]) {
options = options ?? {}
if (options.flags === 'wx' && error.code !== 'EEXIST') {
options.flags = 'w'
}
return [file, data, options]
},
},
}
const WITH_RETRY = [
'_closeFile',
'_copy',
'_getInfo',
'_getSize',
'_list',
'_mkdir',
'_openFile',
'_outputFile',
'_read',
'_readFile',
'_rename',
'_rmdir',
'_truncate',
'_unlink',
'_write',
'_writeFile',
]
const WITH_TIMEOUT = [
'_closeFile',
@@ -164,7 +157,7 @@ export default class RemoteHandlerAbstract {
this.#applySafeGuards(options)
}
_conditionRetry(error) {
#conditionRetry(error) {
return !['EEXIST', 'EISDIR', 'ENOTEMPTY', 'ENOENT', 'ENOTDIR', 'SystemInUse', 'ERR_ASSERTION'].includes(error?.code)
}
@@ -186,14 +179,14 @@ export default class RemoteHandlerAbstract {
}
})
Object.entries(this._withRetry).forEach(([functionName, retryOpts]) => {
this._withRetry.forEach(functionName => {
if (this[functionName] !== undefined) {
// adding the retry on the top level method won't
// cover when _functionName are called internally
this[functionName] = pRetry.wrap(this[functionName], {
delays: [100, 200, 500, 1000, 2000],
// these errors should not change on retry
when: err => this._conditionRetry(err),
when: err => this.#conditionRetry(err),
onRetry(error) {
warn('retrying method on fs ', {
method: functionName,
@@ -201,15 +194,7 @@ export default class RemoteHandlerAbstract {
delay: this.delay,
error,
file: this.arguments?.[0],
retryOpts,
})
if (retryOpts.updateArguments) {
warn('updating arguments ', {
method: functionName,
attemptNumber: this.attemptNumber,
})
this.arguments = retryOpts.updateArguments(error, this.arguments)
}
},
})
}
@@ -280,7 +265,6 @@ export default class RemoteHandlerAbstract {
/**
* write a stream to a file using a temporary file
* on immutable remote it won't use a temp file since it won't be able to delete /rename it
*
* @param {string} path
* @param {ReadableStream} input
@@ -683,7 +667,7 @@ export default class RemoteHandlerAbstract {
}
async _outputStream(path, input, { dirMode, validator }) {
const tmpPath = this.isImmutable() ? path : `${dirname(path)}/.${Date.now()}.${basename(path)}`
const tmpPath = `${dirname(path)}/.${Date.now()}.${basename(path)}`
const output = await this._createOutputStream(tmpPath, {
dirMode,
flags: 'wx',
@@ -693,11 +677,8 @@ export default class RemoteHandlerAbstract {
if (validator !== undefined) {
await validator.call(this, tmpPath)
}
if (!this.isImmutable()) {
await this.__rename(tmpPath, path)
}
await this.__rename(tmpPath, path)
} catch (error) {
// this may fail on immutable
await this.__unlink(tmpPath)
throw error
}
@@ -791,10 +772,6 @@ export default class RemoteHandlerAbstract {
get encryptionAlgorithm() {
return this.#encryptor?.algorithm ?? UNENCRYPTED_ALGORITHM
}
isImmutable() {
return this._remote.immutable === true
}
}
// from implementation methods, which names start with `__`, create public

View File

@@ -10,7 +10,7 @@ import AbstractHandler from './abstract'
import fs from 'fs-extra'
import tmp from 'tmp'
const TIMEOUT = 12e5
const TIMEOUT = 6e5
class TestHandler extends AbstractHandler {
constructor() {
@@ -54,7 +54,7 @@ describe('closeFile()', () => {
const promise = testHandler.closeFile({ fd: undefined, path: '' })
clock.tick(TIMEOUT)
await assert.rejects(promise, new TimeoutError())
await assert.rejects(promise, TimeoutError)
})
})
@@ -64,7 +64,7 @@ describe('getInfo()', () => {
const promise = testHandler.getInfo()
clock.tick(TIMEOUT)
await assert.rejects(promise, new TimeoutError())
await assert.rejects(promise, TimeoutError)
})
})
@@ -74,7 +74,7 @@ describe('getSize()', () => {
const promise = testHandler.getSize('')
clock.tick(TIMEOUT)
await assert.rejects(promise, new TimeoutError())
await assert.rejects(promise, TimeoutError)
})
})
@@ -84,7 +84,7 @@ describe('list()', () => {
const promise = testHandler.list('.')
clock.tick(TIMEOUT)
await assert.rejects(promise, new TimeoutError())
await assert.rejects(promise, TimeoutError)
})
})
@@ -94,7 +94,7 @@ describe('openFile()', () => {
const promise = testHandler.openFile('path')
clock.tick(TIMEOUT)
await assert.rejects(promise, new TimeoutError())
await assert.rejects(promise, TimeoutError)
})
})
@@ -104,7 +104,7 @@ describe('rename()', () => {
const promise = testHandler.rename('oldPath', 'newPath')
clock.tick(TIMEOUT)
await assert.rejects(promise, new TimeoutError())
await assert.rejects(promise, TimeoutError)
})
})
@@ -114,7 +114,7 @@ describe('rmdir()', () => {
const promise = testHandler.rmdir('dir')
clock.tick(TIMEOUT)
await assert.rejects(promise, new TimeoutError())
await assert.rejects(promise, TimeoutError)
})
})

View File

@@ -4,7 +4,6 @@ import {
CopyObjectCommand,
CreateMultipartUploadCommand,
DeleteObjectCommand,
DeleteObjectsCommand,
GetObjectCommand,
GetObjectLockConfigurationCommand,
HeadObjectCommand,
@@ -39,7 +38,6 @@ export default class S3Handler extends RemoteHandlerAbstract {
#bucket
#dir
#s3
#immutable = false
constructor(remote, _opts) {
super(remote, _opts)
@@ -141,13 +139,6 @@ export default class S3Handler extends RemoteHandlerAbstract {
}
}
isImmutable() {
return super.isImmutable() || this.#immutable
}
_conditionRetry(error) {
return ![401, 403, 404, 405].includes(error?.$metadata?.httpStatusCode) && super._conditionRetry(error)
}
async _copy(oldPath, newPath) {
const CopySource = this.#makeCopySource(oldPath)
try {
@@ -393,34 +384,22 @@ export default class S3Handler extends RemoteHandlerAbstract {
)
NextContinuationToken = result.IsTruncated ? result.NextContinuationToken : undefined
try {
await this.#s3.send(
new DeleteObjectsCommand({
Bucket: this.#bucket,
Delete: {
Objects: result.Contents ?? [],
},
})
)
} catch (error) {
warn('Unsupported DeleteObjects, fallback to DeleteObject.', { error, $response: error.$response ?? '' })
await asyncEach(
result.Contents ?? [],
async ({ Key }) => {
// _unlink will add the prefix, but Key contains everything
// also we don't need to check if we delete a directory, since the list only return files
await this.#s3.send(
new DeleteObjectCommand({
Bucket: this.#bucket,
Key,
})
)
},
{
concurrency: 16,
}
)
}
await asyncEach(
result.Contents ?? [],
async ({ Key }) => {
// _unlink will add the prefix, but Key contains everything
// also we don't need to check if we delete a directory, since the list only return files
await this.#s3.send(
new DeleteObjectCommand({
Bucket: this.#bucket,
Key,
})
)
},
{
concurrency: 16,
}
)
} while (NextContinuationToken !== undefined)
}
@@ -441,7 +420,6 @@ export default class S3Handler extends RemoteHandlerAbstract {
// will automatically add the contentMD5 header to any upload to S3
debug(`Object Lock is enable, enable content md5 header`)
this.#s3.middlewareStack.use(getApplyMd5BodyChecksumPlugin(this.#s3.config))
this.#immutable = true
}
} catch (error) {
// maybe the account doesn't have enough privilege to query the object lock configuration

View File

@@ -0,0 +1,437 @@
import Fuse from 'fuse-native';
import * as fs from 'fs';
import * as path from 'path';
import { type DiskBlock, RandomAccessDisk } from '@xen-orchestra/disk-transform';
import { DiskConsumerVhdDiscrete } from 'vhd-lib/disk-consumer/DiskConsumerRaw.mjs';
import fsP from 'fs/promises'
import { getHandler } from '@xen-orchestra/fs';
import { RemoteVhd } from '../backups/disks/RemoteVhd.mjs';
class FuseVHDPlugin {
private fuse: Fuse.Fuse;
private disks: Map<string, DiskConsumerVhdDiscrete>;
private passthroughDir: string;
private openHandles: Map<string, number>
private nextHandle:number = 1
constructor(mountPoint: string, passthroughDir: string) {
this.passthroughDir = passthroughDir;
this.disks = new Map<string, DiskConsumerVhdDiscrete>();
this.openHandles = new Map<string, number>();
// Initialize FUSE operations
const ops: Fuse.Operations = {
// File system operations
getattr: this.getattr.bind(this),
readdir: this.readdir.bind(this),
access: this.access.bind(this),
// File operations
open: this.open.bind(this),
release: this.release.bind(this),
read: this.read.bind(this),
unlink: this.unlink.bind(this),
truncate: this.truncate.bind(this),
ftruncate: this.ftruncate.bind(this),
statfs: this.statfs.bind(this),
// Fallback for unimplemented operations
create: this.passthroughCreate.bind(this),
write: this.passthroughWrite.bind(this),
mkdir: this.passthroughMkdir.bind(this),
rmdir: this.passthroughRmdir.bind(this),
rename: this.passthroughRename.bind(this),
chmod: this.passthroughChmod.bind(this),
chown: this.passthroughChown.bind(this),
utimens: this.passthroughUtimens.bind(this),
};
this.fuse = new Fuse(mountPoint, ops, {
force: true,
mkdir: true,
debug: process.env.DEBUG === 'true'
});
}
// Add a virtual VHD file to the filesystem
public addDisk(pathInMount: string, disk:DiskConsumerVhdDiscrete): void {
// @todo open the disk chain and init it
this.disks.set(pathInMount, disk);
}
// Remove a virtual VHD file from the filesystem
public async removeDisk(pathInMount: string): Promise<void> {
const disk = this.getDisk(pathInMount)
await disk.close()
this.disks.delete(pathInMount);
}
// Mount the filesystem
public mount(): Promise<void> {
console.log('will mount')
return new Promise((resolve, reject) => {
this.fuse.mount(err => {
console.log('mounted', err)
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
// Unmount the filesystem
public unmount(): Promise<void> {
// @todo dispose of all disks
return new Promise((resolve, reject) => {
this.fuse.unmount(err => {
if (err) {
reject(err);
} else {
resolve();
}
});
});
}
// Check if a path is a virtual VHD file
private isDiskFile(filePath: string): boolean {
//console.log('isDiskFile', [...arguments])
return this.disks.has(filePath);
}
// Check if a path is a virtual VHD file
private getDisk(filePath: string): DiskConsumerVhdDiscrete {
//console.log('getDisk', [...arguments])
const disk = this.disks.get(filePath)
if(disk === undefined){
throw new Error(`${filePath} is not mounted`)
}
return disk
}
// Get file attributes
private async getattr(filePath: string, cb: (err: number, stat?: Fuse.Stats) => void): Promise<void> {
//console.log('getattr', [...arguments])
try {
if (this.isDiskFile(filePath)) {
const disk = this.getDisk(filePath)
const size = disk.fileSize
//console.log({filePath, size})
const stats: Fuse.Stats = {
mtime: new Date(),
atime: new Date(),
ctime: new Date(),
size: size,
mode: 0o100644 | Fuse.S_IFREG, // Regular file with rw-r--r-- permissions
uid: process.getuid ? process.getuid() : 0,
gid: process.getgid ? process.getgid() : 0
};
cb(0, stats);
} else {
// Passthrough to underlying filesystem
fs.stat(path.join(this.passthroughDir, filePath), (err, stats) => {
if (err) {
cb(Fuse.ENOENT);
} else {
cb(0, {
mtime: stats.mtime,
atime: stats.atime,
ctime: stats.ctime,
size: stats.size,
mode: stats.mode,
uid: stats.uid,
gid: stats.gid
});
}
});
}
} catch (err) {
cb(Fuse.ENOENT);
}
}
// Read directory contents
private readdir(filePath: string, cb: (err: number, contents?: string[]) => void): void {
//console.log('readdir', [...arguments])
// Combine virtual VHD files with underlying directory contents
const combinedContents: string[] = [];
// Add virtual files that are in this directory
const dirPath = filePath === '/' ? '' : filePath;
for (const vhdFile of this.disks.keys()) {
if (path.dirname(vhdFile).startsWith(dirPath)) {
combinedContents.push(path.basename(vhdFile));
}
}
// Add real files from underlying directory
fs.readdir(path.join(this.passthroughDir, filePath), (err, files) => {
if (err && err.code !== 'ENOENT') {
cb(Fuse.ENOENT);
return;
}
if (!err) {
combinedContents.push(...files);
}
cb(0, combinedContents);
});
}
// Check file access permissions
private access(filePath: string, mode: number, cb: (err: number) => void): void {
console.log('access', [...arguments])
if (this.isDiskFile(filePath)) {
// For virtual files, just check if they exist
cb(0);
} else {
// Passthrough to underlying filesystem
fs.access(path.join(this.passthroughDir, filePath), mode, (err) => {
cb(err ? Fuse.EACCES : 0);
});
}
}
// Open a file
private async open(filePath: string, flags: number, cb: (err: number, fd?: number) => void): Promise<void> {
console.log('open', [...arguments])
try {
if (this.isDiskFile(filePath)) { // file is alreay open
const handle = this.nextHandle ++
this.openHandles.set(filePath, handle);
cb(0, handle);
} else {
// Passthrough to underlying filesystem
fs.open(path.join(this.passthroughDir, filePath), flags, (err, fd) => {
if (err) {
cb(Fuse.ENOENT);
} else {
cb(0, fd);
}
});
}
} catch (err) {
cb(Fuse.ENOENT);
}
}
// Close a file
private async release(filePath: string, fd: number, cb: (err: number) => void): Promise<void> {
console.log('release', [...arguments])
try {
if (this.isDiskFile(filePath)) {
this.openHandles.delete(filePath);
cb(0);
} else {
// Passthrough to underlying filesystem
fs.close(fd, (err) => {
cb(err ? Fuse.EIO : 0);
});
}
} catch (err) {
cb(Fuse.EIO);
}
}
// Read from a file
private async read(filePath: string, fd: number, buf: Buffer, len: number, pos: number, cb: (err: number, bytesRead?: number) => void): Promise<void> {
try {
if (this.isDiskFile(filePath)) {
const bytesRead = await this.getDisk(filePath).read(pos, buf);
cb(bytesRead);
} else {
// Passthrough to underlying filesystem
fs.read(fd, buf, 0, len, pos, (err, bytesRead) => {
cb(err ? Fuse.EIO : 0, bytesRead);
});
}
} catch (err) {
console.error(err)
cb(Fuse.EIO);
}
}
// Delete a file
private async unlink(filePath: string, cb: (err: number) => void): Promise<void> {
console.log('unlink', [...arguments])
try {
if (this.isDiskFile(filePath)) {
this.disks.delete(filePath);
cb(0);
} else {
// Passthrough to underlying filesystem
fs.unlink(path.join(this.passthroughDir, filePath), (err) => {
cb(err ? Fuse.ENOENT : 0);
});
}
} catch (err) {
cb(Fuse.ENOENT);
}
}
// Truncate a file
private truncate(filePath: string, size: number, cb: (err: number) => void): void {
console.log('truncate', [...arguments])
if (this.isDiskFile(filePath)) {
// Virtual VHD files can't be truncated
cb(Fuse.EPERM);
} else {
// Passthrough to underlying filesystem
fs.truncate(path.join(this.passthroughDir, filePath), size, (err) => {
cb(err ? Fuse.ENOENT : 0);
});
}
}
// Truncate an open file
private ftruncate(filePath: string, fd: number, size: number, cb: (err: number) => void): void {
console.log('fttruncate', [...arguments])
if (this.isDiskFile(filePath)) {
// Virtual VHD files can't be truncated
cb(Fuse.EPERM);
} else {
// Passthrough to underlying filesystem
fs.ftruncate(fd, size, (err) => {
cb(err ? Fuse.ENOENT : 0);
});
}
}
// Get filesystem statistics
private statfs(filePath: string, cb: (err: number, stat?: Fuse.StatVfs) => void): void {
console.log('statfss', [...arguments])
// Passthrough to underlying filesystem
fs.statfs(path.join(this.passthroughDir, filePath), (err, stats) => {
if (err) {
cb(Fuse.ENOENT);
} else {
cb(0, {
bsize: stats.bsize,
// frsize: stats.frsize,
blocks: stats.blocks,
bfree: stats.bfree,
bavail: stats.bavail,
files: stats.files,
ffree: stats.ffree,
// favail: stats.favail,
// fsid: stats.fsid,
// flag: stats.flags,
// namemax: stats.namemax
});
}
});
}
// Passthrough implementations for other operations
private passthroughCreate(filePath: string, mode: number, cb: (err: number, fd?: number) => void): void {
fs.open(path.join(this.passthroughDir, filePath), mode | Fuse.O_CREAT, (err, fd) => {
cb(err ? Fuse.EACCES : 0, fd);
});
}
private passthroughWrite(filePath: string, fd: number, buf: Buffer, len: number, pos: number, cb: (err: number, written?: number) => void): void {
fs.write(fd, buf, 0, len, pos, (err, written) => {
cb(err ? Fuse.EIO : 0, written);
});
}
private passthroughMkdir(filePath: string, mode: number, cb: (err: number) => void): void {
fs.mkdir(path.join(this.passthroughDir, filePath), mode, (err) => {
cb(err ? Fuse.EACCES : 0);
});
}
private passthroughRmdir(filePath: string, cb: (err: number) => void): void {
fs.rmdir(path.join(this.passthroughDir, filePath), (err) => {
cb(err ? Fuse.ENOENT : 0);
});
}
private passthroughRename(srcPath: string, destPath: string, cb: (err: number) => void): void {
fs.rename(
path.join(this.passthroughDir, srcPath),
path.join(this.passthroughDir, destPath),
(err) => {
cb(err ? Fuse.ENOENT : 0);
}
);
}
private passthroughChmod(filePath: string, mode: number, cb: (err: number) => void): void {
fs.chmod(path.join(this.passthroughDir, filePath), mode, (err) => {
cb(err ? Fuse.ENOENT : 0);
});
}
private passthroughChown(filePath: string, uid: number, gid: number, cb: (err: number) => void): void {
fs.chown(path.join(this.passthroughDir, filePath), uid, gid, (err) => {
cb(err ? Fuse.ENOENT : 0);
});
}
private passthroughUtimens(filePath: string, atime: Date | number, mtime: Date | number, cb: (err: number) => void): void {
fs.utimes(path.join(this.passthroughDir, filePath), atime, mtime, (err) => {
cb(err ? Fuse.ENOENT : 0);
});
}
}
/*
class FakeDisk extends RandomAccessDisk{
nbBlocks = 3
blockSize = 2*1024*1024
index = [1,2,4]
virtualSize = 100*1024*1024
async readBlock(index: number): Promise<DiskBlock> {
return {
index,
data:Buffer.alloc(this.blockSize, 101)
}
}
getVirtualSize(): number {
return this.virtualSize
}
getBlockSize(): number {
return this.blockSize
}
async init(): Promise<void> {
console.log('init')
}
async close(): Promise<void> {
console.log('closed')
}
isDifferencing(): boolean {
return false
}
getBlockIndexes(): Array<number> {
return this.index
}
hasBlock(index: number): boolean {
return this.index.includes(index)
}
}*/
const test = new FuseVHDPlugin('./mount', '/tmp')
test.mount().catch(console.error)
/*
test.addDisk('/vhd0', new DiskConsumerVhdDiscrete(new FakeDisk()))
await new Promise(resolve =>setTimeout(resolve,2000))
const fd = await fsP.open('./mount/vhd0', 'r')
const source = fd.createReadStream()
let length = 0
for await (const data of source){
length += data.length
}
console.log({length})
export default FuseVHDPlugin;*/
const handler = getHandler({url:'file:///mnt/ssd/vhdblock'})
await handler.sync()
const disk = new RemoteVhd({handler , path: 'xo-vm-backups/d1aa0fbb-8de7-f3a5-5edd-c62faa2ec8fa/vdis/c6f5fd08-69b6-4514-a461-9a9a77fc3327/db01a21c-b1d4-4317-9694-a45da55ff89a/data/5825dd96-4414-4efa-992a-c6d96ea40958.vhd'})
await disk.init()
console.log(disk, disk.getBlockIndexes())
test.addDisk('/660c15cb-1643-4d32-b034-6e5b346a9c20.vhd', new DiskConsumerVhdDiscrete(disk))

View File

@@ -0,0 +1,325 @@
import { getHandler } from '@xen-orchestra/fs'
import { fromCallback } from 'promise-toolbox'
import Fuse from 'fuse-native'
import LRU from 'lru-cache'
import { v4 as uuidv4 } from 'uuid'
import { exec } from 'node:child_process'
import fs from 'node:fs/promises'
import path from 'node:path'
import { VhdFile, VhdSynthetic } from 'vhd-lib'
import { Xapi } from '@xen-orchestra/xapi'
// make an overlayfs with
// lowerDir localPath/xo-instant-start/vhds (will contains the links to vhds)
// workDir localPath/xo-instant-start/workDir
// upperDir localPath/xo-instant-start/upper
// purge any data of workdDir, upper
// mount to localPath/xo-instant-start/merged
// shareable path is localPath/xo-instant-start/merged
// build a s stat object from https://github.com/fuse-friends/fuse-native/blob/master/test/fixtures/stat.js
const stat = st => ({
mtime: st.mtime || new Date(),
atime: st.atime || new Date(),
ctime: st.ctime || new Date(),
size: st.size !== undefined ? st.size : 0,
mode: st.mode === 'dir' ? 16877 : st.mode === 'file' ? 33188 : st.mode === 'link' ? 41453 : st.mode,
uid: st.uid !== undefined ? st.uid : process.getuid(),
gid: st.gid !== undefined ? st.gid : process.getgid(),
})
class FuseBackupRepositories{
#xoAddress
#localPath
#xapi
#fuse
#srRef
#pool
#mounted = new Map()//localDiskPath=> {uuid,vhd, mountedAt}
constructor(localPath, xoaddress, xapi){
this.#localPath = path.resolve(path.join(localPath, 'xo-instant-start') )
this.#xoAddress = xoaddress
this.#xapi = xapi
let pool
Object.values(xapi.objects.all).forEach(object => {
if (object.$type === 'pool') {
pool = object
}
})
this.#pool = pool
}
async #listNfsExports(){
return new Promise((resolve, reject)=>{
exec('showmount -e --no-headers', (error, stdout, stderr) => {
if (error) {
reject(new Error(stderr))
return;
}
resolve(stdout.split("\n")
.filter(_=> _ !== '')
.map(_=>_.split(" ")))
});
})
}
async #isAlreadyInNfsExports(basePath){
const exports = await this.#listNfsExports()
return exports.findIndex(entry=>entry[0] === basePath) >= 0
}
#addToNfsExports(basePath){
return new Promise((resolve, reject)=>{
// @todo : use the host ip instead of the star
// @todo : add the mandatory options to improve reliability
exec(`exportfs 192.168.1.45:${basePath} -o rw,sync,no_root_squash,no_subtree_check`, (error, stdout, stderr) => {
if (error) {
reject(new Error(stderr))
return;
}
resolve(stdout.split("\n").filter(_=> _ !== ''))
});
})
}
#createOverlay({vhdsPath, workPath, writePath, sharePath }){
return new Promise((resolve, reject)=>{
// @todo : use the host ip instead of the star
// options from https://serverfault.com/questions/949892/nfs-export-an-overlay-of-ext4-and-btrfs
exec(`
mount -t overlay overlay -o nfs_export=on,index=on -o lowerdir=${vhdsPath} -o upperdir=${writePath} -o workdir=${workPath} ${sharePath}
`, (error, stdout, stderr) => {
if (error) {
reject(new Error(stderr))
return;
}
resolve(stdout)
});
})
}
async #createFuseMount(vhdsPath, srPath){
const self = this
this.#fuse = new Fuse(vhdsPath, {
async readdir(path, cb) {
console.log('will list', path, self.#mounted.keys())
if (path === '/') {
return cb(null, [srPath])
}
if(path === '/'+srPath){
return cb(null, [...self.#mounted.keys()].map(_=>_.substr(1)))
}
cb(Fuse.ENOENT)
},
async getattr(p, cb) {
console.log('will getattr', p, [...self.#mounted.keys()])
if (p === '/') {
console.log('got /')
return cb(
null,
stat({
mode: 'dir',
size: 4096,
})
)
}
if (p === '/'+srPath) {
console.log('got srPath')
return cb(
null,
stat({
mode: 'dir',
size: 4096,
})
)
}
console.log('path.dirname',path.dirname(p), path.basename(p))
if(p.startsWith('/'+srPath)){
console.log('inside sr', {p,srPath})
let filePath = p.substr(('/'+srPath).length)
if(self.#mounted.has(filePath)){
console.log('got a file')
const size = self.#mounted.get(filePath).size
return cb(
null,
stat({
mode: 'file',
size,
})
)
}
}
cb(Fuse.ENOENT)
},
async read(p, fd, buf, len, pos, cb) {
console.log(' will read')
if(p.startsWith('/'+srPath)){
console.log('inside sr', {p,srPath})
let filePath = p.substr(('/'+srPath).length)
if(self.#mounted.has(filePath)){
console.log('read inside a file',{len, pos})
const remoteDiskPath = self.#mounted.get(filePath).remoteDiskPath
const fd = await fs.open('/mnt/ssd/vhdfile/'+remoteDiskPath, 'r')
const { bytesRead } = await fd.read(buf,0,len,pos)
console.log(' GOT ', bytesRead)
await fd.close()
cb(bytesRead) //buffer is ready
// @todo iplement open close instead of reopening each time
// @todo implement readRVhdData , especially for VhdDirectory/VhdSynthetic
}
}
if(self.#mounted.has('/'+path)){
const size = self.#mounted.get(path).size
// for vhdfile it is a simple fs.read
}
cb(Fuse.ENOENT)
},
})
await fromCallback(cb => this.#fuse.mount(cb))
}
async initialize(){
try{
await fs.rm(this.#localPath, { recursive: true, force: true })
}catch(err){
if(err.code !== 'ENOENT' && err.code !=='ENOTDIR'){
throw err
}
}
await fs.mkdir(this.#localPath)
const vhdsPath = path.join(this.#localPath, 'vhds')
await fs.mkdir(vhdsPath)
const workPath = path.join(this.#localPath, 'work')
await fs.mkdir(workPath)
const writePath = path.join(this.#localPath, 'write')
await fs.mkdir(writePath)
const sharePath = path.join(this.#localPath, 'share')
await fs.mkdir(sharePath)
// add share as a NFS export
await this.#addToNfsExports(sharePath)
// attach SR to host
const hostRef = this.#xapi.getObject(this.#pool.master).$ref
const deviceConfig = {
server: this.#xoAddress, // ip of XO
serverpath: sharePath,
}
this.#srRef = await xapi.SR_create({
device_config: deviceConfig,
host: hostRef,
name_description: 'instant start',
name_label: 'xo-instant-start',
shared: true,
type: 'nfs'
})
const sr = await xapi.call('SR.get_record', this.#srRef)
// create vhds virtual layer in the sr.uuid sub folder
// created by xapi
await this.#createFuseMount(vhdsPath, sr.uuid)
// create overlay fs
await this.#createOverlay({vhdsPath,workPath,writePath,sharePath})
// @todo add a watcher on sharePath
// => if one of the mountedVhd path is removed
// => dismount it
}
async cleanup(){
// purge
// localPath/xo-instant-start/*
// unmount all the vhds
// remove share from host SR
// remove share
}
async mount(handler,remoteDiskPath){
// we can't reuse the fuse-vhd logic directly since we want to mount an arbitrary
// number of vhds
const diskUuid = uuidv4()
console.log({diskUuid})
const path = `/${diskUuid}.vhd`
const disposableVhd = await VhdFile.open(handler, remoteDiskPath)
console.log({disposableVhd})
const vhd = disposableVhd.value
await vhd.readBlockAllocationTable()
// to do : use stream size for vhd directory.synthetic
const size = await handler.getSize(remoteDiskPath)
this.#mounted.set(path, {disposableVhd, mountedAt : new Date() , diskUuid,size, remoteDiskPath})
// not sure why do the disk only reappear after I forget and reattach the SR
// scan the SR to add this disk
const xapi = this.#xapi
let vdiRef/*
for(let i=0; i < 10 && vdiRef === undefined; i ++){
console.log('waiting')
try{
vdiRef = await xapi.getRecordByUuid('VDI', diskUuid)
break
}catch(err){}
await new Promise(resolve=>setTimeout(resolve, 5000))
}
console.log({vdiRef})
// take a snapshot of this disk to ensure xcp don't try to write inside
// await xapi.callAsync('VDI.snapshot', vdiRef)
*/
return diskUuid
}
}
const xapi = new Xapi({
allowUnauthorized: true,
url: 'http://192.168.1.45',
auth: {
user: 'root',
password: '',
},
})
await xapi.connect()
console.log ('connected')
await xapi.objectsFetched
const fbr = new FuseBackupRepositories('./mount', '192.168.1.180', xapi)
await fbr.initialize()
const handler = getHandler({url:'file:///mnt/ssd/vhdfile/'})
await handler.sync()
console.log(handler)
await fbr.mount(handler,
'xo-vm-backups/93454bd8-d763-96f7-d230-50b6545122be/vdis/d8ddef60-d9a4-4cec-9546-522e9c75e356/3b60f2e8-c07a-4fd3-826f-1310368cd664/20241021T145449Z.vhd'
)

View File

@@ -0,0 +1,16 @@
{
"name": "fuse-backups-repository",
"version": "1.0.0",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"author": "",
"license": "ISC",
"description": "",
"dependencies": {
"fuse-native": "^2.2.6",
"lru-cache": "^7.14.0",
"uuid": "^11.0.3"
}
}

View File

@@ -0,0 +1,83 @@
import path from 'node:path'
import { exec } from 'node:child_process'
export class VirtualStorage {
#xoAddress
#localPath
#xapi
#fuse
#srRef
#pool
#mounted = new Map()//localDiskPath=> {uuid,vhd, mountedAt}
constructor({localPath, xoaddress, xapi, backupRepository}) {
this.#localPath = path.resolve(path.join(localPath, 'xo-instant-start'))
this.#xoAddress = xoaddress
this.#xapi = xapi
let pool
Object.values(xapi.objects.all).forEach(object: Object => {
if (object.$type === 'pool') {
pool = object
}
})
this.#pool = pool
}
async #listNfsExports() {
return new Promise((resolve, reject) => {
exec('showmount -e --no-headers', (error, stdout, stderr) => {
if (error) {
reject(new Error(stderr))
return;
}
resolve(stdout.split("\n")
.filter(_ => _ !== '')
.map(_ => _.split(" ")))
});
})
}
async #isAlreadyInNfsExports(basePath) {
const exports = await this.#listNfsExports()
return exports.findIndex(entry => entry[0] === basePath) >= 0
}
#addToNfsExports(basePath) {
return new Promise((resolve, reject) => {
// @todo : use the host ip instead of the star
// @todo : add the mandatory options to improve reliability
exec(`exportfs 192.168.1.45:${basePath} -o rw,sync,no_root_squash,no_subtree_check`, (error, stdout, stderr) => {
if (error) {
reject(new Error(stderr))
return;
}
resolve(stdout.split("\n").filter(_ => _ !== ''))
});
})
}
async init(){
await this.#addToNfsExports(sharePath)
// attach SR to host
const hostRef = this.#xapi.getObject(this.#pool.master).$ref
const deviceConfig = {
server: this.#xoAddress, // ip of XO
serverpath: sharePath,
}
this.#srRef = await this.#xapi.SR_create({
device_config: deviceConfig,
host: hostRef,
name_description: 'instant start',
name_label: 'xo-instant-start',
shared: true,
type: 'nfs'
})
const sr = await this.#xapi.call('SR.get_record', this.#srRef)
}
}

View File

@@ -1,7 +1,7 @@
# how often does the lift immutability script will run to check if
# some files need to be made mutable
liftEvery = "1h"
liftEvery = 1h
# you can add as many remote as you want, if you change the id ( here : remote1)
#[remotes.remote1]

View File

@@ -44,14 +44,14 @@ List of protected files :
```js
const PATHS = [
// xo-config-backups/scheduleId/date/metadata.json
// xo configuration backupq
'xo-config-backups/*/*/data',
'xo-config-backups/*/*/data.json',
'xo-config-backups/*/*/metadata.json',
// xo-pool-metadata-backups/backupId/scheduleId/date/metadata.json
'xo-pool-metadata-backups/*/*/*/metadata.json',
'xo-pool-metadata-backups/*/*/*/data',
// xo-vm-backups/<vmuuid>/
// pool backupq
'xo-pool-metadata-backups/*/metadata.json',
'xo-pool-metadata-backups/*/data',
// vm backups , xo-vm-backups/<vmuuid>/
'xo-vm-backups/*/*.json',
'xo-vm-backups/*/*.xva',
'xo-vm-backups/*/*.xva.checksum',

View File

@@ -1,5 +1,6 @@
#!/usr/bin/env node
import fs from 'node:fs/promises'
import * as Directory from './directory.mjs'
import { createLogger } from '@xen-orchestra/log'
import { listOlderTargets } from './fileIndex.mjs'
@@ -9,8 +10,9 @@ import loadConfig from './_loadConfig.mjs'
const { info, warn } = createLogger('xen-orchestra:immutable-backups:liftProtection')
async function liftRemoteImmutability(immutabilityCachePath, immutabilityDuration) {
for await (const { target } of listOlderTargets(immutabilityCachePath, immutabilityDuration)) {
for await (const { index, target } of listOlderTargets(immutabilityCachePath, immutabilityDuration)) {
await Directory.liftImmutability(target, immutabilityCachePath)
await fs.unlink(index)
await cleanXoCache(target)
}
}

View File

@@ -17,22 +17,22 @@
"xo-lift-remote-immutability": "./liftProtection.mjs"
},
"license": "AGPL-3.0-or-later",
"version": "1.0.29",
"version": "1.0.23",
"engines": {
"node": ">=14.0.0"
},
"dependencies": {
"@vates/async-each": "^1.0.1",
"@xen-orchestra/backups": "^0.68.2",
"@vates/async-each": "^1.0.0",
"@xen-orchestra/backups": "^0.63.0",
"@xen-orchestra/log": "^0.7.1",
"app-conf": "^3.0.0",
"chokidar": "^3.6.0",
"execa": "^5.0.0",
"ms": "^2.1.3",
"vhd-lib": "^4.14.7"
"vhd-lib": "^4.14.0"
},
"devDependencies": {
"rimraf": "^6.0.1",
"rimraf": "^5.0.5",
"tap": "^18.6.1"
},
"scripts": {

View File

@@ -137,13 +137,11 @@ export async function watchRemote(remoteId, { root, immutabilityDuration, rebuil
// watch the remote for any new VM metadata json file
const PATHS = [
// xo-config-backups/scheduleId/date/metadata.json
'xo-config-backups/*/*/data',
'xo-config-backups/*/*/data.json',
'xo-config-backups/*/*/metadata.json',
// xo-pool-metadata-backups/backupId/scheduleId/date/metadata.json
'xo-pool-metadata-backups/*/*/*/metadata.json',
'xo-pool-metadata-backups/*/*/*/data',
'xo-pool-metadata-backups/*/metadata.json',
'xo-pool-metadata-backups/*/data',
// xo-vm-backups/<vmuuid>/
'xo-vm-backups/*/*.json',
'xo-vm-backups/*/*.xva',

View File

@@ -2,39 +2,8 @@
## **next**
- [Host] Fix host dashboard CPU provisioning calculation [Forum#101359](https://xcp-ng.org/forum/topic/11604/xo-6-dedicated-thread-for-all-your-feedback/84) (PR [#9459](https://github.com/vatesfr/xen-orchestra/pull/9459))
## **0.18.0** (2026-01-29)
- [VM/New] Fix wording in "Memory" section (PR [#9309](https://github.com/vatesfr/xen-orchestra/pull/9309))
- [TreeView] Scroll to current item in list view (PR [#9332](https://github.com/vatesfr/xen-orchestra/pull/9332))
- [VM/New] Added VTPM support (PR [#9389](https://github.com/vatesfr/xen-orchestra/pull/9389))
## **0.17.0** (2025-11-27)
- [Host/HostSystemResourceManagement] Fix display when control domain memory is undefined (PR [#9197](https://github.com/vatesfr/xen-orchestra/pull/9197))
## **0.16.0** (2025-10-30)
- [VM/New] Fix the default topology by setting the platform:cores-per-socket value correctly (PR [#9136](https://github.com/vatesfr/xen-orchestra/pull/9136))
## **0.15.0** (2025-09-30)
- [Settings] fix key-value alignment and refactor page (PR [#8981](https://github.com/vatesfr/xen-orchestra/pull/8981))
- [Settings] Add icon for external links on settings page (PR [#8980](https://github.com/vatesfr/xen-orchestra/pull/8980))
- [VM/dashboard] Update QuickInfo card in dashboard to show more information (PR [#8952](https://github.com/vatesfr/xen-orchestra/pull/8952))
- [StateHero] Update VtsStateHero component and modify usages in every component (PR [#8910](https://github.com/vatesfr/pull/8910))
## **0.14.1** (2025-09-04)
- [VM/System] Correctly display enable/disable for secure boot (PR [#8925](https://github.com/vatesfr/xen-orchestra/pull/8925))
## **0.14.0** (2025-08-28)
- [Pool,Host,VM/Dashboard] Remember the last visited tab per object type (Pool/Host/VM) when navigating (PR [#8872](https://github.com/vatesfr/xen-orchestra/pull/8872))
- Replace native `select` with a new custom component (PR [#8681](https://github.com/vatesfr/xen-orchestra/pull/8681))
- Add i18n engage link on the settings page [Issue#8603](https://github.com/vatesfr/xen-orchestra/issues/8603) (PR [#8884](https://github.com/vatesfr/xen-orchestra/pull/8884))
- Migrate progress bar usages to Web Core components and remove old Lite components (PR [#8899](https://github.com/vatesfr/xen-orchestra/pull/8899))
## **0.13.1** (2025-08-06)

View File

@@ -0,0 +1,111 @@
# Modal System Documentation
## Opening a modal
To open a modal, call `useModal(loader, props?)`.
- `loader`: The modal component loader (e.g. `() => import("path/to/MyModal.vue")`)
- `props`: The optional props to pass to the modal component
This will return an object with the following methods:
- `onApprove(cb)`:
- A function to register a callback to be called when the modal is approved.
- The callback will receive the modal payload as first argument, if any.
- The callback can return a Promise, in which case the modal will wait for it to resolve before closing.
- `onDecline(cb)`:
- A function to register a callback to be called when the modal is declined.
- The callback can return a Promise, in which case the modal will wait for it to resolve before closing.
### Static modal
```ts
useModal(MyModal)
```
### Modal with props
```ts
useModal(MyModal, { message: 'Hello world!' })
```
### Handle modal approval
```ts
const { onApprove } = useModal(MyModal, { message: 'Hello world!' })
onApprove(() => console.log('Modal approved'))
```
### Handle modal approval with payload
```ts
const { onApprove } = useModal(MyModal, { message: 'Hello world!' })
onApprove(payload => console.log('Modal approved with payload', payload))
```
### Handle modal decline
```ts
const { onDecline } = useModal(MyModal, { message: 'Hello world!' })
onDecline(() => console.log('Modal declined'))
```
### Handle modal close
```ts
const { onClose } = useModal(MyModal, { message: 'Hello world!' })
onClose(() => console.log('Modal closed'))
```
## Modal controller
Inside the modal component, you can inject the modal controller with `inject(IK_MODAL)!`.
```ts
const modal = inject(IK_MODAL)!
```
You can then use the following properties and methods on the `modal` object:
- `isBusy`: Whether the modal is currently doing something (e.g. waiting for a promise to resolve).
- `approve(payload?: any | Promise<any>)`: Approve the modal with an optional payload.
- Set `isBusy` to `true`.
- Wait for the `payload` to resolve (if any).
- Wait for all callbacks registered with `onApprove` to resolve (if any).
- Close the modal in case of success.
- `decline()`: Decline the modal.
- Set `isBusy` to `true`.
- Wait for all callbacks registered with `onDecline` to resolve (if any).
- Close the modal in case of success.
## Components
Some components are available for quick modal creation.
### `UiModal`
The root component of the modal which will display the backdrop.
A click on the backdrop will execute `modal.decline()`.
It accepts `color` and `disabled` props which will update the `ColorContext` and `DisabledContext`.
`DisabledContext` will also be set to `true` when `modal.isBusy` is `true`.
The component itself is a `form` and is meant to be used with `<UiModal @submit.prevent="modal.approve()">`.
### `ModalApproveButton`
A wrapper around `UiButton` with `type="submit"` and with the `busy` prop set to `modal.isBusy`.
### `ModalDeclineButton`
A wrapper around `UiButton` with an `outline` prop and with the `busy` prop set to `modal.isBusy`.
This button will call `modal.decline()` on click.
Default text is `t("cancel")`.

View File

@@ -1,6 +1,6 @@
{
"name": "@xen-orchestra/lite",
"version": "0.18.0",
"version": "0.13.1",
"type": "module",
"scripts": {
"dev": "GIT_HEAD=$(git rev-parse HEAD) vite",
@@ -28,14 +28,14 @@
"@types/file-saver": "^2.0.7",
"@types/lodash-es": "^4.17.12",
"@types/node": "^18.19.80",
"@vates/types": "^1.19.0",
"@vates/types": "^1.9.0",
"@vitejs/plugin-vue": "^5.2.1",
"@vue/tsconfig": "^0.7.0",
"@vueuse/core": "^13.0.0",
"@vueuse/math": "^13.0.0",
"@vueuse/shared": "^13.0.0",
"@xen-orchestra/web-core": "^0.42.0",
"complex-matcher": "^1.0.0",
"@xen-orchestra/web-core": "^0.26.1",
"complex-matcher": "^0.7.1",
"d3-time-format": "^4.1.0",
"decorator-synchronized": "^0.6.0",
"file-saver": "^2.0.5",

View File

@@ -10,19 +10,19 @@
<RouterView />
</main>
</div>
<VtsTooltipList />
</div>
<VtsModalList />
<VtsTooltipList />
<ModalList />
</template>
<script lang="ts" setup>
import AppHeader from '@/components/AppHeader.vue'
import AppLogin from '@/components/AppLogin.vue'
import AppNavigation from '@/components/AppNavigation.vue'
import ModalList from '@/components/ui/modals/ModalList.vue'
import { useUnreachableHosts } from '@/composables/unreachable-hosts.composable'
import { usePoolStore } from '@/stores/xen-api/pool.store'
import { useXenApiStore } from '@/stores/xen-api.store'
import VtsModalList from '@core/components/modal/VtsModalList.vue'
import VtsTooltipList from '@core/components/tooltip-list/VtsTooltipList.vue'
import { useChartTheme } from '@core/composables/chart-theme.composable'
import { useUiStore } from '@core/stores/ui.store'

View File

@@ -2,15 +2,16 @@
<header class="app-header">
<div class="left">
<UiButtonIcon
v-if="!uiStore.isDesktopLarge"
ref="navigationTrigger"
:class="{ 'menu-to-right': !uiStore.isMobile }"
:icon="faBars"
accent="brand"
icon="fa:bars"
size="medium"
/>
<RouterLink :to="logoRoute" class="logo-container">
<img v-if="uiStore.isMobile" alt="XO Lite" src="../assets/logo.svg" />
<UiLogoText v-else :text="t('xo-lite')" />
<TextLogo v-else />
</RouterLink>
</div>
<slot />
@@ -25,20 +26,19 @@
<script lang="ts" setup>
import AccountMenu from '@/components/account-menu/AccountMenu.vue'
import PoolOverrideWarning from '@/components/PoolOverrideWarning.vue'
import TextLogo from '@/components/TextLogo.vue'
import XoaButton from '@/components/XoaButton.vue'
import { useNavigationStore } from '@/stores/navigation.store'
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
import UiLogoText from '@core/components/ui/logo-text/UiLogoText.vue'
import { useUiStore } from '@core/stores/ui.store'
import { faBars } from '@fortawesome/free-solid-svg-icons'
import { storeToRefs } from 'pinia'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import type { RouteLocationRaw } from 'vue-router'
const uiStore = useUiStore()
const { pool } = usePoolStore().getContext()
const { t } = useI18n()
const navigationStore = useNavigationStore()
const { trigger: navigationTrigger } = storeToRefs(navigationStore)
@@ -80,7 +80,7 @@ const logoRoute = computed<RouteLocationRaw>(() =>
.left {
display: flex;
align-items: center;
gap: 1.6rem;
gap: 2rem;
@media (max-width: 1023px) {
flex: 1;
@@ -96,8 +96,6 @@ const logoRoute = computed<RouteLocationRaw>(() =>
flex: 1;
text-align: center;
}
height: 2.5rem;
text-decoration: none;
}
.right {

View File

@@ -4,7 +4,7 @@
<img alt="XO Lite" src="../assets/logo-title.svg" />
<PoolOverrideWarning />
<p v-if="isHostIsSlaveErr(error)" class="error">
<VtsIcon name="fa:exclamation-circle" size="medium" />
<UiIcon :icon="faExclamationCircle" />
{{ t('login-only-on-master') }}
<a :href="masterUrl.href">{{ masterUrl.hostname }}</a>
</p>
@@ -42,13 +42,14 @@
import FormInput from '@/components/form/FormInput.vue'
import LoginError from '@/components/LoginError.vue'
import PoolOverrideWarning from '@/components/PoolOverrideWarning.vue'
import UiIcon from '@/components/ui/icon/UiIcon.vue'
import type { XenApiError } from '@/libs/xen-api/xen-api.types'
import { usePageTitleStore } from '@/stores/page-title.store'
import { useXenApiStore } from '@/stores/xen-api.store'
import VtsIcon from '@core/components/icon/VtsIcon.vue'
import VtsInputWrapper from '@core/components/input-wrapper/VtsInputWrapper.vue'
import UiButton from '@core/components/ui/button/UiButton.vue'
import UiCheckbox from '@core/components/ui/checkbox/UiCheckbox.vue'
import { faExclamationCircle } from '@fortawesome/free-solid-svg-icons'
import { useLocalStorage, whenever } from '@vueuse/core'
import { storeToRefs } from 'pinia'
import { onMounted, ref, watch } from 'vue'

View File

@@ -1,6 +1,11 @@
<template>
<Transition name="slide">
<nav v-if="isOpen" ref="navElement" class="app-navigation">
<nav
v-if="uiStore.isDesktopLarge || isOpen"
ref="navElement"
:class="{ collapsible: !uiStore.isDesktopLarge }"
class="app-navigation"
>
<StoryMenu v-if="route.meta.hasStoryNav" />
<InfraPoolList v-else />
</nav>
@@ -11,84 +16,34 @@
import StoryMenu from '@/components/component-story/StoryMenu.vue'
import InfraPoolList from '@/components/infra/InfraPoolList.vue'
import { useNavigationStore } from '@/stores/navigation.store'
import { onClickOutside, tryOnMounted, useTimeoutFn, watchImmediate } from '@vueuse/core'
import { useUiStore } from '@core/stores/ui.store'
import { onClickOutside, whenever } from '@vueuse/core'
import { storeToRefs } from 'pinia'
import { ref, watch } from 'vue'
import { ref } from 'vue'
import { useRoute } from 'vue-router'
const route = useRoute()
const uiStore = useUiStore()
const navigationStore = useNavigationStore()
const { isOpen } = storeToRefs(navigationStore)
const { isOpen, trigger } = storeToRefs(navigationStore)
const navElement = ref()
watch(
() => navigationStore.trigger?.value,
triggerElement => {
if (triggerElement && navElement.value) {
onClickOutside(
navElement,
() => {
if (isOpen.value) {
isOpen.value = false
}
},
{
ignore: [triggerElement],
}
)
whenever(isOpen, () => {
const unregisterEvent = onClickOutside(
navElement,
() => {
isOpen.value = false
unregisterEvent?.()
},
{
ignore: [trigger],
controls: false,
}
},
{ immediate: true }
)
const getCurrentNodeId = () => {
const name = route.name as string | undefined
const params = route.params as Record<string, any>
if (name?.startsWith('/pool/[uuid]')) {
return `pool:${params.uuid}`
}
if (name?.startsWith('/host/[uuid]')) {
return `host:${params.uuid}`
}
if (name?.startsWith('/vm/[uuid]')) {
return `vm:${params.uuid}`
}
return undefined
}
const scrollToCurrent = async () => {
const id = getCurrentNodeId()
if (!id) {
return
}
const container = navElement.value as HTMLElement | undefined
const target = container?.querySelector<HTMLElement>(`[data-node-id="${CSS.escape(id)}"]`)
const hasChildren = !id.startsWith('vm:')
if (target) {
useTimeoutFn(async () => {
if (hasChildren) {
target.style.scrollMarginTop = '0.8rem'
useTimeoutFn(async () => {
target.style.scrollMarginTop = ''
}, 1000)
}
target.scrollIntoView({ block: hasChildren ? 'start' : 'center', behavior: 'smooth' })
}, 200)
} else {
useTimeoutFn(async () => {
await scrollToCurrent()
}, 200)
}
}
tryOnMounted(scrollToCurrent)
watchImmediate(route, scrollToCurrent)
)
})
</script>
<style lang="postcss" scoped>
@@ -100,5 +55,20 @@ watchImmediate(route, scrollToCurrent)
padding: 0.5rem;
border-right: 1px solid var(--color-neutral-border);
background-color: var(--color-neutral-background-primary);
&.collapsible {
position: fixed;
z-index: 1;
}
}
.slide-enter-active,
.slide-leave-active {
transition: transform 0.3s ease;
}
.slide-enter-from,
.slide-leave-to {
transform: translateX(-37rem);
}
</style>

View File

@@ -3,14 +3,14 @@
<UiFilter
v-for="filter in activeFilters"
:key="filter"
@edit="openFilterModal(filter)"
@edit="openModal(filter)"
@remove="emit('removeFilter', filter)"
>
{{ filter }}
</UiFilter>
<UiActionButton icon="fa:plus" class="add-filter" @click="openFilterModal()">
{{ t('action:add-filter') }}
<UiActionButton :icon="faPlus" class="add-filter" @click="openModal()">
{{ t('add-filter') }}
</UiActionButton>
</UiFilterGroup>
</template>
@@ -19,12 +19,12 @@
import UiActionButton from '@/components/ui/UiActionButton.vue'
import UiFilter from '@/components/ui/UiFilter.vue'
import UiFilterGroup from '@/components/ui/UiFilterGroup.vue'
import { useModal } from '@/composables/modal.composable'
import type { Filters } from '@/types/filter'
import { useModal } from '@core/packages/modal/use-modal.ts'
import { computed } from 'vue'
import { faPlus } from '@fortawesome/free-solid-svg-icons'
import { useI18n } from 'vue-i18n'
const { availableFilters } = defineProps<{
const props = defineProps<{
activeFilters: string[]
availableFilters: Filters
}>()
@@ -36,18 +36,16 @@ const emit = defineEmits<{
const { t } = useI18n()
const openFilterModal = useModal((editedFilter?: string) => ({
component: import('@/components/modals/CollectionFilterModal.vue'),
props: {
const openModal = (editedFilter?: string) => {
const { onApprove } = useModal<string>(() => import('@/components/modals/CollectionFilterModal.vue'), {
availableFilters: props.availableFilters,
editedFilter,
availableFilters: computed(() => availableFilters),
},
onConfirm: async newFilter => {
if (editedFilter !== undefined) {
emit('removeFilter', editedFilter)
}
})
emit('addFilter', newFilter)
},
}))
if (editedFilter !== undefined) {
onApprove(() => emit('removeFilter', editedFilter))
}
onApprove(newFilter => emit('addFilter', newFilter))
}
</script>

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