Compare commits

..

1 Commits

Author SHA1 Message Date
Pierre Brunet
9829eb58f3 fix: add debug to better understand timeout error 2026-08-07 15:53:52 +02:00
1632 changed files with 16823 additions and 43955 deletions

View File

@@ -85,21 +85,6 @@ module.exports = {
XO_LITE_GIT_HEAD: true,
},
rules: {
'import/extensions': [
'error',
'ignorePackages',
{
pattern: { ts: 'always', vue: 'always' },
checkTypeImports: true,
// '@core/*' and '@/*' look like scoped packages to the plugin, which 'ignorePackages' would skip
pathGroupOverrides: [
{ pattern: '@core/packages/*', action: 'ignore' }, // barrel files
{ pattern: '@core/icons', action: 'ignore' },
{ pattern: '@core/**', action: 'enforce' },
{ pattern: '@/**', action: 'enforce' },
],
},
],
'import/order': [
'error',
{
@@ -269,8 +254,6 @@ module.exports = {
'zh-Hans',
'sk',
'pt',
'ar',
'tr',
],
},
],

View File

@@ -1,34 +0,0 @@
name: Changelog
# only pull requests targeting `master`: the check compares the branch to
# `origin/master`, it would report unrelated packages on a PR based on another
# branch
on:
pull_request:
branches:
- master
jobs:
changed-packages:
runs-on: ubuntu-latest
steps:
# https://github.com/actions/checkout
- uses: actions/checkout@v4
with:
# the whole history is required to compute the merge base with `master`
fetch-depth: 0
# the check only needs commits and trees: `git diff --name-only
# --no-renames` compares tree entries and never reads file contents,
# skipping the historical blobs halves the fetch (~112 MiB → ~53 MiB)
filter: blob:none
# https://github.com/actions/setup-node
- name: Setup Node environment
uses: actions/setup-node@v4
with:
node-version: '>=22.12'
# the script only uses Node builtins, no `yarn install` necessary
- name: Ensure changed packages are listed in CHANGELOG.unreleased.md
run: ./scripts/check-changed-pkgs.js

1
.gitignore vendored
View File

@@ -5,7 +5,6 @@
/@vates/*/dist/
/@vates/*/node_modules/
/@vates/node-vsphere-soap/test/config-test.mjs
/@xen-orchestra/*/dist/
/@xen-orchestra/*/node_modules/
/@xen-orchestra/rest-api/open-api/spec/swagger.json

View File

@@ -5,7 +5,3 @@
# Generated files
/@xen-orchestra/web/src/route-map.d.ts
/@xen-orchestra/lite/src/route-map.d.ts
# Docusaurus MDX content: prettier's markdown parser corrupts JSX
# comments ({/* … */} becomes {/_ … _/}) and other MDX constructs
/docs/docs/**/*.md

View File

@@ -24,7 +24,7 @@
},
"dependencies": {
"@vates/multi-key-map": "^0.2.0",
"@xen-orchestra/async-map": "^0.1.4",
"@xen-orchestra/async-map": "^0.1.3",
"@xen-orchestra/log": "^0.7.2",
"ensure-array": "^1.0.0"
},

View File

@@ -7,7 +7,6 @@ const { warn } = createLogger('vates:nbd-client:multi')
export default class MultiNbdClient {
#clients = []
#nbdConcurrency
#nextClient = 0
#options
#readAhead
#settings
@@ -98,31 +97,8 @@ export default class MultiNbdClient {
* @returns {Promise<Buffer>}
*/
async readBlock(index, size = NBD_DEFAULT_BLOCK_SIZE) {
const clientId = this.#nextClient++ % this.#clients.length
const client = this.#clients[clientId]
try {
return await client.readBlock(index, size)
} catch (err) {
// client.readBlock() already exhausted its own retries/reconnects: this connection is dead.
// Evict it so future reads stop being routed to it, and retry this read on a surviving
// client, since the data is usually still reachable through the others.
this.#evict(client)
if (this.#clients.length === 0) {
throw err
}
warn(`evicted a dead nbd client, retrying block ${index} on a remaining client`, { err })
return this.readBlock(index, size)
}
}
// no-op if `client` was already evicted by a concurrent failed read on the same client
#evict(client) {
const i = this.#clients.indexOf(client)
if (i === -1) {
return
}
this.#clients.splice(i, 1)
client.disconnect().catch(() => {})
const clientId = index % this.#clients.length
return this.#clients[clientId].readBlock(index, size)
}
/**

View File

@@ -1,130 +0,0 @@
import { describe, it, mock } from 'node:test'
import assert from 'node:assert'
// MultiNbdClient instantiates NbdClient itself (`import NbdClient from './index.mjs'`), so the
// only way to control individual connections from a unit test is to replace that module with a
// fake before importing multi.mjs.
const created = []
class FakeNbdClient {
constructor(nbdInfo) {
this.nbdInfo = nbdInfo
this.disconnected = false
// overridden per-test after connect() to script this instance's behavior
this.readBlock = async () => {
throw new Error('readBlock not configured for this fake client')
}
created.push(this)
}
async connect() {}
async disconnect() {
this.disconnected = true
}
async getMap() {
return []
}
}
mock.module('./index.mjs', {
defaultExport: FakeNbdClient,
})
const { default: MultiNbdClient } = await import('./multi.mjs')
// a single settings entry is enough: connect() reuses candidates across concurrent slots, so
// nbdConcurrency still yields that many distinct FakeNbdClient instances
async function connectWithFakes(nbdConcurrency) {
created.length = 0
const client = new MultiNbdClient({ address: 'fake-host' }, { nbdConcurrency })
await client.connect()
return { client, fakes: created.slice() }
}
describe('MultiNbdClient.readBlock eviction', () => {
it('evicts a client whose readBlock rejects and retries on a surviving client', async () => {
const { client, fakes } = await connectWithFakes(2)
const [dead, alive] = fakes
dead.readBlock = async () => {
throw new Error('connection is dead')
}
alive.readBlock = async index => Buffer.from([index])
// index 0 initially routes to `dead` (0 % 2 === 0)
const data = await client.readBlock(0)
assert.deepStrictEqual(data, Buffer.from([0]))
assert.strictEqual(dead.disconnected, true, 'the dead client should have been disconnected')
// future reads must no longer be routed to the evicted client: with only `alive` left,
// every index should now succeed through it
alive.readBlock = async index => Buffer.from([index])
const data2 = await client.readBlock(1)
assert.deepStrictEqual(data2, Buffer.from([1]))
})
it('rejects once every client has been evicted, instead of retrying forever', async () => {
const { client, fakes } = await connectWithFakes(2)
const boom = new Error('connection is dead')
for (const fake of fakes) {
fake.readBlock = async () => {
throw boom
}
}
await assert.rejects(() => client.readBlock(0), boom)
assert.ok(
fakes.every(fake => fake.disconnected),
'every client should have been evicted (and disconnected) before giving up'
)
})
it('evicting the same dead client from concurrent failed reads is idempotent', async () => {
const { client, fakes } = await connectWithFakes(2)
const [dead, alive] = fakes
dead.readBlock = async () => {
throw new Error('connection is dead')
}
alive.readBlock = async index => Buffer.from([index])
let disconnectCalls = 0
dead.disconnect = async () => {
disconnectCalls++
dead.disconnected = true
}
// routing is round-robin by call order (0, 1, 0) over a 2-client pool: the 1st and 3rd
// calls both land on `dead` before either failure has been handled, so they race to evict
// the same client. The exact interleaving isn't guaranteed, only that eviction is safe
// either way and every read still completes.
const [data0, data1, data2] = await Promise.all([client.readBlock(10), client.readBlock(11), client.readBlock(12)])
assert.deepStrictEqual(data0, Buffer.from([10]))
assert.deepStrictEqual(data1, Buffer.from([11]))
assert.deepStrictEqual(data2, Buffer.from([12]))
assert.strictEqual(disconnectCalls, 1, 'the dead client must only be evicted/disconnected once')
})
})
describe('MultiNbdClient.readBlock routing', () => {
it('distributes reads round-robin by call order, not by index residue', async () => {
const { client, fakes } = await connectWithFakes(4)
const readsPerClient = fakes.map(() => 0)
fakes.forEach((fake, i) => {
fake.readBlock = async index => {
readsPerClient[i]++
return Buffer.from([index])
}
})
// a CBT-style changed-block set striding by exactly `nbdConcurrency`: under the old
// `index % clients.length` routing this would collapse entirely onto a single client
const stridedIndexes = Array.from({ length: 20 }, (_, i) => i * 4)
for (const index of stridedIndexes) {
await client.readBlock(index)
}
assert.deepStrictEqual(readsPerClient, [5, 5, 5, 5])
})
})

View File

@@ -13,7 +13,7 @@
"url": "https://vates.fr"
},
"license": "ISC",
"version": "3.5.1",
"version": "3.5.0",
"engines": {
"node": ">=14.0"
},
@@ -21,11 +21,11 @@
"dependencies": {
"@vates/async-each": "^1.0.3",
"@vates/read-chunk": "^1.2.1",
"@xen-orchestra/async-map": "^0.1.4",
"@xen-orchestra/async-map": "^0.1.3",
"@xen-orchestra/disk-transform": "^1.3.3",
"@xen-orchestra/log": "^0.7.2",
"promise-toolbox": "^0.21.0",
"xen-api": "^4.9.0"
"xen-api": "^4.8.0"
},
"devDependencies": {
"tap": "^18.7.0",
@@ -33,7 +33,6 @@
},
"scripts": {
"postversion": "npm publish --access public",
"test": "node --experimental-test-module-mocks --test",
"test-integration": "tap --allow-incomplete-coverage tests/*.integ.mjs"
"test-integration": "tap --allow-incomplete-coverage"
}
}

View File

@@ -153,13 +153,7 @@ CYu1Xn/FVPx1HoRgWc7E8wFhDcA/P3SJtfIQWHB9FzSaBflKGR4t8WCE2eE8+cTB
nbdServer = await spawnNbdKit(path)
}
}
// reading past the end of the export must reject: a single client so the failure isn't
// multiplied by nbdConcurrency evicting and retrying on every other (equally healthy, equally
// unable to satisfy this out-of-range request) client
const singleClient = new MultiNbdClient(connectionSettings, { nbdConcurrency: 1, readAhead: 2 })
await singleClient.connect()
await assert.rejects(() => singleClient.readBlock(100, CHUNK_SIZE))
await singleClient.disconnect()
assert.rejects(() => client.readBlock(100, CHUNK_SIZE))
await client.disconnect()
// double disconnection shouldn't pose any problem

View File

@@ -1,102 +0,0 @@
const XML_ENTITIES = {
'&amp;': '&',
'&apos;': "'",
'&gt;': '>',
'&lt;': '<',
'&quot;': '"',
}
const unescapeXml = text => text.replace(/&(?:amp|apos|gt|lt|quot);/g, entity => XML_ENTITIES[entity])
// node-soap wraps text nodes either as a plain string or as `{ $value }` depending on
// whether the element carries attributes
const valueOf = node => {
if (typeof node === 'string') {
return node
}
if (node !== null && typeof node === 'object' && typeof node.$value === 'string') {
return node.$value
}
}
const faultTypeOfElementName = name => name.replace(/^.*:/, '').replace(/Fault$/, '')
// SOAP 1.1 requires the children of `Fault` to be unqualified, and that is what ESXi and vCenter
// send, but the raw body is only read when node-soap failed to parse the response: it can then be
// anything, e.g. an error emitted by a reverse proxy in front of vCenter. Hence the tolerance to a
// namespace prefix and to attributes on the element
const textOfElement = name =>
new RegExp(`<(?:[\\w.-]+:)?${name}(?:\\s[^>]*)?>([\\s\\S]*?)</(?:[\\w.-]+:)?${name}>`, 'i')
const FAULTCODE_RE = textOfElement('faultcode')
const FAULTSTRING_RE = textOfElement('faultstring')
const LOCALIZED_MESSAGE_RE = textOfElement('localizedMessage')
const DETAIL_CHILD_RE = /<(?:[\w.-]+:)?detail(?:\s[^>]*)?>\s*<([^\s/>]+)/i
/**
* Extracts the vim25 fault of a failed SOAP call.
*
* The fault type (`FileLocked`, `InvalidDeviceSpec`, `ManagedObjectNotFound`, ...) is the only part
* a caller can branch on: `faultstring` and `localizedMessage` are meant for humans and change with
* the locale of the server.
*
* Two sources are used, in order of reliability:
* 1. `rawError.root`, the envelope parsed by node-soap ( see `wsdl.xmlToObject`, which throws on a
* fault and whose error is stored there by node-soap)
* 2. the raw response body, when the parsing itself failed
*
* @param {unknown} rawError - the error passed by node-soap to its callback
* @returns {{ code?: string, faultcode?: string, faultstring?: string, localizedMessage?: string, body?: string }}
*/
export function parseFault(rawError) {
const fault = rawError?.root?.Envelope?.Body?.Fault
const rawBody = rawError?.response?.data ?? rawError?.body
const body = typeof rawBody === 'string' && rawBody !== '<stream>' ? rawBody : undefined
let code, localizedMessage
let faultcode = valueOf(fault?.faultcode)
let faultstring = valueOf(fault?.faultstring)
const detail = fault?.detail
if (detail !== null && typeof detail === 'object') {
// the single child of `detail` names the fault, e.g.
// `<InvalidDeviceSpecFault xsi:type="InvalidDeviceSpec">`
for (const [name, value] of Object.entries(detail)) {
if (name === 'attributes') {
continue
}
code = value?.attributes?.['xsi:type'] ?? faultTypeOfElementName(name)
localizedMessage = valueOf(value?.localizedMessage)
break
}
}
if (body !== undefined) {
if (faultstring === undefined) {
const matches = body.match(FAULTSTRING_RE)
if (matches !== null) {
faultstring = unescapeXml(matches[1])
}
}
if (faultcode === undefined) {
const matches = body.match(FAULTCODE_RE)
if (matches !== null) {
faultcode = unescapeXml(matches[1])
}
}
if (code === undefined) {
const matches = body.match(DETAIL_CHILD_RE)
if (matches !== null) {
code = faultTypeOfElementName(matches[1])
}
}
if (localizedMessage === undefined) {
const matches = body.match(LOCALIZED_MESSAGE_RE)
if (matches !== null) {
localizedMessage = unescapeXml(matches[1])
}
}
}
return { code, faultcode, faultstring, localizedMessage, body }
}

View File

@@ -1,104 +0,0 @@
import assert from 'node:assert/strict'
import { describe, it } from 'node:test'
import { parseFault } from './_parseFault.mjs'
// captured from an ESXi 8 host
const MANAGED_OBJECT_NOT_FOUND = `<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<soapenv:Fault><faultcode>ServerFaultCode</faultcode><faultstring>The object &apos;vim.VirtualMachine:vm-42&apos; has already been deleted or has not been completely created</faultstring><detail><ManagedObjectNotFoundFault xmlns="urn:vim25" xsi:type="ManagedObjectNotFound"><obj type="VirtualMachine">vm-42</obj></ManagedObjectNotFoundFault></detail></soapenv:Fault>
</soapenv:Body>
</soapenv:Envelope>`
// not what a vSphere host sends — SOAP 1.1 requires these children to be unqualified — but a body
// which node-soap failed to parse can come from anything sitting in front of vCenter
const NAMESPACE_PREFIXED = `<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:vim25="urn:vim25" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body>
<soapenv:Fault><soapenv:faultcode>ServerFaultCode</soapenv:faultcode><soapenv:faultstring>Unable to access file since it is locked</soapenv:faultstring><soapenv:detail xmlns="urn:vim25"><vim25:FileLockedFault xsi:type="FileLocked"><vim25:localizedMessage>Unable to access file [ds1] vm/vm.vmdk since it is locked</vim25:localizedMessage></vim25:FileLockedFault></soapenv:detail></soapenv:Fault>
</soapenv:Body>
</soapenv:Envelope>`
describe('parseFault', function () {
it('reads the fault from the envelope parsed by node-soap', function () {
const { code, faultcode, faultstring, localizedMessage } = parseFault({
root: {
Envelope: {
Body: {
Fault: {
faultcode: 'ServerFaultCode',
faultstring: 'Unable to access file since it is locked',
detail: {
FileLockedFault: {
attributes: { 'xsi:type': 'FileLocked' },
localizedMessage: 'Unable to access file [ds1] vm/vm.vmdk since it is locked',
},
},
},
},
},
},
})
assert.equal(code, 'FileLocked')
assert.equal(faultcode, 'ServerFaultCode')
assert.equal(faultstring, 'Unable to access file since it is locked')
assert.equal(localizedMessage, 'Unable to access file [ds1] vm/vm.vmdk since it is locked')
})
it('falls back to the element name when xsi:type is absent', function () {
const { code } = parseFault({
root: { Envelope: { Body: { Fault: { detail: { InvalidDeviceSpecFault: {} } } } } },
})
assert.equal(code, 'InvalidDeviceSpec')
})
it('falls back to the raw body when the envelope could not be parsed', function () {
const { code, faultcode, faultstring, body } = parseFault({
message: 'Request failed with status code 500',
response: { data: MANAGED_OBJECT_NOT_FOUND },
})
assert.equal(code, 'ManagedObjectNotFound')
assert.equal(faultcode, 'ServerFaultCode')
// entities are decoded
assert.match(faultstring, /^The object 'vim\.VirtualMachine:vm-42' has already been deleted/)
assert.equal(body, MANAGED_OBJECT_NOT_FOUND)
})
it('reads a namespace prefixed fault from the raw body', function () {
const { code, faultcode, faultstring, localizedMessage } = parseFault({
response: { data: NAMESPACE_PREFIXED },
})
assert.equal(code, 'FileLocked')
assert.equal(faultcode, 'ServerFaultCode')
assert.equal(faultstring, 'Unable to access file since it is locked')
assert.equal(localizedMessage, 'Unable to access file [ds1] vm/vm.vmdk since it is locked')
})
it('handles a `$value` wrapped text node', function () {
const { faultstring } = parseFault({
root: { Envelope: { Body: { Fault: { faultstring: { $value: 'boom' } } } } },
})
assert.equal(faultstring, 'boom')
})
it('does not throw on an error without any fault', function () {
assert.deepEqual(parseFault(new Error('socket hang up')), {
code: undefined,
faultcode: undefined,
faultstring: undefined,
localizedMessage: undefined,
body: undefined,
})
assert.deepEqual(parseFault(undefined).code, undefined)
})
it('ignores the placeholder body used by node-soap for streamed responses', function () {
assert.equal(parseFault({ body: '<stream>' }).body, undefined)
})
})

View File

@@ -19,29 +19,16 @@ import soap from 'soap'
import Cookie from 'soap-cookie' // required for session persistence
import { createLogger } from '@xen-orchestra/log'
import { parseFault } from './_parseFault.mjs'
// exposed for the consumers talking to the host outside of the WSDL, e.g. `Fetch`
export { parseFault } from './_parseFault.mjs'
const { warn } = createLogger('xo:node-vsphere-soap:client')
class VmwareError extends Error {
constructor(rawError) {
const { code, faultcode, faultstring, localizedMessage, body } = parseFault(rawError)
super(localizedMessage ?? faultstring ?? rawError?.message ?? 'unknown SOAP error')
super(rawError.body)
const matches = rawError.body?.match(/<faultstring[^>]*>(.*)<\/faultstring>/im)
this.message = matches?.[1] ?? rawError.message
this.name = 'VmwareError'
// the vim25 fault type, the only part of a fault a caller can branch on
this.code = code
this.faultcode = faultcode
this.faultstring = faultstring
this.localizedMessage = localizedMessage
this.body = body
if (rawError?.stack !== undefined) {
this.stack = rawError.stack
}
// legacy constraint: not putting the cause since the error failed to be stringified correctly
// down the road, the fault is exposed through own properties instead
warn('SOAP call failed', { code, faultcode, faultstring, localizedMessage })
this.stack = rawError.stack
// not putting the cause since the error failed to be stringified correctly down the road
warn(rawError)
}
}
// Client class
@@ -51,7 +38,6 @@ class VmwareError extends Error {
export function Client(vCenterHostname, username, password, sslVerify) {
this.status = 'disconnected'
this.reconnectCount = 0
this._exitHook = undefined
sslVerify = typeof sslVerify !== 'undefined' ? sslVerify : false
@@ -104,49 +90,44 @@ util.inherits(Client, EventEmitter)
Client.prototype.runCommand = function (command, args) {
const self = this
const cmdargs = args ?? {}
let cmdargs
if (!args || args === null) {
cmdargs = {}
} else {
cmdargs = args
}
const emitter = new EventEmitter()
const onResponse = function (err, result, raw, soapHeader) {
if (err) {
// an error and a result are mutually exclusive: emitting both makes every caller listening
// for 'result' believe the call succeeded, with `result` undefined
_soapErrorHandler(self, emitter, command, cmdargs, err)
return
}
if (command === 'Logout') {
self.status = 'disconnected'
self._unregisterExitHook()
}
emitter.emit('result', result, raw, soapHeader)
}
const send = function () {
self.client.VimService.VimPort[command](cmdargs, onResponse)
}
// check if client has successfully connected
if (self.status === 'ready' || self.status === 'connecting') {
send()
self.client.VimService.VimPort[command](cmdargs, function (err, result, raw, soapHeader) {
if (err) {
_soapErrorHandler(self, emitter, command, cmdargs, err)
}
if (command === 'Logout') {
self.status = 'disconnected'
process.removeAllListeners('beforeExit')
}
emitter.emit('result', result, raw, soapHeader)
})
} else {
// if connection not ready or connecting, reconnect to instance
if (self.status === 'disconnected') {
self.emit('connect')
}
// a failed connection would otherwise leave this listener registered for ever, and the next
// successful one would replay every command whose caller has long given up
const onConnectionError = error => {
self.off('ready', onReady)
emitter.emit('error', error)
}
const onReady = () => {
self.off('error', onConnectionError)
send()
}
self.once('ready', onReady)
self.once('error', onConnectionError)
self.once('ready', function () {
self.client.VimService.VimPort[command](cmdargs, function (err, result, raw, soapHeader) {
if (err) {
_soapErrorHandler(self, emitter, command, cmdargs, err)
}
if (command === 'Logout') {
self.status = 'disconnected'
process.removeAllListeners('beforeExit')
}
emitter.emit('result', result, raw, soapHeader)
})
})
}
return emitter
@@ -172,11 +153,9 @@ Client.prototype._connect = function () {
self.clientopts,
function (err, client) {
if (err) {
self.status = 'disconnected'
// throwing here would be an uncaught exception: we are in an async callback, not in the
// stack of the caller
self.emit('error', new VmwareError(err))
return
const vErr = new VmwareError(err)
self.emit('error', vErr)
throw vErr
}
self.client = client // save client for later use
@@ -207,7 +186,7 @@ Client.prototype._connect = function () {
self.status = 'ready'
self.emit('ready')
self._registerExitHook()
process.once('beforeExit', self._close)
})
.once('error', function (err) {
self.status = 'disconnected'
@@ -223,36 +202,9 @@ Client.prototype._connect = function () {
)
}
// Logs out on process exit, so that a session is not left open on the server until it expires.
//
// The hook must be stored: passing `self._close` directly would call it with `this === process`,
// and removing it with `process.removeAllListeners('beforeExit')` would drop the hooks of every
// other module of the process.
Client.prototype._registerExitHook = function () {
const self = this
if (self._exitHook === undefined) {
self._exitHook = function () {
self._close()
}
process.once('beforeExit', self._exitHook)
}
}
Client.prototype._unregisterExitHook = function () {
const self = this
if (self._exitHook !== undefined) {
process.off('beforeExit', self._exitHook)
self._exitHook = undefined
}
}
Client.prototype._close = function () {
const self = this
self._unregisterExitHook()
if (self.status === 'ready') {
self
.runCommand('Logout', { _this: self.sessionManager })
@@ -268,64 +220,34 @@ Client.prototype._close = function () {
}
}
// Errors are only emitted on `emitter`, the emitter of the failed call: throwing from here would
// be an uncaught exception since we are always in an async callback, and emitting on the client
// would reject unrelated concurrent calls.
//
// Exported for the unit tests: building a `Client` connects to a host.
export function _soapErrorHandler(self, emitter, command, args, err) {
function _soapErrorHandler(self, emitter, command, args, err) {
err = err || { body: 'general error' }
const vErr = new VmwareError(err)
// `NotAuthenticated` is raised when the session expired: log in again and replay the call.
//
// The fault type is used instead of the previous `err.body?.match(...)`: node-soap only fills
// `body` for streamed responses, so the string test never matched and the session was never
// renewed
const isSessionExpired =
vErr.code === 'NotAuthenticated' || /session is not authenticated/i.test(vErr.faultstring ?? vErr.message)
if (!isSessionExpired || self.reconnectCount >= 10) {
emitter.emit('error', vErr)
return
}
// The call is replayed only once a new session is ready. Handing it straight to `runCommand`
// would send it right away while the status is 'connecting' — i.e. on the very session which
// just expired — and the failure of that replay would land back here.
const onConnectionError = function (error) {
self.off('ready', onReady)
emitter.emit('error', error)
}
const onReady = function () {
self.off('error', onConnectionError)
self
.runCommand(command, args)
.once('result', function (result, raw, soapHeader) {
emitter.emit('result', result, raw, soapHeader)
})
.once('error', function (retryError) {
emitter.emit('error', retryError)
})
}
self.once('ready', onReady)
self.once('error', onConnectionError)
// A whole wave of calls can fail on the same expired session, e.g. during an import. Only the
// first one to notice drops it and pays for a retry: the others ride the reconnect it started,
// instead of each burning one of the 10 and of resetting the status under a `_connect` already
// in flight — which used to start a second `soap.createClient` and replace `self.client` under
// the first one.
if (self.status === 'ready') {
if (err.body?.match(/session is not authenticated/)) {
self.status = 'disconnected'
self._unregisterExitHook()
self.reconnectCount += 1
}
if (self.status === 'disconnected') {
// no reconnect in flight: either this call is the first to notice, or the previous attempt
// already failed
self.emit('connect')
process.removeAllListeners('beforeExit')
if (self.reconnectCount < 10) {
self.reconnectCount += 1
self
.runCommand(command, args)
.once('result', function (result, raw, soapHeader) {
emitter.emit('result', result, raw, soapHeader)
})
.once('error', function (err) {
const vErr = new VmwareError(err)
emitter.emit('error', vErr)
throw vErr
})
} else {
const vErr = new VmwareError(err)
emitter.emit('error', vErr)
throw vErr
}
} else {
const vErr = new VmwareError(err)
emitter.emit('error', vErr)
throw vErr
}
}

View File

@@ -1,219 +0,0 @@
import assert from 'node:assert/strict'
import { EventEmitter } from 'node:events'
import { describe, it } from 'node:test'
import { _soapErrorHandler } from './client.mjs'
// what a host answers to any call made on a session which expired
const NOT_AUTHENTICATED = {
root: {
Envelope: {
Body: {
Fault: {
faultcode: 'ServerFaultCode',
faultstring: 'The session is not authenticated.',
detail: { NotAuthenticatedFault: { attributes: { 'xsi:type': 'NotAuthenticated' } } },
},
},
},
},
}
const FILE_LOCKED = {
root: {
Envelope: {
Body: {
Fault: {
faultcode: 'ServerFaultCode',
faultstring: 'Unable to access file since it is locked',
detail: { FileLockedFault: { attributes: { 'xsi:type': 'FileLocked' } } },
},
},
},
},
}
/**
* A stand-in for a connected `Client`, reduced to what `_soapErrorHandler` touches: building a real
* one talks to a host.
*
* `connect` reproduces `_connect`, which only starts connecting from 'disconnected'.
*/
function fakeClient() {
const self = new EventEmitter()
self.status = 'ready'
self.reconnectCount = 0
self.unregisterExitHookCalls = 0
self._unregisterExitHook = () => {
self.unregisterExitHookCalls += 1
}
// the calls handed to `runCommand`, i.e. the ones actually sent to the host
self.sent = []
self.runCommand = (command, args) => {
const emitter = new EventEmitter()
self.sent.push({ args, command, emitter, statusWhenSent: self.status })
return emitter
}
self.connectCalls = 0
self.on('connect', () => {
self.connectCalls += 1
if (self.status === 'disconnected') {
self.status = 'connecting'
}
})
return self
}
// makes one in-flight call fail, and reports what its own emitter received
function failingCall(self, command, rawError = NOT_AUTHENTICATED) {
const emitter = new EventEmitter()
const outcome = {}
emitter.once('result', result => {
outcome.result = result
})
emitter.once('error', error => {
outcome.error = error
})
_soapErrorHandler(self, emitter, command, { _this: command }, rawError)
return outcome
}
describe('_soapErrorHandler', function () {
it('replays a call made on an expired session, once the new session is ready', function () {
const self = fakeClient()
const outcome = failingCall(self, 'RetrievePropertiesEx')
assert.equal(self.reconnectCount, 1)
assert.equal(self.status, 'connecting')
assert.equal(self.unregisterExitHookCalls, 1)
assert.deepEqual(self.sent, [])
self.status = 'ready'
self.emit('ready')
assert.equal(self.sent.length, 1)
assert.equal(self.sent[0].command, 'RetrievePropertiesEx')
self.sent[0].emitter.emit('result', 'replayed')
assert.equal(outcome.result, 'replayed')
})
it('starts a single reconnect for a whole wave of calls on the same session', function () {
const self = fakeClient()
const outcomes = [failingCall(self, 'A'), failingCall(self, 'B'), failingCall(self, 'C')]
// one retry for the wave, not one per call: they used to exhaust the 10 of a busy import
assert.equal(self.reconnectCount, 1)
assert.equal(self.connectCalls, 1)
assert.equal(self.unregisterExitHookCalls, 1)
// and none of them is sent while the reconnect is in flight, which would mean sending it on
// the session which just expired
assert.deepEqual(self.sent, [])
self.status = 'ready'
self.emit('ready')
assert.deepEqual(
self.sent.map(({ command, statusWhenSent }) => [command, statusWhenSent]),
[
['A', 'ready'],
['B', 'ready'],
['C', 'ready'],
]
)
// each replay answers its own caller
self.sent[1].emitter.emit('result', 'B replayed')
assert.equal(outcomes[1].result, 'B replayed')
assert.equal(outcomes[0].result, undefined)
assert.equal(outcomes[2].result, undefined)
})
it('restarts a reconnect which already failed', function () {
const self = fakeClient()
failingCall(self, 'A')
assert.equal(self.connectCalls, 1)
// the reconnect failed, nothing is in flight any more
self.status = 'disconnected'
failingCall(self, 'B')
assert.equal(self.connectCalls, 2)
// the session was already dropped by the first call, the second one must not pay for it again
assert.equal(self.reconnectCount, 1)
})
it('reports a failed reconnect to every waiting call, and stops listening', function () {
const self = fakeClient()
const outcomes = [failingCall(self, 'A'), failingCall(self, 'B')]
const connectionError = new Error('host unreachable')
self.status = 'disconnected'
self.emit('error', connectionError)
assert.equal(outcomes[0].error, connectionError)
assert.equal(outcomes[1].error, connectionError)
assert.deepEqual(self.sent, [])
// a listener left behind would replay a call whose caller has long given up
assert.equal(self.listenerCount('ready'), 0)
assert.equal(self.listenerCount('error'), 0)
})
it('reports the error of a replay which failed too', function () {
const self = fakeClient()
const outcome = failingCall(self, 'A')
self.status = 'ready'
self.emit('ready')
const replayError = new Error('failed again')
self.sent[0].emitter.emit('error', replayError)
assert.equal(outcome.error, replayError)
})
it('gives up after 10 reconnects', function () {
const self = fakeClient()
self.reconnectCount = 10
const outcome = failingCall(self, 'A')
assert.equal(outcome.error.code, 'NotAuthenticated')
assert.equal(self.connectCalls, 0)
assert.equal(self.status, 'ready')
assert.deepEqual(self.sent, [])
})
it('emits an error which is not a session expiry as is, without reconnecting', function () {
const self = fakeClient()
const outcome = failingCall(self, 'A', FILE_LOCKED)
assert.equal(outcome.error.code, 'FileLocked')
assert.equal(self.connectCalls, 0)
assert.equal(self.reconnectCount, 0)
assert.equal(self.status, 'ready')
assert.deepEqual(self.sent, [])
})
it('recognizes an expiry which only says so in its faultstring', function () {
const self = fakeClient()
// no `detail`, hence no fault type to branch on
failingCall(self, 'A', {
root: { Envelope: { Body: { Fault: { faultstring: 'The session is not authenticated.' } } } },
})
assert.equal(self.reconnectCount, 1)
assert.equal(self.connectCalls, 1)
})
})

View File

@@ -31,7 +31,6 @@
"node": ">=14"
},
"scripts": {
"postversion": "npm publish --access public",
"test": "node --test lib/*.test.mjs"
"postversion": "npm publish --access public"
}
}

View File

@@ -1,7 +1,7 @@
// place your own credentials here for a vCenter or ESXi server: they are used by
// vsphere-soap.integ.mjs to connect to a real instance.
//
// copy this file next to it, as `config-test.mjs`. It is ignored by git, do not commit it.
// place your own credentials here for a vCenter or ESXi server
// this information will be used for connecting to a vCenter instance
// for module testing
// name the file config-test.js
export const vCenterTestCreds = {
vCenterIP: 'vcsa',

View File

@@ -0,0 +1,138 @@
/*
vsphere-soap.test.js
tests for the vCenterConnectionInstance class
*/
import assert from 'assert'
import { describe, it } from 'node:test'
import * as vc from '../lib/client.mjs'
// eslint-disable-next-line n/no-missing-import
import { vCenterTestCreds as TestCreds } from '../config-test.mjs'
const VItest = new vc.Client(TestCreds.vCenterIP, TestCreds.vCenterUser, TestCreds.vCenterPassword, false)
describe('Client object initialization:', function () {
it('provides a successful login', { timeout: 5000 }, function (t, done) {
VItest.once('ready', function () {
assert.notEqual(VItest.userName, null)
assert.notEqual(VItest.fullName, null)
assert.notEqual(VItest.serviceContent, null)
done()
}).once('error', function (err) {
console.error(err)
// this should fail if there's a problem
assert.notEqual(VItest.userName, null)
assert.notEqual(VItest.fullName, null)
assert.notEqual(VItest.serviceContent, null)
done()
})
})
})
describe('Client reconnection test:', function () {
it('can successfully reconnect', { timeout: 5000 }, function (t, done) {
VItest.runCommand('Logout', { _this: VItest.serviceContent.sessionManager })
.once('result', function (result) {
// now we're logged out, so let's try running a command to test automatic re-login
VItest.runCommand('CurrentTime', { _this: 'ServiceInstance' })
.once('result', function (result) {
assert(result.returnval instanceof Date)
done()
})
.once('error', function (err) {
console.error(err)
})
})
.once('error', function (err) {
console.error(err)
})
})
})
// these tests don't work yet
describe('Client tests - query commands:', function () {
it('retrieves current time', { timeout: 5000 }, function (t, done) {
VItest.runCommand('CurrentTime', { _this: 'ServiceInstance' }).once('result', function (result) {
assert(result.returnval instanceof Date)
done()
})
})
it('retrieves current time 2 (check for event clobbering)', { timeout: 5000 }, function (t, done) {
VItest.runCommand('CurrentTime', { _this: 'ServiceInstance' }).once('result', function (result) {
assert(result.returnval instanceof Date)
done()
})
})
it('can obtain the names of all Virtual Machines in the inventory', { timeout: 20000 }, function (t, done) {
// get property collector
const propertyCollector = VItest.serviceContent.propertyCollector
// get view manager
const viewManager = VItest.serviceContent.viewManager
// get root folder
const rootFolder = VItest.serviceContent.rootFolder
let containerView, objectSpec, traversalSpec, propertySpec, propertyFilterSpec
// this is the equivalent to
VItest.runCommand('CreateContainerView', {
_this: viewManager,
container: rootFolder,
type: ['VirtualMachine'],
recursive: true,
}).once('result', function (result) {
// build all the data structures needed to query all the vm names
containerView = result.returnval
objectSpec = {
attributes: { 'xsi:type': 'ObjectSpec' }, // setting attributes xsi:type is important or else the server may mis-recognize types!
obj: containerView,
skip: true,
}
traversalSpec = {
attributes: { 'xsi:type': 'TraversalSpec' },
name: 'traverseEntities',
type: 'ContainerView',
path: 'view',
skip: false,
}
objectSpec = { ...objectSpec, selectSet: [traversalSpec] }
propertySpec = {
attributes: { 'xsi:type': 'PropertySpec' },
type: 'VirtualMachine',
pathSet: ['name'],
}
propertyFilterSpec = {
attributes: { 'xsi:type': 'PropertyFilterSpec' },
propSet: [propertySpec],
objectSet: [objectSpec],
}
// TODO: research why it fails if propSet is declared after objectSet
VItest.runCommand('RetrievePropertiesEx', {
_this: propertyCollector,
specSet: [propertyFilterSpec],
options: { attributes: { type: 'RetrieveOptions' } },
})
.once('result', function (result, raw) {
assert.notEqual(result.returnval.objects, null)
if (Array.isArray(result.returnval.objects)) {
assert.strictEqual(result.returnval.objects[0].obj.attributes.type, 'VirtualMachine')
} else {
assert.strictEqual(result.returnval.objects.obj.attributes.type, 'VirtualMachine')
}
done()
})
.once('error', function (err) {
console.error('\n\nlast request : ' + VItest.client.lastRequest, err)
})
})
})
})

View File

@@ -1,7 +1,7 @@
{
"name": "@vates/types",
"private": false,
"version": "2.0.1",
"version": "1.30.1",
"main": "./dist/index.mjs",
"exports": {
".": {
@@ -33,8 +33,7 @@
"@eslint/js": "^9.19.0",
"typescript": "~5.6.3",
"typescript-eslint": "^8.61.0",
"@types/express": "^5.0.0",
"@xen-orchestra/disk-transform": "^1.3.3"
"@types/express": "^5.0.0"
},
"scripts": {
"build": "tsc",

View File

@@ -1,4 +1,4 @@
import type { XapiXoRecord, XoHost, XoNetwork, XoVif } from './xo.mjs'
import type { XoHost, XoNetwork, XoVif } from './xo.mjs'
declare const __brand: unique symbol
@@ -755,9 +755,9 @@ export type TrafficRuleDirection = 'from' | 'to' | 'from/to'
export type RawTrafficRule = {
allow: boolean
protocol: TrafficRuleProtocol
protocol: string
ipRange: string
direction: TrafficRuleDirection
direction: string
port?: string
}
@@ -769,34 +769,3 @@ type BaseTrafficRule = RawTrafficRule & {
export type TrafficRule =
| (BaseTrafficRule & { type: XoVif['type']; sourceId: XoVif['id'] })
| (BaseTrafficRule & { type: XoNetwork['type']; sourceId: XoNetwork['id'] })
export const XAPI_TYPES: readonly string[] = [
'network',
'VIF',
'message',
'gpuGroup',
'host',
'PBD',
'PCI',
'PGPU',
'PIF',
'pool',
'SR',
'VBD',
'VDI',
'VDI-snapshot',
'VDI-unmanaged',
'vgpu',
'vgpuType',
'VM',
'VM-controller',
'VM-snapshot',
'VM-template',
'VTPM',
'SM',
] satisfies readonly XapiXoRecord['type'][]
/** steps of a rolling pool update on one host, in execution order */
export const RPU_RECOVERY_STEP_NAMES = ['evacuate', 'update', 'reboot', 'enable', 'restoreVms'] as const
export type RPU_RECOVERY_STEP_NAME = (typeof RPU_RECOVERY_STEP_NAMES)[number]

View File

@@ -4,34 +4,40 @@ import type { XoApp } from '../xo-app.mjs'
export type SecurityName = '*' | 'token' | 'basic' | 'none'
export type FieldDefinition = { optional?: boolean; nullable?: boolean } & (
export type FieldDefinition =
| {
type: 'string'
example?: string
optional?: boolean
}
| {
type: 'boolean'
example?: boolean
optional?: boolean
}
| {
type: 'number'
example?: number
optional?: boolean
}
| {
type: 'enum'
enum: string[]
example?: string
optional?: boolean
}
| {
type: 'object'
fields: Record<string, FieldDefinition>
optional?: boolean
}
| {
type: 'array'
items: FieldDefinition
example?: unknown[]
optional?: boolean
}
)
export type ParamFieldDefinition = Exclude<
FieldDefinition,
{ type: 'boolean' } | { type: 'object' } | { type: 'array' }

View File

@@ -24,7 +24,6 @@ import type {
VIF_LOCKING_MODE,
VM_OPERATIONS,
} from '../common.mjs'
import type { DiskPassthrough } from '@xen-orchestra/disk-transform'
import type { PassThrough, Readable } from 'node:stream'
import type {
XapiXoRecord,
@@ -477,42 +476,3 @@ export interface Xapi {
}
}
}
/**
* Parameters accepted by the `XapiDiskSource` constructor.
*
* `baseRef` turns the export into a differencing one: leaving it out exports the whole disk.
* `preferNbd` only expresses a preference, {@link XapiDiskSource} silently falls back to a plain
* stream export — and, when `baseRef` can't be used as a base, to a full one.
*/
export interface XapiDiskSourceOptions {
baseRef?: XenApiVdi['$ref']
blockSize?: number
nbdConcurrency?: number
/** When true, only `getBlockIndexes()` may be called: `readBlock()` throws. */
onlyListChangedBlocks?: boolean
preferNbd?: boolean
timeout?: number
vdiRef: XenApiVdi['$ref']
xapi: Xapi
}
/**
* Disk source handling the fallback logic of a VDI export: NBD + CBT, then NBD + stream export
* for the block list, then plain stream export.
*
* {@link XapiDiskSourceOptions.preferNbd} is a preference, not a guarantee: call
* {@link XapiDiskSource.useNbd} and {@link XapiDiskSource.useCbt} after `init()` to know what the
* export actually used.
*/
export interface XapiDiskSource extends DiskPassthrough {
useCbt(): boolean
useNbd(): boolean
}
/**
* Signature of `@xen-orchestra/xapi`'s `parseDateTime`.
*
* Returns a Unix timestamp in seconds, or `null` if the field is empty (as encoded by XAPI).
*/
export type ParseDateTime = (input: string | number | Date) => number | null

View File

@@ -21,7 +21,6 @@ import type {
} from './xo.mjs'
import { VatesTask } from './lib/vates-task.mjs'
import type { PluginRestRouteDefinition } from './lib/rest-api.mjs'
import type { RPU_RECOVERY_STEP_NAME } from './common.mjs'
import {
Xapi,
XapiHostStats,
@@ -126,54 +125,6 @@ type License = {
bundleInfo?: { name: string; id: string }
}
export type PoolRollingUpdateRecoveryStep = {
status: 'pending' | 'running' | 'observed-succeeded' | 'failed' | 'not-needed'
startedAt?: string
finishedAt?: string
}
/** error serialized by the recovery recorder: secret-looking keys are redacted */
export type PoolRollingUpdateRecoveryError = {
name?: string
message?: string
stack?: string
code?: string | number
[key: string]: unknown
}
export type PoolRollingUpdateRecoveryHost = {
status: 'pending' | 'running' | 'succeeded' | 'failed' | 'not-needed'
steps: Record<RPU_RECOVERY_STEP_NAME, PoolRollingUpdateRecoveryStep>
lastError: PoolRollingUpdateRecoveryError | null
}
export type PoolRollingUpdateRecoveryRun = {
runId: string
poolId: string
status: 'preparing' | 'running' | 'interrupted' | 'resuming' | 'failed' | 'cleaning'
startedAt: string
updatedAt: string
finishedAt?: string
interruptedAt?: string
taskId?: string
variant?: 'xcp' | 'xs-cdn' | 'xs-legacy'
hostOrder?: string[]
hosts: Record<string, PoolRollingUpdateRecoveryHost>
lastError: PoolRollingUpdateRecoveryError | null
/** VM UUID -> UUID of the host it must be started on */
haltedPinnedVms: Record<string, string>
}
/** record unreadable or of an unknown schema version: recovery needs a human */
export type PoolRollingUpdateRecoveryBlocked = {
poolId?: string
runId?: string
status: 'blocked'
blockedReason: string
}
export type PoolRollingUpdateRecovery = PoolRollingUpdateRecoveryRun | PoolRollingUpdateRecoveryBlocked
export type XoApp = {
hooks: EventEmitter
_redis: {
@@ -250,11 +201,9 @@ export type XoApp = {
userData?: { ip?: string },
opts?: { bypassOtp?: boolean; bypassTaskCreation?: boolean }
) => Promise<{ bypassOtp: boolean; expiration: number; user: XoUser }>
backupGuard(objectId: XapiXoRecord['id'], opts?: { bypassBackupCheck?: boolean; operation: string }): Promise<void>
backupGuard(poolId: XoPool['id']): Promise<void>
/* Throw if no authorization */
checkFeatureAuthorization(featureCode: FeatureCode): Promise<void>
/* validate, apply and persist the configuration of a plugin */
configurePlugin(id: string, configuration: unknown, mergeWithExisting?: boolean): Promise<void>
/* connect a server (XCP-ng/XenServer) */
connectXenServer(id: XoServer['id']): Promise<void>
// TODO: replace all XoAclBasePrivilege with a more strict type. (discriminate union)
@@ -342,7 +291,7 @@ export type XoApp = {
>
>
getAllSchedules(): Promise<XoSchedule[]>
getAllUsers(opts?: { obfuscatePassword?: boolean }): Promise<XoUser[]>
getAllUsers(): Promise<XoUser[]>
getAllXenServers(): Promise<XoServer[]>
getAuthenticationTokensForUser(userId: XoUser['id']): Promise<XoAuthenticationToken[]>
getBackupNgLogs(): Promise<Record<string, AnyXoLog>>
@@ -363,7 +312,7 @@ export type XoApp = {
) => Record<T['id'], T> | undefined
getTotalBackupSizeOnRemote(id: XoBackupRepository['id']): Promise<{ onDisk: number }>
getSchedule(id: XoSchedule['id']): Promise<XoSchedule>
getUser: (id: XoUser['id'], opts?: { obfuscatePassword?: boolean }) => Promise<XoUser>
getUser: (id: XoUser['id']) => Promise<XoUser>
getXapi(maybeId: XapiXoRecord['id'] | XapiXoRecord): Xapi
getXapiHostStats: (hostId: XoHost['id'], granularity?: XapiStatsGranularity) => Promise<XapiHostStats>
getXapiObject: <T extends XapiXoRecord>(
@@ -373,18 +322,16 @@ export type XoApp = {
getXapiPoolStats(poolId: XoPool['id'], granularity?: XapiStatsGranularity): Promise<XapiPoolStats>
getXapiVmStats: (vmId: XoVm['id'], granularity?: XapiStatsGranularity) => Promise<XapiVmStats>
getXenServer(id: XoServer['id']): Promise<XoServer>
getXoEventEmitterByType(type: string): EventEmitter
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[]>>
}>
/** `null` when the listing of a backup repository failed */
listVmBackupsNg(
backupRepositoryIds: XoBackupRepository['id'][],
opts?: { _forceRefresh?: boolean; vmId?: XoVm['id'] }
): Promise<Record<XoBackupRepository['id'], Record<XoVm['id'], XoVmBackupArchive[]> | null>>
opts?: { _forceRefresh?: boolean; vmId: XoVm['id'] }
): Promise<Record<XoBackupRepository['id'], Record<XoVm['id'], XoVmBackupArchive[]>>>
pingRemote(id: XoBackupRepository['id']): Promise<{ success: true }>
/** Allow to add a new server in the DB (XCP-ng/XenServer) */
registerXenServer(
@@ -394,15 +341,11 @@ export type XoApp = {
readOnly?: XoServer['readOnly']
}
): Promise<XoServer>
rollingPoolReboot(
pool: XoPool,
opts?: { bypassBackupCheck?: boolean; parentTask?: VatesTask; shutdownPinnedVms?: boolean }
): Promise<void>
rollingPoolReboot(pool: XoPool, opts?: { parentTask?: VatesTask; shutdownPinnedVms?: boolean }): Promise<void>
rollingPoolUpdate(
pool: XoPool,
opts?: { bypassBackupCheck?: boolean; rebootVm?: boolean; parentTask?: VatesTask; shutdownPinnedVms?: boolean }
opts?: { rebootVm?: boolean; parentTask?: VatesTask; shutdownPinnedVms?: boolean }
): Promise<void>
getRollingUpdateRecovery(poolId: XoPool['id']): Promise<PoolRollingUpdateRecovery | undefined>
setVmResourceSet(vmId: XoVm['id'], resourceSetId: string | null, force?: boolean): Promise<void>
shareVmResourceSet(vmId: XoVm['id']): Promise<void>
removeUserFromGroup(userId: XoUser['id'], id: XoGroup['id']): Promise<void>

View File

@@ -19,7 +19,7 @@ import type {
VM_POWER_STATE,
} from './common.mjs'
import type * as CMType from './lib/complex-matcher.mjs'
import { XoAclBasePrivilege, XoAclRole } from './lib/xen-orchestra-acl.mjs'
import { XoAclPrivilege, XoAclRole, XoAclSupportedActionsByResource } from './lib/xen-orchestra-acl.mjs'
import type { XenApiHost, XenApiPool } from './xen-api.mjs'
type BaseXapiXo = {
@@ -140,7 +140,6 @@ export type XoAlarm = Omit<XoMessage, '$object' | 'body'> & {
}
// TODO: to be typed when Bastien.N has finished working on the XO task
// Once the [key:string]: unknown is removed, remove the `as XoMessage` in event.class.mts
type BaseXoLog = {
id: Branded<'xo-log'>
infos?: { data: unknown; message: string }[]
@@ -603,7 +602,7 @@ export type XoServer = {
poolNameDescription?: string
poolNameLabel?: string
readOnly: boolean
status: 'connected' | 'disconnecting' | 'disconnected' | 'connecting'
status: 'connected' | 'disconnected' | 'connecting'
username: string
}
@@ -890,7 +889,10 @@ export type XapiXoRecord =
| XoVtpm
| XoSm
export type NonXapiXoRecord =
export type NonXapiXoRecord<
TActionsByResource extends XoAclSupportedActionsByResource = never,
TResource extends string = never,
> =
| AnyXoBackupArchive
| AnyXoJob
| AnyXoLog
@@ -903,9 +905,12 @@ export type NonXapiXoRecord =
| XoTask
| XoUser
| XoAclRole
| XoAclBasePrivilege
| XoAclPrivilege<TActionsByResource, TResource>
export type XoRecord = XapiXoRecord | NonXapiXoRecord
export type XoRecord<
TActionsByResource extends XoAclSupportedActionsByResource = never,
TResource extends string = never,
> = XapiXoRecord | NonXapiXoRecord<TActionsByResource, TResource>
export type AnyXoVm = XoVm | XoVmSnapshot | XoVmTemplate | XoVmController

View File

@@ -4,7 +4,6 @@
"declaration": true,
"strict": true,
"module": "ESNext",
"moduleResolution": "bundler",
"target": "ES2022",
"skipLibCheck": true,
"types": ["node"] // Only use types from Node.js and packages that are explicitly imported

View File

@@ -6,7 +6,7 @@
"main": "dist/index.mjs",
"name": "@xen-orchestra/acl",
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/@xen-orchestra/acl",
"version": "1.6.1",
"version": "1.5.0",
"license": "AGPL-3.0-or-later",
"private": false,
"type": "module",
@@ -30,7 +30,7 @@
},
"devDependencies": {
"@eslint/js": "^9.19.0",
"@vates/types": "^2.0.1",
"@vates/types": "^1.30.1",
"rimraf": "^6.0.1",
"typescript": "~5.6",
"typescript-eslint": "^8.61.0"

View File

@@ -13,11 +13,11 @@ const wrapCall = (fn, arg, thisArg) => {
*
* WARNING: Does not handle plain objects
*
* @template Item, Result, [This=Iterable<Item>]
* @template Item,This
* @param {Iterable<Item>} iterable
* @param {(this: This, item: Item) => (Result | PromiseLike<Result>)} mapFn
* @param {This} [thisArg] defaults to `iterable`
* @returns {Promise<Result[]>}
* @param {(this: This, item: Item) => (Item | PromiseLike<Item>)} mapFn
* @param {This} [thisArg]
* @returns {Promise<Item[]>}
*/
exports.asyncMap = function asyncMap(iterable, mapFn, thisArg = iterable) {
return Promise.all(Array.from(iterable, mapFn, thisArg))
@@ -26,11 +26,11 @@ exports.asyncMap = function asyncMap(iterable, mapFn, thisArg = iterable) {
/**
* Like `asyncMap` but wait for all promises to settle before rejecting
*
* @template Item, Result, [This=Iterable<Item>]
* @template Item,This
* @param {Iterable<Item>} iterable
* @param {(this: This, item: Item) => (Result | PromiseLike<Result>)} mapFn
* @param {This} [thisArg] defaults to `iterable`
* @returns {Promise<Result[]>}
* @param {(this: This, item: Item) => (Item | PromiseLike<Item>)} mapFn
* @param {This} [thisArg]
* @returns {Promise<Item[]>}
*/
exports.asyncMapSettled = function asyncMapSettled(iterable, mapFn, thisArg = iterable) {
return new Promise((resolve, reject) => {

View File

@@ -1,7 +1,7 @@
{
"private": false,
"name": "@xen-orchestra/async-map",
"version": "0.1.4",
"version": "0.1.3",
"license": "ISC",
"description": "Promise.all + map for all iterables",
"keywords": [

View File

@@ -1,6 +1,6 @@
{
"name": "@xen-orchestra/backup-archive",
"version": "1.1.2",
"version": "1.1.1",
"description": "Helper to handle generic backup archives",
"license": "ISC",
"author": "",
@@ -8,8 +8,7 @@
"main": "./dist/index.mjs",
"exports": {
".": "./dist/index.mjs",
"./disks": "./dist/disks/index.mjs",
"./disks/hashed": "./dist/disks/hashed/index.mjs"
"./disks": "./dist/disks/index.mjs"
},
"devDependencies": {
"@eslint/js": "^9.19.0",
@@ -22,7 +21,7 @@
"tar-stream": "^3.1.8",
"@types/tar-stream": "^3.1.4",
"tmp": "^0.2.1",
"@vates/types": "^2.0.1"
"@vates/types": "^1.30.1"
},
"dependencies": {
"@xen-orchestra/log": "^0.7.1",
@@ -33,15 +32,14 @@
"uuid": "^9.0.0",
"promise-toolbox": "^0.21.0",
"@vates/async-each": "^1.0.1",
"vhd-lib": "^4.16.1",
"compare-versions": "^6.1.1"
"vhd-lib": "^4.16.1"
},
"scripts": {
"build": "yarn run clean && tsc",
"dev": "tsc --watch",
"postversion": "npm publish --access public",
"test": "tsc && node --test \"**/*.test.mjs\"",
"test-integration": "tsc && node --test \"**/*.integ.mjs\"",
"test": "yarn run clean && tsc && node --test **/*.test.mjs",
"test-integration": "yarn run clean && tsc && node --test **/*.integ.mjs",
"clean": "rimraf dist/"
},
"private": false,

View File

@@ -1,49 +0,0 @@
import { RemoteHandlerAbstract } from '@xen-orchestra/fs'
import { promisify } from 'node:util'
import zlib from 'node:zlib'
const gzip = promisify(zlib.gzip)
const gunzip = promisify(zlib.gunzip)
type LogWarn = (message: any, opts?: object) => void
/**
* Reads a gzip-compressed JSON cache file, tolerant of a missing or corrupt file.
* Shared with the legacy @xen-orchestra/backups RemoteAdapter.
*/
export async function readBackupCache(
handler: RemoteHandlerAbstract,
path: string,
logWarn: LogWarn
): Promise<Record<string, unknown> | undefined> {
try {
return JSON.parse((await gunzip(await handler.readFile(path))).toString())
} catch (error) {
if (error?.code !== 'ENOENT') {
logWarn('failed to read cache', { error, path })
}
}
}
/**
* Writes data as a gzip-compressed JSON cache file.
* Shared with the legacy @xen-orchestra/backups RemoteAdapter.
*
* No-op on immutable remotes: the cache file may not be modifiable there,
* and callers should be regenerating/reading the data directly instead.
*/
export async function writeBackupCache(
handler: RemoteHandlerAbstract,
path: string,
data: Record<string, unknown>,
logWarn: LogWarn
): Promise<void> {
if (handler.isImmutable()) {
return
}
try {
await handler.writeFile(path, await gzip(JSON.stringify(data)), { flags: 'w' })
} catch (error) {
logWarn('failed to write cache', { error, path })
}
}

View File

@@ -1,16 +0,0 @@
import { RemoteHandlerAbstract } from '@xen-orchestra/fs'
const METADATA_BACKUP_ID_REGEXP =
/^xo-(config|pool-metadata)-backups\/\w{8}(-\w{4}){3}-\w{12}(\/\w{8}(-\w{4}){3}-\w{12})?\/\d{8}T\d{6}Z/
/**
* Deletes an XO config or pool metadata backup directory (not a VM backup).
* Shared with the legacy @xen-orchestra/backups RemoteAdapter.
*/
export async function deleteMetadataBackup(handler: RemoteHandlerAbstract, backupId: string): Promise<void> {
if (!METADATA_BACKUP_ID_REGEXP.test(backupId)) {
throw new Error(`The id (${backupId}) not correspond to a metadata folder`)
}
await handler.rmtree(backupId)
}

View File

@@ -47,7 +47,7 @@ export class RemoteDiskLineage {
constructor(handler: RemoteHandlerAbstract, vdiDir: string, opts: ResolvedBackupCleanOptions) {
this.#handler = handler
this.#vdiDir = normalize(vdiDir)
this.#vdiDir = vdiDir
this.#opts = opts
}

View File

@@ -55,8 +55,6 @@ export interface CheckResult {
export type CleanResult = {
removedFiles: string[]
// Files rewritten in place (e.g. metadata whose size was updated after a merge)
changedFiles?: string[]
merge?: boolean
size?: number
mergedSizes?: Map<string, number>

View File

@@ -17,8 +17,11 @@ import {
import { cleanOrphanDiskDirs } from '@xen-orchestra/backup-archive/disks'
import { asyncEach } from '@vates/async-each'
import { createLogger } from '@xen-orchestra/log'
import { readBackupCache, writeBackupCache } from './BackupCache.mjs'
import { unlinkTolerant } from './_unlinkTolerant.mjs'
import { promisify } from 'node:util'
import zlib from 'node:zlib'
const gzip = promisify(zlib.gzip)
const gunzip = promisify(zlib.gunzip)
const { info: logInfo, warn: logWarn } = createLogger('xo:backup-archive')
@@ -27,7 +30,7 @@ const FILES_TO_KEEP = ['cache.json.gz', 'vdis']
export class VmBackupDirectory implements VmBackupInterface {
handler: RemoteHandlerAbstract
rootPath: string
files: Array<string> = []
files: Array<string> = new Array()
orphans: Set<string> = new Set()
backupArchives: Map<string, VmBackupInterface> = new Map()
opts: ResolvedBackupCleanOptions
@@ -40,9 +43,6 @@ export class VmBackupDirectory implements VmBackupInterface {
// on disk, so clean() must regenerate it even when nothing was merged/removed.
#cacheOutOfSync = false
// Set by #checkCacheCount(): whether cache.json.gz existed at the start of the run.
#cacheExisted = false
constructor(
handler: RemoteHandlerAbstract,
vmBackupPath: string,
@@ -67,11 +67,21 @@ export class VmBackupDirectory implements VmBackupInterface {
}
async #readCache(path: string): Promise<Record<string, unknown> | undefined> {
return readBackupCache(this.handler, path, logWarn)
try {
return JSON.parse((await gunzip(await this.handler.readFile(path))).toString())
} catch (error) {
if (error?.code !== 'ENOENT') {
logWarn('failed to read cache', { error, path })
}
}
}
async #writeCache(path: string, data: Record<string, unknown>): Promise<void> {
return writeBackupCache(this.handler, path, data, logWarn)
try {
await this.handler.writeFile(path, await gzip(JSON.stringify(data)), { flags: 'w' })
} catch (error) {
logWarn('failed to write cache', { error, path })
}
}
async init() {
@@ -80,9 +90,9 @@ export class VmBackupDirectory implements VmBackupInterface {
this.#uniqueLineages = new Map()
for (const fullPath of this.files.filter(path => path.endsWith('.json'))) {
let metadata: PartialBackupMetadata | undefined
let metadata: PartialBackupMetadata | undefined = undefined
try {
metadata = JSON.parse((await this.handler.readFile(fullPath)).toString()) satisfies PartialBackupMetadata
metadata = JSON.parse(await this.handler.readFile(fullPath)) satisfies PartialBackupMetadata
} catch (error) {
this.opts.logWarn(`Issue loading ${basename(fullPath)}`)
}
@@ -166,35 +176,18 @@ export class VmBackupDirectory implements VmBackupInterface {
// Let each archive clean its own files (e.g. remove metadata for incomplete backups)
// and update metadata with merged sizes if applicable
const archiveRemovedFiles = new Set<string>()
const changedFiles = new Set<string>()
const goneArchives: string[] = []
await asyncEach(
Array.from(this.backupArchives.entries()),
async ([metadataPath, archive]: [string, VmBackupInterface]) => {
const { removedFiles, changedFiles: archiveChangedFiles } = await archive.clean({
remove,
mergedSizes: allMergedSizes,
})
Array.from(this.backupArchives.values()),
async (archive: VmBackupInterface) => {
const { removedFiles } = await archive.clean({ remove, mergedSizes: allMergedSizes })
if (removedFiles.length > 0) {
cacheNeedsRegen = true
removedFiles.forEach(file => archiveRemovedFiles.add(file))
}
if (removedFiles.includes(metadataPath)) {
goneArchives.push(metadataPath)
}
archiveChangedFiles?.forEach(file => changedFiles.add(file))
},
{ concurrency: 2 }
)
// an archive whose metadata has just been deleted is not a backup anymore: it must not be
// advertised by the regenerated cache
for (const metadataPath of goneArchives) {
this.backupArchives.delete(metadataPath)
}
if (this.#cacheExisted && (allMergedSizes.size > 0 || cacheNeedsRegen || this.#cacheOutOfSync)) {
if (allMergedSizes.size > 0 || cacheNeedsRegen || this.#cacheOutOfSync) {
await this.#regenerateCache()
}
@@ -217,50 +210,13 @@ export class VmBackupDirectory implements VmBackupInterface {
)
}
const size = [...allMergedSizes.values()].reduce((total, merged) => total + merged, 0)
// `removedFiles` lists the files this run removed, or would have removed if `remove` were set:
// root-level orphans plus the files each archive deemed removable (e.g. the metadata of an
// incomplete backup). Callers acting on it must therefore check `remove` themselves.
orphans.forEach(orphan => archiveRemovedFiles.add(orphan))
return {
removedFiles: Array.from(archiveRemovedFiles),
changedFiles: Array.from(changedFiles),
merge: someLineageMergedOrShouldBe,
size: size,
}
return { removedFiles: orphans, merge: someLineageMergedOrShouldBe, size: size }
}
async #checkCacheCount(): Promise<void> {
const cachePath = `${this.rootPath}/cache.json.gz`
this.#cacheExisted = false
this.#cacheOutOfSync = false
if (!this.files.includes(normalize(cachePath))) {
return
}
if (this.handler.isImmutable()) {
// RemoteAdapter never creates cache.json.gz on immutable repositories: remove the
// leftover, readable or not, and never regenerate it. Best effort: some remotes
// (e.g. S3) may not normalize a permission error to EPERM, so tolerate any error.
try {
await this.handler.unlink(cachePath)
} catch (error) {
this.opts.logWarn('error while deleting leftover backup cache', { path: cachePath, error })
}
return
}
const existingCache = await this.#readCache(cachePath)
if (existingCache === undefined) {
// present but unreadable: drop it, RemoteAdapter will recreate a valid one
this.opts.logWarn('removing unreadable backup cache', { path: cachePath })
await unlinkTolerant(this.handler, cachePath)
return
}
this.#cacheExisted = true
const actual = Object.keys(existingCache).length
const actual = existingCache === undefined ? 0 : Object.keys(existingCache).length
const expected = this.backupArchives.size
this.#cacheOutOfSync = actual !== expected
if (this.#cacheOutOfSync) {
@@ -327,6 +283,7 @@ export class VmBackupDirectory implements VmBackupInterface {
const dir = new VmBackupDirectory(handler, vmBackupPath, cleanOpts)
await dir.init()
await dir.check()
return await dir.clean({ remove: cleanOpts.remove, merge: cleanOpts.merge })
const { merge, size } = await dir.clean({ remove: cleanOpts.remove, merge: cleanOpts.merge })
return { merge, size }
}
}

View File

@@ -10,13 +10,8 @@ import { rimraf } from 'rimraf'
// eslint-disable-next-line n/no-missing-import
import { VmBackupDirectory } from '../dist/VmBackupDirectory.mjs'
import tar from 'tar-stream'
import { promisify } from 'node:util'
import zlib from 'node:zlib'
const { beforeEach, afterEach, describe } = test
const gzip = promisify(zlib.gzip)
const gunzip = promisify(zlib.gunzip)
let tempDir, handler, vmBackupDir
const vmUuid = 'test-vm-uuid'
const rootPath = `xo-vm-backups/${vmUuid}`
@@ -129,10 +124,7 @@ describe('VmBackupDirectory with full backups', { concurrency: 1 }, () => {
test('clean() preserves cache.json.gz', async () => {
await createFullBackupMetadata('backup1.json', 'backup1.xva')
await handler.writeFile(
`${rootPath}/cache.json.gz`,
await gzip(JSON.stringify({ [`/${rootPath}/backup1.json`]: {} }))
)
await handler.writeFile(`${rootPath}/cache.json.gz`, 'cache')
await VmBackupDirectory.cleanVm(handler, rootPath)
@@ -141,104 +133,6 @@ describe('VmBackupDirectory with full backups', { concurrency: 1 }, () => {
assert.ok(remainingFiles.includes('cache.json.gz'))
})
test('clean() removes an unreadable cache.json.gz', async () => {
await createFullBackupMetadata('backup1.json', 'backup1.xva')
await handler.writeFile(`${rootPath}/cache.json.gz`, 'not gzipped json')
await VmBackupDirectory.cleanVm(handler, rootPath, { logWarn: () => {} })
const remainingFiles = await handler.list(rootPath)
assert.ok(!remainingFiles.includes('cache.json.gz'), 'an unreadable cache.json.gz should be removed, not kept')
})
test('clean() on an immutable remote never creates cache.json.gz', async () => {
await createFullBackupMetadata('backup1.json', 'backup1.xva')
await handler.writeFile(`${rootPath}/orphan.xva`, 'orphan-content')
handler.isImmutable = () => true
await VmBackupDirectory.cleanVm(handler, rootPath, { remove: true })
const remainingFiles = await handler.list(rootPath)
assert.ok(!remainingFiles.includes('cache.json.gz'), 'cache.json.gz should never be created on an immutable remote')
})
test('clean() removes a leftover cache.json.gz found on an immutable remote', async () => {
await createFullBackupMetadata('backup1.json', 'backup1.xva')
await handler.writeFile(`${rootPath}/cache.json.gz`, await gzip(JSON.stringify({})))
handler.isImmutable = () => true
await VmBackupDirectory.cleanVm(handler, rootPath)
const remainingFiles = await handler.list(rootPath)
assert.ok(!remainingFiles.includes('cache.json.gz'), 'erroneous cache.json.gz should be removed, not rewritten')
})
test('clean() removes an unreadable leftover cache.json.gz found on an immutable remote', async () => {
await createFullBackupMetadata('backup1.json', 'backup1.xva')
await handler.writeFile(`${rootPath}/cache.json.gz`, 'not gzipped json')
handler.isImmutable = () => true
await VmBackupDirectory.cleanVm(handler, rootPath)
const remainingFiles = await handler.list(rootPath)
assert.ok(
!remainingFiles.includes('cache.json.gz'),
'an unreadable cache.json.gz should be removed from an immutable remote'
)
})
test('clean() tolerates an EPERM while removing the cache of an immutable remote', async () => {
await createFullBackupMetadata('backup1.json', 'backup1.xva')
await handler.writeFile(`${rootPath}/cache.json.gz`, await gzip(JSON.stringify({})))
handler.isImmutable = () => true
handler.unlink = () => {
const error = new Error('EPERM: operation not permitted')
error.code = 'EPERM'
throw error
}
await VmBackupDirectory.cleanVm(handler, rootPath)
const remainingFiles = await handler.list(rootPath)
assert.ok(remainingFiles.includes('cache.json.gz'), 'the immutable cache.json.gz could not be removed')
})
test('clean() keeps maintaining a pre-existing cache.json.gz across a remove', async () => {
await createFullBackupMetadata('backup1.json', 'backup1.xva')
await createFullBackupMetadata('backup2.json', 'backup2.xva')
// a cache with the expected number of entries: only the removal can trigger the regeneration
const cachePath = `${rootPath}/cache.json.gz`
await handler.writeFile(
cachePath,
await gzip(
JSON.stringify({
[`/${rootPath}/backup1.json`]: { stale: true },
[`/${rootPath}/backup2.json`]: { stale: true },
})
)
)
// backup2 loses its XVA: its metadata will be removed by clean()
await handler.unlink(`${rootPath}/backup2.xva`)
await VmBackupDirectory.cleanVm(handler, rootPath, { remove: true, logInfo: () => {}, logWarn: () => {} })
const remainingFiles = await handler.list(rootPath)
assert.ok(remainingFiles.includes('backup1.json'))
assert.ok(remainingFiles.includes('backup1.xva'))
assert.ok(!remainingFiles.includes('backup2.json'), 'metadata of the backup with a missing XVA should be removed')
assert.ok(remainingFiles.includes('cache.json.gz'), 'an existing cache.json.gz must not be dropped by a remove')
const cache = JSON.parse((await gunzip(await handler.readFile(cachePath))).toString())
assert.deepEqual(
Object.keys(cache),
[`/${rootPath}/backup1.json`],
'cache.json.gz should have been regenerated with the surviving backup only'
)
assert.equal(cache[`/${rootPath}/backup1.json`].stale, undefined, 'the entry must come from the archive on disk')
})
test('clean() removes an orphan XVA checksum file (no matching metadata or XVA)', async () => {
await handler.writeFile(`${rootPath}/stray.xva.checksum`, 'sha256:deadbeef')

View File

@@ -1,6 +1,6 @@
import { basename, normalize, resolveFromFile } from '@xen-orchestra/fs/path'
import { basename, normalize } from '@xen-orchestra/fs/path'
import assert from 'node:assert'
import { FileDescriptor, RemoteHandlerAbstract } from '@xen-orchestra/fs'
import { FileDescriptor } from '@xen-orchestra/fs'
import {
ArchiveCleanOptions,
CheckResult,
@@ -8,10 +8,8 @@ import {
VmBackupInterface,
PartialBackupMetadata,
ResolvedBackupCleanOptions,
DEFAULT_REMOVE_CONCURRENCY,
} from './VmBackup.types.mjs'
import { asyncEach } from '@vates/async-each'
import { unlinkTolerant } from './_unlinkTolerant.mjs'
import { RemoteHandlerAbstract } from '@xen-orchestra/fs'
const COMPRESSED_MAGIC_NUMBERS: Buffer[] = [
// https://tools.ietf.org/html/rfc1952.html#page-5
@@ -82,29 +80,6 @@ export async function isValidXva(
const noop = (): void => {}
/**
* Deletes a full VM backup's metadata json and, when provided, its xva and checksum.
* `xva` is the path as stored in the metadata, i.e. relative to the metadata file.
* Shared with the legacy @xen-orchestra/backups RemoteAdapter.
*/
export async function deleteFullVmBackups(
handler: RemoteHandlerAbstract,
backups: Array<{ metadataPath: string; xva?: string }>
): Promise<void> {
await asyncEach(
backups,
async ({ metadataPath, xva }) => {
await unlinkTolerant(handler, metadataPath)
if (xva !== undefined) {
const xvaPath = resolveFromFile(metadataPath, xva)
await unlinkTolerant(handler, xvaPath)
await unlinkTolerant(handler, `${xvaPath}.checksum`)
}
},
{ concurrency: DEFAULT_REMOVE_CONCURRENCY, stopOnError: false }
)
}
export class VmFullBackupArchive implements VmBackupInterface {
handler: RemoteHandlerAbstract
rootPath: string
@@ -183,10 +158,12 @@ export class VmFullBackupArchive implements VmBackupInterface {
files: this.getAssociatedFiles({ prefix: false }),
})
} else {
try {
await deleteFullVmBackups(this.handler, [{ metadataPath: this.metadataPath, xva: this.metadata.xva }])
} catch (error) {
this.opts.logWarn(`Issue removing backup files`, { error, metadataPath: this.metadataPath })
for (const file of removedFiles) {
try {
await this.handler.unlink(file)
} catch (error) {
this.opts.logWarn(`Issue removing ${file}`, { error })
}
}
}
}
@@ -196,7 +173,7 @@ export class VmFullBackupArchive implements VmBackupInterface {
}
getAssociatedFiles({ prefix = false }): Array<string> {
const validFiles = [this.metadataPath, this.xvaPath, `${this.xvaPath}.checksum`]
let validFiles = [this.metadataPath, this.xvaPath, `${this.xvaPath}.checksum`]
return prefix ? validFiles : validFiles.map(file => basename(file))
}
}

View File

@@ -6,13 +6,10 @@ import fs from 'fs-extra'
import * as uuid from 'uuid'
import { getHandler } from '@xen-orchestra/fs'
import { pFromCallback } from 'promise-toolbox'
// `dist/` is built by the `test-integration` script, which starts by removing it: these imports
// cannot be resolved when linting a working tree that has not been built yet
/* eslint-disable n/no-missing-import */
// eslint-disable-next-line n/no-missing-import
import { VmBackupDirectory } from '../dist/VmBackupDirectory.mjs'
import { RemoteVhdDisk } from '../dist/disks/RemoteVhdDisk.mjs'
import { MergeRemoteDisk } from '../dist/disks/MergeRemoteDisk.mjs'
/* eslint-enable n/no-missing-import */
import { VHDFOOTER, VHDHEADER } from './tests.fixtures.mjs'
import { VhdFile, Constants, VhdDirectory, VhdAbstract } from 'vhd-lib'
import { dirname, basename } from 'node:path'
@@ -23,7 +20,6 @@ import { rimraf } from 'rimraf'
const { beforeEach, afterEach, describe } = test
const gunzip = promisify(zlib.gunzip)
const gzip = promisify(zlib.gzip)
let tempDir, handler, jobId, vdiId, basePath, relativePath, vdiId2, basePath2, relativePath2
const rootPath = 'xo-vm-backups/VMUUID/'
@@ -209,8 +205,8 @@ test('it remove backup metadata referencing a missing vhd in delta backup', asyn
assert.equal(matched.length, 2) // all vhds (orphan and child ) should have been deleted
assert.ok(
!(await handler.list(rootPath)).includes('cache.json.gz'),
'cache.json.gz should not be created when none existed before the clean'
(await handler.list(rootPath)).includes('cache.json.gz'),
'cache.json.gz should be regenerated after metadata deletion'
)
})
@@ -368,6 +364,7 @@ test('it merges delta of non destroyed chain', async () => {
logged.push(message)
}
await VmBackupDirectory.cleanVm(handler, rootPath, { remove: true, logInfo, logWarn: logInfo })
assert.equal(logged[0], `unexpected number of entries in backup cache`)
logged = []
await VmBackupDirectory.cleanVm(handler, rootPath, { remove: true, merge: true, logInfo, logWarn: () => {} })
@@ -729,10 +726,10 @@ 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, 6501888)
// no cache.json.gz existed before this run, so a merge must not create one
// cache.json.gz must be regenerated when metadata changes after a merge
assert.ok(
!(await handler.list(rootPath)).includes('cache.json.gz'),
'cache.json.gz should not be created when none existed before the merge'
(await handler.list(rootPath)).includes('cache.json.gz'),
'cache.json.gz should be regenerated after a merge'
)
// broken vhd, non referenced, abandoned should be deleted ( alias and data)
@@ -836,7 +833,7 @@ test('it preserves VDI directory when handler.list() throws during lineage init'
assert.ok(remaining.includes('snapshot.vhd'), 'VHD must survive when handler.list() throws during lineage init')
})
test('it does not create nor warn about the cache when none existed, even with a count mismatch', async () => {
test('it regenerates the cache when its entry count is out of sync, even with nothing to merge/remove', async () => {
// a referenced disk + its metadata, but no cache.json.gz on disk
await generateVhd(`${basePath}/diskA1.vhd`)
await handler.writeFile(
@@ -845,79 +842,6 @@ test('it does not create nor warn about the cache when none existed, even with a
)
await assert.rejects(handler.readFile(`${rootPath}/cache.json.gz`), { code: 'ENOENT' })
const logged = []
// remove/merge both false: cacheNeedsRegen stays false and no merge happens,
// so only a pre-existing cache's count mismatch could trigger regeneration
await VmBackupDirectory.cleanVm(handler, rootPath, {
remove: false,
merge: false,
logInfo: () => {},
logWarn: message => logged.push(message),
})
assert.ok(!logged.includes('unexpected number of entries in backup cache'), 'no cache to be mismatched, no warning')
await assert.rejects(handler.readFile(`${rootPath}/cache.json.gz`), { code: 'ENOENT' })
})
test('it regenerates a pre-existing cache after a merge', async () => {
await handler.writeFile(
`${rootPath}/metadata.json`,
JSON.stringify({
mode: 'delta',
size: 12000, // a size too small, the merge will fix it
vhds: [`${relativePath}/grandchild.vhd`, `${relativePath}/child.vhd`],
})
)
// one orphan, which is a full vhd, no parent
const orphan = await generateVhd(`${basePath}/orphan.vhd`)
// a child to the orphan, orphan will be merged into it
const child = await generateVhd(`${basePath}/child.vhd`, {
header: {
parentUnicodeName: 'orphan.vhd',
parentUuid: orphan.footer.uuid,
},
blocks: [0, 1],
})
await generateVhd(`${basePath}/grandchild.vhd`, {
header: {
parentUnicodeName: 'child.vhd',
parentUuid: child.footer.uuid,
},
})
// a cache with the expected number of entries: it is not out of sync, only the merge can trigger the regeneration
await handler.writeFile(
`${rootPath}/cache.json.gz`,
await gzip(JSON.stringify({ [`/${rootPath}metadata.json`]: { size: 12000 } }))
)
const result = await VmBackupDirectory.cleanVm(handler, rootPath, {
remove: true,
merge: true,
logInfo: () => {},
logWarn: () => {},
})
const metadata = JSON.parse(await handler.readFile(`${rootPath}/metadata.json`))
// size of child + grandchild after orphan has been merged into child
assert.equal(metadata.size, 4299776, 'metadata.size should be updated after merge')
assert.deepEqual(result.changedFiles, [`/${rootPath}metadata.json`], 'the rewritten metadata should be reported')
const cache = JSON.parse((await gunzip(await handler.readFile(`${rootPath}/cache.json.gz`))).toString())
assert.equal(Object.keys(cache).length, 1)
assert.equal(Object.values(cache)[0].size, metadata.size, 'cache entry should carry the post-merge size')
})
test('it regenerates a pre-existing cache when its entry count is out of sync, even with nothing to merge/remove', async () => {
// a referenced disk + its metadata, and a pre-existing cache with the wrong entry count
await generateVhd(`${basePath}/diskA1.vhd`)
await handler.writeFile(
`${rootPath}/metadata.json`,
JSON.stringify({ mode: 'delta', vhds: [`${relativePath}/diskA1.vhd`] })
)
await handler.writeFile(`${rootPath}/cache.json.gz`, await gzip(JSON.stringify({})))
const logged = []
// remove/merge both false: cacheNeedsRegen stays false and no merge happens,
// so only the cache-count mismatch can trigger the regeneration
@@ -933,53 +857,3 @@ test('it regenerates a pre-existing cache when its entry count is out of sync, e
const cache = JSON.parse((await gunzip(await handler.readFile(`${rootPath}/cache.json.gz`))).toString())
assert.equal(Object.keys(cache).length, 1, 'cache should be regenerated to match the archives on disk')
})
test('it regenerates a pre-existing cache after a metadata removal', async () => {
// two backups, each on its own VDI directory, so removing one does not touch the other's disks
await generateVhd(`${basePath}/diskA1.vhd`)
await handler.writeFile(
`${rootPath}/metadata1.json`,
JSON.stringify({ mode: 'delta', vhds: [`${relativePath}/diskA1.vhd`] })
)
// metadata2 references a vhd missing from disk: clean() removes it
await handler.writeFile(
`${rootPath}/metadata2.json`,
JSON.stringify({ mode: 'delta', vhds: [`${relativePath2}/deleted.vhd`] })
)
// a cache with the expected number of entries: only the removal can trigger the regeneration
await handler.writeFile(
`${rootPath}/cache.json.gz`,
await gzip(
JSON.stringify({
[`/${rootPath}metadata1.json`]: { stale: true },
[`/${rootPath}metadata2.json`]: { stale: true },
})
)
)
const logged = []
await VmBackupDirectory.cleanVm(handler, rootPath, {
remove: true,
merge: false,
logInfo: () => {},
logWarn: message => logged.push(message),
})
const rootFiles = await handler.list(rootPath)
assert.ok(rootFiles.includes('metadata1.json'), 'the complete backup must survive')
assert.ok(!rootFiles.includes('metadata2.json'), 'the backup with a missing vhd must be removed')
assert.ok(rootFiles.includes('cache.json.gz'), 'an existing cache.json.gz must not be dropped by a remove')
assert.ok(
!logged.includes('unexpected number of entries in backup cache'),
'the cache matched the archives before the clean: the removal alone must trigger the regeneration'
)
const cache = JSON.parse((await gunzip(await handler.readFile(`${rootPath}/cache.json.gz`))).toString())
assert.deepEqual(
Object.keys(cache),
[`/${rootPath}metadata1.json`],
'the removed backup must be gone from the regenerated cache'
)
assert.equal(cache[`/${rootPath}metadata1.json`].stale, undefined, 'the entry must come from the archive on disk')
})

View File

@@ -5,27 +5,10 @@ import {
ResolvedBackupCleanOptions,
VmBackupInterface,
PartialBackupMetadata,
DEFAULT_REMOVE_CONCURRENCY,
} from './VmBackup.types.mjs'
import { RemoteHandlerAbstract } from '@xen-orchestra/fs'
import { basename, dirname, normalize } from '@xen-orchestra/fs/path'
import { RemoteDiskLineage } from './RemoteDiskLineage.mjs'
import { asyncEach } from '@vates/async-each'
/**
* Deletes a delta VM backup's metadata json. Unused VHDs are detected and removed
* separately by VmBackupDirectory's clean(). Shared with the legacy @xen-orchestra/backups
* RemoteAdapter.
*/
export async function deleteDeltaVmBackups(
handler: RemoteHandlerAbstract,
backups: Array<{ metadataPath: string }>
): Promise<void> {
await asyncEach(backups, ({ metadataPath }) => handler.unlink(metadataPath), {
concurrency: DEFAULT_REMOVE_CONCURRENCY,
stopOnError: false,
})
}
export class VmIncrementalBackupArchive implements VmBackupInterface {
handler: RemoteHandlerAbstract
@@ -149,7 +132,6 @@ export class VmIncrementalBackupArchive implements VmBackupInterface {
}
}
const changedFiles: string[] = []
let mergedSize = 0
if (mergedSizes !== undefined) {
for (const diskPath of this.diskPaths) {
@@ -157,11 +139,10 @@ export class VmIncrementalBackupArchive implements VmBackupInterface {
}
if (mergedSize > 0) {
await this.updateMetadata(mergedSize)
changedFiles.push(this.metadataPath)
}
}
return { removedFiles, changedFiles }
return { removedFiles }
}
/**

View File

@@ -1,20 +0,0 @@
import { RemoteHandlerAbstract } from '@xen-orchestra/fs'
/**
* Deletes a file, ignoring the given error codes.
* By default only a missing file is tolerated.
*/
export async function unlinkTolerant(
handler: RemoteHandlerAbstract,
path: string,
ignoredCodes: string[] = ['ENOENT']
): Promise<void> {
try {
await handler.unlink(path)
} catch (error) {
if (!ignoredCodes.includes(error?.code)) {
error.path ??= path
throw error
}
}
}

View File

@@ -140,7 +140,7 @@ export class MergeRemoteDisk {
try {
const mergeStateContent = await this.#handler.readFile(this.#statePath)
this.#state = JSON.parse(mergeStateContent.toString())
this.#state = JSON.parse(mergeStateContent)
// work-around to bugs introduced in 97d94b795 and 4e50858
//
@@ -344,7 +344,7 @@ export class MergeRemoteDisk {
const parentPath = normalize(vdiDir + '/' + match[1])
let chain
try {
const state = JSON.parse((await handler.readFile(filePath)).toString())
const state = JSON.parse(await handler.readFile(filePath))
if (Array.isArray(state?.chain)) {
chain = state.chain.map((/** @type {string} */ relPath) => normalize(resolveFromFile(filePath, relPath)))
} else {

View File

@@ -229,21 +229,6 @@ export class RemoteDisk extends RandomAccessDisk {
throw new Error(`isDifferencing must be implemented`)
}
/**
* Checks whether this disk (or chain) can act as the merge-target parent for a disk
* about to be written with the given reference configuration.
*
* Base check: this disk's own uuid matches the expected parent uuid. Subclasses should
* override to add implementation-specific compatibility checks (storage sub-format,
* compression, ...) — calling `super.isMergeableParent()` first.
*
* @param {string} parentUuid
* @returns {Promise<boolean>}
*/
async isMergeableParent(parentUuid) {
return this.getUuid() === parentUuid
}
/**
* Abstract
* Rename alias/disk

View File

@@ -17,7 +17,7 @@ import { isVhdAlias, resolveVhdAlias } from 'vhd-lib/aliases.js'
import { stringify } from 'uuid'
import { dirname, join } from 'node:path'
import { RemoteVhdDiskChain } from './RemoteVhdDiskChain.mjs'
import { isInDir, normalize } from '@xen-orchestra/fs/path'
import { normalize } from '@xen-orchestra/fs/path'
export class RemoteVhdDisk extends RemoteDisk {
/**
@@ -81,13 +81,12 @@ export class RemoteVhdDisk extends RemoteDisk {
})
this.#vhd = value
this.#dispose = dispose
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
if (!options.ignoreBlockIndexes) {
await this.#vhd.readBlockAllocationTable()
}
@@ -434,36 +433,6 @@ export class RemoteVhdDisk extends RemoteDisk {
return this.#isDifferencing
}
/**
* Returns the compression codec id. Only meaningful for VHD directories;
* undefined for plain VHDs.
* @returns {string | undefined}
*/
#getCompressionType() {
if (this.#vhd === undefined) {
throw new Error(`can't check compressionType of a RemoteVhdDisk before init`)
}
return this.#vhd instanceof VhdDirectory ? this.#vhd.compressionType : undefined
}
/**
* Adds VHD-specific compatibility checks on top of the uuid check: the storage
* sub-format (VHD directory vs plain) and, for directories, the compression codec
* must match what this remote would write for a new disk.
* @param {string} parentUuid
* @returns {Promise<boolean>}
*/
async isMergeableParent(parentUuid) {
if (!(await super.isMergeableParent(parentUuid))) {
return false
}
const useVhdDirectory = this.#handler.getConfig('useVhdDirectory') ?? false
const compressionType = this.#handler.getConfig('compressionType') ?? 'brotli'
const isDirectory = await this.isDirectory()
return isDirectory ? useVhdDirectory && this.#getCompressionType() === compressionType : !useVhdDirectory
}
/**
* Rename alias/disk
* @param {string} newPath
@@ -571,15 +540,18 @@ export class RemoteVhdDisk extends RemoteDisk {
* @returns {Promise<string[]>}
*/
async listAssociatedFiles(dir) {
const prefix = normalize(dir.endsWith('/') ? dir : dir + '/')
const isInDir = /** @param {string} p */ p => p === dir || p.startsWith(prefix)
const files = []
if (isInDir(this.#path, dir)) {
if (isInDir(this.#path)) {
files.push(this.#path)
}
if (isVhdAlias(this.#path)) {
try {
const resolved = await resolveVhdAlias(this.#handler, this.#path)
if (isInDir(resolved, dir)) {
if (isInDir(resolved)) {
files.push(resolved)
}
} catch {

View File

@@ -1,76 +0,0 @@
import { createLogger } from '@xen-orchestra/log'
import { asBlockHash, BlockHash, HASH_SIZE } from './hbdPaths.mjs'
const { warn } = createLogger('xo:backup-archive:bat')
const ZERO_ENTRY = Buffer.alloc(HASH_SIZE)
export class BlockAllocationTable {
#bat: Buffer
#maxBlockCount: number
static allocate(maxBlockCount: number): BlockAllocationTable {
return new BlockAllocationTable(Buffer.alloc(maxBlockCount * HASH_SIZE), maxBlockCount)
}
static fromBuffer(buffer: Buffer, maxBlockCount: number, force = false): BlockAllocationTable {
const expected = maxBlockCount * HASH_SIZE
if (buffer.length !== expected) {
const message = `unexpected hashes file size: ${buffer.length} instead of ${expected}`
if (force) {
warn(message)
maxBlockCount = Math.min(maxBlockCount, Math.floor(buffer.length / HASH_SIZE))
} else {
throw new Error(message)
}
}
return new BlockAllocationTable(buffer, maxBlockCount)
}
private constructor(bat: Buffer, maxBlockCount: number) {
this.#bat = bat
this.#maxBlockCount = maxBlockCount
}
#entry(index: number): Buffer {
if (index < 0 || index >= this.#maxBlockCount) {
throw new Error(`block index ${index} out of range [0, ${this.#maxBlockCount})`)
}
const offset = index * HASH_SIZE
return this.#bat.subarray(offset, offset + HASH_SIZE)
}
get(index: number): BlockHash {
return this.#entry(index).toString('hex') as BlockHash
}
set(index: number, hash: BlockHash) {
if (this.#entry(index).write(asBlockHash(hash), 'hex') !== HASH_SIZE) {
throw new Error(`incomplete write of block hash ${hash}`)
}
}
isEmpty(index: number): boolean {
return this.#entry(index).equals(ZERO_ENTRY)
}
countAllocated(): number {
let total = 0
for (let idx = 0; idx < this.#maxBlockCount; idx++) {
if (!this.isEmpty(idx)) total++
}
return total
}
indexes(): Array<number> {
const res = new Array<number>()
for (let idx = 0; idx < this.#maxBlockCount; idx++) {
if (!this.isEmpty(idx)) res.push(idx)
}
return res
}
toBuffer(): Buffer {
return this.#bat
}
}

View File

@@ -1,3 +0,0 @@
import { RemoteDisk } from '../RemoteDisk.mjs'
export class HashedDisk extends RemoteDisk {}

View File

@@ -1,79 +0,0 @@
import { test } from 'node:test'
import { strict as assert } from 'node:assert'
import tmp from 'tmp'
import { getHandler } from '@xen-orchestra/fs'
import { pFromCallback } from 'promise-toolbox'
import { rimraf } from 'rimraf'
import { HashedDiskDeduplicated } from '@xen-orchestra/backup-archive/disks/hashed'
const BLOCK_SIZE = 2 * 1024 * 1024
const BLOCK_COUNT = 100
const UNIQUE_PAYLOADS = 70
async function listFiles(handler, dir) {
const found = []
for (const entry of await handler.list(dir, { prependDir: true })) {
try {
found.push(...(await listFiles(handler, entry)))
} catch (error) {
if (error.code !== 'ENOTDIR') {
throw error
}
found.push(entry)
}
}
return found
}
// index i holds payload (i % UNIQUE_PAYLOADS), so the last 30 blocks repeat earlier content
const payloadOf = index => Buffer.alloc(BLOCK_SIZE, (index % UNIQUE_PAYLOADS) % 256)
test('a full disk round trips, and duplicate payloads are stored once', async () => {
const tempDir = await pFromCallback(cb => tmp.dir(cb))
const handler = getHandler({ url: `file://${tempDir}` })
await handler.sync()
try {
const path = 'xo-vm-backups/VMUUID/vdis/job/vdi/20260814T120000000Z.hbd'
const disk = await HashedDiskDeduplicated.create({
handler,
path,
virtualSize: BLOCK_SIZE * BLOCK_COUNT,
blockSize: BLOCK_SIZE,
uuid: '7d1e4c92-3f60-4a8b-b5c7-1e9f08d2a643',
})
for (let index = 0; index < BLOCK_COUNT; index++) {
assert.equal(await disk.writeBlock({ index, data: payloadOf(index) }), BLOCK_SIZE)
}
assert.equal(disk.getBlockIndexes().length, BLOCK_COUNT)
assert.equal(disk.getSizeOnDisk(), BLOCK_COUNT * BLOCK_SIZE)
// the repeated payloads share a hash, so they share a file
assert.equal(disk.getBlockHashAt(0), disk.getBlockHashAt(UNIQUE_PAYLOADS))
await disk.close()
// reopen from scratch: nothing may be kept in memory
const reopened = new HashedDiskDeduplicated({ handler, path })
await reopened.init()
assert.equal(reopened.getBlockIndexes().length, BLOCK_COUNT)
for (let index = 0; index < BLOCK_COUNT; index++) {
const { data } = await reopened.readBlock(index)
assert.ok(data.equals(payloadOf(index)), `block ${index} differs`)
}
const blockFiles = (await listFiles(handler, 'xo-vm-backups')).filter(file => file.includes('/blocks/'))
assert.equal(blockFiles.length, UNIQUE_PAYLOADS, `${BLOCK_COUNT} blocks stored as ${UNIQUE_PAYLOADS} files`)
await reopened.unlink()
assert.deepEqual(await listFiles(handler, 'xo-vm-backups'), [])
} finally {
await handler.forget()
await rimraf(tempDir)
}
})

View File

@@ -1,524 +0,0 @@
import type { DiskBlock } from '@xen-orchestra/disk-transform'
import type { RemoteHandlerAbstract } from '@xen-orchestra/fs'
import { dirname, join } from 'node:path'
import { Readable } from 'node:stream'
import { isInDir, normalize } from '@xen-orchestra/fs/path'
import pRetry from 'promise-toolbox/retry'
import { createLogger } from '@xen-orchestra/log'
import { HashedDisk } from './HashedDisk.mjs'
import { BlockAllocationTable } from './BlockAllocationTable.mjs'
import {
blockRelPath,
buildBlockHeader,
checkVersion,
dataDirName,
decodeBlock,
hashesFileName,
HbdFileError,
sha256hex,
VERSION,
type DedupType,
type BlockHash,
type HashedDiskMetadata,
} from './hbdPaths.mjs'
import { randomUUID } from 'node:crypto'
const { warn } = createLogger('xo:backup-archive:hbd')
/**
* Content addressed disk: block index -> SHA-256 of the block payload, kept in a
* flat binary BAT, and one file per unique payload named after its hash.
*/
export class HashedDiskDeduplicated extends HashedDisk {
#handler: RemoteHandlerAbstract
#path: string
#metadata: HashedDiskMetadata | undefined
#bat: BlockAllocationTable | undefined
#blocksDir: string | undefined
#blockStorePath: string | undefined
#dirty = false
#replacedHashes = new Set<BlockHash>()
constructor({
handler,
path,
blockStorePath,
}: {
handler: RemoteHandlerAbstract
path: string
blockStorePath?: string
}) {
super()
this.#handler = handler
// normalized once here so every path this disk hands out or derives has the
// same shape: callers match them against paths listed from the handler, and
// an unnormalized one silently fails to compare equal
this.#path = normalize(path)
this.#blockStorePath = blockStorePath
}
/**
* New, empty disk on the remote and returns it, opened.
*/
static async create({
handler,
path,
virtualSize,
blockSize,
uuid,
parentUuid,
parentPath,
dedupType = 'PER_DISK',
blockStorePath,
}: {
handler: RemoteHandlerAbstract
path: string
virtualSize: number
blockSize: number
uuid: string
parentUuid?: string
parentPath?: string
dedupType?: DedupType
blockStorePath?: string
}): Promise<HashedDiskDeduplicated> {
const dataDir = dataDirName(uuid)
const hashesPath = join(dataDir, hashesFileName(new Date()))
const metadata = {
version: VERSION,
virtualSize,
blockSize,
uuid,
parentUuid,
parentPath,
dedupType,
localBlocksPath: `${dataDir}/blocks/`,
hashesPath,
} satisfies HashedDiskMetadata
if (metadata.dedupType === 'PER_BACKUP_REPOSITORY' && blockStorePath === undefined) {
throw new Error("Can't init PER_BACKUP_REPOSITORY without blockStorePath")
}
const bat = BlockAllocationTable.allocate(Math.ceil(virtualSize / blockSize))
const disk = new HashedDiskDeduplicated({ handler, path, blockStorePath })
await handler.outputFile(disk.#resolve(hashesPath), bat.toBuffer(), { flags: 'wx' })
await handler.outputFile(path, JSON.stringify(metadata), { flags: 'wx' })
await disk.init()
return disk
}
get #diskDir(): string {
return dirname(this.#path)
}
/**
* Resolves a path stored in the metadata, which is relative to the hbd file.
*/
#resolve(relativePath: string, container: string = this.#diskDir): string {
const resolved = normalize(join(this.#diskDir, relativePath))
if (!isInDir(resolved, container)) {
throw new Error(`path ${relativePath} escapes ${container}`)
}
return resolved
}
get #loadedMetadata(): HashedDiskMetadata {
if (this.#metadata === undefined) {
throw new Error(`can't use a HashedDiskDeduplicated before init`)
}
return this.#metadata
}
get #loadedBat(): BlockAllocationTable {
if (this.#bat === undefined) {
throw new Error(`can't use a HashedDiskDeduplicated before init`)
}
return this.#bat
}
#blockPath(hash: BlockHash): string {
if (this.#blocksDir === undefined) {
throw new Error(`can't use a HashedDiskDeduplicated before init`)
}
return join(this.#blocksDir, blockRelPath(hash))
}
/**
* @param hash always hex
* @returns complete path in store
* Rooted at the remote root, not the disk dir, so no #resolve: the root comes from
* the caller and the hash is always hex
*/
#storePath(hash: BlockHash): string {
if (this.#blockStorePath === undefined) {
throw new Error(`disk ${this.#path} is PER_BACKUP_REPOSITORY but no blockStorePath was given`)
}
return join(this.#blockStorePath, blockRelPath(hash), '0')
}
// ---------------------------------------------------------------- lifecycle
/**
* @param options.force to force read a hashes file whose size disagrees with
* virtualSize / blockSize, instead of refusing to open the disk (useful for first tests)
*/
async init(options: { force?: boolean } = {}): Promise<void> {
if (this.#metadata !== undefined) {
return
}
let metadata: HashedDiskMetadata
let hashesPath: string
let blocksDir: string
try {
metadata = JSON.parse((await this.#handler.readFile(this.#path)).toString())
checkVersion(metadata.version)
const { blockSize, virtualSize } = metadata
if (!Number.isInteger(blockSize) || blockSize <= 0) {
throw new Error(`invalid blockSize ${blockSize}`)
}
if (!Number.isInteger(virtualSize) || virtualSize < 0) {
throw new Error(`invalid virtualSize ${virtualSize}`)
}
const dataDir = this.#resolve(dataDirName(metadata.uuid))
hashesPath = this.#resolve(metadata.hashesPath, dataDir)
blocksDir = this.#resolve(metadata.localBlocksPath, dataDir)
} catch (error: unknown) {
throw new HbdFileError((error as NodeJS.ErrnoException).message, this.#path, error)
}
this.#metadata = metadata
this.#blocksDir = blocksDir
try {
this.#bat = BlockAllocationTable.fromBuffer(
await this.#handler.readFile(hashesPath),
this.getMaxBlockCount(),
options.force
)
} catch (error: unknown) {
this.#metadata = undefined
this.#blocksDir = undefined
throw new HbdFileError((error as NodeJS.ErrnoException).message, hashesPath, error)
}
}
async close(): Promise<void> {
if (this.#dirty) {
await this.flushMetadata()
}
}
// ---------------------------------------------------------------- getters
getVirtualSize(): number {
return this.#loadedMetadata.virtualSize
}
getBlockSize(): number {
return this.#loadedMetadata.blockSize
}
/**
* Virtual usage: what the guest sees as allocated, not the deduplicated footprint
*/
getSizeOnDisk(): number {
return this.#loadedBat.countAllocated() * this.getBlockSize()
}
getPath(): string {
return this.#path
}
getPaths(): Array<string> {
return [this.#path]
}
getUuid(): string {
return this.#loadedMetadata.uuid
}
getParentUuid(): string {
const { parentUuid } = this.#loadedMetadata
if (parentUuid === undefined) {
throw new Error(`disk ${this.#path} has no parent`)
}
return parentUuid
}
getParentPath(): string {
const { parentPath } = this.#loadedMetadata
if (parentPath === undefined) {
throw new Error(`disk ${this.#path} has no parent`)
}
return this.#resolve(parentPath)
}
getMetadata(): HashedDiskMetadata {
return { ...this.#loadedMetadata }
}
isDifferencing(): boolean {
return this.#loadedMetadata.parentUuid !== undefined
}
/** block files are independent, nothing is shared inside a single disk */
async canMergeConcurently(): Promise<boolean> {
return true
}
hasBlock(index: number): boolean {
return !this.#loadedBat.isEmpty(index)
}
getBlockIndexes(): Array<number> {
return this.#loadedBat.indexes()
}
getBlockHashAt(index: number): BlockHash {
return this.#loadedBat.get(index)
}
async #link(existingPath: string, newPath: string): Promise<void> {
try {
await this.#handler.link(existingPath, newPath)
} catch (error: unknown) {
// EEXIST => block already referenced by disk
if ((error as NodeJS.ErrnoException).code !== 'EEXIST') {
throw error
}
}
}
/**
* Writes the block file unless it is already there. 'wx' for concurrent cases
*/
async #storeBlock(hash: BlockHash, data: Buffer): Promise<void> {
try {
await this.#handler.outputFile(this.#blockPath(hash), Buffer.concat([buildBlockHeader(hash), data]), {
flags: 'wx',
})
} catch (error: unknown) {
if ((error as NodeJS.ErrnoException).code !== 'EEXIST') {
throw error
}
// already stored, by another index of this disk or by a previous run
}
}
async #addBlockReference(hash: BlockHash, data: Buffer): Promise<void> {
if (this.#loadedMetadata.dedupType === 'PER_DISK') {
return this.#storeBlock(hash, data)
}
const storePath = this.#storePath(hash)
const blockPath = this.#blockPath(hash)
try {
await this.#link(storePath, blockPath)
return
} catch (error: unknown) {
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
throw error
}
}
// link did not work, we need a new block
const tmp = join(this.#blocksDir!, '.tmp', randomUUID())
await this.#handler.outputFile(tmp, Buffer.concat([buildBlockHeader(hash), data]), { flags: 'wx' })
try {
await this.#link(tmp, storePath)
} finally {
await this.#handler.unlink(tmp, { checksum: false })
}
await this.#link(storePath, blockPath)
}
async readBlock(index: number): Promise<DiskBlock> {
const bat = this.#loadedBat
if (bat.isEmpty(index)) {
throw new Error(`no block at index ${index} of ${this.#path}`)
}
const hash = bat.get(index)
// reads the whole file: that is exactly header + payload, and unlike a
// positional read it also works on an encrypted remote
const buffer = await this.#handler.readFile(this.#blockPath(hash))
const { payload } = decodeBlock(buffer, this.getBlockSize(), hash)
return { index, data: payload }
}
/**
* Purely additive: the previous hash at this index keeps its block file until
* flushMetadata notices no BAT entry references it any more.
* TODO: phase 3
*/
async writeBlock({ index, data }: DiskBlock): Promise<number> {
const blockSize = this.getBlockSize()
if (data.length !== blockSize) {
throw new Error(`expected a ${blockSize} bytes block, got ${data.length}`)
}
const bat = this.#loadedBat
const hash = sha256hex(data)
// unchanged content at this index, nothing to do at all
if (!bat.isEmpty(index) && bat.get(index) === hash) {
return blockSize
}
const replaced = bat.isEmpty(index) ? undefined : bat.get(index)
await this.#addBlockReference(hash, data)
bat.set(index, hash)
if (replaced !== undefined) {
this.#replacedHashes.add(replaced)
}
this.#dirty = true
return blockSize
}
/**
* No-op: the BAT is built exclusively by writeBlock, which knows the hash.
* Declaring an index without content is meaningless in a content addressed
* format.
*/
async setAllocatedBlocks(): Promise<void> {}
// ---------------------------------------------------------------- metadata
/**
* best effort: the new BAT is already safe, a failure only leaks
*/
async #removeOrphans(): Promise<void> {
if (this.#replacedHashes.size === 0) {
return
}
try {
const candidates = new Set(this.#replacedHashes)
// a replaced hash can still be referenced at another index
for (const index of this.#loadedBat.indexes()) {
candidates.delete(this.#loadedBat.get(index))
}
for (const hash of candidates) {
await this.#removeBlockReference(hash)
}
this.#replacedHashes.clear()
} catch (error) {
warn('failed to remove orphaned blocks', { path: this.#path, error })
}
}
/**
* Writes the BAT to a new timestamped file, then points the hbd file at it.
* The previous hashes file is never overwritten, so a crash between the two
* writes leaves the disk readable through the old one. It is removed once
* the hbd points at the new one.
*/
async flushMetadata(): Promise<void> {
const metadata = this.#loadedMetadata
const dataDir = dirname(metadata.hashesPath)
// Every flush writes a new file: the one the hbd still points at must stay
// intact, so a crash before the hbd is updated leaves the disk readable.
// The name has a random part, a collision is only retried for safety.
const hashesPath: string = await pRetry(
async () => {
const path = join(dataDir, hashesFileName(new Date()))
await this.#handler.outputFile(this.#resolve(path), this.#loadedBat.toBuffer(), { flags: 'wx' })
return path
},
{ delay: 0, tries: 3, when: { code: 'EEXIST' } }
)
const newMetadata = { ...metadata, hashesPath }
await this.#handler.outputStream(this.#path, Readable.from(JSON.stringify(newMetadata)), { checksum: false })
this.#metadata = newMetadata
await this.#removeOrphans()
this.#dirty = false
// the hbd no longer points at it. Best effort: the data dir is claimed as
// a whole, so a file left by a failure or a crash is only removed by check()
try {
await this.#handler.unlink(this.#resolve(metadata.hashesPath), { checksum: false })
} catch (error) {
warn('failed to remove the previous hashes file', { path: this.#path, hashesPath: metadata.hashesPath, error })
}
}
/**
* What this disk claims inside `dir`: the hbd file, and its data directory as
* a whole. Used by lineage and remote cleanup to tell owned files from orphans.
*/
async listAssociatedFiles(dir: string): Promise<Array<string>> {
const files = [this.#path, this.#dataDir]
return files.filter(p => isInDir(p, dir))
}
/**
* holds the blocks and every hashes file, current and orphaned
*/
get #dataDir(): string {
return this.#resolve(dataDirName(this.#loadedMetadata.uuid))
}
async unlink(): Promise<void> {
if (this.#loadedMetadata.dedupType === 'PER_BACKUP_REPOSITORY') {
for (const index of this.#loadedBat.indexes()) {
try {
await this.#removeBlockReference(this.#loadedBat.get(index))
} catch (error) {
warn('failed to release block', { path: this.#path, index, error })
}
}
}
await this.#handler.unlink(this.#path)
await this.#handler.rmtree(this.#dataDir)
this.#replacedHashes.clear()
this.#metadata = undefined
this.#bat = undefined
this.#blocksDir = undefined
this.#dirty = false
}
/**
* @param options.skipStoreCheck the caller knows another disk still links
* this block (a parent holding the same hash during a merge), so the store
* file cannot be the last copy: saves one stat per block
*/
async #removeBlockReference(hash: BlockHash, { skipStoreCheck = false } = {}): Promise<void> {
const blockPath = this.#blockPath(hash)
if (this.#loadedMetadata.dedupType === 'PER_DISK' || skipStoreCheck) {
return this.#handler.unlink(blockPath, { checksum: false })
} else {
let nlink: number
try {
nlink = await this.#handler.getLinkCount(blockPath)
} catch (error: unknown) {
if ((error as NodeJS.ErrnoException).code === 'ENOENT') {
return
}
throw error
}
await this.#handler.unlink(blockPath, { checksum: false })
if (nlink === 2) {
await this.#handler.unlink(this.#storePath(hash), { checksum: false })
}
}
}
}

View File

@@ -1,736 +0,0 @@
import { test } from 'node:test'
import { strict as assert } from 'node:assert'
import { stat } from 'node:fs/promises'
import { join } from 'node:path'
import tmp from 'tmp'
import * as uuid from 'uuid'
import { getHandler, NotImplementedError } from '@xen-orchestra/fs'
import { pFromCallback } from 'promise-toolbox'
import { rimraf } from 'rimraf'
import {
asBlockHash,
BlockAllocationTable,
blockRelPath,
buildBlockHeader,
CODEC_BROTLI,
CODEC_RAW,
decodeBlock,
HASH_SIZE,
HashedDiskDeduplicated,
HBD_HEADER_SIZE,
HBD_MAGIC,
parseBlockHeader,
sha256hex,
} from '@xen-orchestra/backup-archive/disks/hashed'
const { beforeEach, afterEach, describe } = test
const BLOCK_SIZE = 4096
const VIRTUAL_SIZE = BLOCK_SIZE * 10
const DISK_UUID = '3a0c1f6e-2b7d-4e58-9f21-6c8d4b0a7e13'
let tempDir, handler, diskDir, diskPath
beforeEach(async () => {
tempDir = await pFromCallback(cb => tmp.dir(cb))
handler = getHandler({ url: `file://${tempDir}` })
await handler.sync()
diskDir = `xo-vm-backups/VMUUID/vdis/${uuid.v4()}`
diskPath = `${diskDir}/20260814T120000000Z.hbd`
})
afterEach(async () => {
await handler.forget()
await rimraf(tempDir)
})
const createDisk = (opts = {}) =>
HashedDiskDeduplicated.create({
handler,
path: diskPath,
virtualSize: VIRTUAL_SIZE,
blockSize: BLOCK_SIZE,
uuid: DISK_UUID,
...opts,
})
const block = byte => Buffer.alloc(BLOCK_SIZE, byte)
const countBlockFiles = () =>
handler
.list(`xo-vm-backups/VMUUID/vdis`, { prependDir: true })
.then(() => listFiles('xo-vm-backups'))
.then(files => files.filter(file => file.includes('/blocks/')).length)
async function listFiles(dir) {
const found = []
for (const entry of await handler.list(dir, { prependDir: true })) {
try {
found.push(...(await listFiles(entry)))
} catch (error) {
if (error.code !== 'ENOTDIR') {
throw error
}
found.push(entry)
}
}
return found
}
describe('hbdPaths', () => {
test('blockRelPath splits the hash into 4 segments of 16 chars', () => {
const hash = sha256hex(Buffer.from('x'))
const segments = blockRelPath(hash).split('/')
assert.equal(segments.length, 4)
segments.forEach(segment => assert.equal(segment.length, 16))
assert.equal(segments.join(''), hash)
})
test('asBlockHash rejects anything that is not a lowercase sha256 hex', () => {
assert.throws(() => asBlockHash('deadbeef'), /not a valid block hash/)
assert.throws(() => asBlockHash('Z'.repeat(64)), /not a valid block hash/)
assert.doesNotThrow(() => asBlockHash(sha256hex(Buffer.from('x'))))
})
test('block header round trips, and its magic reads as HBD in a dump', () => {
const hash = sha256hex(Buffer.from('payload'))
const header = buildBlockHeader(hash, CODEC_BROTLI, 1786807233123)
assert.equal(header.length, HBD_HEADER_SIZE)
assert.equal(header.subarray(0, 4).toString('latin1'), 'HBD\0')
assert.deepEqual(parseBlockHeader(header), {
magic: HBD_MAGIC,
codec: CODEC_BROTLI,
verifiedAt: 1786807233123,
payloadHash: hash,
})
// reserved ranges must stay zeroed
assert.ok(header.subarray(5, 8).every(byte => byte === 0))
assert.ok(header.subarray(48, HBD_HEADER_SIZE).every(byte => byte === 0))
})
test('buildBlockHeader defaults to raw, never verified', () => {
const header = parseBlockHeader(buildBlockHeader(sha256hex(Buffer.from('x'))))
assert.equal(header.codec, CODEC_RAW)
assert.equal(header.verifiedAt, 0)
})
test('decodeBlock returns the payload, and rejects every way it can be wrong', () => {
const data = block(0x42)
const hash = sha256hex(data)
const valid = Buffer.concat([buildBlockHeader(hash), data])
assert.ok(decodeBlock(valid, BLOCK_SIZE, hash).payload.equals(data))
assert.throws(() => decodeBlock(valid.subarray(0, valid.length - 1), BLOCK_SIZE, hash), /truncated block/)
const badMagic = Buffer.from(valid)
badMagic.writeUInt32BE(0xdeadbeef, 0)
assert.throws(() => decodeBlock(badMagic, BLOCK_SIZE, hash), /not a hbd block/)
// right path, content of another hash
assert.throws(() => decodeBlock(valid, BLOCK_SIZE, sha256hex(block(0x43))), /block hash mismatch/)
// payload rotted while the header still claims the old hash
const corrupted = Buffer.from(valid)
corrupted[HBD_HEADER_SIZE + 10] ^= 0xff
assert.throws(() => decodeBlock(corrupted, BLOCK_SIZE, hash), /block corruption on read/)
})
test('BlockAllocationTable stores hashes per entry, not per byte', () => {
const bat = BlockAllocationTable.allocate(10)
const hash = sha256hex(Buffer.from('x'))
assert.ok(bat.isEmpty(0))
assert.equal(bat.countAllocated(), 0)
assert.deepEqual(bat.indexes(), [])
bat.set(9, hash)
assert.equal(bat.get(9), hash)
assert.ok(!bat.isEmpty(9))
assert.ok(bat.isEmpty(8), 'writing entry 9 must not touch entry 8')
assert.deepEqual(bat.indexes(), [9])
assert.equal(bat.toBuffer().length, 10 * HASH_SIZE)
assert.throws(() => bat.get(10), /out of range/)
assert.throws(() => bat.get(-1), /out of range/)
})
test('BlockAllocationTable.set refuses a hash it would only write partially', () => {
const bat = BlockAllocationTable.allocate(2)
const hash = sha256hex(Buffer.from('x'))
bat.set(0, hash)
// a short or non-hex hash writes a prefix and leaves the rest of the entry
for (const bad of ['deadbeef', 'Z'.repeat(64), hash.toUpperCase(), hash + '00', '../../..']) {
assert.throws(() => bat.set(0, bad), /not a valid block hash/)
}
assert.equal(bat.get(0), hash, 'a rejected set leaves the entry untouched')
})
test('BlockAllocationTable.fromBuffer refuses a size mismatch unless forced', () => {
const short = Buffer.alloc(5 * HASH_SIZE)
assert.throws(() => BlockAllocationTable.fromBuffer(short, 10), /unexpected hashes file size/)
const forced = BlockAllocationTable.fromBuffer(short, 10, true)
assert.equal(forced.indexes().length, 0)
assert.throws(() => forced.get(5), /out of range/, 'the smaller count is authoritative')
})
})
describe('HashedDiskDeduplicated', () => {
test('create then init exposes an empty disk', async () => {
const disk = await createDisk()
assert.equal(disk.getVirtualSize(), VIRTUAL_SIZE)
assert.equal(disk.getBlockSize(), BLOCK_SIZE)
assert.equal(disk.getMaxBlockCount(), 10)
assert.equal(disk.getPath(), `/${diskPath}`, 'paths are normalized on the way in')
assert.equal(disk.isDifferencing(), false)
assert.deepEqual(disk.getBlockIndexes(), [])
assert.equal(disk.getSizeOnDisk(), 0)
assert.equal(disk.hasBlock(0), false)
})
test('a differencing disk reports its parent', async () => {
const disk = await createDisk({ parentUuid: 'parent-uuid', parentPath: './parent.hbd' })
assert.equal(disk.isDifferencing(), true)
assert.equal(disk.getParentUuid(), 'parent-uuid')
// relative to the hbd file's directory, normalized with a leading slash
assert.equal(disk.getParentPath(), `/${diskDir}/parent.hbd`)
})
test('writes and reads back the exact bytes', async () => {
const disk = await createDisk()
const data = block(0xaa)
assert.equal(await disk.writeBlock({ index: 3, data }), BLOCK_SIZE)
assert.ok(disk.hasBlock(3))
assert.deepEqual(disk.getBlockIndexes(), [3])
assert.ok((await disk.readBlock(3)).data.equals(data))
})
test('the same payload at two indexes is stored once', async () => {
const disk = await createDisk()
const shared = block(0xaa)
await disk.writeBlock({ index: 0, data: shared })
await disk.writeBlock({ index: 1, data: block(0xbb) })
await disk.writeBlock({ index: 7, data: shared })
assert.equal(disk.getBlockHashAt(0), disk.getBlockHashAt(7))
assert.equal(await countBlockFiles(), 2, '3 writes, 2 unique payloads')
// virtual usage, not the deduplicated footprint
assert.equal(disk.getSizeOnDisk(), 3 * BLOCK_SIZE)
})
test('rejects a block that is not exactly blockSize, and an unallocated read', async () => {
const disk = await createDisk()
await assert.rejects(() => disk.writeBlock({ index: 0, data: Buffer.alloc(10) }), /expected a 4096 bytes block/)
await assert.rejects(() => disk.readBlock(0), /no block at index 0/)
})
test('every init failure names the file it is about', async () => {
const disk = await createDisk()
const { hashesPath } = disk.getMetadata()
const reopen = () => new HashedDiskDeduplicated({ handler, path: diskPath }).init()
const writeHbd = metadata => handler.writeFile(diskPath, JSON.stringify(metadata), { flags: 'w' })
// the odd one out: the offending file is the hashes file, not the hbd
await handler.writeFile(`${diskDir}/${hashesPath}`, Buffer.alloc(HASH_SIZE), { flags: 'w' })
await assert.rejects(reopen, error => {
assert.equal(error.path, `/${diskDir}/${hashesPath}`)
assert.match(error.message, /unexpected hashes file size/)
return true
})
await writeHbd({ ...disk.getMetadata(), version: '99.0.0' })
await assert.rejects(reopen, error => {
assert.equal(error.path, `/${diskPath}`)
assert.match(error.message, /Unsupported hbd version 99\.0\.0/)
return true
})
await writeHbd({ ...disk.getMetadata(), blockSize: 0 })
await assert.rejects(reopen, error => {
assert.equal(error.path, `/${diskPath}`)
assert.match(error.message, /invalid blockSize 0/)
return true
})
await handler.writeFile(diskPath, '{ not json', { flags: 'w' })
await assert.rejects(reopen, error => {
assert.equal(error.path, `/${diskPath}`)
assert.ok(error.cause instanceof SyntaxError, 'the original error is kept as the cause')
return true
})
await assert.rejects(
() => new HashedDiskDeduplicated({ handler, path: `${diskDir}/absent.hbd` }).init(),
error => error.path === `/${diskDir}/absent.hbd`
)
})
test('refuses to open a disk whose metadata points outside of its own data directory', async () => {
const disk = await createDisk()
const metadata = disk.getMetadata()
const reopen = () => new HashedDiskDeduplicated({ handler, path: diskPath }).init()
const writeHbd = patch => handler.writeFile(diskPath, JSON.stringify({ ...metadata, ...patch }), { flags: 'w' })
const escapes = dir => new RegExp(`escapes ${dir} \\(in `)
await writeHbd({ hashesPath: '../../../../hashes.1.hash' })
await assert.rejects(reopen, escapes(`/${diskDir}/data/${DISK_UUID}`))
// inside the disk directory, but belonging to a sibling disk of the chain
await writeHbd({ hashesPath: `data/${uuid.v4()}/hashes.1.hash` })
await assert.rejects(reopen, escapes(`/${diskDir}/data/${DISK_UUID}`))
await writeHbd({ localBlocksPath: '../blocks/' })
await assert.rejects(reopen, escapes(`/${diskDir}/data/${DISK_UUID}`))
// `.` and `..` resolve back to a directory holding other disks, and a
// containment check accepts them: only the uuid format rules them out
for (const broken of ['../../..', '..', '.', 'not-a-uuid']) {
await writeHbd({ uuid: broken })
await assert.rejects(reopen, new RegExp(`not a valid uuid: ${broken.replace(/\./g, '\\.')} \\(in `))
}
// and the whole disk directory is still there
await writeHbd({})
await reopen()
})
test('a failed init leaves the disk closed, so a retry really retries', async () => {
const disk = await createDisk()
const { hashesPath } = disk.getMetadata()
const truncated = await handler.readFile(`${diskDir}/${hashesPath}`)
await handler.writeFile(`${diskDir}/${hashesPath}`, Buffer.alloc(HASH_SIZE), { flags: 'w' })
const reopened = new HashedDiskDeduplicated({ handler, path: diskPath })
await assert.rejects(() => reopened.init(), /unexpected hashes file size/)
// the disk must not consider itself open: fix the file, init again
await handler.writeFile(`${diskDir}/${hashesPath}`, truncated, { flags: 'w' })
await reopened.init()
assert.equal(reopened.getMaxBlockCount(), 10)
assert.deepEqual(reopened.getBlockIndexes(), [])
})
test('close flushes, and a reopened disk sees the same blocks', async () => {
const disk = await createDisk()
const data = block(0xaa)
await disk.writeBlock({ index: 2, data })
await disk.close()
const reopened = new HashedDiskDeduplicated({ handler, path: diskPath })
await reopened.init()
assert.deepEqual(reopened.getBlockIndexes(), [2])
assert.ok((await reopened.readBlock(2)).data.equals(data))
})
test('flushMetadata writes a new hashes file, then removes the previous one', async () => {
const disk = await createDisk()
const first = disk.getMetadata().hashesPath
await disk.writeBlock({ index: 0, data: block(0xaa) })
await disk.flushMetadata()
const second = disk.getMetadata().hashesPath
assert.notEqual(second, first)
const hashesFiles = (await listFiles('xo-vm-backups')).filter(file => file.endsWith('.hash'))
assert.deepEqual(hashesFiles, [`/${diskDir}/${second}`])
})
test('two flushes in a row get distinct hashes files', async () => {
const disk = await createDisk()
await disk.flushMetadata()
const first = disk.getMetadata().hashesPath
await disk.flushMetadata()
assert.notEqual(disk.getMetadata().hashesPath, first)
})
test('a previous hashes file that cannot be removed does not fail the flush', async () => {
const disk = await createDisk()
handler.unlink = async () => {
throw new Error('unlink failed')
}
await disk.writeBlock({ index: 0, data: block(0xaa) })
await disk.flushMetadata()
const reopened = new HashedDiskDeduplicated({ handler, path: diskPath })
await reopened.init()
assert.ok((await reopened.readBlock(0)).data.equals(block(0xaa)))
})
test('overwriting an index leaves the block it dropped on the remote', async () => {
const disk = await createDisk()
await disk.writeBlock({ index: 0, data: block(0xaa) })
await disk.flushMetadata()
await disk.writeBlock({ index: 0, data: block(0xbb) })
await disk.flushMetadata()
assert.equal(await countBlockFiles(), 1)
assert.ok((await disk.readBlock(0)).data.equals(block(0xbb)))
})
test('a corrupted block file is detected on read', async () => {
const disk = await createDisk()
await disk.writeBlock({ index: 0, data: block(0xaa) })
const [blockFile] = (await listFiles('xo-vm-backups')).filter(file => file.includes('/blocks/'))
const buffer = await handler.readFile(blockFile)
buffer[HBD_HEADER_SIZE + 1] ^= 0xff
await handler.writeFile(blockFile, buffer, { flags: 'w' })
await assert.rejects(() => disk.readBlock(0), /block corruption on read/)
})
test('listAssociatedFiles claims the data dir as a whole, not one entry per block', async () => {
const disk = await createDisk()
for (let index = 0; index < 5; index++) {
await disk.writeBlock({ index, data: block(index) })
}
const claimed = await disk.listAssociatedFiles('xo-vm-backups')
// 5 blocks on disk, still 2 claims: the hbd and the directory holding them
assert.deepEqual(claimed, [`/${diskPath}`, `/${diskDir}/data/${DISK_UUID}`])
})
test('listAssociatedFiles drops what falls outside the requested dir', async () => {
const disk = await createDisk()
await disk.writeBlock({ index: 0, data: block(0xaa) })
assert.deepEqual(await disk.listAssociatedFiles('/somewhere/else'), [])
})
test('unlink removes every file of the disk', async () => {
const disk = await createDisk()
await disk.writeBlock({ index: 0, data: block(0xaa) })
await disk.close()
await disk.unlink()
assert.deepEqual(await listFiles('xo-vm-backups'), [])
})
test('the merge lifecycle is not implemented yet', async () => {
const disk = await createDisk()
await assert.rejects(() => disk.mergeBlock(disk, 0, false), /must be implemented/)
await assert.rejects(() => disk.rename('other.hbd'), /must be implemented/)
})
})
describe('HashedDiskDeduplicated with a block store', () => {
const STORE = 'xo-block-store'
const createSharedDisk = async ({ blockStorePath = STORE } = {}) => {
const dir = `xo-vm-backups/VMUUID/vdis/${uuid.v4()}`
const diskUuid = uuid.v4()
const path = `${dir}/20260814T120000000Z.hbd`
const disk = await HashedDiskDeduplicated.create({
handler,
path,
virtualSize: VIRTUAL_SIZE,
blockSize: BLOCK_SIZE,
uuid: diskUuid,
dedupType: 'PER_BACKUP_REPOSITORY',
blockStorePath,
})
return { disk, path, tmpDir: `${dir}/data/${diskUuid}/blocks/.tmp` }
}
const nlink = async path => (await stat(join(tempDir, path))).nlink
test('create refuses PER_BACKUP_REPOSITORY without a blockStorePath, and writes nothing', async () => {
await assert.rejects(
() => createDisk({ dedupType: 'PER_BACKUP_REPOSITORY' }),
/Can't init PER_BACKUP_REPOSITORY without blockStorePath/
)
await assert.rejects(() => listFiles('xo-vm-backups'), { code: 'ENOENT' })
})
test('create records the dedup type in the metadata, but not the store path', async () => {
const { disk } = await createSharedDisk()
const metadata = disk.getMetadata()
assert.equal(metadata.dedupType, 'PER_BACKUP_REPOSITORY')
assert.ok(!JSON.stringify(metadata).includes(STORE), 'the store location must not be remote-controlled')
})
test('two disks writing the same payload share one inode', async () => {
const { disk: a } = await createSharedDisk()
const { disk: b } = await createSharedDisk()
const data = block(0xaa)
await a.writeBlock({ index: 0, data })
await b.writeBlock({ index: 3, data })
const storeFiles = await listFiles(STORE)
assert.equal(storeFiles.length, 1)
assert.equal(await nlink(storeFiles[0]), 3, 'store copy + one link per disk')
assert.ok((await a.readBlock(0)).data.equals(data))
assert.ok((await b.readBlock(3)).data.equals(data))
})
test('five writes of three unique payloads across two disks give three store files', async () => {
const { disk: a } = await createSharedDisk()
const { disk: b } = await createSharedDisk()
await a.writeBlock({ index: 0, data: block(1) })
await a.writeBlock({ index: 1, data: block(2) })
await b.writeBlock({ index: 0, data: block(1) })
await b.writeBlock({ index: 1, data: block(3) })
await b.writeBlock({ index: 2, data: block(2) })
assert.equal((await listFiles(STORE)).length, 3)
// disk side: 2 links in a, 3 in b
assert.equal(await countBlockFiles(), 5)
})
test('the same payload at two indexes of one disk is linked once', async () => {
const { disk } = await createSharedDisk()
const data = block(0xaa)
await disk.writeBlock({ index: 0, data })
await disk.writeBlock({ index: 7, data })
const storeFiles = await listFiles(STORE)
assert.equal(storeFiles.length, 1)
assert.equal(await nlink(storeFiles[0]), 2, 'the second index hits EEXIST on the disk link')
assert.equal(await countBlockFiles(), 1)
})
test('the temporary file of a store miss is removed', async () => {
const { disk, tmpDir } = await createSharedDisk()
await disk.writeBlock({ index: 0, data: block(0xaa) })
assert.deepEqual(await listFiles(tmpDir), [])
})
test('reads go through the disk link, never the store path', async () => {
const { disk } = await createSharedDisk()
const data = block(0xaa)
await disk.writeBlock({ index: 0, data })
const [storeFile] = await listFiles(STORE)
await handler.unlink(storeFile, { checksum: false })
assert.ok((await disk.readBlock(0)).data.equals(data))
})
test('a disk reopened without a store can still be read, but not written', async () => {
const { disk, path } = await createSharedDisk()
const data = block(0xaa)
await disk.writeBlock({ index: 0, data })
await disk.close()
const reopened = new HashedDiskDeduplicated({ handler, path })
await reopened.init()
assert.ok((await reopened.readBlock(0)).data.equals(data))
await assert.rejects(() => reopened.writeBlock({ index: 1, data: block(0xbb) }), /no blockStorePath was given/)
})
test('a handler without link fails at write time', async () => {
const { disk } = await createSharedDisk()
handler.link = async () => {
throw new NotImplementedError()
}
await assert.rejects(() => disk.writeBlock({ index: 0, data: block(0xaa) }), NotImplementedError)
})
})
describe('HashedDiskDeduplicated reference cleanup', () => {
const STORE = 'xo-block-store'
const createSharedDisk = async () => {
const dir = `xo-vm-backups/VMUUID/vdis/${uuid.v4()}`
return HashedDiskDeduplicated.create({
handler,
path: `${dir}/20260814T120000000Z.hbd`,
virtualSize: VIRTUAL_SIZE,
blockSize: BLOCK_SIZE,
uuid: uuid.v4(),
dedupType: 'PER_BACKUP_REPOSITORY',
blockStorePath: STORE,
})
}
// store directories are never removed, only their files
const listStore = () =>
listFiles(STORE).catch(error => {
if (error.code === 'ENOENT') {
return []
}
throw error
})
const nlink = async path => (await stat(join(tempDir, path))).nlink
// the store holds exactly one file per hash still referenced by a live disk
async function assertStoreConsistent(...disks) {
const referenced = new Set()
for (const disk of disks) {
for (const index of disk.getBlockIndexes()) {
referenced.add(disk.getBlockHashAt(index))
}
}
assert.equal((await listStore()).length, referenced.size)
}
test('overwrite then flush releases the old block, store file included', async () => {
const disk = await createSharedDisk()
await disk.writeBlock({ index: 0, data: block(0xaa) })
await disk.flushMetadata()
await disk.writeBlock({ index: 0, data: block(0xbb) })
await disk.flushMetadata()
const storeFiles = await listStore()
assert.equal(storeFiles.length, 1)
assert.equal(await nlink(storeFiles[0]), 2)
assert.equal(await countBlockFiles(), 1)
assert.ok((await disk.readBlock(0)).data.equals(block(0xbb)))
await assertStoreConsistent(disk)
})
test('the old block is released on the flush that follows the overwrite', async () => {
const disk = await createSharedDisk()
await disk.writeBlock({ index: 0, data: block(0xaa) })
await disk.flushMetadata()
await disk.writeBlock({ index: 0, data: block(0xbb) })
assert.equal((await listStore()).length, 2, 'nothing is released before the flush')
await disk.flushMetadata()
assert.equal((await listStore()).length, 1)
})
test('overwriting one of two indexes holding a hash keeps its block', async () => {
const disk = await createSharedDisk()
const shared = block(0xaa)
await disk.writeBlock({ index: 0, data: shared })
await disk.writeBlock({ index: 5, data: shared })
await disk.flushMetadata()
await disk.writeBlock({ index: 0, data: block(0xbb) })
await disk.flushMetadata()
assert.ok((await disk.readBlock(5)).data.equals(shared))
await assertStoreConsistent(disk)
})
test('a hash that moved to another index keeps its block', async () => {
const disk = await createSharedDisk()
const moved = block(0xaa)
await disk.writeBlock({ index: 0, data: moved })
await disk.flushMetadata()
await disk.writeBlock({ index: 1, data: moved })
await disk.writeBlock({ index: 0, data: block(0xbb) })
await disk.flushMetadata()
assert.ok((await disk.readBlock(1)).data.equals(moved))
await assertStoreConsistent(disk)
})
test('a hash replaced before its first flush is released too', async () => {
const disk = await createSharedDisk()
await disk.writeBlock({ index: 0, data: block(0xaa) })
await disk.writeBlock({ index: 0, data: block(0xbb) })
await disk.flushMetadata()
assert.equal(await countBlockFiles(), 1)
await assertStoreConsistent(disk)
})
test('a hash replaced then written back before the flush keeps its block', async () => {
const disk = await createSharedDisk()
await disk.writeBlock({ index: 0, data: block(0xaa) })
await disk.writeBlock({ index: 0, data: block(0xbb) })
await disk.writeBlock({ index: 0, data: block(0xaa) })
await disk.flushMetadata()
assert.ok((await disk.readBlock(0)).data.equals(block(0xaa)))
await assertStoreConsistent(disk)
})
test('a flush with no change leaves every link in place', async () => {
const disk = await createSharedDisk()
await disk.writeBlock({ index: 0, data: block(0xaa) })
await disk.flushMetadata()
await disk.flushMetadata()
const [storeFile] = await listStore()
assert.equal(await nlink(storeFile), 2)
})
test('releasing a block shared with another disk keeps the store file', async () => {
const a = await createSharedDisk()
const b = await createSharedDisk()
await a.writeBlock({ index: 0, data: block(0xaa) })
await b.writeBlock({ index: 0, data: block(0xaa) })
await a.flushMetadata()
await a.writeBlock({ index: 0, data: block(0xbb) })
await a.flushMetadata()
assert.ok((await b.readBlock(0)).data.equals(block(0xaa)))
await assertStoreConsistent(a, b)
})
test('unlinking disks releases the store file only with the last one', async () => {
const a = await createSharedDisk()
const b = await createSharedDisk()
const shared = block(0xaa)
await a.writeBlock({ index: 0, data: shared })
await b.writeBlock({ index: 2, data: shared })
await a.close()
await b.close()
await a.unlink()
const [storeFile] = await listStore()
assert.equal(await nlink(storeFile), 2, 'store copy + b')
assert.ok((await b.readBlock(2)).data.equals(shared))
await b.unlink()
assert.deepEqual(await listStore(), [])
})
test('unlink releases blocks that were never flushed', async () => {
const disk = await createSharedDisk()
await disk.writeBlock({ index: 0, data: block(0xaa) })
await disk.unlink()
assert.deepEqual(await listStore(), [])
assert.deepEqual(await listFiles('xo-vm-backups'), [])
})
test('unlink releases a hash held at several indexes once', async () => {
const disk = await createSharedDisk()
await disk.writeBlock({ index: 0, data: block(0xaa) })
await disk.writeBlock({ index: 1, data: block(0xaa) })
await disk.writeBlock({ index: 2, data: block(0xbb) })
await disk.unlink()
assert.deepEqual(await listStore(), [])
})
})

View File

@@ -1,188 +0,0 @@
// Offset Size Field
// 0 4 magic: 0x48424400 ("HBD\0")
// 4 1 codec: 0x00 = raw (no compression),0x01= brotli compression , reserved for future codecs,
// 5 3 reserved for compression flags (zero)
// 8 8 verified_at: Unix timestamp in milliseconds of last successful hash check (0 = never)
// 16 32 payload_hash: SHA-256 of the raw (uncompressed, unencrypted) payload — redundant with
// the store path but enables self-contained verification without path context
// 48 464 reserved (zero)
// 512 N payload: raw block data (currently uncompressed, unencrypted; N = blockSize)
import crypto from 'node:crypto'
import { validate as validateUuid } from 'uuid'
import type { Branded } from '@vates/types'
import { compareVersions } from 'compare-versions'
import { createLogger } from '@xen-orchestra/log'
const { warn } = createLogger('xo:backup-archive:hbd')
export type BlockHash = Branded<'hbd-block-hash'>
export const VERSION = '0.0.1'
export const HBD_HEADER_SIZE = 512
export const HBD_MAGIC = 0x48424400
export const HASH_SIZE = 32 // bytes, on disk
// block header field offsets, in bytes (see the layout table at the top of this file)
const OFFSET_MAGIC = 0
const OFFSET_CODEC = 4
const OFFSET_VERIFIED_AT = 8
const OFFSET_PAYLOAD_HASH = 16
export const CODEC_RAW = 0x00
export const CODEC_BROTLI = 0x01
const HASH_HEX_LENGTH = HASH_SIZE * 2 // chars, in memory
const HASH_PATH_DEPTH = 4
const HASH_PATH_SEGMENT = HASH_HEX_LENGTH / HASH_PATH_DEPTH
const BLOCK_HASH_RE = new RegExp(`^[0-9a-f]{${HASH_HEX_LENGTH}}$`)
export function asBlockHash(value: string): BlockHash {
if (!BLOCK_HASH_RE.test(value)) {
throw new Error(`not a valid block hash: ${value}`)
}
return value as BlockHash
}
export type DedupType = 'PER_BACKUP_REPOSITORY' | 'PER_DISK'
export interface HashedDiskMetadata {
version: string
virtualSize: number
blockSize: number
uuid: string
parentUuid?: string
parentPath?: string // relative path to parent hbd file from this hbd file
dedupType: DedupType
localBlocksPath: string //relative to this file
hashesPath: string //relative to this file
}
export class HbdFileError extends Error {
path: string
constructor(message: string, path: string, cause?: unknown) {
super(`${message} (in ${path})`, { cause })
this.path = path
}
}
export function checkVersion(version: string) {
if (compareVersions(version, VERSION) > 0) {
throw new Error(`Unsupported hbd version ${version}, expected: ${VERSION}`)
}
}
/**
* Directory holding everything a disk owns (hashes files and blocks), relative
* to its hbd file. Derived from the uuid rather than read from the metadata, so
* it is the same directory whatever the metadata claims.
*/
export function dataDirName(uuid: string): string {
if (!validateUuid(uuid)) {
throw new Error(`not a valid uuid: ${uuid}`)
}
return `data/${uuid}`
}
export function blockRelPath(hash: BlockHash): string {
return `${hash.slice(0, HASH_PATH_SEGMENT)}/${hash.slice(HASH_PATH_SEGMENT, HASH_PATH_SEGMENT * 2)}/${hash.slice(HASH_PATH_SEGMENT * 2, HASH_PATH_SEGMENT * 3)}/${hash.slice(HASH_PATH_SEGMENT * 3, HASH_PATH_SEGMENT * 4)}`
}
export interface HbdBlockHeader {
magic: number
codec: number
verifiedAt: number // ms since epoch, 0 = never verified
payloadHash: BlockHash
}
export function buildBlockHeader(hash: BlockHash, codec = CODEC_RAW, verifiedAt = 0): Buffer {
if (!Number.isInteger(codec) || codec < 0 || codec > 0xff) {
throw new Error(`codec must be a single byte, got ${codec}`)
}
if (!Number.isSafeInteger(verifiedAt) || verifiedAt < 0) {
throw new Error(`verifiedAt must be a non negative safe integer, got ${verifiedAt}`)
}
// zero filled, which is exactly what the reserved ranges (5..7 and 48..511) must contain
const header = Buffer.alloc(HBD_HEADER_SIZE)
// big endian so the bytes read as "HBD\0" in a hex dump
header.writeUInt32BE(HBD_MAGIC, OFFSET_MAGIC)
header.writeUInt8(codec, OFFSET_CODEC)
header.writeBigInt64LE(BigInt(verifiedAt), OFFSET_VERIFIED_AT)
if (header.write(hash, OFFSET_PAYLOAD_HASH, 'hex') !== HASH_SIZE) {
throw new Error(`not a valid block hash: ${hash}`)
}
return header
}
/**
* Accepts a buffer of at least HBD_HEADER_SIZE bytes, so a full block
* (header + payload) can be passed without slicing it first.
*
* Does not validate `magic`: it is returned so the caller decides what a
* mismatch means. Any caller reading a payload MUST check it.
*/
export function parseBlockHeader(buffer: Buffer): HbdBlockHeader {
if (buffer.length < HBD_HEADER_SIZE) {
throw new Error(`a block header is ${HBD_HEADER_SIZE} bytes, got ${buffer.length}`)
}
return {
magic: buffer.readUInt32BE(OFFSET_MAGIC),
codec: buffer.readUInt8(OFFSET_CODEC),
verifiedAt: Number(buffer.readBigInt64LE(OFFSET_VERIFIED_AT)),
payloadHash: buffer.subarray(OFFSET_PAYLOAD_HASH, OFFSET_PAYLOAD_HASH + HASH_SIZE).toString('hex') as BlockHash,
}
}
/**
* Validates a full block file (header + payload) and returns its payload.
*
* `expectedHash` is the hash the BAT holds for this index: it is the authority,
* the header is only cross checked against it. Pure, no I/O — the caller reads
* the bytes and decides what to do with a throw.
*/
export function decodeBlock(
buffer: Buffer,
blockSize: number,
expectedHash: BlockHash
): { header: HbdBlockHeader; payload: Buffer } {
const expectedLength = HBD_HEADER_SIZE + blockSize
if (buffer.length < expectedLength) {
throw new Error(`truncated block: expected ${expectedLength} bytes, got ${buffer.length}`)
}
const header = parseBlockHeader(buffer)
if (header.magic !== HBD_MAGIC) {
throw new Error(`not a hbd block: magic is 0x${header.magic.toString(16)}`)
}
if (header.payloadHash !== expectedHash) {
// wrong file at the right path, or a store file overwritten by another hash
throw new Error(`block hash mismatch: header says ${header.payloadHash}, expected ${expectedHash}`)
}
const payload = buffer.subarray(HBD_HEADER_SIZE, expectedLength)
// Only raw payloads can be checked here. An authenticated encryption codec
// gets the same guarantee from its auth tag at decryption time.
if (header.codec === CODEC_RAW) {
const actualHash = sha256hex(payload)
if (actualHash !== expectedHash) {
warn('block corruption on read', { expected: expectedHash, actual: actualHash })
throw new Error(`block corruption on read: expected ${expectedHash}, got ${actualHash}`)
}
}
return { header, payload }
}
export function hashesFileName(date: Date): string {
return `hashes.${date.getTime()}.${crypto.randomBytes(4).toString('hex')}.hash`
}
export function sha256hex(data: Buffer): BlockHash {
const hash = crypto.createHash('sha256')
return hash.update(data).digest('hex') as BlockHash
}

View File

@@ -1,4 +0,0 @@
export { BlockAllocationTable } from './BlockAllocationTable.mjs'
export { HashedDisk } from './HashedDisk.mjs'
export { HashedDiskDeduplicated } from './HashedDiskDeduplicated.mjs'
export * from './hbdPaths.mjs'

View File

@@ -1,5 +1 @@
export { VmBackupDirectory } from './VmBackupDirectory.mjs'
export { deleteFullVmBackups } from './VmFullBackupArchive.mjs'
export { deleteDeltaVmBackups } from './VmIncrementalBackupArchive.mjs'
export { deleteMetadataBackup } from './MetadataBackup.mjs'
export { readBackupCache, writeBackupCache } from './BackupCache.mjs'

View File

@@ -14,6 +14,5 @@
"types": ["node"] // Only use types from Node.js and packages that are explicitly imported
},
"include": ["src/**/*"],
// *.test.mjs and *.integ.mjs deliberately import from the built dist/ output to test it
"exclude": ["node_modules", "dist", "**/*.test.mjs", "**/*.integ.mjs"]
"exclude": ["node_modules", "dist"]
}

View File

@@ -7,8 +7,8 @@
"bugs": "https://github.com/vatesfr/xen-orchestra/issues",
"dependencies": {
"@vates/async-each": "^1.0.3",
"@xen-orchestra/async-map": "^0.1.4",
"@xen-orchestra/backups": "^0.74.2",
"@xen-orchestra/async-map": "^0.1.3",
"@xen-orchestra/backups": "^0.73.10",
"@xen-orchestra/fs": "^4.9.3",
"filenamify": "^6.0.0",
"getopts": "^2.2.5",
@@ -28,7 +28,7 @@
"scripts": {
"postversion": "npm publish --access public"
},
"version": "1.1.14",
"version": "1.1.13",
"license": "AGPL-3.0-or-later",
"author": {
"name": "Vates SAS",

View File

@@ -1,325 +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 { relativeFromFile } from '@xen-orchestra/fs/path'
import { Disposable, pFromCallback } from 'promise-toolbox'
import { RandomAccessDisk } from '@xen-orchestra/disk-transform'
import { RemoteAdapter } from './RemoteAdapter.mjs'
import { checkDisk } from './_runners/_writers/_checkDisk.mjs'
import { formatFilenameDate } from './_filenameDate.mjs'
import { VHDFOOTER, VHDHEADER } from './tests.fixtures.mjs'
import { openVhd, VhdFile, VhdAbstract, Constants, VhdDirectory } from 'vhd-lib'
import computeGeometryForSize from 'vhd-lib/_computeGeometryForSize.js'
import { dirname, basename } from 'node:path'
import { rimraf } from 'rimraf'
const { beforeEach, afterEach, describe } = test
let tempDir, handler, jobId, vdiId, basePath, relativePath
const vmUuid = 'a1b2c3d4-0000-0000-0000-000000000000'
const rootPath = `xo-vm-backups/${vmUuid}`
beforeEach(async () => {
tempDir = await pFromCallback(cb => tmp.dir(cb))
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 getAdapter({ useVhdDirectory = false, vhdDirectoryCompression, remoteCompressionType } = {}) {
handler = getHandler({ url: `file://${tempDir}`, useVhdDirectory, compressionType: remoteCompressionType })
await handler.sync()
return new RemoteAdapter(handler, { vhdDirectoryCompression })
}
const listVmDir = () => handler.list(rootPath, { ignoreMissing: true })
// write a full backup the way a backup job would, i.e. through the adapter
function writeFullBackup(adapter, timestamp = Date.now()) {
return adapter.writeVmBackupMetadata(vmUuid, {
mode: 'full',
xva: `./${formatFilenameDate(timestamp)}.xva`,
vm: { uuid: vmUuid },
jobId: uuid.v1(),
scheduleId: uuid.v1(),
timestamp,
})
}
// mirrors the helper in _cleanVm.integ.mjs, with compression support for VHD directories.
// VHD directories are only openable through their alias (see RemoteVhdDisk.init), so
// `path` here is always the alias-less name; the alias is created as `${path}.alias.vhd`.
async function generateVhd(path, opts = {}) {
let vhd
let dataPath = path
const { mode = 'file' } = opts
assert.ok(mode === 'file' || mode === 'directory', `unknown mode ${mode}`)
if (mode === 'directory') {
dataPath = dirname(path) + '/data/' + basename(path)
await handler.mkdir(dirname(path) + '/data/')
await handler.mkdir(dataPath)
vhd = new VhdDirectory(handler, dataPath, { compression: opts.compression })
} else {
const fd = await handler.openFile(dataPath, 'wx')
vhd = new VhdFile(handler, fd)
}
vhd.header = { ...VHDHEADER, ...opts.header }
vhd.footer = { ...VHDFOOTER, ...opts.footer, uuid: opts.uuid ?? uniqueIdBuffer() }
if (vhd.header.parentUuid) {
vhd.footer.diskType = Constants.DISK_TYPES.DIFFERENCING
} else {
vhd.footer.diskType = Constants.DISK_TYPES.DYNAMIC
}
if (mode === 'directory') {
await VhdAbstract.createAlias(handler, path + '.alias.vhd', dataPath)
}
await vhd.writeBlockAllocationTable()
await vhd.writeHeader()
await vhd.writeFooter()
return vhd
}
describe('cache.json.gz on an immutable remote', { concurrency: 1 }, () => {
test('writing a backup does not create it', async () => {
const adapter = await getAdapter()
handler.isImmutable = () => true
await writeFullBackup(adapter)
assert.ok(
!(await listVmDir()).includes('cache.json.gz'),
'cache.json.gz must never be created on an immutable remote'
)
})
// deleteFullVmBackups() rather than deleteVmBackup(), because the latter also runs cleanVm()
// which removes a leftover cache and would hide a cache wrongly written by the deletion itself
test('deleting a backup does not create it', async () => {
const adapter = await getAdapter()
handler.isImmutable = () => true
await writeFullBackup(adapter)
const backups = await adapter.listVmBackups(vmUuid)
assert.equal(backups.length, 1)
await adapter.deleteFullVmBackups(backups)
assert.ok(
!(await listVmDir()).includes('cache.json.gz'),
'cache.json.gz must never be created on an immutable remote'
)
})
test('it is still created on a mutable remote', async () => {
const adapter = await getAdapter()
await writeFullBackup(adapter)
assert.ok((await listVmDir()).includes('cache.json.gz'), 'a mutable remote must keep using the cache')
})
})
describe('RemoteAdapter#isMergeableParent', { concurrency: 1 }, () => {
for (const diskIsDirectory of [false, true]) {
for (const useVhdDirectory of [false, true]) {
for (const compressionMatches of [false, true]) {
for (const uuidMatches of [false, true]) {
const expected = uuidMatches && (diskIsDirectory ? useVhdDirectory && compressionMatches : !useVhdDirectory)
test(`diskIsDirectory=${diskIsDirectory} useVhdDirectory=${useVhdDirectory} compressionMatches=${compressionMatches} uuidMatches=${uuidMatches} -> ${expected}`, async () => {
const targetCompression = 'brotli'
const adapter = await getAdapter({ useVhdDirectory, vhdDirectoryCompression: targetCompression })
const targetUuid = uniqueIdBuffer()
await generateVhd(`${basePath}/disk.vhd`, {
mode: diskIsDirectory ? 'directory' : 'file',
compression: diskIsDirectory ? (compressionMatches ? targetCompression : 'gzip') : undefined,
uuid: uuidMatches ? targetUuid : uniqueIdBuffer(),
})
const path = diskIsDirectory ? `${basePath}/disk.vhd.alias.vhd` : `${basePath}/disk.vhd`
assert.equal(await adapter.isMergeableParent(targetUuid, path), expected)
})
}
}
}
}
})
describe('RemoteAdapter#isMergeableParent compression resolution', { concurrency: 1 }, () => {
test('the per-remote compressionType override wins over the adapter default', async () => {
const adapter = await getAdapter({
useVhdDirectory: true,
vhdDirectoryCompression: 'gzip', // config.toml-style default
remoteCompressionType: 'brotli', // per-remote override, should be the one actually compared against
})
const targetUuid = uniqueIdBuffer()
await generateVhd(`${basePath}/disk.vhd`, { mode: 'directory', compression: 'brotli', uuid: targetUuid })
assert.equal(await adapter.isMergeableParent(targetUuid, `${basePath}/disk.vhd.alias.vhd`), true)
})
test('a disk compressed with the adapter default (not the override) is rejected', async () => {
const adapter = await getAdapter({
useVhdDirectory: true,
vhdDirectoryCompression: 'gzip',
remoteCompressionType: 'brotli',
})
const targetUuid = uniqueIdBuffer()
// disk uses the config default, not the remote override that's actually in effect
await generateVhd(`${basePath}/disk.vhd`, { mode: 'directory', compression: 'gzip', uuid: targetUuid })
assert.equal(await adapter.isMergeableParent(targetUuid, `${basePath}/disk.vhd.alias.vhd`), false)
})
test("a remote-level 'none' override means no compression, ignoring the adapter default", async () => {
const adapter = await getAdapter({
useVhdDirectory: true,
vhdDirectoryCompression: 'brotli',
remoteCompressionType: 'none',
})
const targetUuid = uniqueIdBuffer()
// no compression option => VhdDirectory's own getCompressionType() is undefined, matching 'none'
await generateVhd(`${basePath}/disk.vhd`, { mode: 'directory', uuid: targetUuid })
assert.equal(await adapter.isMergeableParent(targetUuid, `${basePath}/disk.vhd.alias.vhd`), true)
})
})
const DEFAULT_BLOCK_SIZE = 0x00200000 // 2MB, from vhd-lib spec
// minimal source disk, enough for writeVhd() to produce a real, readable VHD
class MockDisk extends RandomAccessDisk {
#size
#blockIndexes
#fillByte
#differencing
constructor(nbBlocks, blockIndexes, fillByte, { differencing = false } = {}) {
super()
const { actualSize } = computeGeometryForSize(nbBlocks * DEFAULT_BLOCK_SIZE)
this.#size = actualSize
this.#blockIndexes = blockIndexes
this.#fillByte = fillByte
this.#differencing = differencing
}
async readBlock(index) {
const remaining = this.#size - DEFAULT_BLOCK_SIZE * index
return { index, data: Buffer.alloc(Math.min(remaining, DEFAULT_BLOCK_SIZE), this.#fillByte) }
}
getVirtualSize() {
return this.#size
}
getBlockSize() {
return DEFAULT_BLOCK_SIZE
}
isDifferencing() {
return this.#differencing
}
getBlockIndexes() {
return this.#blockIndexes
}
hasBlock(index) {
return this.#blockIndexes.includes(index)
}
async init() {}
async close() {}
}
// IncrementalRemoteWriter._transfer(): the disk is written
// through the adapter, and the *real* checkDisk() is used as the validator
describe('RemoteAdapter#writeVhd validated by checkDisk', { concurrency: 1 }, () => {
for (const useVhdDirectory of [false, true]) {
const mode = useVhdDirectory ? 'directory' : 'file'
test(`${mode}: writes a base disk that passes validation and reads back`, async () => {
const adapter = await getAdapter({ useVhdDirectory })
const path = `${basePath}/${adapter.getVhdFileName('base')}`
const size = await adapter.writeVhd(path, new MockDisk(2, [0, 1], 0x42), {
validator: tmpPath => checkDisk(handler, tmpPath),
uuid: uniqueIdBuffer(),
})
assert.ok(size > 0, 'reported size should be greater than 0')
assert.equal(basename(path).endsWith('.alias.vhd'), useVhdDirectory)
await Disposable.use(openVhd(handler, path), async vhd => {
assert.equal(vhd.footer.diskType, Constants.DISK_TYPES.DYNAMIC)
await vhd.readBlockAllocationTable()
const { data } = await vhd.readBlock(1)
assert.ok(
data.every(byte => byte === 0x42),
'block 1 should contain the source disk data'
)
})
})
test(`${mode}: writes a differencing disk chained to its parent that passes validation`, async () => {
const adapter = await getAdapter({ useVhdDirectory })
const parentPath = `${basePath}/${adapter.getVhdFileName('20000101T000000Z')}`
const childPath = `${basePath}/${adapter.getVhdFileName('20000102T000000Z')}`
const parentUuid = uniqueIdBuffer()
await adapter.writeVhd(parentPath, new MockDisk(2, [0, 1], 0xaa), {
validator: tmpPath => checkDisk(handler, tmpPath),
uuid: parentUuid,
})
await adapter.writeVhd(childPath, new MockDisk(2, [1], 0xbb, { differencing: true }), {
validator: tmpPath => checkDisk(handler, tmpPath),
uuid: uniqueIdBuffer(),
parentUuid,
parentPath: relativeFromFile(childPath, parentPath),
})
await Disposable.use(openVhd(handler, childPath), async vhd => {
assert.equal(vhd.footer.diskType, Constants.DISK_TYPES.DIFFERENCING)
assert.deepEqual(vhd.header.parentUuid, parentUuid)
assert.equal(vhd.header.parentUnicodeName, relativeFromFile(childPath, parentPath))
})
})
test(`${mode}: a rejected validation leaves no disk behind`, async () => {
const adapter = await getAdapter({ useVhdDirectory })
const path = `${basePath}/${adapter.getVhdFileName('base')}`
await assert.rejects(
adapter.writeVhd(path, new MockDisk(1, [0], 0x11), {
validator: async () => {
throw new Error('boom')
},
uuid: uniqueIdBuffer(),
}),
/boom/
)
// neither the alias/file nor the VHD directory it points to must survive, otherwise the
// next run would chain onto a disk that was never validated
assert.deepEqual(await handler.list(basePath, { ignoreMissing: true }), useVhdDirectory ? ['data'] : [])
assert.deepEqual(await handler.list(`${basePath}/data`, { ignoreMissing: true }), [])
})
}
})

View File

@@ -1,32 +1,26 @@
import { asyncEach } from '@vates/async-each'
import { asyncMap, asyncMapSettled } from '@xen-orchestra/async-map'
import { createLogger } from '@xen-orchestra/log'
import { stringify } from 'uuid'
import { VhdDirectory, VhdSynthetic } from 'vhd-lib'
import { decorateMethodsWith } from '@vates/decorate-with'
import { basename, dirname, join, resolve } from 'node:path'
import { dirname, join, resolve } from 'node:path'
import { synchronized } from 'decorator-synchronized'
import Disposable from 'promise-toolbox/Disposable'
import fromCallback from 'promise-toolbox/fromCallback'
import groupBy from 'lodash/groupBy.js'
import pickBy from 'lodash/pickBy.js'
import reduce from 'lodash/reduce.js'
import zlib from 'zlib'
import { BACKUP_DIR } from './_getVmBackupDir.mjs'
import {
VmBackupDirectory,
deleteFullVmBackups as deleteFullVmBackupFiles,
deleteDeltaVmBackups as deleteDeltaVmBackupFiles,
deleteMetadataBackup as deleteMetadataBackupFiles,
readBackupCache,
writeBackupCache,
} from '@xen-orchestra/backup-archive'
import { VmBackupDirectory } from '@xen-orchestra/backup-archive'
import { fileRestoreDecorators, fileRestoreMethods } from './_fileRestore.mjs'
import { formatFilenameDate } from './_filenameDate.mjs'
import { isMetadataFile } from './_backupType.mjs'
import { readBackupJournal, writeBackupJournalEntries, writeBackupJournalEntry } from './_backupJournal.mjs'
import { isValidXva } from './_isValidXva.mjs'
import { watchStreamSize } from './_watchStreamSize.mjs'
import { RemoteVhdDisk, openDiskChain, openDisposableDisk } from '@xen-orchestra/backup-archive/disks'
import { RemoteVhdDisk, openDiskChain } from '@xen-orchestra/backup-archive/disks'
import { toVhdStream, writeToVhdDirectory } from 'vhd-lib/disk-consumer/index.mjs'
import { ReadAhead } from '@xen-orchestra/disk-transform'
@@ -42,6 +36,8 @@ export const compareTimestamp = (a, b) => a.timestamp - b.timestamp
const noop = Function.prototype
const resolveRelativeFromFile = (file, path) => resolve('/', dirname(file), path).slice(1)
const createSafeReaddir = (handler, methodName) => (path, options) =>
handler.list(path, options).catch(error => {
if (error?.code !== 'ENOENT') {
@@ -51,10 +47,14 @@ const createSafeReaddir = (handler, methodName) => (path, options) =>
})
export class RemoteAdapter {
constructor(handler, { debounceResource = res => res, dirMode, useGetDiskLegacy = false } = {}) {
constructor(
handler,
{ debounceResource = res => res, dirMode, vhdDirectoryCompression, useGetDiskLegacy = false } = {}
) {
this._debounceResource = debounceResource
this._dirMode = dirMode
this._handler = handler
this._vhdDirectoryCompression = vhdDirectoryCompression
this._readCacheListVmBackups = synchronized.withKey()(this._readCacheListVmBackups)
this._useGetDiskLegacy = useGetDiskLegacy
}
@@ -65,25 +65,22 @@ export class RemoteAdapter {
// check if we will be allowed to merge a vhd created in this adapter
// with the vhd at path `path`
//
// only the candidate disk itself is checked (no ancestor walk): mergeBlock() already
// degrades gracefully when parent/child formats differ, so chain-wide uniformity isn't
// a requirement here.
async isMergeableParent(packedParentUid, path) {
return await Disposable.use(openDisposableDisk({ handler: this.handler, path, ignoreBlockIndexes: true }), disk =>
disk.isMergeableParent(stringify(packedParentUid))
)
return await Disposable.use(VhdSynthetic.fromVhdChain(this.handler, path), vhd => {
// this baseUuid is not linked with this vhd
if (!vhd.footer.uuid.equals(packedParentUid)) {
return false
}
// check if all the chain is composed of vhd directory
const isVhdDirectory = vhd.checkVhdsClass(VhdDirectory)
return isVhdDirectory
? this.useVhdDirectory() && this.#getCompressionType() === vhd.compressionType
: !this.useVhdDirectory()
})
}
// Single funnel for all the backup deletions triggered by a user or by retention: forgets them
// from `cache.json.gz` and records them in the journal.
/**
* @param {{ _filename: string, jobId?: string, scheduleId?: string }[]} backups the metadata of
* the deleted backups, or `{ _filename }` alone when it could not be read
* @param {import('./_backupJournal.mjs').BackupJournalReason} reason
* @returns {Promise<void>}
*/
async #forgetVmBackups(backups, reason) {
async #removeVmBackupsFromCache(backups) {
await asyncEach(
Object.entries(
groupBy(
@@ -100,39 +97,27 @@ export class RemoteAdapter {
}
})
)
// will not reject
await writeBackupJournalEntries(
this._handler,
backups.map(({ _filename, jobId, scheduleId }) => ({
event: 'del',
vmUuid: basename(dirname(_filename)),
filename: _filename,
who: jobId === undefined ? undefined : { jobId, scheduleId },
reason,
})),
{ dirMode: this._dirMode }
)
}
/**
* @param {object[]} backups metadata of the backups to delete
* @param {object} [opts]
* @param {import('./_backupJournal.mjs').BackupJournalReason} [opts.reason] what triggered the
* deletion, as recorded in the journal
*/
async deleteDeltaVmBackups(backups, { reason = 'retention' } = {}) {
// this will delete the json, unused VHDs will be detected by `cleanVm`
await deleteDeltaVmBackupFiles(
this._handler,
backups.map(({ _filename }) => ({ metadataPath: _filename }))
)
async deleteDeltaVmBackups(backups) {
const handler = this._handler
await this.#forgetVmBackups(backups, reason)
// this will delete the json, unused VHDs will be detected by `cleanVm`
await asyncMapSettled(backups, ({ _filename }) => handler.unlink(_filename))
await this.#removeVmBackupsFromCache(backups)
}
async deleteMetadataBackup(backupId) {
await deleteMetadataBackupFiles(this._handler, backupId)
const uuidReg = '\\w{8}(-\\w{4}){3}-\\w{12}'
const metadataDirReg = 'xo-(config|pool-metadata)-backups'
const timestampReg = '\\d{8}T\\d{6}Z'
const regexp = new RegExp(`^${metadataDirReg}/${uuidReg}(/${uuidReg})?/${timestampReg}`)
if (!regexp.test(backupId)) {
throw new Error(`The id (${backupId}) not correspond to a metadata folder`)
}
await this._handler.rmtree(backupId)
}
async deleteOldMetadataBackups(dir, retention) {
@@ -143,23 +128,26 @@ export class RemoteAdapter {
await asyncMapSettled(list, timestamp => handler.rmtree(`${dir}/${timestamp}`))
}
/**
* @param {object[]} backups metadata of the backups to delete
* @param {object} [opts]
* @param {import('./_backupJournal.mjs').BackupJournalReason} [opts.reason] what triggered the
* deletion, as recorded in the journal
*/
async deleteFullVmBackups(backups, { reason = 'retention' } = {}) {
await asyncMapSettled(backups, async ({ _filename, xva }) => {
try {
await deleteFullVmBackupFiles(this._handler, [{ metadataPath: _filename, xva }])
} catch (error) {
warn('error while removing full vm backup', { error, filename: _filename, failedPath: error.path })
throw error
}
})
async deleteFullVmBackups(backups) {
const handler = this._handler
await asyncMapSettled(backups, ({ _filename, xva }) =>
Promise.all([
handler.unlink(_filename).catch(error => {
warn('error while removing full vm backup metadata', { error, filename: _filename })
if (error.code !== 'ENOENT') throw error
}),
handler.unlink(resolveRelativeFromFile(_filename, xva)).catch(error => {
warn('error while removing full vm backup file', { error, filename: _filename })
if (error.code !== 'ENOENT') throw error
}),
handler.unlink(resolveRelativeFromFile(_filename, `${xva}.checksum`)).catch(error => {
// checksum can be missing , it's not an issue
if (error.code !== 'ENOENT') throw error
}),
])
)
await this.#forgetVmBackups(backups, reason)
await this.#removeVmBackupsFromCache(backups)
}
deleteVmBackup(file) {
@@ -198,13 +186,13 @@ export class RemoteAdapter {
}
const promises = []
if (delta !== undefined) {
promises.push(this.deleteDeltaVmBackups(delta, { reason: 'user' }))
promises.push(this.deleteDeltaVmBackups(delta))
}
if (full !== undefined) {
promises.push(this.deleteFullVmBackups(full, { reason: 'user' }))
promises.push(this.deleteFullVmBackups(full))
}
if (missingFiles.length) {
promises.push(this.#forgetVmBackups(missingFiles, 'user'))
promises.push(this.#removeVmBackupsFromCache(missingFiles))
}
await Promise.all(promises)
@@ -217,8 +205,12 @@ export class RemoteAdapter {
)
}
#getCompressionType() {
return this._vhdDirectoryCompression
}
useVhdDirectory() {
return this.handler.getConfig('useVhdDirectory')
return this.handler.useVhdDirectory()
}
#useAlias() {
@@ -306,18 +298,18 @@ export class RemoteAdapter {
}
async _readCache(path) {
return readBackupCache(this.handler, path, warn)
try {
return JSON.parse(await fromCallback(zlib.gunzip, await this.handler.readFile(path)))
} catch (error) {
if (error.code !== 'ENOENT') {
warn('#readCache', { error, path })
}
}
}
_updateCache = synchronized.withKey()(this._updateCache)
// eslint-disable-next-line no-dupe-class-members
async _updateCache(path, fn) {
// immutable remote can't use any caching
// since the cache file may be non modifiable, and would then stay billed forever
if (this._handler.isImmutable()) {
return
}
const cache = await this._readCache(path)
if (cache !== undefined) {
fn(cache)
@@ -332,7 +324,11 @@ export class RemoteAdapter {
}
async _writeCache(path, data) {
return writeBackupCache(this.handler, path, data, warn)
try {
await this.handler.writeFile(path, await fromCallback(zlib.gzip, JSON.stringify(data)), { flags: 'w' })
} catch (error) {
warn('#writeCache', { error, path })
}
}
async #getCacheableDataListVmBackups(dir) {
@@ -435,16 +431,6 @@ export class RemoteAdapter {
return backups.sort(compareTimestamp)
}
// read the backup events which happened on this remote after `since` (timestamp in ms),
// oldest first
/**
* @param {number} [since] timestamp in ms, exclusive
* @returns {Promise<import('./_backupJournal.mjs').BackupJournalEntry[]>}
*/
async readBackupJournal(since) {
return readBackupJournal(this._handler, since)
}
async writeVmBackupMetadata(vmUuid, metadata) {
const path = `/${BACKUP_DIR}/${vmUuid}/${formatFilenameDate(metadata.timestamp)}.json`
@@ -452,19 +438,6 @@ export class RemoteAdapter {
dirMode: this._dirMode,
})
// will not throw
await writeBackupJournalEntry(
this._handler,
{
event: 'add',
vmUuid,
filename: path,
who: { jobId: metadata.jobId, scheduleId: metadata.scheduleId },
reason: 'backup',
},
{ dirMode: this._dirMode }
)
// will not throw
await this._updateCache(this.#getVmBackupsCache(vmUuid), backups => {
debug('adding cache entry', { entry: path })
@@ -491,7 +464,7 @@ export class RemoteAdapter {
path,
concurrency: writeBlockConcurrency,
validator,
compression: handler.getConfig('compressionType') ?? 'brotli', // compatibility layer
compression: 'brotli',
uuid,
parentUuid,
parentPath,
@@ -668,51 +641,15 @@ export class RemoteAdapter {
}
}
// journal the metadata files `cleanVm` removed and rewrote
//
// `removedFiles` also lists the files which would have been removed if `remove` were set, and files
// which are not backup metadata (stray xva, checksums, …), hence the filtering.
/**
* @param {RemoteAdapter} adapter
* @param {string} vmBackupPath directory of the cleaned VM, e.g. `xo-vm-backups/<vmUuid>`
* @param {object} cleanOpts the options `cleanVm()` ran with
* @param {boolean} [cleanOpts.remove] whether the removals were actually applied
* @param {object} result the result of `cleanVm()`
* @param {string[]} [result.removedFiles]
* @param {string[]} [result.changedFiles]
* @returns {Promise<void>}
*/
async function journalCleanVm(adapter, vmBackupPath, { remove }, { removedFiles = [], changedFiles = [] }) {
const dir = resolve('/', vmBackupPath)
const vmUuid = basename(dir)
const isVmMetadata = file => isMetadataFile(file) && dirname(resolve('/', file)) === dir
const entries = []
if (remove) {
for (const filename of new Set(removedFiles.filter(isVmMetadata))) {
entries.push({ event: 'del', vmUuid, filename, reason: 'clean-vm' })
}
}
for (const filename of new Set(changedFiles.filter(isVmMetadata))) {
entries.push({ event: 'change', vmUuid, filename, reason: 'merge' })
}
// will not reject
await writeBackupJournalEntries(adapter._handler, entries, { dirMode: adapter._dirMode })
}
Object.assign(RemoteAdapter.prototype, {
cleanVm(vmBackupPath, opts = {}) {
const { lock = true, ...cleanOpts } = opts
const run = async () => {
const result = await VmBackupDirectory.cleanVm(this._handler, vmBackupPath, cleanOpts)
await journalCleanVm(this, vmBackupPath, cleanOpts, result)
return result
}
if (lock) {
return Disposable.use(this._handler.lock(vmBackupPath), run)
return Disposable.use(this._handler.lock(vmBackupPath), () => {
return VmBackupDirectory.cleanVm(this._handler, vmBackupPath, cleanOpts)
})
} else {
return run()
return VmBackupDirectory.cleanVm(this._handler, vmBackupPath, cleanOpts)
}
},
isValidXva,

View File

@@ -1,408 +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 { setTimeout as sleep } from 'node:timers/promises'
import { RemoteAdapter } from './RemoteAdapter.mjs'
import { VHDFOOTER, VHDHEADER } from './tests.fixtures.mjs'
import { VhdFile, Constants } from 'vhd-lib'
import { rimraf } from 'rimraf'
import { BACKUP_JOURNAL_DIR, formatJournalDay, formatJournalTime } from './_backupJournal.mjs'
import { formatFilenameDate } from './_filenameDate.mjs'
const { beforeEach, afterEach, describe } = test
const noop = Function.prototype
const byFilename = (a, b) => (a.filename < b.filename ? -1 : 1)
const vmUuid = 'a1b2c3d4-0000-0000-0000-000000000000'
const rootPath = `xo-vm-backups/${vmUuid}`
let tempDir, adapter, handler, jobId, scheduleId, relativePath, basePath
beforeEach(async () => {
tempDir = await pFromCallback(cb => tmp.dir(cb))
handler = getHandler({ url: `file://${tempDir}` })
await handler.sync()
adapter = new RemoteAdapter(handler)
jobId = uniqueId()
scheduleId = uniqueId()
relativePath = `vdis/${jobId}/${uniqueId()}`
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))
const listJournalDays = () => handler.list(`/${BACKUP_JOURNAL_DIR}`, { ignoreMissing: true })
// paths of the journal entries of every day, oldest first
async function listJournal() {
const paths = []
for (const day of (await listJournalDays()).filter(name => /^\d{8}$/.test(name))) {
paths.push(...(await handler.list(`/${BACKUP_JOURNAL_DIR}/${day}`, { prependDir: true })))
}
return paths.sort()
}
// writes a journal entry the way a past run would have, i.e. in the directory of its own day
function writeJournalEntryAt(timestamp, entry) {
const name = `${formatJournalTime(timestamp)}-000000-${entry.event}-${entry.vmUuid}-${entry.filename.split('/').pop()}`
return handler.outputFile(
`/${BACKUP_JOURNAL_DIR}/${formatJournalDay(timestamp)}/${name}`,
JSON.stringify({ ...entry, timestamp })
)
}
// journal entries are stamped with the writer's clock, therefore a watermark used in an assertion
// must be strictly between the entries written before it and the ones written after it
async function mark() {
await sleep(5)
const since = Date.now()
await sleep(5)
return since
}
async function generateVhd(path, opts = {}) {
const fd = await handler.openFile(path, 'wx')
const vhd = new VhdFile(handler, fd)
vhd.header = { ...VHDHEADER, ...opts.header }
vhd.footer = { ...VHDFOOTER, ...opts.footer, uuid: uniqueIdBuffer() }
vhd.footer.diskType = vhd.header.parentUuid ? Constants.DISK_TYPES.DIFFERENCING : Constants.DISK_TYPES.DYNAMIC
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
}
// enough to satisfy isValidXva(): uncompressed, more than 1024 bytes, a multiple of 512, and ending
// with 1024 zeroed bytes
const createMinimalXva = () => Buffer.alloc(2048)
// write backups the way a backup job would, i.e. through the adapter
async function writeFullBackup(timestamp = Date.now()) {
const xva = `${formatFilenameDate(timestamp)}.xva`
await handler.outputFile(`/${rootPath}/${xva}`, createMinimalXva())
return adapter.writeVmBackupMetadata(vmUuid, {
mode: 'full',
xva: `./${xva}`,
vm: { uuid: vmUuid },
jobId,
scheduleId,
timestamp,
size: await handler.getSize(`/${rootPath}/${xva}`),
})
}
async function writeDeltaBackup(timestamp = Date.now()) {
const vhd = `${formatFilenameDate(timestamp)}.vhd`
await generateVhd(`${basePath}/${vhd}`, { blocks: [0] })
return adapter.writeVmBackupMetadata(vmUuid, {
mode: 'delta',
vhds: { vdi: `${relativePath}/${vhd}` },
vdis: { vdi: {} },
vm: { uuid: vmUuid },
jobId,
scheduleId,
timestamp,
})
}
describe('backup journal', { concurrency: 1 }, () => {
test('writeVmBackupMetadata() records an `add` event', async () => {
const path = await writeFullBackup()
const entries = await adapter.readBackupJournal(0)
assert.equal(entries.length, 1)
const { date, timestamp, _filename, ...entry } = entries[0]
assert.deepEqual(entry, {
event: 'add',
vmUuid,
filename: path,
who: { jobId, scheduleId },
reason: 'backup',
})
assert.equal(date.getTime(), timestamp)
assert.equal(_filename, (await listJournal())[0])
})
test('the entry is stored in the directory of its day, named after the time, the event and the backup', async () => {
const path = await writeFullBackup()
const [entryPath] = await listJournal()
const { timestamp } = (await adapter.readBackupJournal(0))[0]
const name = entryPath.split('/').pop()
assert.equal(entryPath, `/${BACKUP_JOURNAL_DIR}/${formatJournalDay(timestamp)}/${name}`)
assert.equal(name.slice(0, 11), formatJournalTime(timestamp), 'the day must not be repeated in the name')
assert.ok(name.endsWith(`-add-${vmUuid}-${path.split('/').pop()}`), name)
})
test('deleting a backup records a `del` event', async () => {
const full = await writeFullBackup(Date.now() - 2000)
const delta = await writeDeltaBackup(Date.now() - 1000)
const since = await mark()
await adapter.deleteVmBackups([full, delta])
const entries = await adapter.readBackupJournal(since)
assert.deepEqual(
entries
.map(({ event, filename, vmUuid, reason, who }) => ({ event, filename, vmUuid, reason, who }))
.sort(byFilename),
[
{ event: 'del', filename: full, vmUuid, reason: 'user', who: { jobId, scheduleId } },
{ event: 'del', filename: delta, vmUuid, reason: 'user', who: { jobId, scheduleId } },
].sort(byFilename)
)
})
test('deleting a backup through the retention path records the `retention` reason', async () => {
await writeDeltaBackup()
const [backup] = await adapter.listVmBackups(vmUuid)
const since = await mark()
await adapter.deleteDeltaVmBackups([backup])
const entries = await adapter.readBackupJournal(since)
assert.equal(entries.length, 1)
assert.equal(entries[0].event, 'del')
assert.equal(entries[0].reason, 'retention')
})
test('deleting an already deleted backup still records a `del` event', async () => {
const path = await writeFullBackup()
await handler.unlink(path)
const since = await mark()
await adapter.deleteVmBackup(path)
const entries = await adapter.readBackupJournal(since)
assert.equal(entries.length, 1)
assert.equal(entries[0].event, 'del')
assert.equal(entries[0].filename, path)
assert.equal(entries[0].vmUuid, vmUuid)
assert.equal(entries[0].who, undefined)
})
test('a merge records a `change` event, and cleaning an incomplete backup a `del` one', async () => {
// an incomplete delta backup: its disk is missing
await handler.outputFile(
`/${rootPath}/incomplete.json`,
JSON.stringify({ mode: 'delta', vhds: { vdi: `${relativePath}/gone.vhd` }, vdis: { vdi: {} } })
)
// a complete one whose disk has an orphan ancestor to merge
const parent = await generateVhd(`${basePath}/parent.vhd`, { blocks: [0] })
await generateVhd(`${basePath}/child.vhd`, {
header: { parentUnicodeName: 'parent.vhd', parentUuid: parent.footer.uuid },
blocks: [1],
})
await handler.outputFile(
`/${rootPath}/complete.json`,
JSON.stringify({ mode: 'delta', vhds: { vdi: `${relativePath}/child.vhd` }, vdis: { vdi: {} }, size: 1 })
)
const since = await mark()
const result = await adapter.cleanVm(rootPath, {
remove: true,
merge: true,
logInfo: noop,
logWarn: noop,
lock: false,
})
assert.ok(result.size > 0, 'nothing was merged')
const entries = await adapter.readBackupJournal(since)
assert.deepEqual(
entries.map(({ event, filename, vmUuid, reason }) => ({ event, filename, vmUuid, reason })).sort(byFilename),
[
{ event: 'change', filename: `/${rootPath}/complete.json`, vmUuid, reason: 'merge' },
{ event: 'del', filename: `/${rootPath}/incomplete.json`, vmUuid, reason: 'clean-vm' },
]
)
})
test('a dry run of cleanVm() records nothing', async () => {
await handler.outputFile(
`/${rootPath}/incomplete.json`,
JSON.stringify({ mode: 'delta', vhds: { vdi: `${relativePath}/gone.vhd` }, vdis: { vdi: {} } })
)
const since = await mark()
await adapter.cleanVm(rootPath, { remove: false, logInfo: noop, logWarn: noop, lock: false })
assert.deepEqual(await adapter.readBackupJournal(since), [])
})
test('a failure to journal does not fail the operation it journals', async () => {
const outputFile = handler._outputFile.bind(handler)
handler._outputFile = async (path, ...rest) => {
if (path.startsWith(`/${BACKUP_JOURNAL_DIR}/`)) {
const error = new Error('EACCES: permission denied')
error.code = 'EACCES'
throw error
}
return outputFile(path, ...rest)
}
const path = await writeFullBackup()
assert.ok(await handler.getSize(path))
assert.deepEqual(await listJournal(), [])
})
})
describe('readBackupJournal()', { concurrency: 1 }, () => {
const DAY = 24 * 60 * 60 * 1e3
test('returns nothing on a repository without a journal', async () => {
assert.deepEqual(await adapter.readBackupJournal(0), [])
})
test('replays the days since `since`, oldest first', async () => {
const old = `/${rootPath}/old.json`
const twoDaysAgo = Date.now() - 2 * DAY
await writeJournalEntryAt(twoDaysAgo, { event: 'add', vmUuid, filename: old, reason: 'backup' })
const recent = await writeFullBackup()
assert.deepEqual(
(await adapter.readBackupJournal(twoDaysAgo - 1000)).map(_ => _.filename),
[old, recent]
)
})
test('does not read the days older than `since`', async () => {
await writeJournalEntryAt(Date.now() - 2 * DAY, {
event: 'add',
vmUuid,
filename: `/${rootPath}/old.json`,
reason: 'backup',
})
const recent = await writeFullBackup()
const listed = []
const list = handler.list.bind(handler)
handler.list = (dir, ...rest) => {
listed.push(dir)
return list(dir, ...rest)
}
const since = Date.now() - 60e3
assert.deepEqual(
(await adapter.readBackupJournal(since)).map(_ => _.filename),
[recent]
)
// only the journal root and today's directory, whatever the number of days the journal holds
assert.deepEqual(listed, [`/${BACKUP_JOURNAL_DIR}`, `/${BACKUP_JOURNAL_DIR}/${formatJournalDay(since)}`])
})
test('`since` only bounds the time of its own day, not of the days after it', async () => {
// regression guard: entries are named after their time only, so the time of `since` must be
// compared with the entries of its own day and with no other, otherwise an entry of an early
// hour of a later day looks older than a `since` of a late hour
const midnight = Math.floor(Date.now() / DAY) * DAY
const lateYesterday = `/${rootPath}/late-yesterday.json`
const earlyToday = `/${rootPath}/early-today.json`
await writeJournalEntryAt(midnight - 30 * 60e3, { event: 'add', vmUuid, filename: lateYesterday })
await writeJournalEntryAt(midnight + 30 * 60e3, { event: 'add', vmUuid, filename: earlyToday })
assert.deepEqual(
(await adapter.readBackupJournal(midnight - 60 * 60e3)).map(_ => _.filename),
[lateYesterday, earlyToday]
)
// 23:45 of yesterday: its own day is bounded, today is not
assert.deepEqual(
(await adapter.readBackupJournal(midnight - 15 * 60e3)).map(_ => _.filename),
[earlyToday]
)
})
test('returns the entries stamped after `since`, oldest first', async () => {
const first = await writeFullBackup(Date.now() - 2000)
const since = await mark()
const second = await writeDeltaBackup(Date.now() - 1000)
assert.deepEqual(
(await adapter.readBackupJournal(0)).map(_ => _.filename),
[first, second]
)
assert.deepEqual(
(await adapter.readBackupJournal(since)).map(_ => _.filename),
[second]
)
assert.deepEqual(await adapter.readBackupJournal(Date.now() + 1000), [])
})
test('skips truncated entries and unrecognized filenames without hiding their siblings', async () => {
const path = await writeFullBackup()
const [entryPath] = await listJournal()
const day = formatJournalDay(Date.now())
// a partially written entry
await handler.writeFile(
`/${BACKUP_JOURNAL_DIR}/${day}/${formatJournalTime(Date.now())}-000000-add-${vmUuid}-truncated.json`,
'{"ev'
)
// a file which is not a journal entry at all
await handler.writeFile(`/${BACKUP_JOURNAL_DIR}/${day}/README`, 'hello')
// a stray file where only day directories are expected
await handler.writeFile(`/${BACKUP_JOURNAL_DIR}/README`, 'hello')
const entries = await adapter.readBackupJournal(0)
assert.deepEqual(
entries.map(_ => _.filename),
[path]
)
assert.equal(entries[0]._filename, entryPath)
})
})
describe('backup journal on an encrypted remote', { concurrency: 1 }, () => {
test('entries are readable without the encryption key', async () => {
const encryptedDir = await pFromCallback(cb => tmp.dir(cb))
const encryptedHandler = getHandler({
url: `file://${encryptedDir}?encryptionKey="73c1838d7d8a6088ca2317fb5f29cd00"`,
})
try {
await encryptedHandler.sync()
assert.equal(encryptedHandler.isEncrypted, true)
const encryptedAdapter = new RemoteAdapter(encryptedHandler)
await encryptedAdapter.writeVmBackupMetadata(vmUuid, {
mode: 'full',
vm: { uuid: vmUuid },
jobId,
scheduleId,
timestamp: Date.now(),
})
const [day] = await encryptedHandler.list(`/${BACKUP_JOURNAL_DIR}`)
const [name] = await encryptedHandler.list(`/${BACKUP_JOURNAL_DIR}/${day}`)
const raw = await fs.readFile(`${encryptedDir}/${BACKUP_JOURNAL_DIR}/${day}/${name}`)
assert.equal(JSON.parse(String(raw)).event, 'add')
} finally {
await encryptedHandler.forget()
await rimraf(encryptedDir)
}
})
})

View File

@@ -1,272 +0,0 @@
import { asyncEach } from '@vates/async-each'
import { basename, normalize } from '@xen-orchestra/fs/path'
import { createLogger } from '@xen-orchestra/log'
import { randomBytes } from 'node:crypto'
import { utcFormat, utcParse } from 'd3-time-format'
const { debug, warn } = createLogger('xo:backups:backupJournal')
/**
* A remote handler, plus the two unencrypted read/write primitives this module relies on to keep
* the journal readable without the encryption key. They are not part of the handler's declared
* public surface (`@xen-orchestra/fs/src/types/fs.mts`), hence the intersection.
*
* @typedef {import('@xen-orchestra/fs').RemoteHandlerAbstract & {
* _outputFile(file: string, data: string, opts?: { dirMode?: number, flags?: string }): Promise<void>
* _readFile(file: string): Promise<Buffer>
* }} RemoteHandler
*/
/**
* What happened to the backup metadata this entry is about.
*
* - `add`: the backup was written
* - `change`: the metadata was rewritten in place, the backup itself still exists
* - `del`: the backup was removed
*
* @typedef {'add'|'change'|'del'} BackupJournalEvent
*/
/**
* What triggered the event.
*
* - `backup`: a backup job wrote it
* - `retention`: it was rotated out by a retention setting
* - `user`: a user explicitly deleted it
* - `clean-vm`: `cleanVm()` removed it, e.g. the metadata of an incomplete backup
* - `merge`: `cleanVm()` rewrote its size after merging its disks
*
* @typedef {'backup'|'retention'|'user'|'clean-vm'|'merge'} BackupJournalReason
*/
/**
* The XO entities responsible for the event, when they are known.
*
* @typedef {object} BackupJournalWho
* @property {string} [jobId]
* @property {string} [scheduleId]
*/
/**
* An event to append to the journal.
*
* @typedef {object} NewBackupJournalEntry
* @property {BackupJournalEvent} event
* @property {string} vmUuid
* @property {string} filename path of the backup metadata this event is about
* @property {BackupJournalWho} [who]
* @property {BackupJournalReason} [reason]
*/
/**
* An event read back from the journal: what was written, plus the fields derived from the entry
* itself.
*
* `timestamp` is the writer's clock at the time of the write; `date` is that same instant, parsed
* back from the entry name.
*
* @typedef {NewBackupJournalEntry & {
* timestamp: number
* date: Date
* _filename: string
* }} BackupJournalEntry
*/
// Append-only event log of the backups present on a repository.
//
// Entries are never modified nor overwritten, which makes the journal usable on immutable
// (Object Lock) repositories, where `cache.json.gz` cannot be rewritten.
export const BACKUP_JOURNAL_DIR = 'xo-backup-log'
// Same idea as `formatFilenameDate` but with milliseconds, so that two events on the same VM
// within the same second keep distinct, ordered names.
const formatDate = utcFormat('%Y%m%dT%H%M%S.%LZ')
// the time part alone, which is what an entry is named after: its day is already the name of the
// directory holding it
const formatTime = utcFormat('%H%M%S.%LZ')
/**
* Formats a timestamp into the date part of a journal entry name.
*
* Takes a timestamp rather than a `Date` because that is what every caller has; `d3-time-format`
* would coerce it anyway, but its declared signature does not say so.
*
* @param {number} timestamp in ms
* @returns {string}
*/
export const formatJournalDate = timestamp => formatDate(new Date(timestamp))
/**
* Formats a timestamp into the day part of a journal entry path, i.e. the name of the directory
* holding it.
*
* @param {number} timestamp in ms
* @returns {string} `YYYYMMDD`
*/
export const formatJournalDay = timestamp => dayOfDate(formatJournalDate(timestamp))
/**
* Formats a timestamp into the time part of a journal entry name.
*
* @param {number} timestamp in ms
* @returns {string} `HHMMSS.mmmZ`
*/
export const formatJournalTime = timestamp => formatTime(new Date(timestamp))
/**
* Reads back the date of a journal entry, from its day and the time part of its name.
*
* @param {string} date `YYYYMMDDTHHMMSS.mmmZ`, i.e. `<day>T<time>`
* @returns {Date | null} `null` when the name is not a journal entry
*/
export const parseJournalDate = utcParse('%Y%m%dT%H%M%S.%LZ')
// `YYYYMMDDTHHMMSS.mmmZ`, a day and a time joined by a `T`
const DATE_LENGTH = formatJournalDate(0).length
// `YYYYMMDD`, the leading part of a formatted date
const DAY_LENGTH = 8
// `HHMMSS.mmmZ`, a formatted date without its day nor the `T` separating the two
//
// it has a fixed width, therefore sorting the entry names of a day lexicographically sorts them
// chronologically, and so does sorting whole paths across days
const TIME_LENGTH = DATE_LENGTH - DAY_LENGTH - 1
const dayOfDate = date => date.slice(0, DAY_LENGTH)
const isDayName = name => /^\d{8}$/.test(name)
// reassembles what `parseJournalDate()` expects from where each part is stored
const dateOfEntry = (day, name) => parseJournalDate(`${day}T${name.slice(0, TIME_LENGTH)}`)
// `/xo-backup-log/<day>/<time>-<random>-<event>-<vmUuid>-<metadata filename>`
//
// Entries are grouped in one directory per UTC day, so that a reader lists only the days it is
// missing instead of the whole history of the repository, and a purge removes whole directories.
// The day is therefore not repeated in the name: an entry is named after its time only.
//
// Everything after the time is only there to make the journal readable by a human: the date is read
// back from the day and the time, all the other fields are read back from the entry itself.
/**
* @param {object} entry
* @param {number} entry.timestamp the event date, in ms
* @param {BackupJournalEvent} entry.event
* @param {string} entry.vmUuid
* @param {string} entry.filename path of the backup metadata this event is about
* @returns {string} path of the journal entry, unique thanks to a random part
*/
function getEntryPath({ timestamp, event, vmUuid, filename }) {
const unique = randomBytes(3).toString('hex')
const name = `${formatJournalTime(timestamp)}-${unique}-${event}-${vmUuid}-${basename(filename)}`
return `/${BACKUP_JOURNAL_DIR}/${formatJournalDay(timestamp)}/${name}`
}
/**
* Appends an event to the journal.
*
* Never rejects: journaling is best effort, a failure here must not fail the backup or the deletion
* that triggered it. The resulting drift is bounded by the periodic full rebuild of the readers.
*
* The entry is stamped with the writer's clock at the time of this call.
*
* @param {RemoteHandler} handler
* @param {NewBackupJournalEntry} entry
* @param {object} [opts]
* @param {number} [opts.dirMode] mode of the journal directory, if it has to be created
* @returns {Promise<void>}
*/
export async function writeBackupJournalEntry(handler, { event, vmUuid, filename, who, reason }, { dirMode } = {}) {
const timestamp = Date.now()
const path = getEntryPath({ timestamp, event, vmUuid, filename })
try {
// this file is not encrypted, so that it stays readable by tools which don't have the
// encryption key (e.g. the `immutable-backups` daemon)
await handler._outputFile(normalize(path), JSON.stringify({ event, vmUuid, filename, timestamp, who, reason }), {
dirMode,
flags: 'wx',
})
debug('journal entry written', { path })
} catch (error) {
warn('failed to write journal entry', { error, path })
}
}
/**
* Appends multiple events to the journal, concurrently.
*
* Never rejects, see `writeBackupJournalEntry()`. Entries are not written atomically as a group: a
* reader can observe a subset of them.
*
* @param {RemoteHandler} handler
* @param {NewBackupJournalEntry[]} entries
* @param {object} [opts]
* @param {number} [opts.dirMode] mode of the journal directory, if it has to be created
* @returns {Promise<void>}
*/
export async function writeBackupJournalEntries(handler, entries, opts) {
await asyncEach(entries, entry => writeBackupJournalEntry(handler, entry, opts))
}
/**
* Reads the journal entries stamped after `since`, oldest first.
*
* Corrupt or partially written entries are skipped, they must not hide their siblings. Computing the
* watermark to pass as `since` on the next call is the caller's responsibility.
*
* `since` is exclusive: entries stamped exactly at `since` are not returned.
*
* @param {RemoteHandler} handler
* @param {number} [since] timestamp in ms
* @returns {Promise<BackupJournalEntry[]>} oldest first
*/
export async function readBackupJournal(handler, since = 0) {
const minDay = formatJournalDay(since)
const minTime = formatJournalTime(since)
// only the days which can hold entries newer than `since` are listed, therefore the cost of a read
// does not grow with the whole history of the repository
const days = (
await handler.list(`/${BACKUP_JOURNAL_DIR}`, {
filter: name => isDayName(name) && name >= minDay,
ignoreMissing: true,
})
).sort()
/** @type {Array<{ day: string, path: string }>} */
const found = []
for (const day of days) {
// entries are named after their time only: `since` bounds the day it falls into, every later
// day is taken whole
const names = await handler.list(`/${BACKUP_JOURNAL_DIR}/${day}`, {
filter: day === minDay ? name => name.slice(0, TIME_LENGTH) > minTime : undefined,
ignoreMissing: true,
})
for (const name of names) {
found.push({ day, path: `/${BACKUP_JOURNAL_DIR}/${day}/${name}` })
}
}
/** @type {BackupJournalEntry[]} */
const entries = []
await asyncEach(found, async ({ day, path }) => {
const date = dateOfEntry(day, basename(path))
if (date === null) {
debug('ignoring unrecognized journal entry', { path })
return
}
try {
// this file is not encrypted
entries.push({ ...JSON.parse(String(await handler._readFile(normalize(path)))), date, _filename: path })
} catch (error) {
warn(`can't read journal entry`, { error, path })
}
})
// `asyncEach` does not preserve the order of its input
entries.sort((a, b) => (a._filename < b._filename ? -1 : 1))
return entries
}

View File

@@ -1,66 +0,0 @@
import test from 'node:test'
import { strict as assert } from 'node:assert'
import { formatJournalDate, formatJournalDay, formatJournalTime, parseJournalDate } from './_backupJournal.mjs'
const { describe } = test
describe('formatJournalDate()', () => {
test('round trips through parseJournalDate()', () => {
for (const timestamp of [0, 1786373412482, Date.UTC(2026, 11, 31, 23, 59, 59, 999)]) {
assert.equal(parseJournalDate(formatJournalDate(timestamp)).getTime(), timestamp)
}
})
test('is fixed width, therefore lexicographically sortable', () => {
const timestamps = [
0,
// same second
Date.UTC(2026, 7, 10, 10, 30, 12, 1),
Date.UTC(2026, 7, 10, 10, 30, 12, 482),
// day boundary
Date.UTC(2026, 7, 10, 23, 59, 59, 999),
Date.UTC(2026, 7, 11, 0, 0, 0, 0),
// year boundary
Date.UTC(2026, 11, 31, 23, 59, 59, 999),
Date.UTC(2027, 0, 1, 0, 0, 0, 0),
]
const dates = timestamps.map(formatJournalDate)
assert.equal(new Set(dates.map(_ => _.length)).size, 1)
assert.deepEqual([...dates].sort(), dates)
})
})
describe('formatJournalTime()', () => {
test('is the date without its day, which names the directory holding the entry', () => {
for (const timestamp of [0, 1786373412482, Date.UTC(2026, 11, 31, 23, 59, 59, 999)]) {
const day = formatJournalDay(timestamp)
const time = formatJournalTime(timestamp)
assert.equal(`${day}T${time}`, formatJournalDate(timestamp))
assert.equal(parseJournalDate(`${day}T${time}`).getTime(), timestamp)
}
})
test('is fixed width, therefore sorts the entries of a day chronologically', () => {
const times = [
Date.UTC(2026, 7, 10, 0, 0, 0, 0),
// same second
Date.UTC(2026, 7, 10, 10, 30, 12, 1),
Date.UTC(2026, 7, 10, 10, 30, 12, 482),
// last instant of the day
Date.UTC(2026, 7, 10, 23, 59, 59, 999),
].map(formatJournalTime)
assert.equal(new Set(times.map(_ => _.length)).size, 1)
assert.deepEqual([...times].sort(), times)
})
})
describe('parseJournalDate()', () => {
test('returns null on names which are not journal entries', () => {
for (const name of ['', 'README', '20260810T103012Z.json', 'cache.json.gz'.slice(0, 20)]) {
assert.equal(parseJournalDate(name), null)
}
})
})

View File

@@ -230,6 +230,7 @@ test('it merges delta of non destroyed chain', async () => {
logged.push(message)
}
await adapter.cleanVm(rootPath, { remove: true, logInfo, logWarn: logInfo, lock: false })
assert.equal(logged[0], `unexpected number of entries in backup cache`)
logged = []
const result = await adapter.cleanVm(rootPath, { remove: true, merge: true, logInfo, logWarn: () => {}, lock: false })

View File

@@ -16,15 +16,42 @@ import { toQcow2Stream } from '@xen-orchestra/qcow2'
const ensureArray = value => (value === undefined ? [] : Array.isArray(value) ? value : [value])
// The dynamic memory range MUST respect this inequality at any moment: static_min <= dynamic_min <= dynamic_max <= static_max.
// VM.set_memory_limits sets all four fields atomically, so there is no intermediate state for XAPI to reject
export async function updateMemoryFields(xapi, targetVm, vmRecord) {
const staticMin = vmRecord.memory_static_min ?? targetVm.memory_static_min
const staticMax = vmRecord.memory_static_max ?? targetVm.memory_static_max
const dynamicMin = vmRecord.memory_dynamic_min ?? targetVm.memory_dynamic_min
const dynamicMax = vmRecord.memory_dynamic_max ?? targetVm.memory_dynamic_max
const orderedMemoryLimits = ['memory_static_min', 'memory_dynamic_min', 'memory_dynamic_max', 'memory_static_max']
await xapi.call('VM.set_memory_limits', targetVm.$ref, staticMin, staticMax, dynamicMin, dynamicMax)
// The dynamic memory range MUST respect this inequality at any moment: static_min <= dynamic_min <= dynamic_max <= static_max.
// We must update these properties in the right order to avoid XAPI error.
// The order depends on the values. It can be an increase, a decrease or a mix of both, so any order could be required.
export async function updateMemoryFields(xapi, targetVm, vmRecord) {
const memoryValues = {}
for (const key of orderedMemoryLimits) {
memoryValues[key] = {
currentValue: targetVm[key],
newValue: vmRecord[key] ?? targetVm[key],
}
}
while (await updateNextMemoryField(xapi, memoryValues, targetVm.$ref)) {
/* execute until all memory fields are updated */
}
}
// Update one more memory field if needed, then return a boolean describing if a field was updated or if all fields are up to date
async function updateNextMemoryField(xapi, memoryValues, vmRef) {
for (let i = 0; i < orderedMemoryLimits.length; i++) {
const currentField = memoryValues[orderedMemoryLimits[i]]
const nextField = i === orderedMemoryLimits.length - 1 ? undefined : memoryValues[orderedMemoryLimits[i + 1]]
if (
currentField.newValue !== currentField.currentValue &&
(nextField === undefined || currentField.newValue <= nextField.currentValue)
) {
// no need to check that previousField.currentValue <= currentField.newValue, as we can deduce it
await xapi.setField('VM', vmRef, orderedMemoryLimits[i], currentField.newValue)
await xapi.barrier()
currentField.currentValue = currentField.newValue
return true
}
}
return false
}
export async function exportIncrementalVm(

View File

@@ -0,0 +1,122 @@
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { updateMemoryFields } from './_incrementalVm.mjs'
const MOCK_REF = 'mockRef'
function mockXapiVm(initialMemoryValues) {
const res = {
...initialMemoryValues,
updates: [],
barrier: () => {},
setField: (type, ref, field, value) => {
assert(type === 'VM')
assert(ref === MOCK_REF)
res.updates.push({ field, value })
res[field] = value
assert(res.memory_static_min <= res.memory_dynamic_min)
assert(res.memory_dynamic_min <= res.memory_dynamic_max)
assert(res.memory_dynamic_max <= res.memory_static_max)
},
}
return res
}
const tests = [
{
label: 'handles a memory increase',
targetVm: {
memory_static_min: 2,
memory_dynamic_min: 4,
memory_dynamic_max: 4,
memory_static_max: 8,
},
vmRecord: {
memory_static_min: 16,
memory_dynamic_min: 16,
memory_dynamic_max: 16,
memory_static_max: 16,
},
expectedUpdates: [
{ field: 'memory_static_max', value: 16 },
{ field: 'memory_dynamic_max', value: 16 },
{ field: 'memory_dynamic_min', value: 16 },
{ field: 'memory_static_min', value: 16 },
],
},
{
label: 'handles a memory decrease',
targetVm: {
memory_static_min: 4,
memory_dynamic_min: 8,
memory_dynamic_max: 16,
memory_static_max: 16,
},
vmRecord: {
memory_static_min: 2,
memory_dynamic_min: 2,
memory_dynamic_max: 2,
memory_static_max: 2,
},
expectedUpdates: [
{ field: 'memory_static_min', value: 2 },
{ field: 'memory_dynamic_min', value: 2 },
{ field: 'memory_dynamic_max', value: 2 },
{ field: 'memory_static_max', value: 2 },
],
},
{
label: 'handles a more complex case',
targetVm: {
memory_static_min: 1,
memory_dynamic_min: 2,
memory_dynamic_max: 8,
memory_static_max: 16,
},
vmRecord: {
memory_static_min: 4,
memory_dynamic_min: 4,
memory_dynamic_max: 4,
memory_static_max: 4,
},
expectedUpdates: [
{ field: 'memory_dynamic_min', value: 4 },
{ field: 'memory_static_min', value: 4 },
{ field: 'memory_dynamic_max', value: 4 },
{ field: 'memory_static_max', value: 4 },
],
},
{
label: 'avoids updating identical value',
targetVm: {
memory_static_min: 1,
memory_dynamic_min: 2,
memory_dynamic_max: 4,
memory_static_max: 8,
},
vmRecord: {
memory_static_min: 1,
memory_dynamic_min: 2,
memory_dynamic_max: 4,
memory_static_max: 8,
},
expectedUpdates: [],
},
]
describe('updateMemoryFields() should update in the right order', () => {
for (const test of tests) {
it(test.label, async () => {
const mock = mockXapiVm(test.targetVm)
test.targetVm.$ref = MOCK_REF
await updateMemoryFields(mock, test.targetVm, test.vmRecord)
assert.equal(mock.updates.length, test.expectedUpdates.length)
for (let i = 0; i < mock.updates.length; i++) {
assert.equal(mock.updates[i].value, test.expectedUpdates[i].value)
assert.equal(mock.updates[i].field, test.expectedUpdates[i].field)
}
})
}
})

View File

@@ -9,9 +9,7 @@ import { getAdaptersByRemote } from './_getAdaptersByRemote.mjs'
import { IncrementalXapi } from './_vmRunners/IncrementalXapi.mjs'
import { FullXapi } from './_vmRunners/FullXapi.mjs'
import { Throttle } from '@vates/generator-toolbox'
import { asyncEach } from '@vates/async-each'
import createStreamThrottle from './_createStreamThrottle.mjs'
import { selectSynchronizedSnapshotVms } from './_selectSynchronizedSnapshotVms.mjs'
const noop = Function.prototype
@@ -33,9 +31,7 @@ const DEFAULT_XAPI_VM_SETTINGS = {
nRetriesVmBackupFailures: 0,
offlineBackup: false,
offlineSnapshot: false,
snapshotConcurrency: 2,
snapshotRetention: 0,
synchronizedSnapshot: false,
timeout: 0,
useNbd: false,
unconditionalSnapshot: false,
@@ -51,16 +47,6 @@ export const VmsXapi = class VmsXapiBackupRunner extends Abstract {
return baseSettings
}
_getVmBackup(jobMode, opts) {
if (jobMode === 'delta') {
return new IncrementalXapi(opts)
} else if (jobMode === 'full') {
return new FullXapi(opts)
}
throw new Error(`Job mode ${jobMode} not implemented`)
}
async run() {
const job = this._job
@@ -109,81 +95,7 @@ export const VmsXapi = class VmsXapiBackupRunner extends Abstract {
const allSettings = this._job.settings
const baseSettings = this._baseSettings
const preTakenTimestampByVmId = {}
const failedSnapshotByVmId = {}
if (settings.synchronizedSnapshot) {
await Task.run({ properties: { name: 'snapshot VMs' } }, async () => {
await Disposable.use(
Disposable.all(vmIds.map(vmId => this._getRecord('VM', vmId).catch(noop))),
async vms => {
// remove vms that failed (already handled)
vms = vms.filter(_ => _ !== undefined)
const batchIds = selectSynchronizedSnapshotVms(settings.synchronizedSnapshot, vms)
await asyncEach(
[...vms].filter(vm => batchIds.has(vm.uuid)),
async vm => {
const vmSettings = { ...settings, ...allSettings[vm.uuid] }
const opts = {
baseSettings,
config,
getSnapshotNameLabel,
healthCheckSr,
job,
remoteAdapters,
schedule,
settings: vmSettings,
srs,
throttleGenerator,
throttleStream,
vm,
}
let vmBackup
try {
vmBackup = this._getVmBackup(job.mode, opts)
if (
!vmBackup._settings.offlineBackup &&
!vmBackup._settings.offlineSnapshot &&
(await vmBackup._mustDoSnapshot())
) {
await vmBackup._prepareAndSnapshot()
preTakenTimestampByVmId[vm.uuid] = vmBackup.timestamp
}
} catch (error) {
failedSnapshotByVmId[vm.uuid] = error
if (vmBackup !== undefined) {
try {
await vmBackup._fetchJobSnapshots()
await vmBackup._removeUnusedSnapshots()
await vmBackup._cleanMetadata()
} catch (cleanupError) {
// Best effort cleanup
}
}
}
},
{
concurrency: settings.snapshotConcurrency,
}
)
}
)
})
}
const snapshotedVmIds = new Set(vmIds.filter(id => !(id in failedSnapshotByVmId)))
Object.entries(failedSnapshotByVmId).forEach(([vmId, error]) => {
Task.run(
{
properties: { id: vmId, name: 'backup VM', type: 'VM' },
},
() => Promise.reject(error)
).catch(noop)
})
const queue = new Set(snapshotedVmIds)
const queue = new Set(vmIds)
const taskByVmId = {}
const nTriesByVmId = {}
@@ -243,16 +155,21 @@ export const VmsXapi = class VmsXapiBackupRunner extends Abstract {
schedule,
settings: vmSettings,
srs,
// when set, the batch phase already snapshotted this VM; the
// runner re-finds that snapshot by its metadata (see _snapshot)
synchronizedSnapshotTimestamp: preTakenTimestampByVmId[vmUuid],
throttleGenerator,
throttleStream,
vm,
}
const vmBackup = this._getVmBackup(job.mode, opts)
let vmBackup
if (job.mode === 'delta') {
vmBackup = new IncrementalXapi(opts)
} else {
if (job.mode === 'full') {
vmBackup = new FullXapi(opts)
} else {
throw new Error(`Job mode ${job.mode} not implemented`)
}
}
return vmBackup.run().catch(error => {
taskError = error
})

View File

@@ -1,10 +1,13 @@
import { asyncMap } from '@xen-orchestra/async-map'
import { createLogger } from '@xen-orchestra/log'
import { Task } from '@vates/task'
import { DIR_XO_POOL_METADATA_BACKUPS } from '../RemoteAdapter.mjs'
import { forkStreamUnpipe } from './_forkStreamUnpipe.mjs'
import { formatFilenameDate } from '../_filenameDate.mjs'
const { debug } = createLogger('xo:backups:PoolMetadataBackup')
export const PATH_DB_DUMP = '/pool/xmldbdump'
export class PoolMetadataBackup {
@@ -31,7 +34,22 @@ export class PoolMetadataBackup {
const poolDir = `${DIR_XO_POOL_METADATA_BACKUPS}/${schedule.id}/${pool.$id}`
const dir = `${poolDir}/${formatFilenameDate(timestamp)}`
const tasks = Object.values(pool.$xapi.objects.indexes.type.task ?? {})
const pendingTasks = tasks.filter(task => task.status === 'pending')
debug('pool tasks before export', {
total: tasks.length,
pending: pendingTasks.length,
oldestPendingCreated: pendingTasks.map(task => task.created).sort()[0],
})
const stream = (await this._exportPoolMetadata()).body
const startedAt = Date.now()
let bytes = 0
stream.once('data', () => debug('first byte received', { afterMs: Date.now() - startedAt }))
stream.on('data', chunk => (bytes += chunk.length))
stream.once('end', () => debug('stream ended', { bytes, durationMs: Date.now() - startedAt }))
stream.once('error', error => debug('stream errored', { error, bytes, durationMs: Date.now() - startedAt }))
const fileName = `${dir}/data`
const metadata = JSON.stringify(

View File

@@ -1,19 +0,0 @@
import { Task } from '@vates/task'
export function selectSynchronizedSnapshotVms(synchronizedSnapshot, vms) {
if (synchronizedSnapshot === false) {
return new Set()
}
let matches
if (typeof synchronizedSnapshot === 'string') {
matches = vms.filter(vm => vm.tags.includes(synchronizedSnapshot))
} else if (synchronizedSnapshot === true) {
matches = vms
} else {
Task.warning('unsupported synchronizedSnapshot option, expected a boolean or a tag name', { synchronizedSnapshot })
return new Set()
}
return new Set(matches.map(vm => vm.uuid))
}

View File

@@ -1,73 +0,0 @@
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { selectSynchronizedSnapshotVms } from './_selectSynchronizedSnapshotVms.mjs'
// Helper mirroring the minimal VM record shape the selector needs.
const vm = (uuid, tags = []) => ({ uuid, tags })
// `selectSynchronizedSnapshotVms(synchronizedSnapshot, vms)` must return a Set
// of the UUIDs that should be snapshotted together in the batch phase.
// - false -> feature off, no VM is batched
// - true -> every VM is batched, regardless of tags
// - '<tagName>' -> only VMs carrying that exact tag are batched
const tests = [
{
label: 'false disables batching',
setting: false,
vms: [vm('a', ['prod']), vm('b')],
expected: [],
},
{
label: 'true batches every VM regardless of tags',
setting: true,
vms: [vm('a', ['prod']), vm('b')],
expected: ['a', 'b'],
},
{
label: 'tag batches only the VMs carrying it',
setting: 'prod',
vms: [vm('a', ['prod']), vm('b', ['dev']), vm('c', ['prod', 'other'])],
expected: ['a', 'c'],
},
{
label: 'tag carried by no VM yields an empty batch',
setting: 'prod',
vms: [vm('a', ['dev']), vm('b')],
expected: [],
},
{
label: 'tag carried by every VM batches all of them',
setting: 'prod',
vms: [vm('a', ['prod']), vm('b', ['prod'])],
expected: ['a', 'b'],
},
{
label: 'empty VM list yields an empty batch',
setting: true,
vms: [],
expected: [],
},
{
label: 'empty-string tag matches no VM when none carries an empty tag',
setting: '',
vms: [vm('a', ['prod'])],
expected: [],
},
{
label: 'non boolean or string yiels an empty batch',
setting: 1,
vms: [vm('a', ['prod'])],
expected: [],
},
]
describe('selectSynchronizedSnapshotVms()', () => {
for (const { label, setting, vms, expected } of tests) {
it(label, () => {
const result = selectSynchronizedSnapshotVms(setting, vms)
assert.ok(result instanceof Set, 'result must be a Set')
assert.deepEqual([...result].sort(), [...expected].sort())
})
}
})

View File

@@ -80,14 +80,14 @@ export const FullXapi = class FullXapiVmBackupRunner extends AbstractXapi {
const sizeContainer = watchStreamSize(stream)
const transferStart = Date.now()
const timestamp = Date.now()
await this._callWriters(
writer =>
writer.run({
maxStreamLength,
sizeContainer,
stream: forkStreamUnpipe(stream),
timestamp: this.timestamp,
timestamp,
vm,
vmSnapshot: exportedVm,
}),
@@ -95,7 +95,8 @@ export const FullXapi = class FullXapiVmBackupRunner extends AbstractXapi {
)
const { size } = sizeContainer
const duration = Date.now() - transferStart
const end = Date.now()
const duration = end - timestamp
debug('transfer complete', {
duration,
speed: duration !== 0 ? (size * 1e3) / 1024 / 1024 / duration : 0,

View File

@@ -2,12 +2,13 @@ import { createLogger } from '@xen-orchestra/log'
import { asyncEach } from '@vates/async-each'
import assert from 'node:assert'
import * as UUID from 'uuid'
import { AbstractRemote } from './_AbstractRemote.mjs'
import { forkDeltaExport } from './_forkDeltaExport.mjs'
import { IncrementalRemoteWriter } from '../_writers/IncrementalRemoteWriter.mjs'
import { Disposable } from 'promise-toolbox'
import { openDisposableDisk } from '@xen-orchestra/backup-archive/disks'
import { openVhd } from 'vhd-lib'
import { getVmBackupDir } from '../../_getVmBackupDir.mjs'
import { SynchronizedDisk, ThrottledDisk } from '@xen-orchestra/disk-transform'
import { AggregatedIncrementalRemoteWriter } from '../_writers/AggregatedIncrementalRemoteWriter.mjs'
@@ -43,12 +44,9 @@ class IncrementalRemoteVmBackupRunner extends AbstractRemote {
const vmDir = getVmBackupDir(metadata.vm.uuid)
const path = `${vmDir}/${metadata.vhds[id]}`
// don't catch error : we can't recover if the source vhd are missing
await Disposable.use(
openDisposableDisk({ handler: this._sourceRemoteAdapter._handler, path, ignoreBlockIndexes: true }),
disk => {
baseUuidToSrcVdi.set(disk.getParentUuid(), vdi.$snapshot_of$uuid)
}
)
await Disposable.use(openVhd(this._sourceRemoteAdapter._handler, path), vhd => {
baseUuidToSrcVdi.set(UUID.stringify(vhd.header.parentUuid), vdi.$snapshot_of$uuid)
})
}
})

View File

@@ -13,6 +13,7 @@ import {
DELTA_CHAIN_LENGTH,
EXPORTED_SUCCESSFULLY,
setVmDeltaChainLength,
markExportSuccessfull,
} from '../../_otherConfig.mjs'
import { ThrottledDisk, SynchronizedDisk } from '@xen-orchestra/disk-transform'
import { AggregatedIncrementalRemoteWriter } from '../_writers/AggregatedIncrementalRemoteWriter.mjs'
@@ -67,6 +68,7 @@ export const IncrementalXapi = class IncrementalXapiVmBackupRunner extends Abstr
// @todo : reimplement throttle
const timestamp = Date.now()
await this._callWriters(
writer =>
writer.transfer({
@@ -76,7 +78,7 @@ export const IncrementalXapi = class IncrementalXapiVmBackupRunner extends Abstr
// clean; the tip's flag lets the next run skip re-probing
includeNonNbdQcow2Fix: true,
isVhdDifferencing,
timestamp: this.timestamp,
timestamp,
vm,
vmSnapshot: exportedVm,
}),
@@ -89,6 +91,11 @@ export const IncrementalXapi = class IncrementalXapiVmBackupRunner extends Abstr
await setVmDeltaChainLength(this._xapi, exportedVm.$ref, (this._deltaChainLength ?? 0) + 1)
}
// not the case if offlineBackup
if (exportedVm.is_a_snapshot) {
await markExportSuccessfull(this._xapi, exportedVm.$ref)
}
await this._callWriters(writer => writer.cleanup(), 'writer.cleanup()')
}

View File

@@ -7,7 +7,6 @@ import { asyncEach } from '@vates/async-each'
import { decorateMethodsWith } from '@vates/decorate-with'
import { defer } from 'golike-defer'
import { Task } from '@vates/task'
import { formatDateTime } from '@xen-orchestra/xapi'
import { getOldEntries } from '../../_getOldEntries.mjs'
import { Abstract } from './_Abstract.mjs'
@@ -17,11 +16,9 @@ import {
JOB_ID,
SCHEDULE_ID,
VM_UUID,
EXPORTED_SUCCESSFULLY,
resetVmOtherConfig,
setVmOtherConfig,
setVmSnapshotContentKeys,
markExportSuccessfull,
} from '../../_otherConfig.mjs'
const { warn, info } = createLogger('xo:backups:AbstractXapi')
@@ -39,7 +36,6 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
schedule,
settings,
srs,
synchronizedSnapshotTimestamp,
throttleGenerator,
throttleStream,
vm,
@@ -67,9 +63,9 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
// VM (snapshot) that is really exported
this._exportedVm = undefined
this._synchronizedSnapshotTimestamp = synchronizedSnapshotTimestamp
this._vm = vm
this._baseVdis = undefined
this._getSnapshotNameLabel = getSnapshotNameLabel
this._isIncremental = job.mode === 'delta'
this._healthCheckSr = healthCheckSr
@@ -184,27 +180,6 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
}
async _snapshot() {
if (this._synchronizedSnapshotTimestamp !== undefined) {
const datetime = formatDateTime(this._synchronizedSnapshotTimestamp)
const candidates = this._vm.$snapshots.filter(
snapshot =>
snapshot?.other_config[JOB_ID] === this._jobId &&
snapshot?.other_config[DATETIME] === datetime &&
!snapshot.other_config[EXPORTED_SUCCESSFULLY]
)
if (candidates.length === 1) {
this._exportedVm = candidates[0]
this.timestamp = this._synchronizedSnapshotTimestamp
return
}
warn('expected exactly one synchronized snapshot to reuse, taking a fresh one', {
vm: this._vm.uuid,
datetime,
count: candidates.length,
})
}
const vm = this._vm
const xapi = this._xapi
@@ -421,25 +396,10 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
await xapi.barrier()
// ensure cached object are up to date
this._jobSnapshotVdis = this._jobSnapshotVdis.map(vdi => xapi.getObject(vdi.$ref))
let disklessVmSnapshots = this._disklessJobSnapshotVms.map(vm => xapi.getObject(vm.$ref))
const disklessVmSnapshots = this._disklessJobSnapshotVms.map(vm => xapi.getObject(vm.$ref))
// The synchronized snapshot for this run is taken up-front by the batch
// phase but transferred later. Until it has been exported, hide it from
// retention so it is not reclaimed. This makes the pre-transfer pass behave
// like a normal run, where the snapshot does not exist yet.
if (this._synchronizedSnapshotTimestamp !== undefined) {
const datetime = formatDateTime(this._synchronizedSnapshotTimestamp)
const isInFlightSyncSnapshot = ({ other_config }) =>
other_config[DATETIME] === datetime && !other_config[EXPORTED_SUCCESSFULLY]
this._jobSnapshotVdis = this._jobSnapshotVdis.filter(vdi => !isInFlightSyncSnapshot(vdi))
disklessVmSnapshots = disklessVmSnapshots.filter(vm => !isInFlightSyncSnapshot(vm))
}
const isExported = ({ other_config }) => EXPORTED_SUCCESSFULLY in other_config
// get the datetime of the most recent exported snapshot across both VDI and diskless VM snapshots
const lastExportedSnapshotDateTime = [...this._jobSnapshotVdis, ...disklessVmSnapshots]
.filter(isExported)
// get the datetime of the most recent snapshot across both VDI and diskless VM snapshots
const lastSnapshotDateTime = [...this._jobSnapshotVdis, ...disklessVmSnapshots]
.map(({ other_config }) => other_config[DATETIME])
.sort()
.pop()
@@ -459,13 +419,9 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
}
const retention = settings.snapshotRetention ?? 0
await asyncMap(getOldEntries(retention, datetimes), async datetime => {
// keep the last exported snapshot across all schedules for delta
// keep the last snapshot across all schedules for delta
// since we'll need it to compute delta for next backup
if (
this.job.mode === 'delta' &&
lastExportedSnapshotDateTime !== undefined &&
datetime === lastExportedSnapshotDateTime
) {
if (this.job.mode === 'delta' && datetime === lastSnapshotDateTime) {
return
}
const vdis = snapshotPerDatetime[datetime]
@@ -508,9 +464,7 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
vm = vdiVm
}
}
if (vm?.$ref !== undefined) {
this._forgetExportedVm(vm.$ref)
return xapi.VM_destroy(vm.$ref)
} else {
return asyncMap(
@@ -536,15 +490,9 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
}
const retention = settings.snapshotRetention ?? 0
await asyncEach(getOldEntries(retention, datetimes), async datetime => {
if (
this.job.mode === 'delta' &&
lastExportedSnapshotDateTime !== undefined &&
datetime === lastExportedSnapshotDateTime
) {
if (this.job.mode === 'delta' && datetime === lastSnapshotDateTime) {
return
}
this._forgetExportedVm(snapshotPerDatetime[datetime])
await xapi.VM_destroy(snapshotPerDatetime[datetime])
})
})
@@ -556,15 +504,6 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
await asyncEach(snapshots, snapshot => snapshot.$destroy())
}
// _exportedVm is the VM (usually a snapshot) this run exported. Retention may destroy
// it in the same run and everything reading it would then operate on a destroyed VM.
// Forget it as soon as it is reclaimed.
_forgetExportedVm(vmRef) {
if (vmRef === this._exportedVm?.$ref) {
this._exportedVm = undefined
}
}
async _removeSnapshotData() {
// now that we use CBT, we can destroy the data of the snapshot used for this backup
// going back to a previous version of XO not supporting CBT will create a full backup
@@ -612,11 +551,6 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
throw new Error('Not implemented')
}
async _prepareAndSnapshot() {
await this._cleanMetadata()
await this._snapshot()
}
async run($defer) {
const settings = this._settings
assert(
@@ -680,10 +614,6 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
if (this._writers.size !== 0) {
await this._copy()
}
// not the case if offlineBackup
if (this._exportedVm.is_a_snapshot) {
await markExportSuccessfull(this._xapi, this._exportedVm.$ref)
}
} finally {
if (startAfter) {
ignoreErrors.call(vm.$callAsync('start', false, false))

View File

@@ -1,659 +0,0 @@
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { formatDateTime } from '@xen-orchestra/xapi'
import { AbstractXapi } from './_AbstractXapi.mjs'
import { DATETIME, EXPORTED_SUCCESSFULLY, JOB_ID, SCHEDULE_ID } from '../../_otherConfig.mjs'
// Build an AbstractXapi instance without running its heavy constructor, then
// assign only the fields the method under test reads.
const makeRunner = props => Object.assign(Object.create(AbstractXapi.prototype), props)
describe('_snapshot() synchronized-snapshot reuse guard', () => {
it('reuses the batch snapshot, found by metadata, without snapshotting again', async () => {
let mustDoSnapshotCalls = 0
const timestamp = 1717200000000
// the snapshot taken by the batch phase, identified by its other_config
const batchSnapshot = {
$ref: 'batch-snapshot-ref',
other_config: {
[JOB_ID]: 'job-1',
[SCHEDULE_ID]: 'schedule-1',
[DATETIME]: formatDateTime(timestamp),
},
}
const runner = makeRunner({
_synchronizedSnapshotTimestamp: timestamp,
_jobId: 'job-1',
scheduleId: 'schedule-1',
_vm: { uuid: 'vm-uuid', $snapshots: [batchSnapshot] },
_xapi: { barrier: async () => {} },
// if the metadata lookup fails, _snapshot() falls through to here
_mustDoSnapshot: async () => {
mustDoSnapshotCalls++
return false
},
})
await runner._snapshot()
assert.equal(mustDoSnapshotCalls, 0, '_mustDoSnapshot() should not be called when the batch snapshot is found')
assert.equal(runner._exportedVm, batchSnapshot, '_exportedVm should be the batch snapshot found by metadata')
assert.equal(runner.timestamp, timestamp, 'timestamp should be the synchronized snapshot timestamp')
})
it('takes a fresh snapshot when the batch snapshot can no longer be found', async () => {
let mustDoSnapshotCalls = 0
const vm = { uuid: 'vm-uuid', $snapshots: [] } // the pre-taken snapshot is gone
const runner = makeRunner({
_synchronizedSnapshotTimestamp: 1717200000000,
_jobId: 'job-1',
scheduleId: 'schedule-1',
_vm: vm,
_xapi: { barrier: async () => {} },
_settings: {},
_mustDoSnapshot: async () => {
mustDoSnapshotCalls++
return false
},
})
await runner._snapshot()
assert.equal(
mustDoSnapshotCalls,
1,
'a missing batch snapshot should not be reused: _snapshot() should fall through and take a fresh snapshot'
)
assert.equal(
runner._exportedVm,
vm,
'_exportedVm should fall back to the freshly-snapshotted VM, not stay on a stale/missing batch snapshot'
)
})
it('without a pre-taken snapshot and no snapshot needed, exports the live VM', async () => {
let mustDoSnapshotCalls = 0
const vm = { uuid: 'vm-uuid' }
const runner = makeRunner({
_exportedVm: undefined,
_vm: vm,
_xapi: {},
_settings: {},
_mustDoSnapshot: async () => {
mustDoSnapshotCalls++
return false
},
})
await runner._snapshot()
assert.equal(mustDoSnapshotCalls, 1, '_mustDoSnapshot() should be called once when no snapshot was pre-taken')
assert.equal(runner._exportedVm, vm, '_exportedVm should be set to the live VM when no snapshot is needed')
assert.equal(typeof runner.timestamp, 'number', 'timestamp should be set when exporting the live VM')
})
})
describe('_removeUnusedSnapshots() protects the pre-taken synchronized snapshot', () => {
const OLD_DATETIME = '20240101T00:00:00Z'
const SYNC_TIMESTAMP = 1717200000000
const SYNC_DATETIME = formatDateTime(SYNC_TIMESTAMP)
// Full-mode job with snapshotRetention 0, so retention wants to remove every
// snapshot. `vdi-fresh` is the snapshot taken up-front by the synchronized
// batch phase (identified by SYNC_TIMESTAMP); until it is exported it must be
// hidden from retention.
const makeRemoveRunner = ({ exported }) => {
const destroyed = []
const snapshotVm = ($ref, name_label) => ({
$ref,
name_label,
is_control_domain: false,
$snapshot_of: 'live-vm-ref',
other_config: {},
})
const freshSnapshotVm = snapshotVm('vm-fresh', 'fresh')
const oldSnapshotVm = snapshotVm('vm-old', 'old')
const vdi = ($ref, datetime, snapshotVmRecord, isExported = false) => ({
$ref,
other_config: {
[DATETIME]: datetime,
[SCHEDULE_ID]: 'schedule-1',
...(isExported ? { [EXPORTED_SUCCESSFULLY]: 'true' } : {}),
},
$VBDs: [{ $VM: snapshotVmRecord }],
})
// the old snapshot was exported by a previous run
const oldVdi = vdi('vdi-old', OLD_DATETIME, oldSnapshotVm, true)
const freshVdi = vdi('vdi-fresh', SYNC_DATETIME, freshSnapshotVm, exported)
const registry = { 'vdi-old': oldVdi, 'vdi-fresh': freshVdi }
const runner = makeRunner({
_synchronizedSnapshotTimestamp: SYNC_TIMESTAMP,
_vm: { uuid: 'live-uuid', $snapshots: [] },
_baseSettings: { snapshotRetention: 0 },
_jobSnapshotVdis: [oldVdi, freshVdi],
_disklessJobSnapshotVms: [],
job: { mode: 'full', settings: {} },
_xapi: {
barrier: async () => {},
getObject: ref => registry[ref],
VM_destroy: async ref => {
destroyed.push(ref)
},
VDI_destroy: async ref => {
destroyed.push(ref)
},
},
})
return { runner, destroyed }
}
it('does not destroy the pre-taken snapshot before it has been transferred', async () => {
const { runner, destroyed } = makeRemoveRunner({ exported: false })
await runner._removeUnusedSnapshots()
assert.deepEqual(destroyed, ['vm-old'], 'only the older snapshot should be removed')
})
it('destroys the snapshot once it has been transferred (retention 0, no leak)', async () => {
const { runner, destroyed } = makeRemoveRunner({ exported: true })
await runner._removeUnusedSnapshots()
assert.deepEqual(destroyed.sort(), ['vm-fresh', 'vm-old'], 'both snapshots should be removed after transfer')
})
})
describe('_removeUnusedSnapshots() in the synchronized batch pre-snapshot state', () => {
it('delta mode: keeps the base snapshot when the fresh one has not been taken yet', async () => {
const destroyed = []
const BASE_DATETIME = '2024-06-01T00:00:00Z'
const baseSnapshotVm = {
$ref: 'vm-base',
name_label: 'base',
is_control_domain: false,
$snapshot_of: 'live-vm-ref',
}
const baseVdi = {
$ref: 'vdi-base',
other_config: { [DATETIME]: BASE_DATETIME, [SCHEDULE_ID]: 'schedule-1', [EXPORTED_SUCCESSFULLY]: 'true' },
$VBDs: [{ $VM: baseSnapshotVm }],
}
const registry = { 'vdi-base': baseVdi }
const runner = makeRunner({
// batch pre-snapshot state: the synchronized snapshot has not been taken yet
_exportedVm: undefined,
_vm: { uuid: 'live-uuid', $snapshots: [] },
_baseSettings: { snapshotRetention: 0 },
_jobSnapshotVdis: [baseVdi],
_disklessJobSnapshotVms: [],
job: { mode: 'delta', settings: {} },
_xapi: {
barrier: async () => {},
getObject: ref => registry[ref],
VM_destroy: async ref => {
destroyed.push(ref)
},
VDI_destroy: async ref => {
destroyed.push(ref)
},
},
})
await runner._removeUnusedSnapshots()
assert.deepEqual(destroyed, [], 'the base snapshot must be kept as the delta base for the upcoming transfer')
})
})
describe('_removeUnusedSnapshots() after a failed transfer', () => {
const BASE_DATETIME = '20260902T090100Z'
const FAILED_DATETIME = '20260902T092200Z'
const makeFailedRunRunner = ({ freshExported = false } = {}) => {
const destroyed = []
const snapshotVm = $ref => ({
$ref,
name_label: $ref,
is_control_domain: false,
$snapshot_of: 'live-vm-ref',
other_config: {},
})
const baseSnapshotVm = snapshotVm('vm-base')
const freshSnapshotVm = snapshotVm('vm-failed')
const vdi = ($ref, datetime, snapshotVmRecord, isExported) => ({
$ref,
other_config: {
[DATETIME]: datetime,
[SCHEDULE_ID]: 'schedule-1',
...(isExported ? { [EXPORTED_SUCCESSFULLY]: 'true' } : {}),
},
$VBDs: [{ $VM: snapshotVmRecord }],
})
// the base of the last successful run and the snapshot of the run that just failed
const baseVdi = vdi('vdi-base', BASE_DATETIME, baseSnapshotVm, true)
const freshVdi = vdi('vdi-failed', FAILED_DATETIME, freshSnapshotVm, freshExported)
const registry = { 'vdi-base': baseVdi, 'vdi-failed': freshVdi }
const runner = makeRunner({
// no synchronized snapshot: this is a plain incremental replication job
_synchronizedSnapshotTimestamp: undefined,
_vm: { uuid: 'live-uuid', $snapshots: [] },
_baseSettings: { snapshotRetention: 0 },
_jobSnapshotVdis: [baseVdi, freshVdi],
_disklessJobSnapshotVms: [],
job: { mode: 'delta', settings: {} },
_xapi: {
barrier: async () => {},
getObject: ref => registry[ref],
VM_destroy: async ref => {
destroyed.push(ref)
},
VDI_destroy: async ref => {
destroyed.push(ref)
},
},
})
return { runner, destroyed }
}
it('keeps the last successfully exported snapshot as the delta base', async () => {
const { runner, destroyed } = makeFailedRunRunner()
await runner._removeUnusedSnapshots()
assert.equal(
destroyed.includes('vm-base'),
false,
'the last exported snapshot is the only usable delta base: destroying it forces a full on the next run'
)
})
it('reclaims the snapshot of the failed run (never exported, retention 0)', async () => {
const { runner, destroyed } = makeFailedRunRunner()
await runner._removeUnusedSnapshots()
assert.deepEqual(destroyed, ['vm-failed'], 'only the never-exported snapshot should be removed')
})
it('keeps the most recent snapshot once the transfer succeeded', async () => {
const { runner, destroyed } = makeFailedRunRunner({ freshExported: true })
await runner._removeUnusedSnapshots()
assert.deepEqual(destroyed, ['vm-base'], 'the newly exported snapshot should replace the previous base')
})
it('keeps the newest exported snapshot even when several runs failed in a row', async () => {
const { runner, destroyed } = makeFailedRunRunner()
// a second consecutive failure adds another never-exported snapshot
const secondFailedVm = {
$ref: 'vm-failed-2',
name_label: 'vm-failed-2',
is_control_domain: false,
$snapshot_of: 'live-vm-ref',
other_config: {},
}
const secondFailedVdi = {
$ref: 'vdi-failed-2',
other_config: { [DATETIME]: '20260902T092600Z', [SCHEDULE_ID]: 'schedule-1' },
$VBDs: [{ $VM: secondFailedVm }],
}
runner._jobSnapshotVdis.push(secondFailedVdi)
const getObject = runner._xapi.getObject
runner._xapi.getObject = ref => (ref === 'vdi-failed-2' ? secondFailedVdi : getObject(ref))
await runner._removeUnusedSnapshots()
assert.deepEqual(
destroyed.sort(),
['vm-failed', 'vm-failed-2'],
'both failed snapshots should be reclaimed and the exported base kept'
)
})
})
describe('_removeUnusedSnapshots() reclaims orphan / CBT snapshot VDIs (no attached VM)', () => {
// Guards the `else` branch: snapshot VDIs that are not attached to any user VM
// (e.g. CBT metadata, orphans) must be reclaimed via VDI_destroy, not VM_destroy.
it('destroys snapshot VDIs directly when they are not attached to any VM', async () => {
const vmDestroyed = []
const vdiDestroyed = []
const orphanVdi = {
$ref: 'vdi-orphan',
other_config: { [DATETIME]: '2024-01-01T00:00:00Z', [SCHEDULE_ID]: 'schedule-1' },
$VBDs: [], // not attached to any VM
}
const registry = { 'vdi-orphan': orphanVdi }
const runner = makeRunner({
_exportedVm: undefined,
_vm: { uuid: 'live-uuid', $snapshots: [] },
_baseSettings: { snapshotRetention: 0 },
_jobSnapshotVdis: [orphanVdi],
_disklessJobSnapshotVms: [],
job: { mode: 'full', settings: {} },
_xapi: {
barrier: async () => {},
getObject: ref => registry[ref],
VM_destroy: async ref => {
vmDestroyed.push(ref)
},
VDI_destroy: async ref => {
vdiDestroyed.push(ref)
},
},
})
await runner._removeUnusedSnapshots()
assert.deepEqual(vdiDestroyed, ['vdi-orphan'], 'the orphan VDI should be reclaimed via VDI_destroy')
assert.deepEqual(vmDestroyed, [], 'no VM should be destroyed for an orphan VDI')
})
})
describe('_removeUnusedSnapshots() diskless VM snapshots', () => {
const OLD_DATETIME = '20240101T00:00:00Z'
const SYNC_TIMESTAMP = 1717200000000
const SYNC_DATETIME = formatDateTime(SYNC_TIMESTAMP)
// A diskless VM's backup snapshots are tracked as VM snapshots (no VDIs to
// anchor them). `dl-fresh` is the snapshot the synchronized batch pre-took,
// identified by SYNC_TIMESTAMP.
const makeDisklessRunner = ({ exported, mode = 'full' }) => {
const destroyed = []
const oldSnap = { $ref: 'dl-old', other_config: { [DATETIME]: OLD_DATETIME, [SCHEDULE_ID]: 'schedule-1' } }
const freshSnap = { $ref: 'dl-fresh', other_config: { [DATETIME]: SYNC_DATETIME, [SCHEDULE_ID]: 'schedule-1' } }
if (exported) freshSnap.other_config[EXPORTED_SUCCESSFULLY] = 'true'
const registry = { 'dl-old': oldSnap, 'dl-fresh': freshSnap }
const runner = makeRunner({
_synchronizedSnapshotTimestamp: SYNC_TIMESTAMP,
_vm: { uuid: 'live-uuid', $snapshots: [] },
_baseSettings: { snapshotRetention: 0 },
_jobSnapshotVdis: [],
_disklessJobSnapshotVms: [oldSnap, freshSnap],
job: { mode, settings: {} },
_xapi: {
barrier: async () => {},
getObject: ref => registry[ref],
VM_destroy: async ref => {
destroyed.push(ref)
},
VDI_destroy: async ref => {
destroyed.push(ref)
},
},
})
return { runner, destroyed }
}
it('does not destroy the pre-taken diskless snapshot before it has been transferred', async () => {
const { runner, destroyed } = makeDisklessRunner({ exported: false })
await runner._removeUnusedSnapshots()
assert.deepEqual(destroyed, ['dl-old'], 'only the older diskless snapshot should be removed')
})
it('destroys the diskless snapshot once it has been transferred (retention 0, no leak)', async () => {
const { runner, destroyed } = makeDisklessRunner({ exported: true })
await runner._removeUnusedSnapshots()
assert.deepEqual(
destroyed.sort(),
['dl-fresh', 'dl-old'],
'both diskless snapshots should be removed after transfer'
)
})
it('keeps the most recent diskless snapshot in delta mode (base for next delta)', async () => {
// Even after transfer (exported), delta mode must retain the latest
// snapshot so the next run can compute its delta against it.
const { runner, destroyed } = makeDisklessRunner({ exported: true, mode: 'delta' })
await runner._removeUnusedSnapshots()
assert.deepEqual(destroyed, ['dl-old'], 'the most recent diskless snapshot should be kept in delta mode')
})
})
describe('_removeUnusedSnapshots() forgets the exported snapshot when it reclaims it', () => {
// `_exportedVm` is read after retention has run (by `_removeSnapshotData()`), so it must
// not survive the destruction of the VM it points at.
const BASE_DATETIME = '20260902T090100Z'
const SYNC_TIMESTAMP = 1717200000000
const makeRunner_ = ({ freshDatetime, freshExported = false, synchronized = false, exportedVmRef }) => {
const destroyed = []
const snapshotVm = $ref => ({
$ref,
name_label: $ref,
is_control_domain: false,
$snapshot_of: 'live-vm-ref',
other_config: {},
})
const baseSnapshotVm = snapshotVm('vm-base')
const freshSnapshotVm = snapshotVm('vm-fresh')
const vdi = ($ref, datetime, snapshotVmRecord, isExported) => ({
$ref,
other_config: {
[DATETIME]: datetime,
[SCHEDULE_ID]: 'schedule-1',
...(isExported ? { [EXPORTED_SUCCESSFULLY]: 'true' } : {}),
},
$VBDs: [{ $VM: snapshotVmRecord }],
})
const baseVdi = vdi('vdi-base', BASE_DATETIME, baseSnapshotVm, true)
const freshVdi = vdi('vdi-fresh', freshDatetime, freshSnapshotVm, freshExported)
const registry = { 'vdi-base': baseVdi, 'vdi-fresh': freshVdi }
const vms = { 'vm-base': baseSnapshotVm, 'vm-fresh': freshSnapshotVm }
const runner = makeRunner({
_synchronizedSnapshotTimestamp: synchronized ? SYNC_TIMESTAMP : undefined,
_exportedVm: vms[exportedVmRef],
_vm: { uuid: 'live-uuid', $snapshots: [] },
_baseSettings: { snapshotRetention: 0 },
_jobSnapshotVdis: [baseVdi, freshVdi],
_disklessJobSnapshotVms: [],
job: { mode: 'delta', settings: {} },
_xapi: {
barrier: async () => {},
getObject: ref => registry[ref],
VM_destroy: async ref => {
destroyed.push(ref)
},
VDI_destroy: async ref => {
destroyed.push(ref)
},
},
})
return { runner, destroyed }
}
it('clears _exportedVm when the snapshot of the failed run is reclaimed', async () => {
const { runner, destroyed } = makeRunner_({ freshDatetime: '20260902T092200Z', exportedVmRef: 'vm-fresh' })
await runner._removeUnusedSnapshots()
assert.deepEqual(destroyed, ['vm-fresh'], 'the never-exported snapshot should be reclaimed')
assert.equal(runner._exportedVm, undefined, '_exportedVm must not outlive the VM it points at')
})
it('keeps _exportedVm when the snapshot survives retention (synchronized snapshot)', async () => {
// the in-flight synchronized snapshot is hidden from retention, so it is still
// there afterwards and its data must still be purgeable
const { runner, destroyed } = makeRunner_({
freshDatetime: formatDateTime(SYNC_TIMESTAMP),
synchronized: true,
exportedVmRef: 'vm-fresh',
})
await runner._removeUnusedSnapshots()
assert.deepEqual(destroyed, [], 'the in-flight synchronized snapshot must be kept')
assert.notEqual(runner._exportedVm, undefined, '_exportedVm should be kept while the snapshot exists')
})
it('keeps _exportedVm when another snapshot is reclaimed', async () => {
// nominal run: the fresh snapshot has been exported, the previous base ages out
const { runner, destroyed } = makeRunner_({
freshDatetime: '20260902T092200Z',
freshExported: true,
exportedVmRef: 'vm-fresh',
})
await runner._removeUnusedSnapshots()
assert.deepEqual(destroyed, ['vm-base'], 'only the previous base should be reclaimed')
assert.notEqual(runner._exportedVm, undefined, 'the exported snapshot is untouched')
})
it('clears _exportedVm when a reclaimed diskless snapshot is the exported one', async () => {
const destroyed = []
const oldSnap = { $ref: 'dl-old', other_config: { [DATETIME]: '20240101T000000Z', [SCHEDULE_ID]: 'schedule-1' } }
const registry = { 'dl-old': oldSnap }
const runner = makeRunner({
_exportedVm: oldSnap,
_vm: { uuid: 'live-uuid', $snapshots: [] },
_baseSettings: { snapshotRetention: 0 },
_jobSnapshotVdis: [],
_disklessJobSnapshotVms: [oldSnap],
job: { mode: 'full', settings: {} },
_xapi: {
barrier: async () => {},
getObject: ref => registry[ref],
VM_destroy: async ref => {
destroyed.push(ref)
},
VDI_destroy: async () => {},
},
})
await runner._removeUnusedSnapshots()
assert.deepEqual(destroyed, ['dl-old'], 'the diskless snapshot should be reclaimed')
assert.equal(runner._exportedVm, undefined, '_exportedVm must not outlive the VM it points at')
})
})
describe('run() purges the snapshot data only while the snapshot exists', () => {
// `_removeSnapshotData()` runs from the `finally` of run(), right after
// `_removeUnusedSnapshots()`. Whether it acts is decided by `_exportedVm` alone: the
// snapshot of a failed run is reclaimed (nothing to purge), but a synchronized snapshot
// is hidden from retention and survives, so its data must still be reclaimed.
const makeRunRunner = ({ copyFails = false, isSnapshot = true, snapshotReclaimed = copyFails } = {}) => {
const calls = { markExportSuccessfull: 0, vmDestroyed: [], dataDestroyed: [] }
const runner = makeRunner({
_healthCheckSr: undefined,
// the only configuration in which _removeSnapshotData() acts
_settings: { offlineBackup: false, snapshotRetention: 0, preferNbd: true, cbtDestroySnapshotData: true },
_vm: {
uuid: 'live-uuid',
power_state: 'Halted',
blocked_operations: {},
update_blocked_operations: async () => {},
$call: async () => {},
},
_writers: new Set([{ beforeBackup: async () => {}, afterBackup: async () => {} }]),
_xapi: {
VM_getDisks: async () => ['vdi-ref'],
// used by markExportSuccessfull()
setFieldEntry: async () => {
calls.markExportSuccessfull++
},
call: async (method, ref) => {
calls.vmDestroyed.push(`${method}:${ref}`)
},
VDI_dataDestroy: async ref => {
calls.dataDestroyed.push(ref)
},
},
_cleanMetadata: async () => {},
_fetchJobSnapshots: async () => {},
_selectBaseVm: async () => {},
_removeUnusedSnapshots: async function () {
if (snapshotReclaimed) {
this._forgetExportedVm(this._exportedVm?.$ref)
}
},
_snapshot: async function () {
this._exportedVm = {
$ref: 'snapshot-ref',
is_a_snapshot: isSnapshot,
// a snapshot of the live VM; undefined for an offline backup, where the live VM is exported
$snapshot_of: isSnapshot ? 'live-vm-ref' : undefined,
}
},
_copy: async () => {
if (copyFails) {
throw new Error('transfer failed: target unreachable')
}
},
})
return { runner, calls }
}
it('does not purge anything when the failed run snapshot has been reclaimed', async () => {
const { runner, calls } = makeRunRunner({ copyFails: true })
await assert.rejects(runner.run(), /transfer failed/)
assert.deepEqual(calls.vmDestroyed, [], 'the snapshot is already destroyed: nothing to purge')
assert.deepEqual(calls.dataDestroyed, [], 'no VDI to data_destroy either')
})
it('purges the snapshot data of a failed run whose snapshot survived retention', async () => {
// synchronized snapshot: hidden from retention, so it is still holding its data
const { runner, calls } = makeRunRunner({ copyFails: true, snapshotReclaimed: false })
await assert.rejects(runner.run(), /transfer failed/)
assert.deepEqual(calls.vmDestroyed, ['VM.destroy:snapshot-ref'], 'the surviving snapshot should be destroyed')
assert.deepEqual(calls.dataDestroyed, ['vdi-ref'], 'its data should be reclaimed, as before this fix')
})
it('purges the snapshot data when the transfer succeeded', async () => {
const { runner, calls } = makeRunRunner()
await runner.run()
assert.equal(calls.markExportSuccessfull, 2, 'the exported snapshot and its VDIs should be marked')
assert.deepEqual(calls.vmDestroyed, ['VM.destroy:snapshot-ref'], 'the exported snapshot should be purged')
assert.deepEqual(calls.dataDestroyed, ['vdi-ref'], 'its data should be reclaimed')
})
it('does not purge anything when the live VM was exported (offline backup)', async () => {
const { runner, calls } = makeRunRunner({ isSnapshot: false })
await runner.run()
assert.equal(calls.markExportSuccessfull, 0, 'the live VM is not marked as exported')
assert.deepEqual(calls.vmDestroyed, [], 'the live VM must never be destroyed')
})
})

View File

@@ -14,7 +14,7 @@ import { getOldEntries } from '../../_getOldEntries.mjs'
import { MixinRemoteWriter } from './_MixinRemoteWriter.mjs'
import { AbstractIncrementalWriter } from './_AbstractIncrementalWriter.mjs'
import { checkDisk } from './_checkDisk.mjs'
import { checkVhd } from './_checkVhd.mjs'
import { packUuid } from './_packUuid.mjs'
import { openDiskChain } from '@xen-orchestra/backup-archive/disks'
import { VDI_FORMAT_QCOW2 } from '@xen-orchestra/xapi'
@@ -274,10 +274,7 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
}
const transferred = await adapter.writeVhd(path, disk, {
// no checksum for VHDs, because they will be invalidated by
// merges and chains
checksum: false,
validator: tmpPath => checkDisk(handler, tmpPath),
validator: tmpPath => checkVhd(handler, tmpPath),
writeBlockConcurrency: this._config.writeBlockConcurrency,
uuid: packUuid(vdi.uuid),
parentUuid,

View File

@@ -263,7 +263,6 @@ export class IncrementalXapiWriter extends MixinXapiWriter(AbstractIncrementalWr
vdiRef: activeVdi.$ref,
baseRef: snapshot.$ref,
onlyListChangedBlocks: true,
preferNbd: this._settings.preferNbd,
})
await diffDisk.init()
if (diffDisk.getBlockIndexes().length === 0) {

View File

@@ -1,6 +0,0 @@
import { openDisposableDisk } from '@xen-orchestra/backup-archive/disks'
import Disposable from 'promise-toolbox/Disposable'
export async function checkDisk(handler, path) {
await Disposable.use(openDisposableDisk({ handler, path }), () => {})
}

View File

@@ -0,0 +1,6 @@
import { openVhd } from 'vhd-lib'
import Disposable from 'promise-toolbox/Disposable'
export async function checkVhd(handler, path) {
await Disposable.use(openVhd(handler, path), () => {})
}

View File

@@ -8,7 +8,7 @@
"type": "git",
"url": "https://github.com/vatesfr/xen-orchestra.git"
},
"version": "0.74.2",
"version": "0.73.10",
"engines": {
"node": ">=14.18"
},
@@ -27,17 +27,17 @@
"@vates/disposable": "^0.1.6",
"@vates/fuse-vhd": "^2.1.3",
"@vates/generator-toolbox": "^1.1.3",
"@vates/nbd-client": "^3.5.1",
"@vates/nbd-client": "^3.5.0",
"@vates/parse-duration": "^0.1.1",
"@vates/task": "^0.7.0",
"@vates/types": "^2.0.1",
"@xen-orchestra/async-map": "^0.1.4",
"@vates/types": "^1.30.1",
"@xen-orchestra/async-map": "^0.1.3",
"@xen-orchestra/disk-transform": "^1.3.3",
"@xen-orchestra/fs": "^4.9.3",
"@xen-orchestra/log": "^0.7.2",
"@xen-orchestra/qcow2": "^1.3.1",
"@xen-orchestra/template": "^0.1.1",
"@xen-orchestra/backup-archive": "^1.1.2",
"@xen-orchestra/backup-archive": "^1.1.1",
"app-conf": "^3.0.0",
"compare-versions": "^6.0.0",
"d3-time-format": "^4.1.0",
@@ -52,11 +52,11 @@
"parse-pairs": "^2.0.0",
"promise-toolbox": "^0.21.0",
"proper-lockfile": "^4.1.2",
"tar": "^7.5.19",
"tar": "^7.5.3",
"uuid": "^9.0.0",
"value-matcher": "^0.2.0",
"vhd-lib": "^4.16.1",
"xen-api": "^4.9.0",
"xen-api": "^4.8.0",
"yazl": "^2.5.1"
},
"devDependencies": {
@@ -67,7 +67,7 @@
"typescript": "^5.9.3"
},
"peerDependencies": {
"@xen-orchestra/xapi": "^8.10.5"
"@xen-orchestra/xapi": "^8.10.2"
},
"license": "AGPL-3.0-or-later",
"author": {

View File

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

View File

@@ -1,7 +1,7 @@
{
"private": false,
"name": "@xen-orchestra/disk-cli",
"version": "2.2.1",
"version": "2.2.0",
"description": "CLI tool to inspect and manage disks in backup repositories",
"type": "module",
"bin": {
@@ -20,8 +20,8 @@
},
"dependencies": {
"@vates/async-each": "^1.0.3",
"@xen-orchestra/backups": "^0.74.2",
"@xen-orchestra/backup-archive": "^1.1.2",
"@xen-orchestra/backups": "^0.73.10",
"@xen-orchestra/backup-archive": "^1.1.1",
"@xen-orchestra/disk-transform": "^1.3.3",
"@xen-orchestra/fs": "^4.9.3",
"@xen-orchestra/qcow2": "^1.3.1",

View File

@@ -59,7 +59,7 @@ export async function transformCommand(handlerUrl: string, diskPath: string, ext
} else if (format === 'vhd') {
stream = await toVhdStream(disk)
} else {
stream = await toQcow2Stream(disk)
stream = toQcow2Stream(disk)
}
await pipeline(stream, process.stdout, { end: false })

View File

@@ -13,13 +13,6 @@ export function isLegacyEncryptionAlgorithm(algorithm) {
}
function getEncryptor(algorithm = DEFAULT_ENCRYPTION_ALGORITHM, key) {
if (key === undefined && algorithm !== UNENCRYPTED_ALGORITHM) {
const error = new Error(
`This remote is encrypted with ${algorithm} but no encryption key is configured. Data cannot be read.`
)
error.code = 'MISSING_ENCRYPTION_KEY'
throw error
}
if (key === undefined) {
return {
id: 'NULL_ENCRYPTOR',

View File

@@ -16,13 +16,6 @@ import { createChecksumStream, validChecksumOfReadStream } from './checksum'
import { DEFAULT_ENCRYPTION_ALGORITHM, UNENCRYPTED_ALGORITHM, _getEncryptor } from './_encryptor'
const { info, warn } = createLogger('xo:fs:abstract')
export class NotImplementedError extends Error {
constructor(message = 'Not implemented') {
super(message)
this.name = 'NotImplementedError'
this.code = 'ENOTIMP'
}
}
const checksumFile = file => file + '.checksum'
const computeRate = (hrtime, size) => {
@@ -41,8 +34,6 @@ const WITH_LIMIT = [
'copy',
'getInfo',
'getSizeOnDisk',
'getLinkCount',
'link',
'list',
'mkdir',
'openFile',
@@ -61,9 +52,7 @@ const WITH_RETRY = {
_closeFile: {},
_copy: {},
_getInfo: {},
_getLinkCount: {},
_getSize: {},
_link: {},
_list: {},
_mkdir: {},
_openFile: {},
@@ -89,9 +78,7 @@ const WITH_TIMEOUT = [
'_closeFile',
'_createReadStream',
'_getInfo',
'_getLinkCount',
'_getSize',
'_link',
'_list',
'_rename',
'_copy',
@@ -136,10 +123,6 @@ class PrefixWrapper {
return entries
}
async link(existingPath, newPath) {
return this._handler.link(this._resolve(existingPath), this._resolve(newPath))
}
rename(oldPath, newPath) {
return this._handler.rename(this._resolve(oldPath), this._resolve(newPath))
}
@@ -161,10 +144,6 @@ export default class RemoteHandlerAbstract {
return this.#rawEncryptor
}
getConfig(key) {
return this._remote[key]
}
constructor(remote, options = {}) {
if (remote.url === 'test://') {
this._remote = remote
@@ -186,18 +165,7 @@ export default class RemoteHandlerAbstract {
}
_conditionRetry(error) {
return ![
'EEXIST',
'EISDIR',
'ENOTEMPTY',
'ENOENT',
'ENOTDIR',
'ENOTIMP',
'ENOTSUP',
'EPERM',
'SystemInUse',
'ERR_ASSERTION',
].includes(error?.code)
return !['EEXIST', 'EISDIR', 'ENOTEMPTY', 'ENOENT', 'ENOTDIR', 'SystemInUse', 'ERR_ASSERTION'].includes(error?.code)
}
#applySafeGuards(options) {
@@ -255,7 +223,7 @@ export default class RemoteHandlerAbstract {
// - some preprocessing may be applied on parameters that should not be done multiple times (e.g. prefixing paths)
get type() {
throw new NotImplementedError()
throw new Error('Not implemented')
}
addPrefix(prefix) {
@@ -373,31 +341,10 @@ export default class RemoteHandlerAbstract {
return this.getSizeOnDisk(file)
}
async __getLinkCount(file) {
return this._getLinkCount(normalizePath(file))
}
async getSizeOnDisk(file) {
return this._getSize(typeof file === 'string' ? normalizePath(file) : file)
}
async #link(existingPath, newPath, createTree = true) {
try {
await this._link(existingPath, newPath)
} catch (error) {
// ENOENT can be a missing target directory OR a missing source
if (error.code === 'ENOENT' && createTree) {
await this._mktree(dirname(newPath))
return this.#link(existingPath, newPath, false)
}
throw error
}
}
async __link(existingPath, newPath) {
return this.#link(normalizePath(existingPath), normalizePath(newPath))
}
async __list(dir, { filter, ignoreMissing = false, prependDir = false } = {}) {
try {
const virtualDir = normalizePath(dir)
@@ -656,8 +603,14 @@ export default class RemoteHandlerAbstract {
}
}
// Methods that can be implemented by inheriting classes
useVhdDirectory() {
return this._remote.useVhdDirectory ?? false
}
async _closeFile(fd) {
throw new NotImplementedError()
throw new Error('Not implemented')
}
async _createOutputStream(file, { dirMode, ...options } = {}) {
@@ -674,13 +627,13 @@ export default class RemoteHandlerAbstract {
}
async _createReadStream(file, options) {
throw new NotImplementedError()
throw new Error('Not implemented')
}
// createWriteStream takes highWaterMark as option even if it's not documented.
// Source: https://stackoverflow.com/questions/55026306/how-to-set-writeable-highwatermark
async _createWriteStream(file, options) {
throw new NotImplementedError()
throw new Error('Not implemented')
}
// called to finalize the remote
@@ -694,24 +647,16 @@ export default class RemoteHandlerAbstract {
return () => Promise.resolve()
}
async _getLinkCount(path) {
throw new NotImplementedError()
}
async _getSize(file) {
throw new NotImplementedError()
}
async _link(existingPath, newPath) {
throw new NotImplementedError()
throw new Error('Not implemented')
}
async _list(dir) {
throw new NotImplementedError()
throw new Error('Not implemented')
}
async _mkdir(dir) {
throw new NotImplementedError()
throw new Error('Not implemented')
}
async _mktree(dir, { mode } = {}) {
@@ -728,7 +673,7 @@ export default class RemoteHandlerAbstract {
}
async _openFile(path, flags) {
throw new NotImplementedError()
throw new Error('Not implemented')
}
async _outputFile(file, data, { dirMode, flags }) {
@@ -766,7 +711,7 @@ export default class RemoteHandlerAbstract {
}
_read(file, buffer, position) {
throw new NotImplementedError()
throw new Error('Not implemented')
}
_readFile(file, options) {
@@ -774,14 +719,14 @@ export default class RemoteHandlerAbstract {
}
async _rename(oldPath, newPath) {
throw new NotImplementedError()
throw new Error('Not implemented')
}
async _copy(oldPath, newPath) {
throw new NotImplementedError()
throw new Error('Not implemented')
}
async _rmdir(dir) {
throw new NotImplementedError()
throw new Error('Not implemented')
}
async _rmtree(dir) {
@@ -821,7 +766,7 @@ export default class RemoteHandlerAbstract {
async _sync() {}
async _unlink(file) {
throw new NotImplementedError()
throw new Error('Not implemented')
}
async _write(file, buffer, position) {
@@ -839,11 +784,11 @@ export default class RemoteHandlerAbstract {
}
async _writeFd(fd, buffer, position) {
throw new NotImplementedError()
throw new Error('Not implemented')
}
async _writeFile(file, data, options) {
throw new NotImplementedError()
throw new Error('Not implemented')
}
get isEncrypted() {

View File

@@ -6,16 +6,16 @@ import { DEFAULT_ENCRYPTION_ALGORITHM, _getEncryptor } from './_encryptor'
import { Disposable, pFromCallback, TimeoutError } from 'promise-toolbox'
import { getSyncedHandler } from '.'
import { rimraf } from 'rimraf'
import AbstractHandler, { NotImplementedError } from './abstract'
import AbstractHandler from './abstract'
import fs from 'fs-extra'
import tmp from 'tmp'
const TIMEOUT = 12e5
class TestHandler extends AbstractHandler {
constructor(remoteOverrides = {}) {
constructor() {
const options = { timeout: TIMEOUT, withRetry: [] }
super({ url: 'test://', ...remoteOverrides }, options)
super({ url: 'test://' }, options)
Object.defineProperty(this, 'isEncrypted', {
get: () => false, // encryption is tested separately
})
@@ -58,35 +58,6 @@ describe('closeFile()', () => {
})
})
describe('NotImplementedError', () => {
it('is thrown by an operation the handler does not implement', async () => {
const testHandler = new TestHandler()
await assert.rejects(testHandler.link('a', 'b'), error => {
assert.ok(error instanceof NotImplementedError)
assert.equal(error.code, 'ENOTIMP')
return true
})
})
it('is never retried', () => {
const testHandler = new TestHandler()
assert.equal(testHandler._conditionRetry(new NotImplementedError()), false)
assert.equal(testHandler._conditionRetry(new Error('transient')), true, 'an error without code still is')
})
})
describe('getConfig()', () => {
it('is undefined when not set on the remote', () => {
assert.equal(new TestHandler().getConfig('compressionType'), undefined)
})
it('reads the remote-level compressionType override', () => {
assert.equal(new TestHandler({ compressionType: 'brotli' }).getConfig('compressionType'), 'brotli')
})
})
describe('getInfo()', () => {
it('throws in case of timeout', async () => {
const testHandler = new TestHandler()
@@ -254,17 +225,4 @@ describe('encryption', () => {
Disposable.use(getSyncedHandler({ url: `file://${dir}?encryptionKey="73c1838d7d8a6088ca2317fb5f29cd91"` }), noop)
)
})
it('sync should fail with a clear error when the key is removed from a non empty remote', async () => {
const encryptor = _getEncryptor(DEFAULT_ENCRYPTION_ALGORITHM, '73c1838d7d8a6088ca2317fb5f29cd91')
await fs.writeFile(`${dir}/encryption.json`, `{"algorithm": "${DEFAULT_ENCRYPTION_ALGORITHM}"}`)
await fs.writeFile(`${dir}/metadata.json`, encryptor.encryptData(`{"random": "NOTSORANDOM"}`))
await fs.writeFile(`${dir}/nonempty.json`, 'content')
// no encryptionKey in the url => must not fall back to NULL_ENCRYPTOR
await assert.rejects(Disposable.use(getSyncedHandler({ url: `file://${dir}` }), noop), {
code: 'MISSING_ENCRYPTION_KEY',
})
})
})

View File

@@ -19,12 +19,6 @@ export default class AzureHandler extends RemoteHandlerAbstract {
#blobServiceClient
#containerClient
getConfig(key) {
if (key === 'useVhdDirectory') {
return true // compatibility layer
}
return super.getConfig(key)
}
constructor(remote, _opts) {
super(remote, _opts)
const { username, path, password, host, protocol } = parse(remote.url)
@@ -319,4 +313,8 @@ export default class AzureHandler extends RemoteHandlerAbstract {
await blobBatchClient.submitBatch(batch)
}
}
useVhdDirectory() {
return true
}
}

View File

@@ -7,7 +7,6 @@ import RemoteHandlerS3 from './s3'
import RemoteHandlerSmb from './smb'
import RemoteHandlerAzure from './azure'
export { DEFAULT_ENCRYPTION_ALGORITHM, UNENCRYPTED_ALGORITHM, isLegacyEncryptionAlgorithm } from './_encryptor'
export { NotImplementedError } from './abstract'
const HANDLERS = {
file: RemoteHandlerLocal,
@@ -39,4 +38,5 @@ export const getSyncedHandler = async (...opts) => {
}
}
export { default as RemoteHandlerAbstract } from './abstract.js'
export { default as RemoteHandlerAbstract } from './abstract.js'

View File

@@ -129,20 +129,11 @@ export default class LocalHandler extends RemoteHandlerAbstract {
return info
}
async _getLinkCount(path) {
const stats = await this.#addSyncStackTrace(fs.stat, this.getFilePath(path))
return stats.nlink
}
async _getSize(file) {
const stats = await this.#addSyncStackTrace(fs.stat, this.getFilePath(typeof file === 'string' ? file : file.path))
return stats.size
}
async _link(existingPath, newPath) {
return this.#addSyncStackTrace(fs.link, this.getFilePath(existingPath), this.getFilePath(newPath))
}
async _list(dir) {
return this.#addSyncStackTrace(fs.readdir, this.getFilePath(dir))
}

View File

@@ -11,16 +11,6 @@ export { basename, dirname, join }
// - no duplicate slashes
export const normalize = path => resolve('/', path)
// true if `path` is `dir` itself, or is contained in `dir`
export function isInDir(path, dir) {
const normalizedDir = normalize(dir)
const normalizedPath = normalize(path)
return (
normalizedPath === normalizedDir || normalizedPath.startsWith(normalizedDir === '/' ? '/' : normalizedDir + '/')
)
}
export function split(path) {
const parts = normalize(path).split(sep)

View File

@@ -1,7 +1,7 @@
import { describe, it } from 'node:test'
import { strict as assert } from 'assert'
import { isInDir, relativeFromFile } from './path.js'
import { relativeFromFile } from './path.js'
describe('relativeFromFile()', function () {
for (const [title, args] of Object.entries({
@@ -15,25 +15,3 @@ describe('relativeFromFile()', function () {
})
}
})
describe('isInDir()', function () {
for (const [title, [args, expected]] of Object.entries({
'the dir itself': [['/foo/bar', '/foo/bar'], true],
'a direct child': [['/foo/bar/baz.vhd', '/foo/bar'], true],
'a deep child': [['/foo/bar/baz/qux.vhd', '/foo/bar'], true],
'a sibling with a longer name': [['/foo/bar-baz/qux.vhd', '/foo/bar'], false],
'a sibling': [['/foo/baz/qux.vhd', '/foo/bar'], false],
'the parent dir': [['/foo', '/foo/bar'], false],
'a relative path': [['foo/bar/baz.vhd', '/foo/bar'], true],
'a relative dir': [['/foo/bar/baz.vhd', 'foo/bar'], true],
'a trailing slash on the dir': [['/foo/bar/baz.vhd', '/foo/bar/'], true],
'duplicate slashes': [['//foo///bar//baz.vhd', '/foo/bar'], true],
'a dot segment': [['/foo/bar/./baz.vhd', '/foo/bar'], true],
'an escaping dot dot segment': [['/foo/bar/../baz.vhd', '/foo/bar'], false],
'the root dir': [['/foo/bar.vhd', '/'], true],
})) {
it('works with ' + title, function () {
assert.equal(isInDir(...args), expected)
})
}
})

View File

@@ -47,13 +47,6 @@ export default class S3Handler extends RemoteHandlerAbstract {
#maxPartNumber
#minPartSize
getConfig(key) {
if (key === 'useVhdDirectory') {
return true // compatibility layer
}
return super.getConfig(key)
}
constructor(remote, _opts) {
super(remote, _opts)
const {
@@ -502,4 +495,8 @@ export default class S3Handler extends RemoteHandlerAbstract {
}
}
}
useVhdDirectory() {
return true
}
}

View File

@@ -2,17 +2,11 @@ import type { Readable, Writable } from 'stream'
// ─── Supporting types ────────────────────────────────────────────────────────
/** thrown when a handler does not support an operation, never retried */
export declare class NotImplementedError extends Error {
code: 'ENOTIMP'
}
export interface RemoteInfo {
url: string
encryptionKey?: string
immutable?: boolean
useVhdDirectory?: boolean
compressionType?: string
[key: string]: unknown
}
@@ -126,7 +120,6 @@ export abstract class RemoteHandlerAbstract {
abstract get encryptionAlgorithm(): string
abstract sync(): Promise<void>
abstract forget(): Promise<void>
abstract link(existingPath: string, newPath: string): Promise<void>
abstract list(dir: string, options?: ListOptions): Promise<string[]>
abstract mkdir(dir: string, options?: MkdirOptions): Promise<void>
abstract mktree(dir: string, options?: MkdirOptions): Promise<void>
@@ -137,7 +130,7 @@ export abstract class RemoteHandlerAbstract {
options?: ReadStreamOptions
): Promise<Readable & { length?: number; maxStreamLength?: number }>
abstract readFile(file: string, options?: ReadFileOptions): Promise<Buffer>
abstract readFile(file: string, options?: ReadFileOptions): Promise<string>
abstract read(file: FileDescriptor, buffer: Buffer, position?: number): Promise<ReadResult>
@@ -162,14 +155,12 @@ export abstract class RemoteHandlerAbstract {
abstract closeFile(fd: FileDescriptor): Promise<void>
abstract getInfo(): Promise<RemoteInfoResult>
abstract getLinkCount(path: string): Promise<number>
abstract getSize(file: FileDescriptor): Promise<number>
abstract getSizeOnDisk(file: FileDescriptor): Promise<number>
abstract lock(path: string): Promise<LockDisposer>
abstract test(): Promise<TestResult>
abstract isImmutable(): boolean
abstract getConfig(key: 'useVhdDirectory'): boolean | undefined
abstract getConfig(key: 'compressionType'): string | undefined
abstract getConfig(key: string): unknown
abstract useVhdDirectory(): boolean
abstract addPrefix(prefix: string): RemoteHandlerAbstract
}

View File

@@ -1,7 +1,6 @@
export { basename, dirname, join } from 'path'
export declare const normalize: (path: string) => string
export declare function isInDir(path: string, dir: string): boolean
export declare function split(path: string): string[]
export declare const relativeFromFile: (file: string, path: string) => string
export declare const resolveFromFile: (file: string, path: string) => string

View File

@@ -16,13 +16,13 @@
"xo-immutable-remote": "./dist/protectRemotes.mjs"
},
"license": "AGPL-3.0-or-later",
"version": "3.0.5",
"version": "3.0.4",
"engines": {
"node": ">=20.0.0"
},
"dependencies": {
"@vates/async-each": "^1.0.3",
"@xen-orchestra/backups": "^0.74.2",
"@xen-orchestra/backups": "^0.73.10",
"@xen-orchestra/log": "^0.7.2",
"app-conf": "^3.0.0",
"execa": "^5.0.0",

View File

@@ -1,20 +1,5 @@
# ChangeLog
## **next**
- [Host] Add possibility to reboot a host (PR [#10250](https://github.com/vatesfr/xen-orchestra/pull/10250))
- [Web-Core/TabItem] Update the component to remove uppercase for better readability (PR [#10338](https://github.com/vatesfr/xen-orchestra/pull/10338))
## **0.25.0** (2026-08-31)
- [Treeview] Add VM tree actions (PR [#10304](https://github.com/vatesfr/xen-orchestra/pull/10304))
- [Pool/networks] Add the possibility to create new network or bonded network (PR [#10145](https://github.com/vatesfr/xen-orchestra/pull/10145))
- [VM] Add VDIs page with table and side panel (PR [#10269](https://github.com/vatesfr/xen-orchestra/pull/10269))
- [Host/Network] Add ability to rescan physical network interfaces (PIFs) (PR [#10147](https://github.com/vatesfr/xen-orchestra/pull/10147))
- Fix inconsistent spacing in side panel cards (PR [#10279](https://github.com/vatesfr/xen-orchestra/pull/10279))
- Fix missing collapse buttons on pools and hosts in the tree sidebar (added `hasChildren` prop) (PR [#10244](https://github.com/vatesfr/xen-orchestra/pull/10244))
- [Pool/networks] Add the possibility to create new internal network (PR [#10235](https://github.com/vatesfr/xen-orchestra/pull/10235))
## **0.24.0** (2026-07-30)
- [Host/dashboard] Switch CPU and RAM panels order to match Pool dashboard layout (PR [#10059](https://github.com/vatesfr/xen-orchestra/pull/10059))

View File

@@ -1,6 +1,6 @@
{
"name": "@xen-orchestra/lite",
"version": "0.25.0",
"version": "0.24.0",
"type": "module",
"scripts": {
"dev": "GIT_HEAD=$(git rev-parse HEAD) vite",
@@ -23,21 +23,18 @@
"@fortawesome/vue-fontawesome": "^3.0.8",
"@intlify/unplugin-vue-i18n": "^6.0.3",
"@novnc/novnc": "~1.5.0",
"@regle/core": "^1.26.0",
"@regle/rules": "^1.26.0",
"@regle/schemas": "^1.20.2",
"@tsconfig/node18": "^18.2.4",
"@types/d3-time-format": "^4.0.3",
"@types/file-saver": "^2.0.7",
"@types/lodash-es": "^4.17.12",
"@types/node": "^18.19.80",
"@vates/types": "^2.0.1",
"@vates/types": "^1.30.1",
"@vitejs/plugin-vue": "^6.0.0",
"@vue/tsconfig": "^0.9.0",
"@vueuse/core": "^14.0.0",
"@vueuse/math": "^14.0.0",
"@vueuse/shared": "^14.0.0",
"@xen-orchestra/web-core": "^0.60.0",
"@xen-orchestra/web-core": "^0.58.0",
"complex-matcher": "^1.1.1",
"d3-time-format": "^4.1.0",
"decorator-synchronized": "^0.6.0",

View File

@@ -19,13 +19,13 @@
import AppHeader from '@/components/AppHeader.vue'
import AppLogin from '@/components/AppLogin.vue'
import AppNavigation from '@/components/AppNavigation.vue'
import { useUnreachableHosts } from '@/composables/unreachable-hosts.composable.ts'
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
import { useXenApiStore } from '@/stores/xen-api.store.ts'
import { useUnreachableHosts } from '@/composables/unreachable-hosts.composable'
import { usePoolStore } from '@/stores/xen-api/pool.store'
import { useXenApiStore } from '@/stores/xen-api.store'
import VtsOverlayList from '@core/components/overlay/VtsOverlayList.vue'
import VtsTooltipList from '@core/components/tooltip-list/VtsTooltipList.vue'
import { useChartTheme } from '@core/composables/chart-theme.composable.ts'
import { useUiStore } from '@core/stores/ui.store.ts'
import { useChartTheme } from '@core/composables/chart-theme.composable'
import { useUiStore } from '@core/stores/ui.store'
import { useActiveElement, useMagicKeys, whenever } from '@vueuse/core'
import { logicAnd } from '@vueuse/math'
import { computed } from 'vue'

View File

@@ -26,11 +26,11 @@
import AccountMenu from '@/components/account-menu/AccountMenu.vue'
import PoolOverrideWarning from '@/components/PoolOverrideWarning.vue'
import XoaButton from '@/components/XoaButton.vue'
import { useNavigationStore } from '@/stores/navigation.store.ts'
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.ts'
import { useUiStore } from '@core/stores/ui.store'
import { storeToRefs } from 'pinia'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'

View File

@@ -42,9 +42,9 @@
import FormInput from '@/components/form/FormInput.vue'
import LoginError from '@/components/LoginError.vue'
import PoolOverrideWarning from '@/components/PoolOverrideWarning.vue'
import type { XenApiError } from '@/libs/xen-api/xen-api.types.ts'
import { usePageTitleStore } from '@/stores/page-title.store.ts'
import { useXenApiStore } from '@/stores/xen-api.store.ts'
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'

View File

@@ -5,7 +5,7 @@
</template>
<script lang="ts" setup>
import markdown from '@/libs/markdown.ts'
import markdown from '@/libs/markdown'
import { useEventListener } from '@vueuse/core'
import { computed, type Ref, ref } from 'vue'

View File

@@ -10,7 +10,7 @@
<script lang="ts" setup>
import StoryMenu from '@/components/component-story/StoryMenu.vue'
import InfraPoolList from '@/components/infra/InfraPoolList.vue'
import { useNavigationStore } from '@/stores/navigation.store.ts'
import { useNavigationStore } from '@/stores/navigation.store'
import { onClickOutside, tryOnMounted, useTimeoutFn, watchImmediate } from '@vueuse/core'
import { storeToRefs } from 'pinia'
import { ref, watch } from 'vue'

View File

@@ -5,7 +5,7 @@
</template>
<script lang="ts" setup>
import { type AcceptedLanguage, highlight } from '@/libs/highlight.ts'
import { type AcceptedLanguage, highlight } from '@/libs/highlight'
import { computed } from 'vue'
const props = withDefaults(

View File

@@ -19,7 +19,7 @@
import UiActionButton from '@/components/ui/UiActionButton.vue'
import UiFilter from '@/components/ui/UiFilter.vue'
import UiFilterGroup from '@/components/ui/UiFilterGroup.vue'
import type { Filters } from '@/types/filter.ts'
import type { Filters } from '@/types/filter'
import { useOverlay } from '@core/packages/overlay/use-overlay.ts'
import { useI18n } from 'vue-i18n'

View File

@@ -19,8 +19,8 @@
<script lang="ts" setup>
import UiActionButton from '@/components/ui/UiActionButton.vue'
import { buildComplexMatcherNode } from '@/libs/complex-matcher.utils.ts'
import type { Filter, FilterComparisons, FilterComparisonType, Filters, FilterType, NewFilter } from '@/types/filter.ts'
import { buildComplexMatcherNode } from '@/libs/complex-matcher.utils'
import type { Filter, FilterComparisons, FilterComparisonType, Filters, FilterType, NewFilter } from '@/types/filter'
import VtsSelect from '@core/components/select/VtsSelect.vue'
import UiInput from '@core/components/ui/input/UiInput.vue'
import { useFormSelect } from '@core/packages/form-select'

View File

@@ -22,7 +22,7 @@
import UiActionButton from '@/components/ui/UiActionButton.vue'
import UiFilter from '@/components/ui/UiFilter.vue'
import UiFilterGroup from '@/components/ui/UiFilterGroup.vue'
import type { ActiveSorts, Sorts } from '@/types/sort.ts'
import type { ActiveSorts, Sorts } from '@/types/sort'
import VtsIcon from '@core/components/icon/VtsIcon.vue'
import { useOverlay } from '@core/packages/overlay/use-overlay.ts'
import { useI18n } from 'vue-i18n'

View File

@@ -14,12 +14,12 @@
</template>
<script lang="ts" setup>
import type { XenApiPatchWithHostRefs } from '@/composables/host-patches.composable.ts'
import type { XenApiPatchWithHostRefs } from '@/composables/host-patches.composable'
import VtsRow from '@core/components/table/VtsRow.vue'
import VtsTable from '@core/components/table/VtsTable.vue'
import { useTableState } from '@core/composables/table-state.composable.ts'
import { useUiStore } from '@core/stores/ui.store.ts'
import { usePatchColumns } from '@core/tables/column-sets/patch-columns.ts'
import { useTableState } from '@core/composables/table-state.composable'
import { useUiStore } from '@core/stores/ui.store'
import { usePatchColumns } from '@core/tables/column-sets/patch-columns'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'

View File

@@ -11,7 +11,7 @@
</template>
<script lang="ts" setup>
import type { XenApiError } from '@/libs/xen-api/xen-api.types.ts'
import type { XenApiError } from '@/libs/xen-api/xen-api.types'
import VtsIcon from '@core/components/icon/VtsIcon.vue'
import { useI18n } from 'vue-i18n'

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