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
1654 changed files with 17107 additions and 47441 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,13 +0,0 @@
'use strict'
module.exports = {
overrides: [
{
// .mjs files importing compiled .mts sources (`./x.mjs` only exists in `dist/`)
files: ['src/**/*.mjs'],
rules: {
'n/no-missing-import': 'off',
},
},
],
}

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,16 +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",
"@vates/read-chunk": "^1.2.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

@@ -2,16 +2,14 @@
/**
* @typedef {import('@xen-orchestra/disk-transform').DiskBlock} DiskBlock
* @typedef {import('@xen-orchestra/fs').DiskFormat} DiskFormat
*/
import { RandomAccessDisk } from '@xen-orchestra/disk-transform'
export class RemoteDisk extends RandomAccessDisk {
/**
* Abstract
* @param {Object} [options]
* @param {boolean} [options.force]
* @param {boolean} [options.ignoreBlockIndexes] skip reading the block index when the format allows it
* @param {Object} options
* @param {boolean} options.force
* @returns {Promise<void>}
*/
async init(options = { force: false }) {
@@ -231,22 +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
* @param {{ diskFormat: DiskFormat }} options format of the disks written to the remote
* @returns {Promise<boolean>}
*/
async isMergeableParent(parentUuid, { diskFormat }) {
return this.getUuid() === parentUuid
}
/**
* Abstract
* Rename alias/disk

View File

@@ -1,275 +0,0 @@
// @ts-check
/**
* @typedef {import('@xen-orchestra/disk-transform').DiskBlock} DiskBlock
*/
import { RemoteDisk } from './RemoteDisk.mjs'
/**
* A chain of disks of the same format, oldest first, read as a single disk.
*
* Format agnostic: the format specific parts (size on disk, concurrent merge,
* block location) are implemented by the subclasses.
*/
export class RemoteDiskChain extends RemoteDisk {
/**
* @type {RemoteDisk[]}
*/
#disks
/**
* @param {Object} params
* @param {RemoteDisk[]} params.disks
*/
constructor({ disks }) {
super()
this.#disks = disks
}
/**
* The disks of the chain, oldest first
* @returns {RemoteDisk[]}
*/
get disks() {
return this.#disks
}
/**
* Initializes the VHD chain
* @param {Object} options
* @param {boolean} options.force
* @returns {Promise<void>}
*/
async init(options) {
try {
await Promise.all(this.#disks.map(disk => disk.init(options)))
let parentUuid = ''
for (const [index, disk] of this.#disks.entries()) {
if (index !== 0) {
if (!disk.isDifferencing()) {
throw Object.assign(new Error("Can't init vhd directory with non differencing child disks"), {
code: 'NOT_SUPPORTED',
})
}
if (disk.getParentUuid() !== parentUuid) {
throw Object.assign(new Error("Can't init vhd directory with incorrect parentage"), {
code: 'NOT_SUPPORTED',
})
}
}
parentUuid = disk.getUuid()
}
} catch (error) {
await this.close()
throw error
}
}
/**
* Closes the VHD.
* @returns {Promise<void>}
*/
async close() {
await Promise.all(this.#disks.map(disk => disk.close()))
}
/**
* @returns {number}
*/
getVirtualSize() {
return this.#disks[this.#disks.length - 1].getVirtualSize()
}
/**
* @returns {number}
*/
getBlockSize() {
return this.#disks[this.#disks.length - 1].getBlockSize()
}
/**
* @returns {string}
*/
getPath() {
return this.#disks[this.#disks.length - 1].getPath()
}
/**
* Disk chains return an array of disk paths.
*
* @returns {string[]}
*/
getPaths() {
return this.#disks.map(disk => disk.getPath())
}
/**
* @returns {string}
*/
getUuid() {
return this.#disks[this.#disks.length - 1].getUuid()
}
/**
* @returns {number} getMaxBlockCount
*/
getMaxBlockCount() {
return this.#disks[this.#disks.length - 1].getMaxBlockCount()
}
/**
* Checks if the VHD contains a specific block.
* @param {number} index
* @returns {boolean}
*/
hasBlock(index) {
for (const disk of this.#disks) {
if (disk.hasBlock(index)) {
return true
}
}
return false
}
/**
* Gets the indexes of all blocks in the VHD.
* @returns {Array<number>}
*/
getBlockIndexes() {
const indexes = new Set()
for (const disk of this.#disks) {
for (const index of disk.getBlockIndexes()) {
indexes.add(index)
}
}
return [...indexes]
}
/**
* Returns the parent non inizialized instance
* @returns {RemoteDisk}
*/
instantiateParent() {
return this.#disks[0].instantiateParent()
}
/**
* Writes a full block into this VHD.
* @param {DiskBlock} diskBlock
* @return {Promise<number>} blockSize
*/
async writeBlock(diskBlock) {
throw new Error(`Can't write blocks into a disk chain`)
}
/**
* Reads a specific block from the VHD.
* @param {number} index
* @returns {Promise<DiskBlock>} diskBlock
*/
async readBlock(index) {
const disk = this.newestDiskWith(index)
if (disk === undefined) {
throw new Error(`Block ${index} not found in chain `)
}
return disk.readBlock(index)
}
/**
* Reads a specific block from the child disk to copy/move it to this disk.
* @param {RemoteDisk} childDisk
* @param {number} index
* @param {boolean} isResumingMerge
* @returns {Promise<number>} blockSize
*/
async mergeBlock(childDisk, index, isResumingMerge) {
throw new Error(`Can't merge block into a disk chain`)
}
/**
* @returns {object}
*/
getMetadata() {
return this.#disks[this.#disks.length - 1].getMetadata()
}
/**
* @param {RemoteDisk} childDisk
* @returns {Promise<void>}
*/
async flushMetadata(childDisk) {
throw new Error(`Can't flush metadata on a disk chain`)
}
/**
* @param {RemoteDisk} childDisk
* @returns {Promise<void>}
*/
mergeMetadata(childDisk) {
throw new Error(`Can't merge metadata on a disk chain`)
}
/**
* Checks if the VHD is a differencing disk.
* @returns {boolean}
*/
isDifferencing() {
return this.#disks[0].isDifferencing()
}
/**
* Abstract
* Rename alias/disk
* @param {string} newPath
*/
async rename(newPath) {
throw new Error(`Can't rename a disk chain`)
}
/**
* Deletes all the disks
* @param {Object} options
*/
async unlink({ force = false } = {}) {
for (const disk of this.#disks) {
await disk.unlink({ force })
}
}
/**
* Checks the integrity of the disk's external reference (e.g. alias target).
* @param {Object} [opts]
* @param {boolean} [opts.remove]
* @param {Function} [opts.logWarn]
* @param {Function} [opts.logInfo]
* @returns {Promise<string | undefined>}
*/
async clean(opts = {}) {
throw new Error(`Can't clean a disk chain`)
}
/**
*
* @returns {RemoteDisk|undefined}
*/
getRootDisk() {
return this.#disks[0]
}
/**
* The disk holding the current content of a block: the newest one having it
* @param {number} index
* @returns {RemoteDisk|undefined}
*/
newestDiskWith(index) {
for (let i = this.#disks.length - 1; i >= 0; i--) {
if (this.#disks[i].hasBlock(index)) {
return this.#disks[i]
}
}
return undefined
}
}

View File

@@ -6,7 +6,6 @@
* @typedef {import('vhd-lib/_createFooterHeader.js').VhdFooter} VhdFooter
* @typedef {import('@xen-orchestra/disk-transform').DiskBlock} DiskBlock
* @typedef {import('@xen-orchestra/fs').RemoteHandlerAbstract} RemoteHandlerAbstract
* @typedef {import('@xen-orchestra/fs').DiskFormat} DiskFormat
*
*/
@@ -18,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 {
/**
@@ -82,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()
}
@@ -435,37 +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
* @param {{ diskFormat: DiskFormat }} options format of the disks written to the remote
* @returns {Promise<boolean>}
*/
async isMergeableParent(parentUuid, { diskFormat }) {
if (!(await super.isMergeableParent(parentUuid, { diskFormat }))) {
return false
}
const compressionType = this.#handler.getConfig('compressionType') ?? 'brotli'
const isDirectory = await this.isDirectory()
return isDirectory
? diskFormat === 'vhdDirectory' && this.#getCompressionType() === compressionType
: diskFormat === 'vhd'
}
/**
* Rename alias/disk
* @param {string} newPath
@@ -573,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

@@ -3,11 +3,17 @@
/**
* @typedef {import('./RemoteVhdDisk.mjs').VhdFooter} VhdFooter
* @typedef {import('./RemoteVhdDisk.mjs').RemoteVhdDisk} RemoteVhdDisk
* @typedef {import('@xen-orchestra/disk-transform').DiskBlock} DiskBlock
*/
import { RemoteDiskChain } from './RemoteDiskChain.mjs'
import { RemoteDisk } from './RemoteDisk.mjs'
export class RemoteVhdDiskChain extends RemoteDisk {
/**
* @type {RemoteVhdDisk[]}
*/
#disks
export class RemoteVhdDiskChain extends RemoteDiskChain {
/**
* @type {number}
*/
@@ -33,15 +39,55 @@ export class RemoteVhdDiskChain extends RemoteDiskChain {
* @param {RemoteVhdDisk[]} params.disks
*/
constructor({ disks }) {
super({ disks })
super()
this.#disks = disks
}
/**
* The VHD disks of the chain, oldest first
* @returns {RemoteVhdDisk[]}
* Initializes the VHD chain
* @param {Object} options
* @param {boolean} options.force
* @returns {Promise<void>}
*/
get disks() {
return /** @type {RemoteVhdDisk[]} */ (super.disks)
async init(options) {
try {
await Promise.all(this.#disks.map(disk => disk.init(options)))
let parentUuid = ''
for (const [index, disk] of this.#disks.entries()) {
if (index !== 0) {
if (!disk.isDifferencing()) {
throw Object.assign(new Error("Can't init vhd directory with non differencing child disks"), {
code: 'NOT_SUPPORTED',
})
}
if (disk.getParentUuid() !== parentUuid) {
throw Object.assign(new Error("Can't init vhd directory with incorrect parentage"), {
code: 'NOT_SUPPORTED',
})
}
}
parentUuid = disk.getUuid()
}
} catch (error) {
await this.close()
throw error
}
}
/**
* Closes the VHD.
* @returns {Promise<void>}
*/
async close() {
await Promise.all(this.#disks.map(disk => disk.close()))
}
/**
* @returns {number}
*/
getVirtualSize() {
return this.#disks[this.#disks.length - 1].getVirtualSize()
}
/**
@@ -61,6 +107,36 @@ export class RemoteVhdDiskChain extends RemoteDiskChain {
)
}
/**
* @returns {number}
*/
getBlockSize() {
return this.#disks[this.#disks.length - 1].getBlockSize()
}
/**
* @returns {string}
*/
getPath() {
return this.#disks[this.#disks.length - 1].getPath()
}
/**
* Disk chains return an array of disk paths.
*
* @returns {string[]}
*/
getPaths() {
return this.#disks.map(disk => disk.getPath())
}
/**
* @returns {string}
*/
getUuid() {
return this.#disks[this.#disks.length - 1].getUuid()
}
/**
* @returns {Promise<boolean>} canMergeConcurently
*/
@@ -68,24 +144,148 @@ export class RemoteVhdDiskChain extends RemoteDiskChain {
return this.isDirectory()
}
/**
* @returns {number} getMaxBlockCount
*/
getMaxBlockCount() {
return this.#disks[this.#disks.length - 1].getMaxBlockCount()
}
/**
* Checks if the VHD contains a specific block.
* @param {number} index
* @returns {boolean}
*/
hasBlock(index) {
for (const disk of this.#disks) {
if (disk.hasBlock(index)) {
return true
}
}
return false
}
/**
* Gets the indexes of all blocks in the VHD.
* @returns {Array<number>}
*/
getBlockIndexes() {
const indexes = new Set()
for (const disk of this.#disks) {
for (const index of disk.getBlockIndexes()) {
indexes.add(index)
}
}
return [...indexes]
}
/**
* Returns the parent non inizialized instance
* @returns {RemoteDisk}
*/
instantiateParent() {
return this.#disks[0].instantiateParent()
}
/**
* Writes a full block into this VHD.
* @param {DiskBlock} diskBlock
* @return {Promise<number>} blockSize
*/
async writeBlock(diskBlock) {
throw new Error(`Can't write blocks into a disk chain`)
}
/**
* Reads a specific block from the VHD.
* @param {number} index
* @returns {Promise<DiskBlock>} diskBlock
*/
async readBlock(index) {
const reversedDisks = this.#disks.slice().reverse()
for (const disk of reversedDisks) {
if (disk.hasBlock(index)) {
return disk.readBlock(index)
}
}
throw new Error(`Block ${index} not found in chain `)
}
/**
* Reads a specific block from the child disk to copy/move it to this disk.
* @param {RemoteDisk} childDisk
* @param {number} index
* @param {boolean} isResumingMerge
* @returns {Promise<number>} blockSize
*/
async mergeBlock(childDisk, index, isResumingMerge) {
throw new Error(`Can't merge block into a disk chain`)
}
/**
* Gets a specific block path from the VHD directory disk.
* @param {number} index
* @returns {string} blockPath
*/
getBlockPath(index) {
const disk = /** @type {RemoteVhdDisk | undefined} */ (this.newestDiskWith(index))
if (disk === undefined) {
throw new Error(`Block ${index} not found in chain`)
for (const disk of [...this.#disks].reverse()) {
if (disk.hasBlock(index)) {
return disk.getBlockPath(index)
}
}
return disk.getBlockPath(index)
throw new Error(`Block ${index} not found in chain`)
}
/**
* @returns {VhdFooter}
*/
getMetadata() {
return /** @type {VhdFooter} */ (super.getMetadata())
return this.#disks[this.#disks.length - 1].getMetadata()
}
/**
* @param {RemoteDisk} childDisk
* @returns {Promise<void>}
*/
async flushMetadata(childDisk) {
throw new Error(`Can't flush metadata on a disk chain`)
}
/**
* @param {RemoteDisk} childDisk
* @returns {Promise<void>}
*/
mergeMetadata(childDisk) {
throw new Error(`Can't merge metadata on a disk chain`)
}
/**
* Checks if the VHD is a differencing disk.
* @returns {boolean}
*/
isDifferencing() {
return this.#disks[0].isDifferencing()
}
/**
* Abstract
* Rename alias/disk
* @param {string} newPath
*/
async rename(newPath) {
throw new Error(`Can't rename a disk chain`)
}
/**
* Deletes all the disks
* @param {Object} options
*/
async unlink({ force = false } = {}) {
for (const disk of this.#disks) {
await disk.unlink({ force })
}
}
/**
@@ -93,7 +293,7 @@ export class RemoteVhdDiskChain extends RemoteDiskChain {
* @returns {Promise<boolean>}
*/
async isDirectory() {
for (const disk of this.disks) {
for (const disk of this.#disks) {
if (!(await disk.isDirectory())) {
return false
}
@@ -101,11 +301,23 @@ export class RemoteVhdDiskChain extends RemoteDiskChain {
return true
}
/**
* Checks the integrity of the disk's external reference (e.g. alias target).
* @param {Object} [opts]
* @param {boolean} [opts.remove]
* @param {Function} [opts.logWarn]
* @param {Function} [opts.logInfo]
* @returns {Promise<string | undefined>}
*/
async clean(opts = {}) {
throw new Error(`Can't clean a disk chain`)
}
/**
*
* @returns {RemoteVhdDisk|undefined}
*/
getRootDisk() {
return /** @type {RemoteVhdDisk|undefined} */ (super.getRootDisk())
return this.#disks[0]
}
}

View File

@@ -1,119 +0,0 @@
import { createLogger } from '@xen-orchestra/log'
import { asBlockHash, BlockHash, HASH_SIZE } from './hbdPaths.mjs'
import { readChunkStrict } from '@vates/read-chunk'
import { Readable } from 'node:stream'
const { warn } = createLogger('xo:backup-archive:bat')
const ZERO_ENTRY = Buffer.alloc(HASH_SIZE)
// a whole number of entries per read: no entry is ever split across two chunks
const CHUNK_ENTRIES = 2048 // 64 KiB
export class BlockAllocationTable {
#bat: Buffer
#maxBlockCount: number
static allocate(maxBlockCount: number): BlockAllocationTable {
return new BlockAllocationTable(Buffer.alloc(maxBlockCount * HASH_SIZE), maxBlockCount)
}
resize(maxBlockCount: number): void {
const batLength = maxBlockCount * HASH_SIZE
if (batLength > this.#bat.length) {
const bat = Buffer.alloc(maxBlockCount * HASH_SIZE)
this.#bat.copy(bat, 0, 0, Math.min(this.#bat.length, bat.length))
this.#bat = bat
} else {
this.#bat = this.#bat.subarray(0, batLength)
}
this.#maxBlockCount = 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)
}
entryAt(index: number): Buffer {
return this.#entry(index)
}
sameAt(index: number, other: BlockAllocationTable, otherIndex: number): boolean {
if (index >= this.#maxBlockCount) {
return false
}
return this.entryAt(index).equals(other.entryAt(otherIndex))
}
hashAt(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 {
if (index >= this.#maxBlockCount) {
return true
}
const offset = index * HASH_SIZE
return this.#bat.compare(ZERO_ENTRY, 0, HASH_SIZE, offset, offset + HASH_SIZE) === 0
}
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
}
static async *readChunks(
stream: Readable,
blockCount: number
): AsyncGenerator<{ firstIndex: number; bat: BlockAllocationTable }> {
for (let firstIndex = 0; firstIndex < blockCount; firstIndex += CHUNK_ENTRIES) {
const count = Math.min(CHUNK_ENTRIES, blockCount - firstIndex)
const chunk = (await readChunkStrict(stream, count * HASH_SIZE)) as Buffer
yield { firstIndex, bat: new BlockAllocationTable(chunk, count) }
}
}
}

View File

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

View File

@@ -1,50 +0,0 @@
import { RemoteDiskChain } from '../RemoteDiskChain.mjs'
// type only: HashedDiskDeduplicated imports this class at runtime
import type { HashedDiskDeduplicated } from './HashedDiskDeduplicated.mjs'
import type { BlockHash } from './hbdPaths.mjs'
/**
* A chain of hbd disks, oldest first, read as a single disk.
*
* The child of a hbd merge is always one of these (see openDiskChain): it
* exposes what the merge needs from the newest disk holding each block.
*/
export class HashedDiskChain extends RemoteDiskChain {
constructor({ disks }: { disks: HashedDiskDeduplicated[] }) {
super({ disks })
}
get disks(): HashedDiskDeduplicated[] {
return super.disks as HashedDiskDeduplicated[]
}
getBlockHashAt(index: number): BlockHash {
return this.#newestDiskWith(index).getBlockHashAt(index)
}
getBlockPath(index: number): string {
return this.#newestDiskWith(index).getBlockPath(index)
}
/** block files are independent, nothing is shared inside a single disk */
async canMergeConcurently(): Promise<boolean> {
return true
}
/** Virtual usage of each disk, as HashedDiskDeduplicated.getSizeOnDisk */
getSizeOnDisk(): number {
return this.disks.reduce((size, disk) => size + disk.getSizeOnDisk(), 0)
}
getRootDisk(): HashedDiskDeduplicated | undefined {
return this.disks[0]
}
#newestDiskWith(index: number): HashedDiskDeduplicated {
const disk = this.newestDiskWith(index)
if (disk === undefined) {
throw new Error(`Block ${index} not found in chain`)
}
return disk as HashedDiskDeduplicated
}
}

View File

@@ -1,241 +0,0 @@
import { test } from 'node:test'
import { strict as assert } from 'node:assert'
import tmp from 'tmp'
import * as uuid from 'uuid'
import { getHandler } from '@xen-orchestra/fs'
import { normalize } from '@xen-orchestra/fs/path'
import { pFromCallback } from 'promise-toolbox'
import { rimraf } from 'rimraf'
import { openDiskChain } from '@xen-orchestra/backup-archive/disks'
import { HashedDiskChain, HashedDiskDeduplicated, HbdFileError } from '@xen-orchestra/backup-archive/disks/hashed'
const { beforeEach, afterEach, describe } = test
const BLOCK_SIZE = 4096
const BLOCK_COUNT = 4
const block = byte => Buffer.alloc(BLOCK_SIZE, byte)
let tempDir, handler, diskDir
beforeEach(async () => {
tempDir = await pFromCallback(cb => tmp.dir(cb))
handler = getHandler({ url: `file://${tempDir}` })
await handler.sync()
diskDir = `xo-vm-backups/VMUUID/vdis/job/${uuid.v4()}`
})
afterEach(async () => {
await handler.forget()
await rimraf(tempDir)
})
const diskPath = n => `${diskDir}/2026081${n}T120000000Z.hbd`
/**
* Writes a chain of hbd disks, oldest first: `contents[n]` maps index -> fill byte of disk n
* @returns the paths and uuids, oldest first
*/
async function writeChain(contents) {
const disks = []
for (const [n, content] of contents.entries()) {
const path = diskPath(n)
const diskUuid = uuid.v4()
const parent = disks[n - 1]
const disk = await HashedDiskDeduplicated.create({
handler,
path,
virtualSize: BLOCK_SIZE * BLOCK_COUNT,
blockSize: BLOCK_SIZE,
uuid: diskUuid,
parentUuid: parent?.uuid,
parentPath: parent === undefined ? undefined : `./2026081${n - 1}T120000000Z.hbd`,
dedupType: 'PER_BACKUP_REPOSITORY',
})
for (const [index, byte] of Object.entries(content)) {
await disk.writeBlock({ index: Number(index), data: block(byte) })
}
await disk.close()
disks.push({ path, uuid: diskUuid })
}
return disks
}
async function openChain(paths) {
const disks = []
for (const path of paths) {
const disk = new HashedDiskDeduplicated({ handler, path })
await disk.init()
disks.push(disk)
}
return new HashedDiskChain({ disks })
}
// 3 disks: index 0 only in the base, 1 rewritten by each disk, 2 only in the middle one, 3 nowhere
const CHAIN_OF_3 = [{ 0: 0x10, 1: 0x11 }, { 1: 0x21, 2: 0x22 }, { 1: 0x31 }]
describe('HashedDiskChain', () => {
test('reads each block from the newest disk holding it', async () => {
const written = await writeChain(CHAIN_OF_3)
const chain = await openChain(written.map(_ => _.path))
assert.deepEqual([...chain.getBlockIndexes()].sort(), [0, 1, 2])
assert.equal(chain.hasBlock(3), false)
for (const [index, byte] of [
[0, 0x10],
[1, 0x31],
[2, 0x22],
]) {
assert.ok((await chain.readBlock(index)).data.equals(block(byte)), `block ${index}`)
}
await assert.rejects(() => chain.readBlock(3), /not found in chain/)
})
test('getBlockHashAt and getBlockPath come from the newest disk holding the block', async () => {
const written = await writeChain(CHAIN_OF_3)
const chain = await openChain(written.map(_ => _.path))
const [base, middle, top] = chain.disks
assert.equal(chain.getBlockHashAt(1), top.getBlockHashAt(1))
assert.equal(chain.getBlockPath(1), top.getBlockPath(1))
assert.equal(chain.getBlockHashAt(2), middle.getBlockHashAt(2))
assert.equal(chain.getBlockPath(2), middle.getBlockPath(2))
assert.equal(chain.getBlockPath(0), base.getBlockPath(0))
// the path is a real file, holding the block of that disk
await handler.readFile(chain.getBlockPath(2))
assert.throws(() => chain.getBlockHashAt(3), /not found in chain/)
assert.throws(() => chain.getBlockPath(3), /not found in chain/)
})
test('exposes the newest disk identity and the summed size', async () => {
const written = await writeChain(CHAIN_OF_3)
const chain = await openChain(written.map(_ => _.path))
assert.equal(chain.getUuid(), written[2].uuid)
assert.equal(chain.getPath(), normalize(written[2].path))
assert.deepEqual(
chain.getPaths(),
written.map(_ => normalize(_.path))
)
assert.equal(chain.getRootDisk(), chain.disks[0])
assert.equal(chain.getSizeOnDisk(), (2 + 2 + 1) * BLOCK_SIZE)
assert.equal(await chain.canMergeConcurently(), true)
})
test('init refuses a broken parentage, and closes the disks', async () => {
const written = await writeChain(CHAIN_OF_3)
// the middle disk is skipped: the top one is not a child of the base
const disks = [written[0], written[2]].map(({ path }) => new HashedDiskDeduplicated({ handler, path }))
const closed = []
for (const disk of disks) {
disk.close = async () => closed.push(disk)
}
await assert.rejects(() => new HashedDiskChain({ disks }).init(), { code: 'NOT_SUPPORTED' })
assert.equal(closed.length, 2)
})
})
describe('merging a chain child into a hbd', () => {
async function openParentAndChildChain() {
const written = await writeChain(CHAIN_OF_3)
const parent = new HashedDiskDeduplicated({ handler, path: written[0].path })
await parent.init()
const child = await openChain(written.slice(1).map(_ => _.path))
return { written, parent, child }
}
test('mergeBlock links the block of the newest child disk, and skips identical or absent blocks', async () => {
const { parent, child } = await openParentAndChildChain()
assert.equal(await parent.mergeBlock(child, 1, false), BLOCK_SIZE)
assert.equal(parent.getBlockHashAt(1), child.getBlockHashAt(1))
assert.ok((await parent.readBlock(1)).data.equals(block(0x31)))
// already holding the child's content
assert.equal(await parent.mergeBlock(child, 1, false), 0)
// nothing in the child at this index
assert.equal(await parent.mergeBlock(child, 3, false), 0)
})
test('flushMetadata(child) re-syncs every index of the chain', async () => {
const { parent, child } = await openParentAndChildChain()
await parent.flushMetadata(child)
for (const [index, byte] of [
[0, 0x10],
[1, 0x31],
[2, 0x22],
]) {
assert.ok((await parent.readBlock(index)).data.equals(block(byte)), `block ${index}`)
}
})
test('mergeMetadata(child) takes the identity of the newest disk of the chain', async () => {
const { written, parent, child } = await openParentAndChildChain()
await parent.mergeMetadata(child)
assert.equal(parent.getUuid(), written[2].uuid)
})
test('refuses a child of another type, and never skips the re-sync silently', async () => {
const { parent } = await openParentAndChildChain()
await assert.rejects(() => parent.flushMetadata({}), /can't merge different disk types/)
await assert.rejects(() => parent.mergeMetadata({}), /can't merge different disk types/)
})
})
describe('openDiskChain on hbd disks', () => {
test('returns a HashedDiskChain of the whole chain', async () => {
const written = await writeChain(CHAIN_OF_3)
const chain = await openDiskChain({ handler, path: written[2].path })
try {
assert.ok(chain instanceof HashedDiskChain)
assert.deepEqual(
chain.getPaths(),
written.map(_ => normalize(_.path))
)
} finally {
await chain.close()
}
})
test('stops at `until`, like a merge opens its child', async () => {
const written = await writeChain(CHAIN_OF_3)
const chain = await openDiskChain({ handler, path: written[2].path, until: normalize(written[0].path) })
try {
assert.ok(chain instanceof HashedDiskChain)
assert.deepEqual(
chain.getPaths(),
written.slice(1).map(_ => normalize(_.path))
)
} finally {
await chain.close()
}
})
test('refuses a hbd whose parent is not a hbd', async () => {
const written = await writeChain([{ 0: 0x10 }])
// points the disk at a VHD parent: it is opened as a hbd, and can't be read as one
const metadata = JSON.parse(await handler.readFile(written[0].path))
await handler.writeFile(`${diskDir}/parent.vhd`, Buffer.alloc(1024))
await handler.writeFile(
written[0].path,
JSON.stringify({ ...metadata, parentUuid: uuid.v4(), parentPath: './parent.vhd' }),
{ flags: 'w' }
)
await assert.rejects(
() => openDiskChain({ handler, path: written[0].path }),
error => error instanceof HbdFileError && error.path.endsWith('parent.vhd')
)
})
})

View File

@@ -1,305 +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 { getHandler } from '@xen-orchestra/fs'
import { pFromCallback } from 'promise-toolbox'
import { rimraf } from 'rimraf'
import { MergeRemoteDisk } from '@xen-orchestra/backup-archive/disks'
import { HashedDiskDeduplicated } from '@xen-orchestra/backup-archive/disks/hashed'
// not exported by the package: built by the `test-integration` script
import { RemoteDiskLineage } from '../../../dist/RemoteDiskLineage.mjs'
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)
}
})
// ---------------------------------------------------------------- merge
const STORE = 'xo-block-store'
const VDI_DIR = 'xo-vm-backups/VMUUID/vdis/job/vdi'
const PARENT = { path: `${VDI_DIR}/20260814T120000000Z.hbd`, uuid: '0b3f2c7e-8a41-4d5f-9c26-7e1a5b8d3f04' }
const CHILD = { path: `${VDI_DIR}/20260815T120000000Z.hbd`, uuid: 'c4e9a1d2-6b7f-4e83-a5c0-2d8f9b1e6a37' }
const MERGE_BLOCKS = 5
// 3 changed, 2 shared with the parent
const parentContent = index => Buffer.alloc(BLOCK_SIZE, index + 1)
const childContent = index => (index % 2 === 0 ? Buffer.alloc(BLOCK_SIZE, 0x80 + index) : parentContent(index))
async function withRemote(fn) {
const tempDir = await pFromCallback(cb => tmp.dir(cb))
const handler = getHandler({ url: `file://${tempDir}` })
await handler.sync()
try {
await fn(handler, tempDir)
} finally {
await handler.forget()
await rimraf(tempDir)
}
}
async function createChain(handler) {
const common = {
handler,
virtualSize: BLOCK_SIZE * MERGE_BLOCKS,
blockSize: BLOCK_SIZE,
dedupType: 'PER_BACKUP_REPOSITORY',
blockStorePath: STORE,
}
const parent = await HashedDiskDeduplicated.create({ ...common, ...PARENT })
const child = await HashedDiskDeduplicated.create({
...common,
...CHILD,
parentUuid: PARENT.uuid,
parentPath: './20260814T120000000Z.hbd',
})
for (let index = 0; index < MERGE_BLOCKS; index++) {
await parent.writeBlock({ index, data: parentContent(index) })
await child.writeBlock({ index, data: childContent(index) })
}
await parent.close()
await child.close()
}
const openDisk = async (handler, path) => {
const disk = new HashedDiskDeduplicated({ handler, path, blockStorePath: STORE })
await disk.init()
return disk
}
// what is left after a merge: the child content, under the child name and uuid
async function assertMerged(handler, tempDir) {
const merged = await openDisk(handler, CHILD.path)
assert.equal(merged.getUuid(), CHILD.uuid)
assert.equal(merged.isDifferencing(), false, 'the merged disk keeps the parent own (absent) parent')
for (let index = 0; index < MERGE_BLOCKS; index++) {
assert.ok((await merged.readBlock(index)).data.equals(childContent(index)), `block ${index} differs`)
}
await assert.rejects(() => handler.readFile(PARENT.path), { code: 'ENOENT' })
const files = await listFiles(handler, VDI_DIR)
assert.equal(
files.some(file => file.includes(`/data/${CHILD.uuid}/`)),
false,
'the child data dir is gone'
)
assert.equal(
files.some(file => file.endsWith('.merge.json')),
false,
'no merge state left'
)
// one store file per block still referenced, each held by the store copy and the merged disk only
const storeFiles = await listFiles(handler, STORE)
assert.equal(storeFiles.length, MERGE_BLOCKS)
for (const storeFile of storeFiles) {
assert.equal((await stat(join(tempDir, storeFile))).nlink, 2, storeFile)
}
}
test('MergeRemoteDisk merges a hashed child into its parent', async () => {
await withRemote(async (handler, tempDir) => {
await createChain(handler)
const merger = new MergeRemoteDisk(handler, { removeUnused: true })
await merger.merge(await openDisk(handler, PARENT.path), await openDisk(handler, CHILD.path))
await assertMerged(handler, tempDir)
})
})
test('MergeRemoteDisk resumes a hashed merge interrupted before the parent was flushed', async () => {
await withRemote(async (handler, tempDir) => {
await createChain(handler)
// first run: dies on the 4th block, like a killed process, so nothing is flushed
const parent = await openDisk(handler, PARENT.path)
const mergeBlock = parent.mergeBlock.bind(parent)
let calls = 0
parent.mergeBlock = (...args) => {
if (++calls === 4) {
throw new Error('crash')
}
return mergeBlock(...args)
}
parent.close = async () => {}
const firstRun = new MergeRemoteDisk(handler, { removeUnused: true, mergeBlockConcurrency: 1, writeStateDelay: 0 })
const child = await openDisk(handler, CHILD.path)
await assert.rejects(() => firstRun.merge(parent, child), /crash/)
assert.ok(
(await listFiles(handler, VDI_DIR)).some(file => file.endsWith('.merge.json')),
'the merge state is kept'
)
// second run: fresh disks, restarts from the saved block and skips the ones before
const resumed = new MergeRemoteDisk(handler, { removeUnused: true })
await resumed.merge(await openDisk(handler, PARENT.path), await openDisk(handler, CHILD.path))
await assertMerged(handler, tempDir)
})
})
// ---------------------------------------------------------------- merge through RemoteDiskLineage
// what a backup cleanup does: the lineage opens the merge child with openDiskChain, so the
// child is a HashedDiskChain, never a bare disk
const GRANDCHILD = { path: `${VDI_DIR}/20260816T120000000Z.hbd`, uuid: 'e2a7c5b1-9d34-4f6e-8b02-5c1d7a9e3f48' }
const grandchildContent = index => (index === 1 ? Buffer.alloc(BLOCK_SIZE, 0xc1) : childContent(index))
async function addGrandchild(handler) {
const grandchild = await HashedDiskDeduplicated.create({
handler,
...GRANDCHILD,
virtualSize: BLOCK_SIZE * MERGE_BLOCKS,
blockSize: BLOCK_SIZE,
dedupType: 'PER_BACKUP_REPOSITORY',
blockStorePath: STORE,
parentUuid: CHILD.uuid,
parentPath: './20260815T120000000Z.hbd',
})
await grandchild.writeBlock({ index: 1, data: grandchildContent(1) })
await grandchild.close()
}
const LINEAGE_OPTS = { remove: true, merge: true, logInfo: () => {}, logWarn: () => {} }
// only `activePath` is still referenced by a backup: every older disk is merged into it
async function cleanLineage(handler, activePath, opts = {}) {
const lineage = new RemoteDiskLineage(handler, VDI_DIR, { ...LINEAGE_OPTS, ...opts })
await lineage.init()
lineage.addActiveDiskPath(activePath)
return lineage.clean()
}
test('RemoteDiskLineage merges a chain of 2 hbd disks', async () => {
await withRemote(async (handler, tempDir) => {
await createChain(handler)
const { merge } = await cleanLineage(handler, CHILD.path)
assert.equal(merge, true)
await assertMerged(handler, tempDir)
})
})
test('RemoteDiskLineage merges a chain of 3 hbd disks', async () => {
await withRemote(async handler => {
await createChain(handler)
await addGrandchild(handler)
await cleanLineage(handler, GRANDCHILD.path)
assert.deepEqual(
(await handler.list(VDI_DIR)).filter(name => name.endsWith('.hbd')),
['20260816T120000000Z.hbd'],
'only the active disk is left'
)
const merged = await openDisk(handler, GRANDCHILD.path)
assert.equal(merged.getUuid(), GRANDCHILD.uuid)
assert.equal(merged.isDifferencing(), false)
for (let index = 0; index < MERGE_BLOCKS; index++) {
assert.ok((await merged.readBlock(index)).data.equals(grandchildContent(index)), `block ${index} differs`)
}
// the store only holds what the merged disk still references
const referenced = new Set(merged.getBlockIndexes().map(index => merged.getBlockHashAt(index)))
assert.equal((await listFiles(handler, STORE)).length, referenced.size)
})
})
test('RemoteDiskLineage resumes an interrupted merge of a hbd chain', async () => {
await withRemote(async (handler, tempDir) => {
await createChain(handler)
// first run: dies on the 4th block, like a killed process
const { mergeBlock } = HashedDiskDeduplicated.prototype
let calls = 0
HashedDiskDeduplicated.prototype.mergeBlock = function (...args) {
if (++calls === 4) {
throw new Error('crash')
}
return mergeBlock.apply(this, args)
}
try {
await assert.rejects(() => cleanLineage(handler, CHILD.path, { mergeBlockConcurrency: 1 }), /crash/)
} finally {
HashedDiskDeduplicated.prototype.mergeBlock = mergeBlock
}
assert.ok(
(await listFiles(handler, VDI_DIR)).some(file => file.endsWith('.merge.json')),
'the merge state is kept'
)
// second run: a fresh lineage finds the merge state and resumes it
await cleanLineage(handler, CHILD.path)
await assertMerged(handler, tempDir)
})
})

View File

@@ -1,810 +0,0 @@
import type { DiskBlock } from '@xen-orchestra/disk-transform'
import { type RemoteHandlerAbstract, type DiskFormat } from '@xen-orchestra/fs'
import { basename, 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 { HashedDiskChain } from './HashedDiskChain.mjs'
import { BlockAllocationTable } from './BlockAllocationTable.mjs'
import {
blockRelPath,
checkVersion,
dataDirName,
decodeBlock,
encodeBlock,
hashesFileName,
HbdFileError,
sha256hex,
VERSION,
type DedupType,
type BlockHash,
type HashedDiskMetadata,
HashEntrySet,
HBD_HEADER_SIZE,
BLOCK_STORE_PATH,
parseBlockHeader,
CODEC_RAW,
setVerifiedAt,
HBD_MAGIC,
} from './hbdPaths.mjs'
import { randomUUID } from 'node:crypto'
const { warn, debug } = createLogger('xo:backup-archive:hbd')
const LEFTOVER_SAMPLE = 5
/**
* What a hbd can be merged with: a single hbd, or a chain of them
*/
type MergeChild = HashedDiskDeduplicated | HashedDiskChain
function assertMergeChild(childDisk: unknown): asserts childDisk is MergeChild {
if (!(childDisk instanceof HashedDiskDeduplicated || childDisk instanceof HashedDiskChain)) {
throw new Error(`can't merge different disk types`)
}
}
/**
* 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
#dataDir: string | undefined
#blocksDir: string | undefined
#blockStorePath: string
#dirty = false
#oldBlockCount = 0
#scrubEnabled: boolean
#scrubMaxAgeMs: number
#blocksScrubbed = 0
#blocksCorrupted = 0
constructor({
handler,
path,
blockStorePath = BLOCK_STORE_PATH,
scrubEnabled = false,
scrubMaxAgeMs = 30 * 86400e3, // 30 days
}: {
handler: RemoteHandlerAbstract
path: string
blockStorePath?: string
scrubEnabled?: boolean
scrubMaxAgeMs?: number
}) {
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
this.#scrubEnabled = scrubEnabled && !this.#handler.isEncrypted
if (scrubEnabled && !this.#scrubEnabled) {
warn("Scrubbing can't be enabled on a encrypted remote", { path: this.#path })
}
this.#scrubMaxAgeMs = scrubMaxAgeMs
}
/**
* New, empty disk on the remote and returns it, opened.
*/
static async create({
handler,
path,
virtualSize,
blockSize,
uuid,
parentUuid,
parentPath,
dedupType = 'PER_DISK',
blockStorePath = BLOCK_STORE_PATH,
scrubEnabled,
scrubMaxAgeMs,
}: {
handler: RemoteHandlerAbstract
path: string
virtualSize: number
blockSize: number
uuid: string
parentUuid?: string
parentPath?: string
dedupType?: DedupType
blockStorePath?: string
scrubEnabled?: boolean
scrubMaxAgeMs?: number
}): 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
const bat = BlockAllocationTable.allocate(Math.ceil(virtualSize / blockSize))
const disk = new HashedDiskDeduplicated({ handler, path, blockStorePath, scrubEnabled, scrubMaxAgeMs })
await handler.outputFile(disk.#resolve(hashesPath), bat.toBuffer(), { flags: 'wx' })
await handler.outputFile(path, JSON.stringify(metadata), { flags: 'wx' })
await disk.init()
return disk
}
// ---------------------------------------------------------------- getters
get #diskDir(): string {
return dirname(this.#path)
}
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
}
/**
* holds the blocks and every hashes file, current and orphaned
*/
get #loadedDataDir(): string {
if (this.#dataDir === undefined) {
throw new Error(`can't use a HashedDiskDeduplicated before init`)
}
return this.#dataDir
}
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.hashAt(index)
}
/**
* Path of the file holding the block at this index, inside this disk
*/
getBlockPath(index: number): string {
if (!this.hasBlock(index)) {
throw new Error(`no block at index ${index} of ${this.#path}`)
}
return this.#blockPath(this.getBlockHashAt(index))
}
/** store blocks fully reread and checked since this disk was opened */
getBlocksScrubbed(): number {
return this.#blocksScrubbed
}
/** store blocks found corrupted, and rewritten, since this disk was opened */
getBlocksCorrupted(): number {
return this.#blocksCorrupted
}
async isMergeableParent(parentUuid: string, { diskFormat }: { diskFormat: DiskFormat }): Promise<boolean> {
return (await super.isMergeableParent(parentUuid, { diskFormat })) && diskFormat === 'hbd'
}
/**
* The parent of a hbd is always opened as a hbd: a chain never mixes formats,
* a parent of another format fails at init
*/
instantiateParent(): HashedDiskDeduplicated {
return new HashedDiskDeduplicated({
handler: this.#handler,
path: this.getParentPath(),
blockStorePath: this.#blockStorePath,
scrubEnabled: this.#scrubEnabled,
scrubMaxAgeMs: this.#scrubMaxAgeMs,
})
}
// ---------------------------------------------------------------- public
/**
* @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 dataDir: string
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}`)
}
// named after the uuid at creation, not the current one: a merge gives
// the disk its child's uuid but leaves the directory where it is
dataDir = this.#resolve(dataDirName(basename(dirname(metadata.localBlocksPath))))
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.#dataDir = dataDir
this.#blocksDir = blocksDir
try {
this.#bat = BlockAllocationTable.fromBuffer(
await this.#handler.readFile(hashesPath),
this.getMaxBlockCount(),
options.force
)
this.#oldBlockCount = this.getMaxBlockCount()
} catch (error: unknown) {
this.#metadata = undefined
this.#dataDir = undefined
this.#blocksDir = undefined
throw new HbdFileError((error as NodeJS.ErrnoException).message, hashesPath, error)
}
}
async close(): Promise<void> {
if (this.#dirty) {
await this.flushMetadata()
}
}
async rename(newPath: string): Promise<void> {
newPath = normalize(newPath)
if (dirname(newPath) !== this.#diskDir) {
throw new Error(`can't move ${this.#path} out of its directory, to ${newPath}`)
}
await this.#handler.rename(this.#path, newPath)
this.#path = newPath
}
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.hashAt(index)
// reads the whole file: that is exactly header + payload, and unlike a
// positional read it also works on an encrypted remote
const blockPath = this.#blockPath(hash)
const buffer = await this.#handler.readFile(blockPath)
let payload: Buffer
try {
;({ payload } = decodeBlock(buffer, hash))
} catch (error: unknown) {
// says which file of which disk is broken
throw new HbdFileError(`${(error as Error).message} at index ${index} of ${this.#path}`, blockPath, error)
}
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.
*/
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.hashAt(index) === hash) {
return blockSize
}
await this.#addBlockReference(hash, data)
this.#setHash(index, hash)
return blockSize
}
/**
* The child is usually a chain (see openDiskChain): only its public methods are used
*/
async mergeBlock(childDisk: MergeChild, index: number, isResumingMerge: boolean): Promise<number> {
if (!childDisk.hasBlock(index)) {
return 0
}
const childHash = childDisk.getBlockHashAt(index)
if (this.hasBlock(index) && this.getBlockHashAt(index) === childHash) {
return 0
}
await this.#link(childDisk.getBlockPath(index), this.#blockPath(childHash))
this.#setHash(index, childHash)
return this.getBlockSize()
}
/**
* 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> {}
async resize(blockCount: number): Promise<void> {
if (blockCount === this.getMaxBlockCount()) {
return
}
const bat = this.#loadedBat
bat.resize(blockCount)
this.#metadata = { ...this.#loadedMetadata, virtualSize: blockCount * this.getBlockSize() }
this.#dirty = true
}
/**
* 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(childDisk?: unknown): Promise<void> {
if (childDisk !== undefined) {
assertMergeChild(childDisk)
await this.#mergeWithChild(childDisk)
}
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.#resolve(metadata.hashesPath))
this.#oldBlockCount = this.getMaxBlockCount()
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 })
}
}
async #mergeWithChild(childDisk: MergeChild): Promise<void> {
if (childDisk.getBlockSize() !== this.getBlockSize()) {
throw new Error(`can't merge a ${childDisk.getBlockSize()} bytes block disk into a ${this.getBlockSize()} one`)
}
// mergeBlock skips the indexes already holding the child's content
for (const index of childDisk.getBlockIndexes()) {
await this.mergeBlock(childDisk, index, true)
}
}
async clean({
remove = false,
logWarn = (message: string, data?: object) => {},
logInfo = (message: string, data?: object) => {},
} = {}): Promise<string | undefined> {
const current = basename(this.#loadedMetadata.hashesPath)
const leftovers: string[] = []
for (const filename of await this.#handler.list(this.#loadedDataDir)) {
if (filename !== current && /^hashes\..+\.hash$/.test(filename)) {
leftovers.push(join(this.#loadedDataDir, filename))
}
}
if (this.#loadedMetadata.dedupType === 'PER_BACKUP_REPOSITORY') {
const tmpDir = this.#tmpDir
for (const filename of await this.#handler.list(tmpDir, { ignoreMissing: true })) {
leftovers.push(join(this.#tmpDir, filename))
}
}
if (leftovers.length > 0) {
logInfo('leftover files of a hashed disk', {
disk: this.#path,
count: leftovers.length,
sample: leftovers.slice(0, LEFTOVER_SAMPLE),
})
}
if (remove) {
for (const path of leftovers) {
debug('leftover file of a hashed disk', { disk: this.#path, path })
await this.#handler
.unlink(path, { checksum: false })
.catch(error => logWarn('failed to remove a leftover file', { path, error }))
}
}
return undefined
}
async mergeMetadata(childDisk: unknown): Promise<void> {
assertMergeChild(childDisk)
// on a chain, the metadata of its newest disk
const { uuid, virtualSize } = childDisk.getMetadata()
if (Math.ceil(virtualSize / this.getBlockSize()) !== this.getMaxBlockCount()) {
throw new Error(`the BAT of ${this.#path} is not sized for its child, resize first`)
}
const metadata = { ...this.#loadedMetadata, uuid, virtualSize }
await this.#handler.outputStream(this.#path, Readable.from(JSON.stringify(metadata)), { checksum: false })
this.#metadata = metadata
}
/**
* 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.#loadedDataDir]
return files.filter(p => isInDir(p, dir))
}
async unlink(): Promise<void> {
if (this.#loadedMetadata.dedupType === 'PER_BACKUP_REPOSITORY') {
for (const index of this.#loadedBat.indexes()) {
try {
await this.#removeBlockReference(this.#loadedBat.hashAt(index))
} catch (error) {
warn('failed to release block', { path: this.#path, index, error })
}
}
}
await this.#handler.unlink(this.#path)
await this.#handler.rmtree(this.#loadedDataDir)
this.#metadata = undefined
this.#bat = undefined
this.#dataDir = undefined
this.#blocksDir = undefined
this.#dirty = false
}
// ---------------------------------------------------------------- private
/**
* 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
}
#blockPath(hash: BlockHash): string {
if (this.#blocksDir === undefined) {
throw new Error(`can't use a HashedDiskDeduplicated before init`)
}
return join(this.#blocksDir, blockRelPath(hash))
}
get #tmpDir(): string {
if (this.#blocksDir === undefined) {
throw new Error(`can't use a HashedDiskDeduplicated before init`)
}
return join(this.#blocksDir, '.tmp')
}
/**
* @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, copy = 0): string {
return join(this.#blockStorePath, blockRelPath(hash), String(copy))
}
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), encodeBlock(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 blockPath = this.#blockPath(hash)
for (let copy = 0; ; copy++) {
const storePath = this.#storePath(hash, copy)
try {
await this.#link(storePath, blockPath)
} catch (error: unknown) {
const { code } = error as NodeJS.ErrnoException
if (code === 'EMLINK') {
continue
}
if (code !== 'ENOENT') {
throw error
}
// link did not work, we need a new block
const tmp = join(this.#tmpDir, randomUUID())
await this.#handler.outputFile(tmp, encodeBlock(hash, data), { flags: 'wx' })
try {
await this.#link(tmp, storePath)
await this.#link(storePath, blockPath)
} finally {
await this.#handler
.unlink(tmp, { checksum: false })
.catch(error => warn('failed to remove a temporary block file', { path: this.#path, tmp, error }))
}
return
}
if (this.#scrubEnabled) {
await this.#scrub(hash, data, storePath)
}
return
}
}
/**
* best effort: the new BAT is already safe, a failure only leaks
*/
async #removeOrphans(previousHashesPath: string): Promise<void> {
const stream = await this.#handler.createReadStream(previousHashesPath)
try {
const current = this.#loadedBat
const candidates = new HashEntrySet()
// Pass 1: Entries of the previous BAT this flush replaced
for await (const { firstIndex, bat } of BlockAllocationTable.readChunks(stream, this.#oldBlockCount)) {
for (const index of bat.indexes()) {
if (!current.sameAt(firstIndex + index, bat, index)) {
candidates.add(Buffer.from(bat.entryAt(index)))
}
}
}
// Pass 2: A replaced hash can still be referenced at another index
for (const index of current.indexes()) {
if (candidates.size === 0) {
break
}
candidates.delete(current.entryAt(index))
}
// Removal
for (const entry of candidates) {
await this.#removeBlockReference(entry.toString('hex') as BlockHash)
}
} catch (error) {
warn('failed to remove orphaned blocks', { path: this.#path, error })
} finally {
stream.destroy()
}
}
/**
* @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
nlink = await this.#handler.getLinkCount(blockPath)
if (nlink === 0) {
return // already removed
}
await this.#handler.unlink(blockPath, { checksum: false })
if (nlink === 2) {
await this.#removeOrphanStoreCopy(hash)
}
}
}
async #removeOrphanStoreCopy(hash: BlockHash): Promise<void> {
const first = this.#storePath(hash)
const dir = dirname(first)
// first, check /0
if ((await this.#linkCount(first)) === 1) {
await this.#handler.unlink(first, { checksum: false })
} else {
// if /0 copy is not used for this disk, check the other paths
for (const name of await this.#handler.list(dir, { ignoreMissing: true })) {
if (name === '0') {
continue
}
const path = join(dir, name)
if ((await this.#linkCount(path)) === 1) {
await this.#handler.unlink(path, { checksum: false })
}
}
}
await this.#handler.rmdir(dir).catch(error => {
if (error.code !== 'ENOTEMPTY' && error.code !== 'EEXIST') {
warn('failed to remove an empty store directory', { dir, error })
}
})
}
async #linkCount(path: string): Promise<number> {
return this.#handler.getLinkCount(path).catch(error => {
warn('failed to read a store copy link count', { path, error })
return 0
})
}
#setHash(index: number, hash: BlockHash): void {
this.#loadedBat.set(index, hash)
this.#dirty = true
}
async #scrub(hash: BlockHash, data: Buffer, storePath: string): Promise<void> {
try {
const headerBuffer = Buffer.alloc(HBD_HEADER_SIZE)
const now = Date.now()
// read metadata
await this.#handler.read(storePath, headerBuffer, 0)
const header = parseBlockHeader(headerBuffer)
// a header we can't trust (wrong magic, another hash, a date in the future)
// must not let its verifiedAt skip the check
const trusted = header.magic === HBD_MAGIC && header.payloadHash === hash && header.verifiedAt <= now
if (trusted && now - header.verifiedAt < this.#scrubMaxAgeMs) {
return
}
this.#blocksScrubbed++
// check block
const buffer = await this.#handler.readFile(storePath)
let corrupted = false
try {
decodeBlock(buffer, hash)
} catch {
corrupted = true
}
// update medata or rewrite block
if (!corrupted) {
await this.#handler.write(storePath, setVerifiedAt(headerBuffer, now), 0)
} else {
this.#blocksCorrupted++
warn('corrupted store block, repaired', { hash, storePath })
await this.#handler.outputFile(storePath, encodeBlock(hash, data, CODEC_RAW, now), {
flags: 'w',
})
}
} catch (error) {
warn('failed to scrub a store block', { hash, storePath, error })
}
}
}

View File

@@ -1,231 +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 4 payload_length: bytes stored after the header, uint32 LE (never 0)
// 52 460 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'
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
// the block store, at the remote root: shared by every hashed disk of the remote
export const BLOCK_STORE_PATH = 'xo-block-store'
// 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
const OFFSET_PAYLOAD_LENGTH = 48
export const CODEC_RAW = 0x00
export const CODEC_BROTLI = 0x01
const HASH_HEX_LENGTH = HASH_SIZE * 2 // chars, in memory
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, 2)}/${hash.slice(2, 4)}/${hash}`
}
export interface HbdBlockHeader {
magic: number
codec: number
verifiedAt: number // ms since epoch, 0 = never verified
payloadHash: BlockHash
payloadLength: number // bytes stored after the header
}
export function buildBlockHeader(hash: BlockHash, payloadLength: number, 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}`)
}
if (!Number.isInteger(payloadLength) || payloadLength <= 0 || payloadLength > 0xffffffff) {
throw new Error(`payloadLength must be a positive 32 bits integer, got ${payloadLength}`)
}
// zero filled, which is exactly what the reserved ranges (5..7 and 52..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)
header.writeUInt32LE(payloadLength, OFFSET_PAYLOAD_LENGTH)
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,
payloadLength: buffer.readUInt32LE(OFFSET_PAYLOAD_LENGTH),
}
}
/** a whole block file: its header, with the payload length recorded, then the payload */
export function encodeBlock(hash: BlockHash, data: Buffer, codec = CODEC_RAW, verifiedAt = 0): Buffer {
return Buffer.concat([buildBlockHeader(hash, data.length, codec, verifiedAt), data])
}
/**
* 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, expectedHash: BlockHash): { header: HbdBlockHeader; payload: Buffer } {
if (buffer.length < HBD_HEADER_SIZE) {
throw new Error(`truncated block: expected at least ${HBD_HEADER_SIZE} 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)}`)
}
// the file is checked against its own header only
// Every block records its length, 0 means a damaged header
const { payloadLength } = header
if (payloadLength === 0) {
throw new Error('not a hbd block: no payload length')
}
const expectedLength = HBD_HEADER_SIZE + payloadLength
if (buffer.length < expectedLength) {
throw new Error(`truncated block: expected ${expectedLength} bytes, got ${buffer.length}`)
}
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) {
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
}
export function setVerifiedAt(header: Buffer, verifiedAt: number): Buffer {
header.writeBigInt64LE(BigInt(verifiedAt), OFFSET_VERIFIED_AT)
return header
}
export class HashEntrySet {
#keys = new Set<string>()
add(entry: Buffer): this {
this.#keys.add(entry.toString('latin1'))
return this
}
has(entry: Buffer): boolean {
return this.#keys.has(entry.toString('latin1'))
}
delete(entry: Buffer): boolean {
return this.#keys.delete(entry.toString('latin1'))
}
get size(): number {
return this.#keys.size
}
*[Symbol.iterator](): Iterator<Buffer> {
for (const key of this.#keys) {
yield Buffer.from(key, 'latin1')
}
}
}

View File

@@ -1,7 +0,0 @@
export { BlockAllocationTable } from './BlockAllocationTable.mjs'
export { HashedDisk } from './HashedDisk.mjs'
export { HashedDiskChain } from './HashedDiskChain.mjs'
export { HashedDiskDeduplicated } from './HashedDiskDeduplicated.mjs'
export * from './hbdPaths.mjs'
export { scanBlockStore } from './scanBlockStore.mjs'
export { writeHbd } from './writeHbd.mjs'

View File

@@ -1,86 +0,0 @@
import { asyncEach } from '@vates/async-each'
import type { RemoteHandlerAbstract } from '@xen-orchestra/fs'
import { basename, join, normalize } from '@xen-orchestra/fs/path'
import { asBlockHash, BLOCK_STORE_PATH, decodeBlock } from './hbdPaths.mjs'
// <store>/<ab>/<cd>/<hash>/<copy>: copies are always at this depth
const COPY_DEPTH = 4
export async function scanBlockStore(
handler: RemoteHandlerAbstract,
{
remove = false,
verify = false,
logInfo = () => {},
logWarn = () => {},
logDebug = () => {},
}: {
remove?: boolean
verify?: boolean
logInfo?: (message: string, data?: object) => void
logWarn?: (message: string, data?: object) => void
logDebug?: (message: string, data?: object) => void
} = {}
): Promise<{ removed: number }> {
let removed = 0
async function visit(dir: string, depth: number): Promise<void> {
let names: string[]
try {
names = await handler.list(dir, { ignoreMissing: true })
} catch (error) {
if ((error as NodeJS.ErrnoException).code === 'ENOTDIR') {
return // not a store directory, left alone
}
throw error
}
await asyncEach(
names,
async name => {
const path = join(dir, name)
if (depth + 1 < COPY_DEPTH) {
await visit(path, depth + 1) // a hash level: go down
} else if (depth + 1 === COPY_DEPTH) {
if (await removeIfOrphan(path)) {
removed++ // a store copy
} else if (verify) {
// <ab>/<cd>/<hash>/<copy>: the copy's directory is named after the full hash
await verifyCopy(path, basename(dir))
}
}
},
{
concurrency: 2,
}
)
}
async function removeIfOrphan(path: string): Promise<boolean> {
try {
if ((await handler.getLinkCount(path)) !== 1) {
return false // still linked by a disk
}
logDebug('orphan store file', { path })
if (remove) {
await handler.unlink(path, { checksum: false })
}
return true
} catch (error) {
logDebug('failed to check a store copy', { path, error })
return false
}
}
async function verifyCopy(path: string, hashCopy: string): Promise<void> {
try {
const hash = asBlockHash(hashCopy)
const buffer = await handler.readFile(path)
decodeBlock(buffer, hash)
} catch (error) {
logWarn('corrupted store block', { path, error })
}
}
await visit(normalize(BLOCK_STORE_PATH), 0)
return { removed }
}

View File

@@ -1,93 +0,0 @@
import type { Disk, DiskBlock } from '@xen-orchestra/disk-transform'
import { type RemoteHandlerAbstract } from '@xen-orchestra/fs'
import { asyncEach } from '@vates/async-each'
import { createLogger } from '@xen-orchestra/log'
import { HashedDiskDeduplicated } from './HashedDiskDeduplicated.mjs'
const { warn } = createLogger('xo:backup-archive:hbd')
/**
* Writes every block of `source` to a new hbd disk at `path`, sharing its
* blocks with the whole backup repository.
*
* On failure, the partial disk is removed and the blocks it already
* referenced are released.
*
* @returns the number of bytes read from the source
*/
export async function writeHbd(
handler: RemoteHandlerAbstract,
path: string,
source: Disk,
{
uuid,
parentUuid,
parentPath,
concurrency = 16,
validator = async () => {},
signal,
}: {
uuid: string
parentUuid?: string
parentPath?: string
concurrency?: number
validator?: (path: string) => Promise<void>
signal?: AbortSignal
}
): Promise<number> {
let disk: HashedDiskDeduplicated | undefined
// asyncEach rejects on the first error without waiting for the other
// iterations: the cleanup must not run while a block is still being
// referenced, or that reference would never be released
const pendingWrites = new Set<Promise<number>>()
try {
signal?.throwIfAborted()
const blockSize = source.getBlockSize()
disk = await HashedDiskDeduplicated.create({
handler,
path,
virtualSize: source.getVirtualSize(),
blockSize,
uuid,
parentUuid,
parentPath,
dedupType: 'PER_BACKUP_REPOSITORY',
})
let transferred = 0
const target = disk
await asyncEach(
source.diskBlocks(),
async ({ index, data }: DiskBlock) => {
signal?.throwIfAborted()
transferred += data.length
// the last block of a disk whose size is not a multiple of the block size
if (data.length < blockSize) {
const padded = Buffer.alloc(blockSize)
data.copy(padded)
data = padded
}
const write = target.writeBlock({ index, data })
pendingWrites.add(write)
try {
await write
} finally {
pendingWrites.delete(write)
}
},
{ concurrency }
)
await disk.flushMetadata()
await validator(path)
return transferred
} catch (error) {
await source.close().catch(() => {})
await Promise.allSettled(pendingWrites)
if (disk !== undefined) {
await disk.unlink().catch(unlinkError => warn('failed to remove partial hbd', { path, error: unlinkError }))
}
throw error
}
}

View File

@@ -1,198 +0,0 @@
import { test } from 'node:test'
import { strict as assert } from 'node:assert'
import tmp from 'tmp'
import * as uuid from 'uuid'
import { getHandler } from '@xen-orchestra/fs'
import { normalize } from '@xen-orchestra/fs/path'
import { pFromCallback } from 'promise-toolbox'
import { rimraf } from 'rimraf'
import { BLOCK_STORE_PATH, HashedDiskDeduplicated, writeHbd } from '@xen-orchestra/backup-archive/disks/hashed'
const { beforeEach, afterEach, describe } = test
const BLOCK_SIZE = 4096
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)
})
/**
* Minimal source disk: yields `blocks` in order, then optionally throws
*/
function fakeSource(blocks, { virtualSize = blocks.reduce((sum, b) => sum + b.length, 0), failAfter } = {}) {
let closed = false
return {
get closed() {
return closed
},
getBlockSize: () => BLOCK_SIZE,
getVirtualSize: () => virtualSize,
async *diskBlocks() {
for (const [index, data] of blocks.entries()) {
if (index === failAfter) {
throw new Error('source failure')
}
yield { index, data }
}
},
async close() {
closed = true
},
}
}
// what is left of the disk dir: `data/` itself is shared with the other disks of the dir
async function listDiskDir() {
const list = async path => (await handler.list(path).catch(() => [])).sort()
return { files: await list(diskDir), data: await list(`${diskDir}/data`) }
}
async function listStore() {
const entries = []
for (const ab of await handler.list(BLOCK_STORE_PATH).catch(() => [])) {
for (const cd of await handler.list(`${BLOCK_STORE_PATH}/${ab}`)) {
entries.push(...(await handler.list(`${BLOCK_STORE_PATH}/${ab}/${cd}`)))
}
}
return entries
}
describe('writeHbd', () => {
test('writes every block and reads them back', async () => {
const blocks = [Buffer.alloc(BLOCK_SIZE, 1), Buffer.alloc(BLOCK_SIZE, 2), Buffer.alloc(BLOCK_SIZE, 3)]
const transferred = await writeHbd(handler, diskPath, fakeSource(blocks), { uuid: uuid.v4() })
assert.equal(transferred, 3 * BLOCK_SIZE)
const disk = new HashedDiskDeduplicated({ handler, path: diskPath })
await disk.init()
assert.deepEqual(disk.getBlockIndexes(), [0, 1, 2])
assert.equal(disk.getVirtualSize(), 3 * BLOCK_SIZE)
assert.equal(disk.getMetadata().dedupType, 'PER_BACKUP_REPOSITORY')
for (const [index, data] of blocks.entries()) {
assert.deepEqual((await disk.readBlock(index)).data, data)
}
})
test('pads a short last block with zeros', async () => {
const blocks = [Buffer.alloc(BLOCK_SIZE, 1), Buffer.alloc(BLOCK_SIZE / 2, 2)]
const transferred = await writeHbd(handler, diskPath, fakeSource(blocks), { uuid: uuid.v4() })
// counts what was read from the source, not the padding
assert.equal(transferred, BLOCK_SIZE + BLOCK_SIZE / 2)
const disk = new HashedDiskDeduplicated({ handler, path: diskPath })
await disk.init()
const { data } = await disk.readBlock(1)
assert.equal(data.length, BLOCK_SIZE)
assert.deepEqual(data.subarray(0, BLOCK_SIZE / 2), Buffer.alloc(BLOCK_SIZE / 2, 2))
assert.deepEqual(data.subarray(BLOCK_SIZE / 2), Buffer.alloc(BLOCK_SIZE / 2, 0))
})
test('identical blocks share a single store entry', async () => {
const blocks = [Buffer.alloc(BLOCK_SIZE, 1), Buffer.alloc(BLOCK_SIZE, 1), Buffer.alloc(BLOCK_SIZE, 2)]
await writeHbd(handler, diskPath, fakeSource(blocks), { uuid: uuid.v4() })
assert.equal((await listStore()).length, 2)
})
test('stores parent uuid and path', async () => {
const parentUuid = uuid.v4()
await writeHbd(handler, diskPath, fakeSource([Buffer.alloc(BLOCK_SIZE, 1)]), {
uuid: uuid.v4(),
parentUuid,
parentPath: '20260813T120000000Z.hbd',
})
const disk = new HashedDiskDeduplicated({ handler, path: diskPath })
await disk.init()
assert.equal(disk.isDifferencing(), true)
assert.equal(disk.getParentUuid(), parentUuid)
assert.equal(disk.getParentPath(), normalize(`${diskDir}/20260813T120000000Z.hbd`))
})
test('calls the validator with the disk path once written', async () => {
let validatedPath
await writeHbd(handler, diskPath, fakeSource([Buffer.alloc(BLOCK_SIZE, 1)]), {
uuid: uuid.v4(),
validator: async path => {
// the disk must already be complete and readable
const disk = new HashedDiskDeduplicated({ handler, path })
await disk.init()
assert.deepEqual(disk.getBlockIndexes(), [0])
validatedPath = path
},
})
assert.equal(validatedPath, diskPath)
})
describe('on failure', () => {
test('removes the partial disk and releases its blocks', async () => {
const source = fakeSource([Buffer.alloc(BLOCK_SIZE, 7), Buffer.alloc(BLOCK_SIZE, 8)], {
virtualSize: 2 * BLOCK_SIZE,
failAfter: 1,
})
await assert.rejects(writeHbd(handler, diskPath, source, { uuid: uuid.v4() }), { message: 'source failure' })
assert.equal(source.closed, true)
assert.deepEqual(await listDiskDir(), { files: ['data'], data: [] })
assert.deepEqual(await listStore(), [])
})
test('keeps blocks still referenced by another disk', async () => {
const shared = Buffer.alloc(BLOCK_SIZE, 1)
const otherPath = `${diskDir}/20260813T120000000Z.hbd`
await writeHbd(handler, otherPath, fakeSource([shared]), { uuid: uuid.v4() })
const source = fakeSource([shared, Buffer.alloc(BLOCK_SIZE, 2)], { virtualSize: 2 * BLOCK_SIZE, failAfter: 1 })
await assert.rejects(writeHbd(handler, diskPath, source, { uuid: uuid.v4() }))
assert.equal((await listStore()).length, 1)
const other = new HashedDiskDeduplicated({ handler, path: otherPath })
await other.init()
assert.deepEqual((await other.readBlock(0)).data, shared)
})
test('removes the disk when the validator rejects', async () => {
await assert.rejects(
writeHbd(handler, diskPath, fakeSource([Buffer.alloc(BLOCK_SIZE, 1)]), {
uuid: uuid.v4(),
validator: async () => {
throw new Error('invalid')
},
}),
{ message: 'invalid' }
)
assert.deepEqual(await listDiskDir(), { files: ['data'], data: [] })
assert.deepEqual(await listStore(), [])
})
test('does not start when the signal is already aborted', async () => {
const controller = new AbortController()
controller.abort()
await assert.rejects(
writeHbd(handler, diskPath, fakeSource([Buffer.alloc(BLOCK_SIZE, 1)]), {
uuid: uuid.v4(),
signal: controller.signal,
})
)
assert.deepEqual(await listDiskDir(), { files: [], data: [] })
})
})
})

View File

@@ -1,16 +1,22 @@
import { instantiateDisk } from './instantiateDisk.mjs'
export { isDisk } from './instantiateDisk.mjs'
import { RemoteVhdDisk } from './RemoteVhdDisk.mjs'
export { RemoteDisk } from './RemoteDisk.mjs'
export { RemoteVhdDisk } from './RemoteVhdDisk.mjs'
export { openDiskChain } from './openDiskChain.mjs'
export { MergeRemoteDisk } from './MergeRemoteDisk.mjs'
const DISK_EXTENSIONS = ['.vhd']
/**
* @typedef {import('@xen-orchestra/fs').RemoteHandlerAbstract} RemoteHandlerAbstract
* @typedef {import('./RemoteDisk.mjs').RemoteDisk} RemoteDisk
* @typedef {import('./MergeRemoteDisk.mjs').MergeState} MergeState
*/
export function isDisk(path) {
return DISK_EXTENSIONS.some(ext => path.endsWith(ext))
}
/**
*
* @param {Object} params
@@ -21,7 +27,7 @@ export { MergeRemoteDisk } from './MergeRemoteDisk.mjs'
* @returns {Promise<Disposable<RemoteDisk>>}
*/
export async function openDisposableDisk({ handler, path, force = false, ignoreBlockIndexes = false }) {
const disk = instantiateDisk(handler, path)
const disk = new RemoteVhdDisk({ handler, path })
if (ignoreBlockIndexes) {
// Best-effort init: return the disk even if init fails so that callers
// can still use operations that work without a fully-opened VHD (e.g. unlink, checkAlias).
@@ -44,7 +50,7 @@ export async function openDisposableDisk({ handler, path, force = false, ignoreB
* @returns {Promise<RemoteDisk>}
*/
export async function openDisk({ handler, path, force = false, ignoreBlockIndexes = false }) {
const disk = instantiateDisk(handler, path)
const disk = new RemoteVhdDisk({ handler, path })
if (ignoreBlockIndexes) {
// Best-effort init: return the disk even if init fails so that callers
// can still use operations that work without a fully-opened VHD (e.g. unlink, checkAlias).

View File

@@ -1,24 +0,0 @@
// @ts-check
/**
* @typedef {import('@xen-orchestra/fs').RemoteHandlerAbstract} RemoteHandlerAbstract
* @typedef {import('./RemoteDisk.mjs').RemoteDisk} RemoteDisk
*/
import { RemoteVhdDisk } from './RemoteVhdDisk.mjs'
// eslint rule off for src/**/*.mjs already
import { HashedDiskDeduplicated } from './hashed/HashedDiskDeduplicated.mjs'
const DISK_EXTENSIONS = ['.vhd', '.hbd']
export function isDisk(path) {
return DISK_EXTENSIONS.some(ext => path.endsWith(ext))
}
/**
* The disk format is chosen by the file extension, never by the remote config
* @param {RemoteHandlerAbstract} handler
* @param {string} path
* @returns {RemoteDisk}
*/
export function instantiateDisk(handler, path) {
return path.endsWith('.hbd') ? new HashedDiskDeduplicated({ handler, path }) : new RemoteVhdDisk({ handler, path })
}

View File

@@ -4,28 +4,9 @@
* @typedef {import('@xen-orchestra/fs').RemoteHandlerAbstract} RemoteHandlerAbstract
* @typedef {import('./RemoteDisk.mjs').RemoteDisk} RemoteDisk
*/
import { defer } from 'golike-defer'
import { RemoteVhdDisk } from './RemoteVhdDisk.mjs'
import { defer } from 'golike-defer'
import { RemoteVhdDiskChain } from './RemoteVhdDiskChain.mjs'
import { HashedDiskDeduplicated } from './hashed/HashedDiskDeduplicated.mjs'
import { HashedDiskChain } from './hashed/HashedDiskChain.mjs'
import { instantiateDisk } from './instantiateDisk.mjs'
/**
* The chain class of the disks' format: a chain never mixes formats
* @param {string} path
* @param {RemoteDisk[]} disks
* @returns {RemoteDisk}
*/
function newChain(path, disks) {
if (disks.every(disk => disk instanceof HashedDiskDeduplicated)) {
return new HashedDiskChain({ disks })
}
if (disks.every(disk => disk instanceof RemoteVhdDisk)) {
return new RemoteVhdDiskChain({ disks })
}
throw new Error(`mixed disk formats in chain ${path}`)
}
/**
* @param {any} $defer
@@ -39,15 +20,15 @@ function newChain(path, disks) {
*/
async function _openDiskChain($defer, { handler, path, until, force = false, ignoreBlockIndexes = false }) {
/**
* @type {RemoteDisk}
* @type {RemoteVhdDisk}
*/
let disk
/**
* @type {Array<RemoteDisk>}
* @type {Array<RemoteVhdDisk>}
*/
const disks = []
$defer.onFailure(() => Promise.all(disks.map(disk => disk.close())))
disk = instantiateDisk(handler, path)
disk = new RemoteVhdDisk({ handler, path })
await disk.init({ force, ignoreBlockIndexes })
disks.push(disk)
@@ -59,14 +40,15 @@ async function _openDiskChain($defer, { handler, path, until, force = false, ign
}
// Instantiate + init the parent directly (instead of openParent()) so the
// block allocation table read can be skipped when ignoreBlockIndexes is set.
disk = disk.instantiateParent()
disk = /** @type {RemoteVhdDisk} */ (disk.instantiateParent())
await disk.init({ force, ignoreBlockIndexes })
disks.unshift(disk)
}
if (!foundRootDisk) {
throw new Error(`trying to open chain from ${path} to ${until}, root disk not found`)
}
return newChain(path, disks)
// the root disk
return new RemoteVhdDiskChain({ disks })
}
/**

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,488 +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 { openDisposableDisk } from '@xen-orchestra/backup-archive/disks'
import { BLOCK_STORE_PATH, HashedDiskDeduplicated } from '@xen-orchestra/backup-archive/disks/hashed'
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,
diskFormat,
vhdDirectoryCompression,
remoteCompressionType,
} = {}) {
handler = getHandler({
url: `file://${tempDir}`,
useVhdDirectory,
diskFormat,
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)
})
}
}
}
}
})
// a folder can hold disks of several formats, but a chain never mixes them: only a disk
// of the format this remote writes can be the parent of the next delta
describe('RemoteAdapter#isMergeableParent across disk formats', { concurrency: 1 }, () => {
const COMPRESSION = 'brotli'
// disk kind on the remote -> the only remote format that may chain onto it
const DISK_KINDS = {
file: 'vhd',
directory: 'vhdDirectory',
hbd: 'hbd',
}
async function createParent(kind, diskUuid) {
if (kind === 'hbd') {
const path = `${basePath}/disk.hbd`
const disk = await HashedDiskDeduplicated.create({
handler,
path,
virtualSize: DEFAULT_BLOCK_SIZE,
blockSize: DEFAULT_BLOCK_SIZE,
uuid: uuid.stringify(diskUuid),
dedupType: 'PER_BACKUP_REPOSITORY',
})
await disk.close()
return path
}
await generateVhd(`${basePath}/disk.vhd`, {
mode: kind,
compression: kind === 'directory' ? COMPRESSION : undefined,
uuid: diskUuid,
})
return kind === 'directory' ? `${basePath}/disk.vhd.alias.vhd` : `${basePath}/disk.vhd`
}
for (const [kind, matchingFormat] of Object.entries(DISK_KINDS)) {
for (const diskFormat of Object.values(DISK_KINDS)) {
for (const uuidMatches of [false, true]) {
const expected = uuidMatches && diskFormat === matchingFormat
test(`${kind} disk on a ${diskFormat} remote, uuidMatches=${uuidMatches} -> ${expected}`, async () => {
const adapter = await getAdapter({ diskFormat, remoteCompressionType: COMPRESSION })
const targetUuid = uniqueIdBuffer()
const path = await createParent(kind, uuidMatches ? targetUuid : uniqueIdBuffer())
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 writeDisk() 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#writeDisk 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.getDiskFileName('base')}`
const size = await adapter.writeDisk(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.getDiskFileName('20000101T000000Z')}`
const childPath = `${basePath}/${adapter.getDiskFileName('20000102T000000Z')}`
const parentUuid = uniqueIdBuffer()
await adapter.writeDisk(parentPath, new MockDisk(2, [0, 1], 0xaa), {
validator: tmpPath => checkDisk(handler, tmpPath),
uuid: parentUuid,
})
await adapter.writeDisk(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.getDiskFileName('base')}`
await assert.rejects(
adapter.writeDisk(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 }), [])
})
}
})
// every `<hash>` entry of the shared block store
async function listBlockStore() {
const hashes = []
for (const ab of await handler.list(BLOCK_STORE_PATH, { ignoreMissing: true })) {
for (const cd of await handler.list(`${BLOCK_STORE_PATH}/${ab}`)) {
hashes.push(...(await handler.list(`${BLOCK_STORE_PATH}/${ab}/${cd}`)))
}
}
return hashes
}
describe('RemoteAdapter#writeDisk on a hbd remote', { concurrency: 1 }, () => {
const writeHbdDisk = (adapter, path, disk, opts) =>
adapter.writeDisk(path, disk, {
validator: tmpPath => checkDisk(handler, tmpPath),
uuid: uniqueIdBuffer(),
...opts,
})
test('names the disk file .hbd', async () => {
const adapter = await getAdapter({ diskFormat: 'hbd' })
assert.equal(adapter.getDiskFileName('20000101T000000Z'), '20000101T000000Z.hbd')
})
test('writes a base disk that passes validation and reads back', async () => {
const adapter = await getAdapter({ diskFormat: 'hbd' })
const path = `${basePath}/${adapter.getDiskFileName('base')}`
const source = new MockDisk(2, [0, 1], 0x42)
const diskUuid = uniqueIdBuffer()
const size = await writeHbdDisk(adapter, path, source, { uuid: diskUuid })
// what was read from the source: its 2 blocks, not its (geometry rounded) virtual size
assert.equal(size, 2 * DEFAULT_BLOCK_SIZE)
await Disposable.use(openDisposableDisk({ handler, path }), async disk => {
// the writer passes packed uuids, the hbd metadata holds them as strings
assert.equal(disk.getUuid(), uuid.stringify(diskUuid))
assert.equal(disk.isDifferencing(), false)
assert.deepEqual(disk.getBlockIndexes(), [0, 1])
for (const index of [0, 1]) {
const { data } = await disk.readBlock(index)
const expected = (await source.readBlock(index)).data
assert.deepEqual(data.subarray(0, expected.length), expected, `block ${index} should match the source`)
}
})
})
test('writes a differencing disk chained to its parent that passes validation', async () => {
const adapter = await getAdapter({ diskFormat: 'hbd' })
const parentPath = `${basePath}/${adapter.getDiskFileName('20000101T000000Z')}`
const childPath = `${basePath}/${adapter.getDiskFileName('20000102T000000Z')}`
const parentUuid = uniqueIdBuffer()
await writeHbdDisk(adapter, parentPath, new MockDisk(2, [0, 1], 0xaa), { uuid: parentUuid })
await writeHbdDisk(adapter, childPath, new MockDisk(2, [1], 0xbb, { differencing: true }), {
parentUuid,
parentPath: relativeFromFile(childPath, parentPath),
})
await Disposable.use(openDisposableDisk({ handler, path: childPath }), async disk => {
assert.equal(disk.isDifferencing(), true)
assert.equal(disk.getParentUuid(), uuid.stringify(parentUuid))
assert.equal(disk.getParentPath(), `/${parentPath}`)
assert.deepEqual(disk.getBlockIndexes(), [1])
})
})
test('identical content is stored once for the whole remote', async () => {
const adapter = await getAdapter({ diskFormat: 'hbd' })
const otherBasePath = `${rootPath}/vdis/${jobId}/${uniqueId()}`
await writeHbdDisk(adapter, `${basePath}/${adapter.getDiskFileName('a')}`, new MockDisk(2, [0, 1], 0x42))
const storeAfterFirst = await listBlockStore()
// another VDI of the same remote, same content
await writeHbdDisk(adapter, `${otherBasePath}/${adapter.getDiskFileName('b')}`, new MockDisk(2, [0, 1], 0x42))
assert.deepEqual((await listBlockStore()).sort(), storeAfterFirst.sort())
})
test('a rejected validation leaves no disk and no block behind', async () => {
const adapter = await getAdapter({ diskFormat: 'hbd' })
const path = `${basePath}/${adapter.getDiskFileName('base')}`
await assert.rejects(
writeHbdDisk(adapter, path, new MockDisk(1, [0], 0x11), {
validator: async () => {
throw new Error('boom')
},
}),
/boom/
)
// `data/` itself is shared with the other disks of the directory
assert.deepEqual(await handler.list(basePath, { ignoreMissing: true }), ['data'])
assert.deepEqual(await handler.list(`${basePath}/data`, { ignoreMissing: true }), [])
assert.deepEqual(await listBlockStore(), [])
})
})

View File

@@ -1,35 +1,27 @@
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 { writeHbd } from '@xen-orchestra/backup-archive/disks/hashed'
import { ReadAhead } from '@xen-orchestra/disk-transform'
export const DIR_XO_CONFIG_BACKUPS = 'xo-config-backups'
@@ -44,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') {
@@ -53,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
}
@@ -67,29 +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), { diskFormat: this.#diskFormat })
)
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()
})
}
get #diskFormat() {
return this.handler.getConfig('diskFormat')
}
// 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(
@@ -106,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) {
@@ -149,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) {
@@ -204,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)
@@ -223,24 +205,24 @@ export class RemoteAdapter {
)
}
#getCompressionType() {
return this._vhdDirectoryCompression
}
useVhdDirectory() {
return this.handler.getConfig('diskFormat') === 'vhdDirectory'
return this.handler.useVhdDirectory()
}
#useAlias() {
return this.useVhdDirectory()
}
// if we use alias on this remote, we have to name the file alias.{vhd|hbd}
getDiskFileName(baseName) {
if (this.#diskFormat === 'hbd') {
return `${baseName}.hbd`
} else {
if (this.#useAlias()) {
return `${baseName}.alias.vhd`
}
return `${baseName}.vhd`
// if we use alias on this remote, we have to name the file alias.vhd
getVhdFileName(baseName) {
if (this.#useAlias()) {
return `${baseName}.alias.vhd`
}
return `${baseName}.vhd`
}
async listAllVms() {
@@ -316,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)
@@ -342,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) {
@@ -445,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`
@@ -462,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 })
@@ -490,45 +453,33 @@ export class RemoteAdapter {
return path
}
async writeDisk(path, disk, { validator = noop, writeBlockConcurrency, uuid, parentUuid, parentPath } = {}) {
async writeVhd(path, disk, { validator = noop, writeBlockConcurrency, uuid, parentUuid, parentPath } = {}) {
const handler = this._handler
const diskFormat = this.#diskFormat
switch (diskFormat) {
case 'vhd': {
const stream = await toVhdStream(disk, { uuid, parentUuid, parentPath })
const size = await this.outputStream(path, stream, {
validator,
// no checksum for VHDs, because they will be invalidated by
// merges and chains
checksum: false,
})
await validator(path)
return size
}
case 'vhdDirectory':
return await writeToVhdDirectory({
disk,
target: {
handler,
path,
concurrency: writeBlockConcurrency,
validator,
compression: handler.getConfig('compressionType') ?? 'brotli', // compatibility layer
uuid,
parentUuid,
parentPath,
},
})
case 'hbd':
return await writeHbd(handler, path, disk, {
uuid: stringify(uuid),
parentUuid: parentUuid && stringify(parentUuid),
parentPath,
if (this.useVhdDirectory()) {
return await writeToVhdDirectory({
disk,
target: {
handler,
path,
concurrency: writeBlockConcurrency,
validator,
})
default:
throw new Error(`unknown disk format ${diskFormat} for ${path}`)
compression: 'brotli',
uuid,
parentUuid,
parentPath,
},
})
} else {
const stream = await toVhdStream(disk, { uuid, parentUuid, parentPath })
const size = await this.outputStream(path, stream, {
validator,
// no checksum for VHDs, because they will be invalidated by
// merges and chains
checksum: false,
})
await validator(path)
return size
}
}
@@ -690,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,9 +14,9 @@ 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 { isDisk, openDiskChain } from '@xen-orchestra/backup-archive/disks'
import { openDiskChain } from '@xen-orchestra/backup-archive/disks'
import { VDI_FORMAT_QCOW2 } from '@xen-orchestra/xapi'
import { diskHasData } from './_diskHasData.mjs'
@@ -39,7 +39,7 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
const vhdDir = `${vdisDir}/${srcVdiUuid}`
try {
const vhds = await handler.list(vhdDir, {
filter: _ => _[0] !== '.' && isDisk(_),
filter: _ => _[0] !== '.' && _.endsWith('.vhd'),
ignoreMissing: true,
prependDir: true,
})
@@ -92,7 +92,7 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
// parentDestPath is the chain tip = most-recent backup; its filename is stable under
// merges (merges rename the OLDER disks), so unlike the root it maps reliably to its
// metadata json.
const parentDate = basename(parentDestPath).replace(/\.(alias\.vhd|vhd|hbd)$/, '')
const parentDate = basename(parentDestPath).replace(/\.(alias\.)?vhd$/, '')
let metadata
try {
metadata = await this._adapter.readVmBackupMetadata(`${this._vmBackupDir}/${parentDate}.json`)
@@ -225,7 +225,7 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
// don't do delta for it
vdi.uuid
: vdi.$snapshot_of$uuid
}/${adapter.getDiskFileName(filenameDate)}`
}/${adapter.getVhdFileName(filenameDate)}`
)
let metadataContent = await this._isAlreadyTransferred(timestamp)
@@ -273,11 +273,8 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
parentPath = relativeFromFile(path, parentDestPath)
}
const transferred = await adapter.writeDisk(path, disk, {
// no checksum for VHDs, because they will be invalidated by
// merges and chains
checksum: false,
validator: tmpPath => checkDisk(handler, tmpPath),
const transferred = await adapter.writeVhd(path, disk, {
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

@@ -1,148 +0,0 @@
# Hashed disks (`.hbd`)
A content addressed disk format: each block is stored once, named after the SHA-256 of its content.
- [File structure on remote](#file-structure-on-remote)
- [Files](#files)
- [`<datetime>.hbd`](#datetimehbd)
- [`hashes.<ms>.<random>.hash`](#hashesmsrandomhash)
- [Block file](#block-file)
- [Dedup types](#dedup-types)
- [Reference counting](#reference-counting)
- [Link limit (`EMLINK`)](#link-limit-emlink)
- [Lifecycle](#lifecycle)
## File structure on remote
```
<remote>
├─ xo-vm-backups
│ └─ <VM UUID>
│ └─ vdis
│ └─ <job UUID>
│ └─ <VDI UUID>
│ ├─ <YYYYMMDD>T<HHmmss>.hbd // one per backup
│ └─ data
│ └─ <disk UUID at creation>
│ ├─ hashes.<ms>.<random>.hash // the BAT
│ └─ blocks
│ └─ <ab>/<cd>/<hash> // one file per unique block
└─ xo-block-store // PER_BACKUP_REPOSITORY only
└─ <ab>/<cd>/<hash>
├─ 0 // store copy
└─ 1, 2… // overflow copies, when 0 hits the link limit
```
- `<ab>/<cd>`: the first 2 bytes of the hash, so at most 256 entries per level whatever the number of blocks
- `<hash>`: the full hash, 64 hex characters
- the data directory keeps the uuid the disk had when it was created: a merge changes the disk uuid, not the directory
## Files
### `<datetime>.hbd`
```json
{
"version": "0.0.1",
"virtualSize": 21474836480,
"blockSize": 2097152,
"uuid": "<disk UUID>",
"parentUuid": "<parent UUID>",
"parentPath": "./<parent datetime>.hbd",
"dedupType": "PER_BACKUP_REPOSITORY",
"localBlocksPath": "data/<disk UUID at creation>/blocks/",
"hashesPath": "data/<disk UUID at creation>/hashes.<ms>.<random>.hash"
}
```
- paths are relative to the `.hbd` file, and must stay inside the disk data directory
- `parentUuid` / `parentPath` are absent on a full disk
### `hashes.<ms>.<random>.hash`
The BAT: a flat binary file, one 32-byte SHA-256 per block index.
```
offset index * 32
size ceil(virtualSize / blockSize) * 32
empty 32 zero bytes
```
- a new file at each flush, never overwritten: the `.hbd` points at the current one
- any other `hashes.*.hash` in the same directory is a leftover of a crash
### Block file
```
0..511 header
0..3 magic "HBD\0"
4 codec (0 raw, 1 brotli)
8..15 verifiedAt (ms, 0 = never)
16..47 SHA-256 of the payload
48..51 payloadLength (uint32 LE, never 0)
52..511 reserved (zero)
512.. payload (payloadLength bytes)
```
## Dedup types
| `dedupType` | Blocks | Needs hard links |
| ----------------------- | ----------------------------------------------------------------- | ---------------- |
| `PER_DISK` | real files in the disk `blocks/` | no |
| `PER_BACKUP_REPOSITORY` | hard links to `xo-block-store`, shared by all disks of the remote | yes |
- `PER_DISK` for remotes without hard links (S3, Azure)
- the store location is given by the caller, never read from the `.hbd`
- `BLOCK_STORE_PATH` (`xo-block-store`) by default
## Reference counting
No counter file: the link count of the inode is the count.
```
xo-block-store/<h>/0 ─┐
diskA/blocks/<h> ─┼──▶ [ inode ] nlink = 3
diskB/blocks/<h> ─┘
```
- `nlink - 1` = number of disks using the block
- a store file at `nlink = 1` is used by no disk: the GC scan (`scanBlockStore`) removes it
- maintenance only, run by an admin with no backup job running: `xo-disk-cli scan-store <remote url> [--remove] [--verify]`
- after a backup cleanup: a leftover temp file (`blocks/.tmp/`) keeps its store file at `nlink = 2` until the disk `clean()` removes it
- reads always go through the disk own link, never through the store
### Link limit (`EMLINK`)
An inode accepts a limited number of links (ext4: 65000, XFS: 65535). A common block, the all-zero one first, can reach it on a large remote.
```
xo-block-store/<h>/0 ─┐
disk 1 … disk 64999 ─┴──▶ [ inode #1 ] nlink = 65000 (full)
xo-block-store/<h>/1 ─┐
disk 65000 ─┴──▶ [ inode #2 ] nlink = 2
```
- `link` fails with `EMLINK` on `0`: try the next copies `1`, `2`…
- all full: publish a new copy `N+1`, then link to it
- each copy is its own inode, so its count is independent
- releasing a block removes the copy that drops to `nlink = 1`, not always `0`
## Lifecycle
| Step | What happens |
| ------ | -------------------------------------------------------------------------------------------------- |
| write | link from the store, or publish a new store file (temp file, then `link`) |
| flush | new BAT, then `.hbd`, then release the blocks no index uses any more, then remove the previous BAT |
| merge | parent takes the child blocks and uuid, then is renamed to the child path |
| unlink | release every block of the BAT, then remove the data directory and the `.hbd` |
| clean | `clean()` removes leftover BATs, `scanBlockStore` removes store files at `nlink = 1` |
- write: `writeHbd(handler, path, source, { uuid, parentUuid, parentPath })`, called by `RemoteAdapter.writeDisk` when the remote `diskFormat` is `hbd`
- on failure, waits for the pending block writes, then `unlink()`: no reference is left behind
- merge: the child is a `HashedDiskChain` (opened by `openDiskChain`), never a bare disk
- `mergeBlock` links `child.getBlockPath(index)` into the parent, skipped when the parent already holds the same hash
- clean: `clean()` is the disk hook called by `RemoteDiskLineage`; it also removes leftover temp files (`blocks/.tmp/`)
- releasing a block: unlink the disk link, and the store file too if this disk was its last user
- a crash at any step leaves a readable disk: only leftovers, cleaned later

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,12 +1,10 @@
```
$ xo-disk-cli --help
Usage: xo-disk-cli <command> <handler-url> <path> [options]
xo-disk-cli scan-store <handler-url> [--remove] [--verify] [--verbose]
Commands:
info Show disk info (virtual size, uid, parent uid, block size); --chain shows the full parent chain, --size adds the size on disk
list List all disks at a path and display their properties in a table; --size adds the size on disk
scan-store Maintenance of the hbd block store: reports the unused blocks, --remove deletes them, --verify rereads every block. Run with no backup job using the remote, after a backup cleanup
transform Convert a disk to another format and write to stdout (raw | vhd | qcow2)
```
@@ -99,28 +97,6 @@ $ xo-disk-cli list file:///mnt/backups /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/
└──────────────┴──────────────────────────────────────┴─────────────┴──────────────┴─────────────┴──────────────────────────────────────┘
```
### `scan-store`
Maintenance of the block store (`xo-block-store/`) of a remote holding hbd (deduplicated) disks. Never run by a backup.
```
xo-disk-cli scan-store <handler-url> [--remove] [--verify] [--verbose]
```
- reports the store blocks no disk uses any more (link count 1); `--remove` deletes them
- `--verify` rereads every block still in use and checks it against its hash; a corrupted block is reported, never repaired nor removed
- `--verbose` prints every unused block
- run it with no backup job using the remote, after a backup cleanup: a temp file left by an interrupted backup keeps its block in use until the cleanup removes it
```
$ xo-disk-cli scan-store file:///mnt/backups
unused store blocks: 12 found (dry run, use --remove to delete them)
$ xo-disk-cli scan-store file:///mnt/backups --remove --verify
unused store blocks: 12 removed
corrupted store blocks: 0
```
### `transform`
Convert a disk (or its full parent chain if differencing) to the specified format and write the result to stdout. Redirect to a file to save the output.

View File

@@ -19,12 +19,10 @@ npm install --global @xen-orchestra/disk-cli
```
$ xo-disk-cli --help
Usage: xo-disk-cli <command> <handler-url> <path> [options]
xo-disk-cli scan-store <handler-url> [--remove] [--verify] [--verbose]
Commands:
info Show disk info (virtual size, uid, parent uid, block size); --chain shows the full parent chain, --size adds the size on disk
list List all disks at a path and display their properties in a table; --size adds the size on disk
scan-store Maintenance of the hbd block store: reports the unused blocks, --remove deletes them, --verify rereads every block. Run with no backup job using the remote, after a backup cleanup
transform Convert a disk to another format and write to stdout (raw | vhd | qcow2)
```
@@ -117,28 +115,6 @@ $ xo-disk-cli list file:///mnt/backups /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/
└──────────────┴──────────────────────────────────────┴─────────────┴──────────────┴─────────────┴──────────────────────────────────────┘
```
### `scan-store`
Maintenance of the block store (`xo-block-store/`) of a remote holding hbd (deduplicated) disks. Never run by a backup.
```
xo-disk-cli scan-store <handler-url> [--remove] [--verify] [--verbose]
```
- reports the store blocks no disk uses any more (link count 1); `--remove` deletes them
- `--verify` rereads every block still in use and checks it against its hash; a corrupted block is reported, never repaired nor removed
- `--verbose` prints every unused block
- run it with no backup job using the remote, after a backup cleanup: a temp file left by an interrupted backup keeps its block in use until the cleanup removes it
```
$ xo-disk-cli scan-store file:///mnt/backups
unused store blocks: 12 found (dry run, use --remove to delete them)
$ xo-disk-cli scan-store file:///mnt/backups --remove --verify
unused store blocks: 12 removed
corrupted store blocks: 0
```
### `transform`
Convert a disk (or its full parent chain if differencing) to the specified format and write the result to stdout. Redirect to a file to save the output.

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

@@ -1,35 +0,0 @@
import Disposable from 'promise-toolbox/Disposable'
import { getSyncedHandler } from '@xen-orchestra/fs'
import { scanBlockStore } from '@xen-orchestra/backup-archive/disks/hashed'
/**
* Maintenance of the block store of a hbd remote: never run by a backup.
*
* Without --remove, only reports. To run with no backup job using the remote.
*/
export async function scanStoreCommand(handlerUrl: string, _path: string, extraArgs: string[]): Promise<void> {
const remove = extraArgs.includes('--remove')
const verify = extraArgs.includes('--verify')
const verbose = extraArgs.includes('--verbose')
await Disposable.use(getSyncedHandler({ url: handlerUrl }), async handler => {
let corrupted = 0
const { removed } = await scanBlockStore(handler, {
remove,
verify,
logWarn: (message, data: { path?: string; error?: Error } = {}) => {
corrupted++
console.error(`${message}: ${data.path} (${data.error?.message ?? 'unknown error'})`)
},
logDebug: verbose
? (message, data: { path?: string } = {}) => console.error(`${message}: ${data.path}`)
: () => {},
})
const orphans = remove ? `${removed} removed` : `${removed} found (dry run, use --remove to delete them)`
console.log(`unused store blocks: ${orphans}`)
if (verify) {
console.log(`corrupted store blocks: ${corrupted}`)
}
})
}

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

@@ -46,21 +46,6 @@ declare module '@xen-orchestra/backup-archive/disks/openDiskChain.mjs' {
}): Promise<RandomAccessDisk>
}
declare module '@xen-orchestra/backup-archive/disks/hashed' {
import type { RemoteHandler } from '@xen-orchestra/fs'
export function scanBlockStore(
handler: RemoteHandler,
opts?: {
remove?: boolean
verify?: boolean
logInfo?: (message: string, data?: object) => void
logWarn?: (message: string, data?: object) => void
logDebug?: (message: string, data?: object) => void
}
): Promise<{ removed: number }>
}
declare module '@xen-orchestra/backup-archive/disks' {
import type { RemoteHandler } from '@xen-orchestra/fs'
import type { RandomAccessDisk } from '@xen-orchestra/disk-transform'

View File

@@ -2,7 +2,6 @@
import { infoCommand } from './commands/info.mjs'
import { listCommand } from './commands/list.mjs'
import { scanStoreCommand } from './commands/scanStore.mjs'
import { transformCommand } from './commands/transform.mjs'
type CommandFn = (handlerUrl: string, path: string, extraArgs: string[]) => Promise<void>
@@ -10,19 +9,13 @@ type CommandFn = (handlerUrl: string, path: string, extraArgs: string[]) => Prom
const COMMANDS: Record<string, CommandFn> = {
info: infoCommand,
list: listCommand,
'scan-store': scanStoreCommand,
transform: transformCommand,
}
// commands working on the whole remote: no <path>
const REMOTE_COMMANDS = new Set(['scan-store'])
function showHelp(exitCode: number): never {
const commandDescriptions: Record<string, string> = {
info: 'Show disk info (virtual size, uid, parent uid, block size); --chain shows the full parent chain, --size adds the size on disk',
list: 'List all disks at a path and display their properties in a table; --size adds the size on disk',
'scan-store':
'Maintenance of the hbd block store: reports the unused blocks, --remove deletes them, --verify rereads every block. Run with no backup job using the remote, after a backup cleanup',
transform: 'Convert a disk to another format and write to stdout (raw | vhd | qcow2)',
}
@@ -31,7 +24,6 @@ function showHelp(exitCode: number): never {
.join('\n')
process.stdout.write(`Usage: xo-disk-cli <command> <handler-url> <path> [options]
xo-disk-cli scan-store <handler-url> [--remove] [--verify] [--verbose]
Commands:
${commandList}
@@ -41,25 +33,20 @@ Examples:
xo-disk-cli info file:///mnt/backups /xo-vm-backups/uuid/disk.alias.vhd --chain --size
xo-disk-cli list file:///mnt/backups /xo-vm-backups/uuid/
xo-disk-cli list file:///mnt/backups /xo-vm-backups/uuid/ --size
xo-disk-cli scan-store file:///mnt/backups
xo-disk-cli scan-store file:///mnt/backups --remove --verify
xo-disk-cli transform file:///mnt/backups /xo-vm-backups/uuid/disk.vhd raw > disk.img
xo-disk-cli transform file:///mnt/backups /xo-vm-backups/uuid/disk.vhd qcow2 > disk.qcow2
`)
process.exit(exitCode)
}
const [, , command, handlerUrl, ...args] = process.argv
const [, , command, handlerUrl, diskPath, ...extraArgs] = process.argv
if (!command || command === '--help' || command === '-h') {
showHelp(0)
}
const needsPath = !REMOTE_COMMANDS.has(command)
const [diskPath, ...extraArgs] = needsPath ? args : ['', ...args]
if (!handlerUrl || (needsPath && !diskPath)) {
console.error(needsPath ? 'Error: handler-url and disk-path are required\n' : 'Error: handler-url is required\n')
if (!handlerUrl || !diskPath) {
console.error('Error: handler-url and disk-path are required\n')
showHelp(1)
}

View File

@@ -1,130 +0,0 @@
/**
* Tests for the `scan-store` command.
*
* Focus:
* - Dry run by default: --remove and --verify are only passed when asked.
* - The summary tells removed from found, and counts the corrupted blocks.
* - Handler is always disposed, even when the scan throws.
*
* Design: module mocks are registered once at the top level. currentScanImpl is
* reset in beforeEach and set per-test.
*/
import { describe, test, mock, beforeEach } from 'node:test'
import assert from 'node:assert/strict'
type ScanOpts = {
remove?: boolean
verify?: boolean
logWarn?: (message: string, data?: object) => void
logDebug?: (message: string, data?: object) => void
}
const handlerDispose = mock.fn(() => Promise.resolve())
const mockHandler = {}
// Records the options each scanBlockStore call received.
const scanOpts: ScanOpts[] = []
// Reassigned per-test to control what scanBlockStore does.
let currentScanImpl: (opts: ScanOpts) => Promise<{ removed: number }> = async () => ({ removed: 0 })
mock.module('@xen-orchestra/fs', {
namedExports: {
getSyncedHandler: () => Promise.resolve({ value: mockHandler, dispose: handlerDispose }),
},
})
mock.module('@xen-orchestra/backup-archive/disks/hashed', {
namedExports: {
scanBlockStore: (handler: unknown, opts: ScanOpts) => {
assert.equal(handler, mockHandler)
scanOpts.push(opts)
return currentScanImpl(opts)
},
},
})
const { scanStoreCommand } = await import('../../commands/scanStore.mjs')
// Captures console.log and console.error without polluting test output.
async function capture(fn: () => Promise<void>): Promise<{ out: string; err: string }> {
const out: string[] = []
const err: string[] = []
const { log, error } = console
console.log = (...args: unknown[]) => out.push(args.map(String).join(' '))
console.error = (...args: unknown[]) => err.push(args.map(String).join(' '))
try {
await fn()
} finally {
console.log = log
console.error = error
}
return { out: out.join('\n'), err: err.join('\n') }
}
beforeEach(() => {
scanOpts.length = 0
handlerDispose.mock.resetCalls()
currentScanImpl = async () => ({ removed: 0 })
})
describe('scanStoreCommand', () => {
test('is a dry run by default', async () => {
currentScanImpl = async () => ({ removed: 3 })
const { out } = await capture(() => scanStoreCommand('file:///backups', '', []))
assert.equal(scanOpts.length, 1)
assert.equal(scanOpts[0].remove, false)
assert.equal(scanOpts[0].verify, false)
assert.match(out, /unused store blocks: 3 found \(dry run/)
assert.doesNotMatch(out, /corrupted/)
assert.equal(handlerDispose.mock.callCount(), 1)
})
test('--remove deletes the unused blocks', async () => {
currentScanImpl = async () => ({ removed: 2 })
const { out } = await capture(() => scanStoreCommand('file:///backups', '', ['--remove']))
assert.equal(scanOpts[0].remove, true)
assert.match(out, /unused store blocks: 2 removed/)
})
test('--verify counts and reports the corrupted blocks', async () => {
currentScanImpl = async ({ logWarn }) => {
logWarn!('corrupted store block', { path: '/xo-block-store/ab/cd/abcd/0', error: new Error('hash mismatch') })
logWarn!('corrupted store block', { path: '/xo-block-store/ef/01/ef01/0', error: new Error('bad magic') })
return { removed: 0 }
}
const { out, err } = await capture(() => scanStoreCommand('file:///backups', '', ['--verify']))
assert.equal(scanOpts[0].verify, true)
assert.match(out, /corrupted store blocks: 2/)
assert.match(err, /abcd\/0 \(hash mismatch\)/)
assert.match(err, /ef01\/0 \(bad magic\)/)
})
test('--verbose prints every unused block', async () => {
currentScanImpl = async ({ logDebug }) => {
logDebug!('orphan store file', { path: '/xo-block-store/ab/cd/abcd/0' })
return { removed: 1 }
}
const quiet = await capture(() => scanStoreCommand('file:///backups', '', []))
const verbose = await capture(() => scanStoreCommand('file:///backups', '', ['--verbose']))
assert.equal(quiet.err, '')
assert.match(verbose.err, /orphan store file: \/xo-block-store\/ab\/cd\/abcd\/0/)
})
test('disposes the handler when the scan throws', async () => {
currentScanImpl = async () => {
throw new Error('EACCES')
}
await assert.rejects(() => scanStoreCommand('file:///backups', '', ['--remove']), /EACCES/)
assert.equal(handlerDispose.mock.callCount(), 1)
})
})

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) => {
@@ -36,18 +29,11 @@ const DEFAULT_MAX_PARALLEL_OPERATIONS = 10
const ENCRYPTION_DESC_FILENAME = 'encryption.json'
const ENCRYPTION_METADATA_FILENAME = 'metadata.json'
// value of a remote option the remote URL does not set
const CONFIG_DEFAULTS = {
diskFormat: 'vhd',
}
const WITH_LIMIT = [
'closeFile',
'copy',
'getInfo',
'getSizeOnDisk',
'getLinkCount',
'link',
'list',
'mkdir',
'openFile',
@@ -66,9 +52,7 @@ const WITH_RETRY = {
_closeFile: {},
_copy: {},
_getInfo: {},
_getLinkCount: {},
_getSize: {},
_link: {},
_list: {},
_mkdir: {},
_openFile: {},
@@ -94,9 +78,7 @@ const WITH_TIMEOUT = [
'_closeFile',
'_createReadStream',
'_getInfo',
'_getLinkCount',
'_getSize',
'_link',
'_list',
'_rename',
'_copy',
@@ -141,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))
}
@@ -166,15 +144,6 @@ export default class RemoteHandlerAbstract {
return this.#rawEncryptor
}
getConfig(key) {
const value = this._remote[key]
if (value === undefined && key === 'diskFormat') {
// handle legacy
return this._remote.useVhdDirectory ? 'vhdDirectory' : 'vhd'
}
return value ?? CONFIG_DEFAULTS[key]
}
constructor(remote, options = {}) {
if (remote.url === 'test://') {
this._remote = remote
@@ -196,19 +165,7 @@ export default class RemoteHandlerAbstract {
}
_conditionRetry(error) {
return ![
'EEXIST',
'EISDIR',
'EMLINK',
'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) {
@@ -266,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) {
@@ -384,36 +341,10 @@ export default class RemoteHandlerAbstract {
return this.getSizeOnDisk(file)
}
async __getLinkCount(file) {
return this._getLinkCount(normalizePath(file)).catch(error => {
if (error.code === 'ENOENT') {
return 0
}
throw error
})
}
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)
@@ -672,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 } = {}) {
@@ -690,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
@@ -710,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 } = {}) {
@@ -744,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 }) {
@@ -782,7 +711,7 @@ export default class RemoteHandlerAbstract {
}
_read(file, buffer, position) {
throw new NotImplementedError()
throw new Error('Not implemented')
}
_readFile(file, options) {
@@ -790,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) {
@@ -837,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) {
@@ -855,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,47 +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')
})
it('defaults diskFormat to vhd when the remote does not set it', () => {
assert.equal(new TestHandler().getConfig('diskFormat'), 'vhd')
})
it('defaults useVhdDirectory is undefined', () => {
assert.equal(new TestHandler().getConfig('useVhdDirectory'), undefined)
})
it('reads the remote-level diskFormat', () => {
assert.equal(new TestHandler({ diskFormat: 'hbd' }).getConfig('diskFormat'), 'hbd')
})
})
describe('getInfo()', () => {
it('throws in case of timeout', async () => {
const testHandler = new TestHandler()
@@ -266,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 === 'diskFormat') {
return 'vhdDirectory'
}
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

@@ -1,41 +0,0 @@
import { describe, it } from 'node:test'
import { strict as assert } from 'assert'
import { getHandler } from '.'
// building a handler does not connect: these only read the parsed remote URL
const diskFormatOf = url => getHandler({ url }).getConfig('diskFormat')
const AZURE_KEY = Buffer.from('key').toString('base64')
describe('getConfig("diskFormat")', () => {
describe('file', () => {
it('defaults to vhd', () => {
assert.equal(diskFormatOf('file:///backups'), 'vhd')
})
it('reads a legacy useVhdDirectory remote as vhdDirectory', () => {
assert.equal(diskFormatOf('file:///backups?useVhdDirectory=true'), 'vhdDirectory')
})
it('reads the diskFormat option', () => {
assert.equal(diskFormatOf('file:///backups?diskFormat=%22hbd%22'), 'hbd')
})
})
// object storage only holds VHD directories, whatever the URL says
describe('s3', () => {
it('is always vhdDirectory', () => {
assert.equal(diskFormatOf('s3://user:pass@s3.example.org/bucket/dir'), 'vhdDirectory')
assert.equal(diskFormatOf('s3://user:pass@s3.example.org/bucket/dir?diskFormat=%22hbd%22'), 'vhdDirectory')
})
})
describe('azure', () => {
it('is always vhdDirectory', () => {
const url = `azure://account:${AZURE_KEY}@account.blob.core.windows.net/container/dir`
assert.equal(diskFormatOf(url), 'vhdDirectory')
assert.equal(diskFormatOf(`${url}?diskFormat=%22hbd%22`), 'vhdDirectory')
})
})
})

View File

@@ -110,30 +110,6 @@ handlers.forEach(url => {
})
})
// no hard links on object storage
describe('#getLinkCount()', () => {
it('counts one link for a plain file', { skip: skipFsNotInAzure() }, async () => {
await handler.outputFile('file', TEST_DATA)
assert.equal(await handler.getLinkCount('file'), 1)
})
it('counts every name sharing the file', { skip: skipFsNotInAzure() }, async () => {
await handler.outputFile('file', TEST_DATA)
await handler.link('file', 'dir/other')
assert.equal(await handler.getLinkCount('file'), 2)
assert.equal(await handler.getLinkCount('dir/other'), 2)
})
it('returns 0 for a missing file, like after its last unlink', { skip: skipFsNotInAzure() }, async () => {
assert.equal(await handler.getLinkCount('missing'), 0)
await handler.outputFile('file', TEST_DATA)
await handler.unlink('file')
assert.equal(await handler.getLinkCount('file'), 0)
})
})
describe('#list()', () => {
it(`should list the content of folder`, async () => {
await handler.outputFile('file', TEST_DATA)

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'

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