Compare commits

..

189 Commits

Author SHA1 Message Date
ayoublkj
f093a5f2fc fix out-of-range block access in BlockAllocationTable.isEmpty 2026-11-02 16:55:15 +01:00
Pierre Brunet
8ae04ff682 chore: small doc for developpers 2026-10-16 11:16:22 +02:00
Pierre Brunet
14cd0ab194 feat: new scan-store command in disk-cli 2026-10-16 11:16:02 +02:00
Pierre Brunet
6e0fcee851 feat: update test 2026-10-16 11:15:26 +02:00
Pierre Brunet
5864611d1d fix: explicit error with path when decodeBlock get an error 2026-10-16 11:15:07 +02:00
Pierre Brunet
cef045ce5c feat: add qa tests 2026-10-16 10:46:49 +02:00
Pierre Brunet
9153119721 feat: test, test and retest 2026-10-16 10:36:38 +02:00
Pierre Brunet
bc14329527 feat: new HashedDiskChain, add several method to be compatible with openDiskChain 2026-10-16 10:30:53 +02:00
Pierre Brunet
21cd3210aa fix: eslintrc for CI 2026-10-16 10:29:47 +02:00
Pierre Brunet
471b6dc9ce feat: new class RemoteDiskChain and derive to RemoteVhdDiskChain 2026-10-16 10:20:49 +02:00
Pierre Brunet
829ae36060 feat: add tests 2026-10-16 09:59:48 +02:00
Pierre Brunet
10f9ac3abc fix: vhd and hbd can no longer be mixed 2026-10-16 09:59:31 +02:00
Pierre Brunet
05c3950a0a feat: update isMergeableParent and add it to hbd disk 2026-10-16 09:56:08 +02:00
Pierre Brunet
b79be832e6 feat: add writeHbd and fix imports 2026-10-15 17:23:19 +02:00
Pierre Brunet
603a5af87c feat: update getVhdFileName to getDiskFileName and writeVhd to writeDisk 2026-10-15 16:57:48 +02:00
Pierre Brunet
71022570f4 feat: instantiate vhd and hbd disks in disks 2026-10-15 16:56:51 +02:00
Pierre Brunet
688212dfb0 fixup! feat(fs): use diskFormat for vhdDirectory 2026-10-15 16:45:49 +02:00
Pierre Brunet
6641e721ee feat: blockStorePath is now a constant 2026-10-15 16:45:02 +02:00
Pierre Brunet
36e39fda86 feat(fs): use diskFormat for vhdDirectory 2026-10-15 16:39:57 +02:00
Pierre Brunet
fe9b39350a feat: add payload_length in header 2026-10-15 11:00:56 +02:00
Pierre Brunet
def5d43906 fix: Flo's comments 2026-10-15 11:00:56 +02:00
Pierre Brunet
9f21a1ecb2 feat: scrubbing during backup and verify during scanBlockStore 2026-10-15 11:00:56 +02:00
Pierre Brunet
1b8660f322 fix: wrong typing in fs 2026-10-15 10:57:56 +02:00
Pierre Brunet
3498d82c89 fix: protect unlink in addBlockReference 2026-10-15 10:57:25 +02:00
Pierre Brunet
bd213abee0 feat: remove hash dir if there are no links anymore 2026-10-15 10:57:25 +02:00
Pierre Brunet
f43c417a8d fix: replace loop by asyncEach 2026-10-15 10:57:25 +02:00
Pierre Brunet
7cb855de9a feat: log for unlink and getLinkCount only if error not ENOENT 2026-10-15 10:57:25 +02:00
Pierre Brunet
9b06dcc16a fix: replace hash split path by <ab>/<cd>/<hash> 2026-10-15 10:57:25 +02:00
Pierre Brunet
725a535d17 fix: use logDebug instead of logInfo in scan and do not rmdir after cleanup 2026-10-15 10:57:25 +02:00
Pierre Brunet
2a2a2959e9 fix: add tmpDir getter to avoid different versions 2026-10-15 10:57:25 +02:00
Pierre Brunet
31c97be353 feat: EMLINK error and implementation of copy paths 2026-10-15 10:57:25 +02:00
Pierre Brunet
319884327e feat: add checkAndClean and scanBlockStore (for maintenance) 2026-10-15 10:57:25 +02:00
Pierre Brunet
18e8077302 fix: remove comment done 2026-10-15 10:55:56 +02:00
Pierre Brunet
d893058ade fix: reordering only, for better reading 2026-10-15 10:55:56 +02:00
Pierre Brunet
a1c94c23dc feat: use sameAt where possible 2026-10-15 10:53:21 +02:00
Pierre Brunet
00d60f9fe6 fix: remove releaseChildReferences handled by MergeRemoteDisk.removeUnused and refactor removeOrphans to use hashEntrySet 2026-10-15 10:53:21 +02:00
Pierre Brunet
02636f9e1b fix: update types in fs 2026-10-15 10:53:21 +02:00
Pierre Brunet
5b081feb60 feat: add new class HashEntrySet to handle mem-saving keys 2026-10-15 10:53:21 +02:00
Pierre Brunet
4d0135ccb5 feat: add comparison methods and static readChunks 2026-10-15 10:53:21 +02:00
Pierre Brunet
a65e9ea41b fix(bat): better isEmpty 2026-10-15 10:53:21 +02:00
Pierre Brunet
98ffc8731c feat: add integ tests for merge 2026-10-15 10:53:21 +02:00
Pierre Brunet
69676b40fd feat: add rename method 2026-10-15 10:53:21 +02:00
Pierre Brunet
3efbf37743 feat: add merge step and tests 2026-10-15 10:53:21 +02:00
Pierre Brunet
d405391eae fix: rename replacedHashes to orphanHashes for better understanding 2026-10-15 10:53:21 +02:00
Pierre Brunet
c5dd87bb35 feat: new resize method 2026-10-15 10:53:21 +02:00
Pierre Brunet
f50985e775 fix: update dataDir init to be created from path and not from uuid as a disk can change of uuid with merge 2026-10-15 10:53:21 +02:00
Pierre Brunet
f785fd19fe fix: use NotImplementedError 2026-10-09 10:24:24 +02:00
Pierre Brunet
32d582ae8f feat: add skipStoreCheck option 2026-10-01 14:38:07 +02:00
Pierre Brunet
3a8de6ac2e feat: handle orphan and replaced hashes to clean 2026-10-01 14:38:07 +02:00
Pierre Brunet
d10411236e feat: add getLinkCount in fs to use it in hashedDisks 2026-10-01 14:38:07 +02:00
Pierre Brunet
007d7356fc fix: use NotImplementedError in tests 2026-10-01 14:37:49 +02:00
Pierre Brunet
a766292fbe fix: add error 2026-09-30 17:22:28 +02:00
Pierre Brunet
1b8c2d0f7b fix(fs): add export and tests 2026-09-30 16:13:08 +02:00
Pierre Brunet
b95a508e1b feat: new tests for flushMetadata 2026-09-30 15:40:28 +02:00
Pierre Brunet
661b8dd9a4 feat(fs): new NotImplementedError 2026-09-30 15:40:08 +02:00
Pierre Brunet
5f98708d50 fix: florent's comments 2026-09-30 15:17:26 +02:00
Pierre Brunet
bb9fac64c0 fix: use pRetry instead of manual loop 2026-09-30 11:53:15 +02:00
Pierre Brunet
cf7d9bf2d3 feat: add tests 2026-09-29 15:50:22 +02:00
Pierre Brunet
aa43ba637e feat: replace storeBlock by addBlockReference 2026-09-29 15:43:49 +02:00
Pierre Brunet
b08f4815cf feat(@xen-orchestra/fs): add new method link() 2026-09-29 11:41:20 +02:00
Pierre Brunet
97d816e8e9 fix: Florent's comments 2026-09-23 16:08:03 +02:00
Pierre Brunet
51d8323265 fix: outputStream for metadata 2026-09-22 16:02:35 +02:00
Pierre Brunet
d17877913a fix: protect paths with #resolve() guard 2026-09-22 15:34:51 +02:00
Pierre Brunet
8afc462a0e fix: create new metadata instead of updating it 2026-09-16 17:20:09 +02:00
Pierre Brunet
28ac84ee4e fix: getMetadata returns now a copy 2026-09-16 17:15:40 +02:00
Pierre Brunet
1ba2a6532f fix: allow dependency patch 2026-09-16 17:10:44 +02:00
Pierre Brunet
2090bf3b41 fix(fs): readFile always return a Promise<Buffer> 2026-09-16 17:09:11 +02:00
Pierre Brunet
4415cbe442 fix: add paths to new HbdFileError 2026-09-16 16:56:49 +02:00
Pierre Brunet
0756af85f1 chore: update comment 2026-09-16 16:29:07 +02:00
Pierre Brunet
2f59184ff1 fix from Florent's comments 2026-09-16 16:17:39 +02:00
Pierre Brunet
cefb48edd9 chore: update dependencies 2026-09-16 15:00:04 +02:00
Pierre Brunet
10f42de713 fix(fs/backups): update isInDir and move it to fs/path 2026-09-16 14:44:04 +02:00
Pierre Brunet
949d5315db chore: update yarn.lock 2026-09-16 14:40:57 +02:00
Pierre Brunet
e80bb9c362 feat: add methods for dedup 2026-09-16 14:35:23 +02:00
Pierre Brunet
291ea94197 feat: add methods to handle and read blocks 2026-09-16 11:24:47 +02:00
spacotte-vates
ea2acac77b fix(backups): don't destroy the delta base after failed transfer (#10369)
XO-2994

Customer reported that after a failed replication transfer, the next run was a full and a VM was left orphaned on the target.

This is due to _removeUnusedSnapshots() protecting the last snapshot irrelevant of if it was successfully transferred and thus, in the case of a failed transfer, breaking the delta chain
2026-09-16 10:53:02 +02:00
Pierre Brunet
14b7115cf1 fix(openmetrics): share metrics collection on slow pools (#10401) 2026-09-16 10:19:42 +02:00
MlssFrncJrg
d0645598b9 feat(xo-server/proxy): check proxy licenses from XOA instead of blocking backups on it (#10280)
XO-2768
2026-09-15 20:42:18 +02:00
Thomas Moraine
83b2fd9056 docs(releases.md): document security support (#10379)
Document which Xen Orchestra versions receive security fixes
in the actual XO doc, not just in SECURITY.md.

Signed-off-by: Thomas Moraine <thomas.moraine@vates.tech>
2026-09-15 17:13:13 +02:00
Florent BEAUCHAMP
0c04076324 feat(v2v): use CBT to discover allocated blocks instead of vddk (#10384)
Faster (25 GiB test VM: the map goes from 2.5s to 50ms) and fewer moving
parts: the vddk map needs nbdkit, the vddk library and nbdinfo, all
version-coupled, where CBT is a handful of documented calls every backup
product has relied on for years.

Checked on ESXi 8.0.1 that enabling CBT on a disk which already holds data
backfills the tracking file, so the first query reports what was already
written and not only what is written afterwards. Against `nbdinfo --map` the
two maps differ by 960 KiB which reads back as zeros: CBT reports the blocks
that were written where the vddk reports the ones VMFS allocated.

CBT must be enabled before the migration, it cannot usefully be turned on
during the run:
- powered off VM: nothing else to do, the reconfigure writes the tracking
  file and the query answers straight away
- running VM: the query needs a snapshot, and tracking only starts at the
  next stun (snapshot create/delete, power cycle, vMotion)
2026-09-15 16:47:03 +02:00
spacotte-vates
c37c4a286d fix(xo-server): fix cache issue on vmBackupOnRemote (#10277) 2026-09-15 15:56:09 +02:00
Mathieu Lantin
21d99ee856 fix(xo-server-netbox): use numeric comparison to find the most specific prefix (#10297)
Fixes #10240
2026-09-15 14:59:32 +02:00
Bastien Nollet
fec5508ce8 chore(xo-server): remove unused files (#10397) 2026-09-15 14:46:00 +02:00
Florent BEAUCHAMP
f55c77a11a Feat: check changed packages list in CI (#10392) 2026-09-15 11:17:58 +02:00
Pierre Brunet
76225348fa fix: add error when encryption key removed from url (#10339) 2026-09-15 11:10:43 +02:00
Marie Garde
67327eb791 feat(xo6): add disabled icon host (#10188) 2026-09-15 11:09:03 +02:00
Pierre Brunet
e87f4555dd fix(backups): validate data on alias to vhd, not directly on alias (#10393) 2026-09-15 09:53:41 +02:00
vates-bot
3d0ba7ca34 feat(web-stack/i18n): update Xen Orchestra 6 (#10316) 2026-09-14 13:32:06 +02:00
Mathieu
9f337ace71 feat(xo-server,rest-api,xo-web/rpu): persist a recovery record across restarts (#10331)
* feat(xo-server,rest-api,xo-web/rpu): persist a recovery record across restarts

A rolling pool update now writes a `rpuRecovery` record (LevelDB, one per
pool) before its first side effect and keeps it updated during the run:
operator options, update variant, host order, initial VM placement, per-host
step statuses, last filtered error, and the pinned VMs shut down for their
host's reboot (previously only tracked in memory, so an xo-server crash left
them halted with nothing to restart them). A record left in a live status at
xo-server boot is flipped to `interrupted`; a successful run deletes its
record; an unreadable or unknown-version record is reported as `blocked`
without touching the stored value.

The status is exposed through `pool.getRollingUpdateRecovery` and
`GET /rest/v0/pools/{id}/rolling_update_recovery` (filtered view: never the
raw intent, reusing the existing pool permissions), and the pool Patches tab
in XO5 shows a warning with per-host progress, the last error and the pinned
VMs still halted.

First card of the RPU resume-after-failure spike: the record only reports
for now, resuming an interrupted run comes separately.

* docs(changelog): entry for the RPU recovery record (#10331)

* fix(xo-server,rest-api,xo-web/rpu): updates after review

* test(xo-server/rpu): cover the recovery record during the migrate back phase

The migrate back phase now retries the rejected migrations before giving
up, so a host is only recorded as failed once the retry passes are over,
and a pool which opted out of the phase must still close its `restoreVms`
steps, otherwise a finished run reads as still running in the record.

Both are asserted through a recorder spying on the step transitions.

* fix(xo-server/rpu): keep per-key reads in the recovery reconciliation

* test(xo-server/rpu): stub the recovery recorder in the rolling pool update tests

Since #10313, XenServers.rollingPoolUpdate runs the backup guard itself and
its tests drive it with a fake app. With the recovery record, the run also
calls app.startRpuRecoveryRun, which the fake app did not have.

The stub records its call, so the tests also check that a refusal from the
backup guard leaves no record behind.

* fix(xo-server/rpu): do not fail a successful run when its record cannot be deleted
2026-09-14 12:09:15 +02:00
Thomas Moraine
3b08f236a4 docs(xo): fix redirections (#10387)
* docs(docusaurus.config.ts): fix redirection inconsistencies

A few page redirections were missing, some were duplicates, and some pointed to the wrong URLs.

This commit cleans up redirections, updates the target URLs and adds the missing redirections.
2026-09-14 09:42:26 +02:00
Florent BEAUCHAMP
99312eca2b docs(backups): document object lock (#10373)
* docs(backups): document object lock
2026-09-11 17:47:47 +02:00
Florent BEAUCHAMP
3bf50c38ee fix(vmware-explorer): fixes omnibus (#10363)
This branch is a reliability overhaul of the ESXi/vSphere source side of V2V, plus a scope reduction of the package. The SOAP plumbing is rewritten:

    VimClient wraps @vates/node-vsphere-soap in a promise API with one emitter per call (no more cross-talk between concurrent calls, no listener leak) and a pTimeout;
    vim25 faults are now parsed (_parseFault.mjs) so callers get a real fault type instead of task execution failed;
    the library no longer throws from async callbacks (which killed xo-server) and its beforeExit logout hook is per-client instead of removeAllListeners.
    Request specs are built in explicit schema order (soap/specs.mjs) with xsi:type, and property values are normalized (soap/normalize.mjs) so search() and the new #retrieveProperty share one shape.
    search() now paginates, cancels the retrieval and destroys the container view.
    Datastore HTTP downloads get session-cookie reuse, retry with jittered backoff, a headers-only timeout, and range-honouring validation.
    Task waiting polls with backoff and per-operation timeouts (6 h for snapshot consolidation).
    nbdkit servers are memoized by a key that includes the export options, the readiness wait races the process death instead of sleeping 2 s
    the password file is 0600 and unlinked
    the thumbprint is read over TLS in-process instead of two openssl spawns.
    The old VHD-over-datastore readers (VhdEsxi*, Datastore*, openDeltaVmdkAsVhd) are deleted, hence the majo, rleaving the vddk/NBD path with a COWD grain-directory parser as data-map fallback.
    ~1.7k lines of unit tests are added.
2026-09-11 17:36:38 +02:00
Mathieu
ebbd9e42e2 fix(xo-server,rest-api): apply the backup guard to rolling pool operations started over REST (#10313)
* fix(xo-server,rest-api): apply the backup guard to rolling pool operations started over REST

The JSON-RPC methods pool.rollingUpdate and pool.rollingReboot refused to run
while a backup job targets the pool, but the REST actions
POST /pools/:id/actions/rolling_update and rolling_reboot called the
orchestrators directly and skipped that check.

The guard now lives in XenServers.rollingPoolUpdate and Pools.rollingPoolReboot,
so every entry point (JSON-RPC, REST, scheduled jobs) applies the same rule.
The bypass moves into backupGuard(poolId, { bypassBackupCheck, operation }),
which logs a single warning with the operation and the user, and the other
callers (host.restart, host.restartAgent, host.stop, sr.reclaimSpace and their
REST counterparts) use it instead of their own if/else and log.

The REST rolling actions accept bypassBackupCheck in their body and record the
body in the task params, like the host actions do.

* fix(xo-server,rest-api): pass the targeted object ID to the backup guard
2026-09-11 16:49:14 +02:00
Pierre Brunet
f9049754b4 fix(plugin/ldap): fix changelog (#10383) 2026-09-11 15:37:08 +02:00
Mathieu
b61e0dacba fix(xo-server): destroy proxied request when the client is gone (#10388)
Introduced by 9470349
2026-09-11 15:13:46 +02:00
Grandalf
df7b62654c feat(rest-api): migrate functions to registerRestRoutes (#9895) 2026-09-11 15:06:16 +02:00
Pierre Brunet
adecd7306e feat(backups): replace vhd-lib calls with abstract methods (#10124)
* feat: add setChainToParent in order to point header/footer to a new parent

* feat: add getCompressionType and use it in isMergeableParent in RemoteAdapter

* feat: use openDisposableDisk instead of openVhd

* fixup! feat: add setChainToParent in order to point header/footer to a new parent

* feat: add tests for setChainToParent

* fix: from review

* feat: make isMergeableParent contained in remoteDisk

* fix: remove chainToParent now useless

* feat: remove compressionType and isMergeableParent where unneeded

* feat: update test

* feat: handle compressionType in remoteAdapter and fs

* fix: use remoteHandler as config getter

* feat: remove useless isDirectory in remoteDisk

* fix: small change on mode option
2026-09-11 11:42:51 +02:00
Florent BEAUCHAMP
595687dabe docs(backups): precise the prerequisite for NBD (#10377)
* docs(backups): precise the prerequisite for NBD
Co-authored-by: Thomas Moraine <thomas.moraine@vates.tech>
Co-authored-by: Florent BEAUCHAMP <florent.beauchamp@gmail.com>

---------

Co-authored-by: Thomas Moraine <thomas.moraine@vates.tech>
2026-09-11 10:02:11 +02:00
Thomas Moraine
79118de1ad docs(xo): add redirections following doc url changes (#10385)
* docs(xo): add page redirections

Since we changed how the sidebar was generated,
many page URLs changed in the process,
but redirections weren't implemented yet.
This broke several links to the documentation.
This commit adds redirections so the links don't result in 404 errors anymore.

Signed-off-by: Thomas Moraine <thomas.moraine@vates.tech>

* docs(xo): update outdated URLs in the XO app

Following the recent overhaul of the documentation URLs, some links in the XO app were still pointing to obsolete pages.

This commit updates them to use the current URLs and prevents 404 errors.

Signed-off-by: Thomas Moraine <thomas.moraine@vates.tech>

* docs(intro.md): update link to V2V migration guide

Signed-off-by: Thomas Moraine <thomas.moraine@vates.tech>

---------

Signed-off-by: Thomas Moraine <thomas.moraine@vates.tech>
2026-09-11 09:57:39 +02:00
Thomas Moraine
12d77efe17 docs(xo): fix broken links in the xo app (#10382)
Since the XO documentation structure was changed recently,
so did the URLs to each documentation pages.
This broke multiple links in the XO app,
which pointed to the XO doc.

This commit updates the links to the current URLs,
so that the link work as intended.

Signed-off-by: Thomas Moraine <thomas.moraine@vates.tech>
2026-09-11 07:46:42 +02:00
MathieuRA
280c05ac48 feat(rest-api/SSE): SSE support now XO objects changes 2026-09-10 16:41:55 +02:00
MathieuRA
d13fad62bd fix(rest-api): use previousObj instead of object for message SSE events 2026-09-10 16:41:55 +02:00
MathieuRA
e0fb16a421 feat(xo-server): server status become a persistant property 2026-09-10 16:41:55 +02:00
Florent BEAUCHAMP
db8fe8d472 feat(rest-api): export vdi and vdi snapshot content as qcow2 + vdi export fixes (#10350) 2026-09-10 14:38:47 +02:00
Grandalf
2aa3bd602e feat/backups/journal log (#10256)
* fix fbeauchamp comments

* feat(backups): add a journal

* fix cache writing on immutable remotes

* add typing

* feat(backups): shard the journal per UTC day, one entry per time

`readBackupJournal()` listed the whole `xo-backup-log/` and filtered the names
client-side, so the cost of a read grew with the whole history of the repository.

Store the entries as `/xo-backup-log/<YYYYMMDD>/<HHMMSS.mmmZ>-<rand>-<event>-<vmUuid>-<file>`
and list only the days which can hold entries newer than `since`: a read now costs one
listing of the journal root plus one listing per day it is missing — normally a single
day, at most two, since a reader rebuilds from scratch when its watermark crosses a UTC
day. Purging old entries also becomes a directory removal instead of a per-object sweep.

The day is not repeated in the entry name, so `since` bounds the time of its own day
only; every later day is taken whole.

* fix pipeline

---------

Co-authored-by: All-Ki <killian.allegrain@vates.tech>
2026-09-10 14:26:41 +02:00
Florent BEAUCHAMP
b32fd39c19 fix(qcow2): improve qcow2 stream index computation (used for backup/replication and export) (#10333)
* feat(qcow2): improve generation speed

the idea is to build a bit index of the clusters to store them efficiently instead
of going through all the possible blocks 3 times at different phases of the generation.
The memory consumption is 2MB/TB of disk

this index generation can still be quite long , so we use setImmediate from
time to time to le the rest of the nodejs event loop run

also make this index phase abortable
2026-09-10 13:49:32 +02:00
Thomas Moraine
0115680129 doc(restapi.md): document maximum token validity (#10347) 2026-09-09 15:22:57 +02:00
Dan Pollak
e50f033361 fix(xo-server): correct spelling of "across" in migration logic and messages (#10372) 2026-09-09 14:21:10 +02:00
OlivierFL
5cf93b3c3c feat(web-core/tab-item): update UiTabItem component to v7 (#10338) 2026-09-09 12:39:43 +02:00
Mathieu
505ac6caf5 fix(xo-server): keep localhost proxy targets on wildcard binds (#10335)
* fix(xo-server): keep localhost proxy targets on wildcard binds

Since 82f047ef9 (#9572), [http.proxies] targets pointing at localhost are
rewritten to the hostname of the HTTPS listen config. With the default XOA
config (hostname = '0.0.0.0') this produced targets such as
http://0.0.0.0:9004/metrics and, worse, routed these internal requests
through the proxy-aware HTTP agent: with an httpProxy configured,
/openmetrics scrapes left the appliance for the corporate proxy and were
denied there.

Only rewrite when the bind address is a specific one (the #9500 case, where
localhost is not reachable) and pick the agent from the original target
locality, so requests to the machine itself never go through the HTTP proxy.

Seen in support ticket 7763112.

* chore(CHANGELOG.unreleased): entry for #10335

* chore(CHANGELOG.unreleased): clarify localhost targets always bypass the HTTP proxy
2026-09-09 12:00:54 +02:00
OlivierFL
e428304aea feat(xo6/web-core): implement tests on frontend (#10012) 2026-09-09 11:48:41 +02:00
Pierre Brunet
11eed70342 fix(xen-api): update undici to prevent timeout error (#10282) 2026-09-09 11:16:07 +02:00
Sandrine Barrucand
699d78b1ca fix(web-stack): use correct color for no-data stars (#10327) 2026-09-09 10:43:09 +02:00
Pierre Donias
43f81f87e3 feat(xo-web/vm/tab-backups): open edit form in same tab (#10342)
Opening the form in a new tab reloaded the whole app, so every object
was fetched again from scratch. Until that fetch finished, the form
could not be properly auto-filled. Navigating in the same tab reuses
the already loaded objects, so the form is populated right away.
2026-09-08 16:38:00 +02:00
Dan Pollak
77d07cf4ac Docs: Fix typo (#10362) 2026-09-08 15:43:02 +02:00
ayoub-el-kajji-v
dc107da91a fix(xo-server): change current_operations display for xo host and poo… (#10283) 2026-09-08 14:54:24 +02:00
Thomas Moraine
c9391b075e docs(xo): fix wrong page order and restore missing external links (#10370)
docs(xo): fix wrong page order and restore missing links

After ve changed how the sidebar
was generated (from manual declarations to automatic generation)
Some pages went out of order and didn't
have the proper sidebar title.
This commit fixes that.
Also, the external links in the sidebar disappeared.
We can't add them in an auto-generated sidebar, so we circumvent
that by creating dedicated pages for external resources
and re-adding the links there.

Signed-off-by: Thomas Moraine <thomas.moraine@vates.tech>
2026-09-08 14:33:29 +02:00
Mathieu
91d0f0fbcb feat(xo-server): make the RPU/RPR migrate back phase reliable and optional (#10295)
Fixes #10260.
Introduced by #7242.
Takes over #10274.
2026-09-08 12:00:33 +02:00
Thomas Moraine
f99d7ab761 doc(xo): sidebar refactor (#10354)
We now generate the sidebar automatically (based on the documentation folder structure and _category.json files), instead of declaring the doc structure manually in sidebars.ts.
Simpler management

This makes the sidebar easier to understand and maintain. It is now managed the exact same way as the sidebars for the Vates VMS and XCP-ng documentations.
Clickable breadcrumbs

The autogenerated sidebar also creates category index pages, which makes breadcrumb categories clickable, as they already are in the Vates VMS and XCP-ng documentations.
Preview
Capture d'écran 2026-09-08 094848
Unlisted pages

Pages that should remain accessible but be hidden from the sidebar are now hidden using the unlisted: true metadata, instead of simply being omitted from sidebars.ts.
Internal links and redirection

Finally, the PR updates internal links and redirects to reflect the new folder structure and URLs.
2026-09-08 11:40:01 +02:00
Florent BEAUCHAMP
e58587aa1d fix(xo-server): auto reconnection infinite loop when pool is already connectd (#10355)
* don't rearm after a fatal error before connection setting changed ( does not affect the normal route on non fatal error like newtork issue)
* serialize error correctly in database to ensure the "avoid a database write per auto-reconnect" corectly trigger
a lot of more cleanup to ensure that the connection is really dropped even if the host changed its id
* fix a mishnalding in the grace period before marking a pool disconnected . this will keep the ui in sync AND not redownload all the xapi object for a transient issue
* fix an error transmitted as raw, so the user was only seeing {}
2026-09-08 11:25:51 +02:00
Grandalf
067aba2bfc feat(backups): add a cache guard and migrate required to backup-archive (#10243)
[XO-2789]
* Extracts the backup migration logic into backup-archive and adds a cache guard for future performance improvements
* don't generate or read cache file on immutable backup repository
* clean cache file on immutable backup repository
2026-09-08 11:11:47 +02:00
Sandrine Barrucand
bbeb67092e fix(web-stack): use correct color for 404 (#10325) 2026-09-08 10:15:14 +02:00
Alina D
a974448339 feat(xo6): add the VM name to actions that open a modal (#10310) 2026-09-08 10:11:09 +02:00
amouillard-vates
069bb79d4a feat(xo6): sr dedicated page hosts tab (#10140)
* Update CHANGELOG.unreleased.md

* Hosts tab

* Hosts side panel

* Update CHANGELOG.unreleased.md

* Route + fix import

* The dev routes

* Simplify SrHeader

* Refactoring

* Fix type

* locale

* Simplify pbd connection status

* Refactor srs get

* New import rules

* Fixes

* Singular locale

* Refactor + sr status

* Push generated routes

* Switch order

* PR Fixes

* Comment fixes

* Changelog packages

* Cleanup changelog

* Keep unreleased
2026-09-08 10:04:07 +02:00
Sandrine Barrucand
ead446fcdb fix(web-stack): use correct color for console offline SVG sparks (#10309) 2026-09-07 17:40:44 +02:00
Sandrine Barrucand
03865bc5fe feat(xo6/host): reconfigure the management interface to another PIF (#10110) 2026-09-04 14:20:23 +02:00
Elise-F
35e8c513d8 feat(lite): add action reboot on host (#10250)
* feat(host): add action reboot on host

* update changelog file

* fix missing ts extension and clean code

* add header state

* feedback one
2026-09-04 14:20:02 +02:00
Florent BEAUCHAMP
00943b92e7 docs(xo-server): rest api guidelines (#10071)
improve the xo guidelines
2026-09-04 13:36:45 +02:00
Bastien Nollet
4416d55d7a feat: release 6.8.2 (#10360) 2026-09-04 12:00:25 +02:00
Bastien Nollet
9f72a1f900 feat: technical release (#10358)
* feat(@xen-orchestra/proxy): 0.31.10

* feat(xo-server): 5.208.3

* chore(CHANGELOG): update next
2026-09-04 11:20:47 +02:00
Florent BEAUCHAMP
003cc6f9cc fix(proxy): fetch failed (#10346)
* fix(backups): fetch failed

disable compresion between xoa on proxy on xoa side

* fix(xo-proxy): disable compression on the proxy

it was disable with hrp, replaced by #10038 since it was never
sending accept-encoding header

compression can be put back later on a route by route basis after
careful checks ( for example : file restore, backup listing )
2026-09-03 12:56:36 +02:00
Bastien Nollet
bca8f02b8a feat: release 6.8.1 (#10341) 2026-09-02 11:18:21 +02:00
Bastien Nollet
7a18762da4 feat: technical release (#10334)
* feat(@xen-orchestra/xapi): 8.10.5

* feat(@xen-orchestra/backups): 0.74.2

* feat(@xen-orchestra/proxy): 0.31.9

* feat(xo-server): 5.208.2

* chore(CHANGELOG): update next
2026-09-01 16:26:11 +02:00
Florent BEAUCHAMP
1004edb51f fix(backups): failing replication of qcow2 disks (#10319)
* fix(backups):  task label NBT->NBD

* fix: still force a list block only call for NBD + stream scenario , that was failing to transfer disk on fallback
2026-09-01 15:28:47 +02:00
Marie Garde
a67dd73304 feat(xo6/traffic rule): edit a traffic rule (#10056) 2026-09-01 11:22:03 +02:00
Mathieu
a2ce3bbc48 fix(@xen-orchestra/qa-test): downgrade engine to 22 to avoid build issue (#10323)
* fix(@xen-orchestra/qa-test): downgrade engine to 22 to avoid build issue

* fix >=
2026-09-01 09:14:56 +02:00
Bastien Nollet
3034955277 feat(lite): 0.25.0 (#10329) 2026-08-31 18:37:24 +02:00
Bastien Nollet
faf6745471 feat: release 6.8 (#10328) 2026-08-31 17:59:40 +02:00
Bastien Nollet
7e022940c3 feat: technical release (#10326)
* feat(@vates/types): 2.0.1

* feat(@xen-orchestra/web): 0.60.1

* feat(xo-server): 5.208.1

* chore(CHANGELOG): update next
2026-08-31 15:55:42 +02:00
Bastien Nollet
b33894c067 feat : technical release (#10322)
* feat(@xen-orchestra/web): 0.60.0

* feat(xo-server): 5.208.0

* feat(xo-server-openmetrics): 1.9.2

* feat(xo-web): 5.203.0

* chore(CHANGELOG): update next
2026-08-31 15:15:41 +02:00
Mathieu
2fba0ff4df fix(openmetrics): keep the Prometheus secret across xo-server restarts (#10290)
* fix(openmetrics): keep the Prometheus secret across xo-server restarts

The `secret` property of `configurationSchema` used a random `default`. That
expression is re-evaluated every time the module is loaded, and xo-server never
persists the values ajv fills in from schema defaults, so each restart handed
the metrics endpoint a brand new bearer token and Prometheus started getting
401s.

Drop the default and generate the secret in `load()` instead, saving it through
`xo.configurePlugin()` so it survives a restart.

Introduced by #9323
See https://xcp-ng.org/forum/topic/12415

* chore(changelog): add openmetrics secret entry

* fix(xo-server-openmetrics): generate a 256-bit Prometheus secret

Buffer.from(getRandomValues(new Uint32Array(8))) coerces each 32-bit
element to a single byte, so the generated secret held 64 bits of
entropy instead of 256. Use randomBytes(32) instead.

Introduced by fe29bd0d4
2026-08-31 13:45:02 +02:00
Pierre Donias
62cc3e3f5d feat(xo-web/new VM): allow admin to create VM in resource set (#10259) 2026-08-31 10:55:00 +02:00
Elise-F
d2d2d57c81 feat(lite): add action create internal network (#10235)
* feat(lite): add create network and network bonded actions

* remove vlan required and info message

* feedback number one

* feat(lite): add create network and network bonded actions

* feat(lite): add action create internal network

* update changelog file

* fix rebase

* feedback number one

* remove as const in cancelRoute

* feedback number two
2026-08-31 10:51:27 +02:00
Mathieu
c7bf0c59ef fix(@xen-orchestra/qa-test): fix node version (#10320) 2026-08-31 10:48:19 +02:00
Marie Garde
62013d4e79 feat(xo6): add detach host button (#10179)
* feat(xo6): rebase detach

* add redirect when detach ok

* fix post rebase

* remove dev route

* returns from MR

* add check master host

* use linked translation

* rebase ok
2026-08-31 09:03:33 +02:00
Bastien Nollet
6a4415ea1d feat: technical release (#10318)
* feat(@vates/nbd-client): 3.5.1

* feat(@vates/types): 2.0.0

* feat(@xen-orchestra/acl): 1.6.1

* feat(@xen-orchestra/backup-archive): 1.1.2

* feat(@xen-orchestra/xapi): 8.10.4

* feat(@xen-orchestra/backups): 0.74.1

* feat(@xen-orchestra/web-core): 0.60.0

* feat(@xen-orchestra/mcp): 1.4.2

* feat(@xen-orchestra/proxy): 0.31.8

* feat(@xen-orchestra/rest-api): 0.39.0

* feat(@xen-orchestra/web): 0.59.0

* feat(xo-server): 5.207.4

* feat(xo-server-ipmi-sensors): 2.1.1

* feat(xo-server-openmetrics): 1.9.1

* feat(xo-server-sdn-controller): 1.5.0

* chore(CHANGELOG): update next
2026-08-28 14:56:02 +02:00
Florent BEAUCHAMP
14e4c7d62c fix(backups): timeout NBD transfer omnibus fixes (#10306)
* fix(backups): timeout was not used correctly for NBD transfers
* fix(nbd-client): evict a dead client in multi instead
actual code was retrying 5 times, each time with a 60s timeout
multi also have its own retry on conneciton
since the client used is determnistic for a block, any stalled client
will be hammerred for a lot of time before giving up

this PR evict a nbd client that is failing to read a block (with its
retry logic)

* fix(nbd-client/multi): better spread read accross client
the actual code derivate the clientId from the block index
we have no information on the block distribution, only hopes that
it's random enough
this PR introduce a mechanism to use a round robin to select
the next client

* fix: correct fall back to full with /without nbd on qcow2
2026-08-28 10:57:17 +02:00
Marie Garde
d541af2c41 feat(xo6): add restart toolstack host button (#10178)
* feat(xo6): rebase from master

* add check restart toolstack on buttons

* add tooltip message

* Fix for PR

* remove loader

* add chengelog

* remove route map

* return form PR
2026-08-28 10:37:38 +02:00
Sandrine Barrucand
cdc4ddb652 feat(xo6/backups): add header title (#10303) 2026-08-27 11:49:53 +02:00
Joris K
2ebf18a636 feat(xo-lite): add vm tree actions and loader (#10304) 2026-08-27 10:56:34 +02:00
Grandalf
dfb4c925ec fix(sdn-controller): delete saved port on traffic rule patch (#10307) 2026-08-27 10:17:20 +02:00
Enée DI IORIO
c0d92f3061 feat(web-core): upgrade UiCheckbox component to v8 (#9777) 2026-08-27 10:12:31 +02:00
vates-bot
642dce30ef feat(web-stack/i18n): update Xen Orchestra 6 (#10181) 2026-08-27 10:11:02 +02:00
Thierry Goettelmann
970eca135e fix(@vates/types,@xen-orchestra/rest-api): remove ACL type parameters from XoRecord (#10308)
Introduced by 63d4334837
2026-08-26 18:12:53 +02:00
Bastien Nollet
9cdaf6bb41 feat: technical release (#10305)
* feat(@xen-orchestra/async-map): 0.1.4

* feat(xo-common): 0.11.0

* feat(xen-api): 4.9.0

* feat(@vates/types): 1.30.2

* feat(@xen-orchestra/acl): 1.6.0

* feat(@xen-orchestra/xapi): 8.10.3

* feat(@xen-orchestra/backups): 0.74.0

* feat(@xen-orchestra/backups-cli): 1.1.14

* feat(@xen-orchestra/disk-cli): 2.2.1

* feat(@xen-orchestra/immutable-backups): 3.0.5

* feat(@xen-orchestra/web-core): 0.59.0

* feat(@xen-orchestra/mixins): 0.20.2

* feat(@xen-orchestra/proxy): 0.31.7

* feat(@xen-orchestra/proxy-cli): 0.3.3

* feat(@xen-orchestra/qa-test): 1.2.0

* feat(@xen-orchestra/rest-api): 0.38.0

* feat(@xen-orchestra/upload-ova): 0.1.9

* feat(@xen-orchestra/web): 0.58.0

* feat(xo-acl-resolver): 0.5.4

* feat(xo-cli): 0.32.4

* feat(xo-server): 5.207.3

* feat(xo-server-audit): 0.15.2

* feat(xo-server-ipmi-sensors): 2.1.0

* feat(xo-server-netbox): 1.13.2

* feat(xo-server-sdn-controller): 1.4.1

* feat(xo-web): 5.202.0

* chore(CHANGELOG): update next
2026-08-25 16:19:35 +02:00
Florent BEAUCHAMP
9b4e1aee3e fix(xo-server): task controller leaking memory (#10237) 2026-08-25 15:42:12 +02:00
Thomas Moraine
ab7b2fc7a9 docs(xo): refine page titles and navigation structure (#10276)
* docs(xo): refine page titles and navigation structure

Make page titles clearer and more consistent with their content and
purpose. Reorder some pages (and sections) and align their sidebar labels with
their titles to make the documentation easier to navigate and
understand.

Signed-off-by: Thomas Moraine <thomas.moraine@vates.tech>

* docs(sidebars.ts): move discover xo category back to where it was

Applying the change suggested by olivierlambert.
The 'Discover Xen Orchestra' category now follows
the 'Getting started' category.
The 'architecture' page/ 'How XO 6 is organized' stays
at the end of the Getting Started category.

Signed-off-by: Thomas Moraine <thomas.moraine@vates.tech>

* docs(xo): specify navbar titles

Applying changes suggested by olivierlambert.

Some titles in the navigation bar were made too long,
in an attempt to make them identical to the titles in the corresponding doc pages.
Having different titles in the navbar and in the actual page
is not a defect, and can indeed help readers scan the
document structure quicker.
As a result, we're (re-)adding sidebar_label metadata
to specify a navbar title where the page title was too long.

Signed-off-by: Thomas Moraine <thomas.moraine@vates.tech>

* docs(xo): revert individual page renames

Applying changes suggested by olivierlambert, following,
the reasoning he explained in the pull request.

Signed-off-by: Thomas Moraine <thomas.moraine@vates.tech>

* docs(intro_support.md) change title to 'support'

Apply change suggested by olivierlambert.
'Support' instead of 'Support options' is shorter and
carries the same meaning overall.

Signed-off-by: Thomas Moraine <thomas.moraine@vates.tech>

* docs(xo): update outdated internal link labels

A few commits ago, some page titles were changed.

This did not break any internal links, but it left some link labels outdated. This commit updates those labels to match the current page titles.

Signed-off-by: Thomas Moraine <thomas.moraine@vates.tech>

* docs: convert page titles to sentence case

Applying changes suggested by olivierlambert

Some page titles were still using title case, even though we use sentence case throughout the XO documentation.

This commit updates those titles to follow the same convention.

Signed-off-by: Thomas Moraine <thomas.moraine@vates.tech>

* docs(xo): switch gerund titles to noun forms

Some page titles used gerunds (the -ing form), while others used nouns or noun phrases, resulting in an inconsistent style.

This commit changes the gerund titles to noun-based titles for consistency.

The "Troubleshooting" title is kept as-is because it is a noun, despite ending in -ing.

Signed-off-by: Thomas Moraine <thomas.moraine@vates.tech>

---------

Signed-off-by: Thomas Moraine <thomas.moraine@vates.tech>
2026-08-25 14:23:34 +02:00
Thierry Goettelmann
9cdd8e9d45 chore(web-core,web,lite): enforce .ts extension in imports (#10299) 2026-08-25 11:01:00 +02:00
Sandrine Barrucand
14e5352a40 feat(xo6/vm): add guest tools status (#10077) 2026-08-25 10:40:50 +02:00
Marie Garde
d955ffc4d1 feat(xo6): add smart reboot host button (#10177)
* feat(xo6): reset smart reboot branch ok

* Last returns

* Remove route map

* rebase ok

* add check onConfirm smart reboot
2026-08-25 09:56:16 +02:00
spacotte-vates
f812eaaeb6 feat(backup): implement synchronized snapshot option back (#10136)
Adds a synchronizedSnapshot backup setting. When enabled, all of a job's VM snapshots are taken up front in a batch before any transfer begins, and each VM's backup then reuses its pre-taken snapshot instead of snapshotting again.

Settings:
synchronizedSnapshot:

    false (default)
    true (synchronize every VM in the job)
    <tag> (synchronize only VMs carrying that tag, others are backed up normally).

snapshotConcurrency: max concurrent snapshots during the batch phase (default 2).

A batch member that fails to open is silently dropped from synchronization and backed up normally.

Unit tested where applicable and e2e tests added in qa-test.

Checkbox added in xo5 backup jobs to synchronize snapshots, tags not supported yet.
2026-08-24 17:58:03 +02:00
amouillard-vates
814bc96a8b feat(xo6): sr dedicated page general tab (#10100)
* feat(xo6): sr dedicated page general tab

* Remove dev routes

* Update CHANGELOG.unreleased.md

* Rename sr usage warning

* Rename vdi allocated space warning

* Remove useless variable

* Remove useless destructuring

* Remove useless destructuring

* Use UiInfo component and normalize margins

* Change variable name

* Add pool/host breadcrumb options

* Normalize fromContext with vdi page

* SR space unwritable alert

* Side panel space card info message

* Usage warning color

* Fix PR comments

* Add sr uuid resolver

* Fix CI

* Update getters name

* Full width UiInfo

* Consistent srUsagePercentage check

* Remove superfluous destructuration

* Reuse existing SR_SCOPE_TYPE

* Remove dev routes

* CSS nesting

* Fix PR comments

* Dev routes + UiPanelCard

* Move getSrPageLocation
2026-08-24 11:13:13 +02:00
Alina D
9ef53890b8 feat(xo-lite): add vdi page (#10269) 2026-08-21 17:31:45 +02:00
spacotte-vates
8b4505a2d5 fix(xo-server): changing vif mac adress destroy traffic rules (#10284) 2026-08-21 17:15:48 +02:00
amouillard-vates
a68c9534e9 fix(lite): add hasChildren prop to xo-lite tree view elements (#10244) 2026-08-21 14:59:23 +02:00
Bastien Nollet
46b0dc67bb chore(backups): use set_memory_limits instead of convoluted code (#10286) 2026-08-21 14:36:22 +02:00
Thierry Goettelmann
249137793f fix(web-core,web,lite): align side panel card spacing with the design system (#10279) 2026-08-20 12:03:44 +02:00
amouillard-vates
96e7e23f40 feat(xo-lite): enable scan PIFs button on host network page (#10147) 2026-08-19 14:01:04 +02:00
Anupam Mediratta
6c3e3e781d fix(backups): upgrade tar to 7.5.19 (CVE-2026-59873) (#10159) 2026-08-19 10:42:23 +02:00
Marie Garde
bcb0a7041f feat(xo6): add force reboot host button (#10175)
* manual rebase

* returns from stack PR

* rebase ok

* returns from PR

* fix import

* remove unescessary params

* remove reoute map

* Last return
2026-08-18 11:48:42 +02:00
Alina D
db0d009d5b feat(xo6/pool): add forget action (#10130) 2026-08-18 11:17:18 +02:00
Elise-F
de1c231873 feat(lite): add create network and network bonded actions (#10145)
* feat(lite): add create network and network bonded actions

* update changelog file

* remove vlan required and info message

* feedback number one

* feedback number two
2026-08-18 10:49:27 +02:00
Marie Garde
4235644950 feat(xo6): add reboot host button (#10141)
* continuefeat(xo6/host): add reboot host button

* fix fr.json

* Add loader on evacuate and reboot

* add check message evacuate VMs

* Fix message

* Returns from PR

* Remove vm migrate from host operations

* Change accent modal

* Rebase master ok

* Fix rebase
2026-08-17 09:40:40 +02:00
Marie Garde
7942d6a84a feat(xo6): add disable host and evacuate VMs (#10090)
* feat(xo6): add disable and enable host button

* Add button enable disable

* remove route map file

* Refacto for PR

* Add modal

* refacto for PR

* fix i18n

* fix route map

* change modale to VtsActionModale

* refacto for MR

* fix type VtsActionModal

* refacto for MR

* add enable disable un treeview

* refacto treeview

* wip

* add shutdown and start button and job

* Update changelog and remove route map

* wip i18n

* tests ok

* fix build

* refacto for mr

* refacto for PR

* add check pending action

* add check host not halted

* feat(xo6): add disable and enable host button

* Add button enable disable

* Refacto for PR

* Add modal

* refacto for PR

* change key i18n

* change modale to VtsActionModale

* refacto for MR

* fix type VtsActionModal

* refacto for MR

* refacto treeview

* wip

* Update changelog and remove route map

* wip

* wip forget

* test and refacto for PR

* fix error rebase

* fx rebase missing

* fix rebase

* fix rebase

* wip

* add shutdown and start button and job

* tests ok

* refacto for mr

* add check host not halted

* wip

* rebase for PR

* fx rebase missing

* wip

* change order button

* wip

* wip forget

* wip

* button and job ok

* add modal disable host and evacuate vm but tests not done

* refacto for PR

* fix fr json and route map

* fix rebase

* fix PR

* remove route map

* last fix

* Returns from PR

* Returns from PR

* Add ? on confirm i18n

* Fix job disable and enable running message

* Fix enable job

* Fix enable job

* Returns from PR

* Fix post rebase

* Fix post rebase

* Fix post rebase

* fix from rebase

* Returns from PR

* Returns from PR

* rebase ok
2026-08-17 08:33:33 +02:00
amouillard-vates
c5faec4cf6 fix(lite): remove multi-selection from pool networks table (#10268) 2026-08-14 15:39:33 +02:00
Thomas Moraine
c9149618f8 docs(xo): rename security tab into traffic rules (#10267)
The Pools -> Security tab in Xen Orchestra was
recently renamed as 'Traffic rules'.
This commit updates the XO documentation (screenshots included) to reflect that change.

Signed-off-by: Thomas Moraine <thomas.moraine@vates.tech>
2026-08-14 13:42:38 +02:00
Elise-F
438415a882 feat(xo6/traffic rules): added the error message related to the method and updated UI (#10202) 2026-08-14 10:41:45 +02:00
OlivierFL
ed78cc10cf feat(xo-6/vif): add VIF name in head bar on VIF detail page (#10252) 2026-08-14 09:05:02 +02:00
Marie Garde
1c18215bd1 feat(xo6): add host action button forget (#10089)
* feat(xo6): add disable and enable host button

* Add button enable disable

* remove route map file

* Refacto for PR

* Add modal

* refacto for PR

* change key i18n

* fix i18n

* fix route map

* change modale to VtsActionModale

* refacto for MR

* fix type VtsActionModal

* refacto for MR

* add enable disable un treeview

* refacto treeview

* wip

* add shutdown and start button and job

* Update changelog and remove route map

* wip i18n

* tests ok

* fix build

* refacto for mr

* refacto for PR

* add check pending action

* add check host not halted

* feat(xo6): add disable and enable host button

* Add button enable disable

* Refacto for PR

* Add modal

* refacto for PR

* change key i18n

* change modale to VtsActionModale

* refacto for MR

* fix type VtsActionModal

* refacto for MR

* refacto treeview

* wip

* Update changelog and remove route map

* refacto for mr

* wip

* add forget button host

* update button for menuitem

* wip forget

* test and refacto for PR

* fix error rebase

* fx rebase missing

* add changelog

* fix rebase

* fix rebase

* Add ? on confirm i18n

* Returns from PR

* rebase overlay ok

* fix changelog

* Add redirect if still on host page after forget

* Add redirect after delete
2026-08-14 09:00:50 +02:00
Pierre Donias
7cdb792bfe fix(xo-web/vm/console): make collapsed header state reliable (#10007)
The console tab kept its own `minimalLayout` state to track whether the page header was collapsed, separate from the VM page's `collapsedHeader`. The two desynced because the tab remounts on navigation while the VM page stays mounted.

Fix:
- Single source of truth `collapsedHeader` in the parent index.js
- Pass it to the child tab-console.js along with `setCollapsedHeader`
- Replace the `_toggleHeader` toggle with an explicit `_setCollapsedHeader(value)` setter
- Remove the duplicate local `minimalLayout` state that could get out of sync and use `collapsedHeader` instead
- Force off on VM shutdown (console no longer displayed) and on unmount (user changed page)
2026-08-13 15:15:25 +02:00
Grandalf
0601716fa4 fix(backups): return backups repository info one by one instead of erroring on first failure (#10205) 2026-08-13 15:09:53 +02:00
spacotte-vates
d53d2fc1c2 fix(xo-server): fix target not found error for warm migration (#10210) 2026-08-13 09:56:10 +02:00
Bruno Verachten
11ff21097f docs(snapshots): note that reverting restores VM metadata too (#10196)
Surfaced via https://xcp-ng.org/forum/topic/12148.
2026-08-12 17:39:33 +02:00
Greg-hub-dev
828c15cbb4 docs(backups.md) : Delete future RAM backup feature details (#10223) 2026-08-12 15:03:33 +02:00
Grandalf
798732e62a fix(async-map): allow return type to be different than input type (#10227) 2026-08-12 10:50:44 +02:00
Mathieu
1bfcc50b23 fix(xen-api): update platform for cores-per-socket update (#10201)
XO-2814
2026-08-10 15:52:07 +02:00
Olivier Lambert
c5d791a7de docs: full documentation revamp (#10212) 2026-08-07 16:36:09 +02:00
Grandalf
3293e69cc2 refactor(xo-server): remove hrp dependency (#10038)
replace http-request-plus external depedency by a a native wrapper around fetch
2026-08-07 11:58:20 +02:00
Grandalf
a0193085f5 feat(ipmi): add get sensors route (#10003) 2026-08-07 11:38:28 +02:00
1654 changed files with 47437 additions and 17103 deletions

View File

@@ -85,6 +85,21 @@ 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',
{
@@ -254,6 +269,8 @@ module.exports = {
'zh-Hans',
'sk',
'pt',
'ar',
'tr',
],
},
],

34
.github/workflows/changelog-check.yml vendored Normal file
View File

@@ -0,0 +1,34 @@
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,6 +5,7 @@
/@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,3 +5,7 @@
# 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.3",
"@xen-orchestra/async-map": "^0.1.4",
"@xen-orchestra/log": "^0.7.2",
"ensure-array": "^1.0.0"
},

View File

@@ -7,6 +7,7 @@ const { warn } = createLogger('vates:nbd-client:multi')
export default class MultiNbdClient {
#clients = []
#nbdConcurrency
#nextClient = 0
#options
#readAhead
#settings
@@ -97,8 +98,31 @@ export default class MultiNbdClient {
* @returns {Promise<Buffer>}
*/
async readBlock(index, size = NBD_DEFAULT_BLOCK_SIZE) {
const clientId = index % this.#clients.length
return this.#clients[clientId].readBlock(index, 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(() => {})
}
/**

View File

@@ -0,0 +1,130 @@
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.0",
"version": "3.5.1",
"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.3",
"@xen-orchestra/async-map": "^0.1.4",
"@xen-orchestra/disk-transform": "^1.3.3",
"@xen-orchestra/log": "^0.7.2",
"promise-toolbox": "^0.21.0",
"xen-api": "^4.8.0"
"xen-api": "^4.9.0"
},
"devDependencies": {
"tap": "^18.7.0",
@@ -33,6 +33,7 @@
},
"scripts": {
"postversion": "npm publish --access public",
"test-integration": "tap --allow-incomplete-coverage"
"test": "node --experimental-test-module-mocks --test",
"test-integration": "tap --allow-incomplete-coverage tests/*.integ.mjs"
}
}

View File

@@ -153,7 +153,13 @@ CYu1Xn/FVPx1HoRgWc7E8wFhDcA/P3SJtfIQWHB9FzSaBflKGR4t8WCE2eE8+cTB
nbdServer = await spawnNbdKit(path)
}
}
assert.rejects(() => client.readBlock(100, CHUNK_SIZE))
// 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()
await client.disconnect()
// double disconnection shouldn't pose any problem

View File

@@ -0,0 +1,102 @@
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

@@ -0,0 +1,104 @@
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,16 +19,29 @@ 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) {
super(rawError.body)
const matches = rawError.body?.match(/<faultstring[^>]*>(.*)<\/faultstring>/im)
this.message = matches?.[1] ?? rawError.message
const { code, faultcode, faultstring, localizedMessage, body } = parseFault(rawError)
super(localizedMessage ?? faultstring ?? rawError?.message ?? 'unknown SOAP error')
this.name = 'VmwareError'
this.stack = rawError.stack
// not putting the cause since the error failed to be stringified correctly down the road
warn(rawError)
// 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 })
}
}
// Client class
@@ -38,6 +51,7 @@ 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
@@ -90,44 +104,49 @@ util.inherits(Client, EventEmitter)
Client.prototype.runCommand = function (command, args) {
const self = this
let cmdargs
if (!args || args === null) {
cmdargs = {}
} else {
cmdargs = args
}
const 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') {
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)
})
send()
} else {
// if connection not ready or connecting, reconnect to instance
if (self.status === 'disconnected') {
self.emit('connect')
}
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)
})
})
// 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)
}
return emitter
@@ -153,9 +172,11 @@ Client.prototype._connect = function () {
self.clientopts,
function (err, client) {
if (err) {
const vErr = new VmwareError(err)
self.emit('error', vErr)
throw vErr
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
}
self.client = client // save client for later use
@@ -186,7 +207,7 @@ Client.prototype._connect = function () {
self.status = 'ready'
self.emit('ready')
process.once('beforeExit', self._close)
self._registerExitHook()
})
.once('error', function (err) {
self.status = 'disconnected'
@@ -202,9 +223,36 @@ 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 })
@@ -220,34 +268,64 @@ Client.prototype._close = function () {
}
}
function _soapErrorHandler(self, emitter, command, args, err) {
// 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) {
err = err || { body: 'general error' }
if (err.body?.match(/session is not authenticated/)) {
self.status = 'disconnected'
process.removeAllListeners('beforeExit')
const vErr = new VmwareError(err)
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)
// `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)
throw 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') {
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')
}
}

View File

@@ -0,0 +1,219 @@
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,6 +31,7 @@
"node": ">=14"
},
"scripts": {
"postversion": "npm publish --access public"
"postversion": "npm publish --access public",
"test": "node --test lib/*.test.mjs"
}
}

View File

@@ -1,7 +1,7 @@
// 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
// 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.
export const vCenterTestCreds = {
vCenterIP: 'vcsa',

View File

@@ -1,138 +0,0 @@
/*
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": "1.30.1",
"version": "2.0.1",
"main": "./dist/index.mjs",
"exports": {
".": {
@@ -33,7 +33,8 @@
"@eslint/js": "^9.19.0",
"typescript": "~5.6.3",
"typescript-eslint": "^8.61.0",
"@types/express": "^5.0.0"
"@types/express": "^5.0.0",
"@xen-orchestra/disk-transform": "^1.3.3"
},
"scripts": {
"build": "tsc",

View File

@@ -1,4 +1,4 @@
import type { XoHost, XoNetwork, XoVif } from './xo.mjs'
import type { XapiXoRecord, 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: string
protocol: TrafficRuleProtocol
ipRange: string
direction: string
direction: TrafficRuleDirection
port?: string
}
@@ -769,3 +769,34 @@ 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,40 +4,34 @@ import type { XoApp } from '../xo-app.mjs'
export type SecurityName = '*' | 'token' | 'basic' | 'none'
export type FieldDefinition =
export type FieldDefinition = { optional?: boolean; nullable?: boolean } & (
| {
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,6 +24,7 @@ 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,
@@ -476,3 +477,42 @@ 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,6 +21,7 @@ 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,
@@ -125,6 +126,54 @@ 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: {
@@ -201,9 +250,11 @@ export type XoApp = {
userData?: { ip?: string },
opts?: { bypassOtp?: boolean; bypassTaskCreation?: boolean }
) => Promise<{ bypassOtp: boolean; expiration: number; user: XoUser }>
backupGuard(poolId: XoPool['id']): Promise<void>
backupGuard(objectId: XapiXoRecord['id'], opts?: { bypassBackupCheck?: boolean; operation: string }): 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)
@@ -291,7 +342,7 @@ export type XoApp = {
>
>
getAllSchedules(): Promise<XoSchedule[]>
getAllUsers(): Promise<XoUser[]>
getAllUsers(opts?: { obfuscatePassword?: boolean }): Promise<XoUser[]>
getAllXenServers(): Promise<XoServer[]>
getAuthenticationTokensForUser(userId: XoUser['id']): Promise<XoAuthenticationToken[]>
getBackupNgLogs(): Promise<Record<string, AnyXoLog>>
@@ -312,7 +363,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']) => Promise<XoUser>
getUser: (id: XoUser['id'], opts?: { obfuscatePassword?: boolean }) => Promise<XoUser>
getXapi(maybeId: XapiXoRecord['id'] | XapiXoRecord): Xapi
getXapiHostStats: (hostId: XoHost['id'], granularity?: XapiStatsGranularity) => Promise<XapiHostStats>
getXapiObject: <T extends XapiXoRecord>(
@@ -322,16 +373,18 @@ 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[]>>>
opts?: { _forceRefresh?: boolean; vmId?: XoVm['id'] }
): Promise<Record<XoBackupRepository['id'], Record<XoVm['id'], XoVmBackupArchive[]> | null>>
pingRemote(id: XoBackupRepository['id']): Promise<{ success: true }>
/** Allow to add a new server in the DB (XCP-ng/XenServer) */
registerXenServer(
@@ -341,11 +394,15 @@ export type XoApp = {
readOnly?: XoServer['readOnly']
}
): Promise<XoServer>
rollingPoolReboot(pool: XoPool, opts?: { parentTask?: VatesTask; shutdownPinnedVms?: boolean }): Promise<void>
rollingPoolReboot(
pool: XoPool,
opts?: { bypassBackupCheck?: boolean; parentTask?: VatesTask; shutdownPinnedVms?: boolean }
): Promise<void>
rollingPoolUpdate(
pool: XoPool,
opts?: { rebootVm?: boolean; parentTask?: VatesTask; shutdownPinnedVms?: boolean }
opts?: { bypassBackupCheck?: boolean; 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 { XoAclPrivilege, XoAclRole, XoAclSupportedActionsByResource } from './lib/xen-orchestra-acl.mjs'
import { XoAclBasePrivilege, XoAclRole } from './lib/xen-orchestra-acl.mjs'
import type { XenApiHost, XenApiPool } from './xen-api.mjs'
type BaseXapiXo = {
@@ -140,6 +140,7 @@ 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 }[]
@@ -602,7 +603,7 @@ export type XoServer = {
poolNameDescription?: string
poolNameLabel?: string
readOnly: boolean
status: 'connected' | 'disconnected' | 'connecting'
status: 'connected' | 'disconnecting' | 'disconnected' | 'connecting'
username: string
}
@@ -889,10 +890,7 @@ export type XapiXoRecord =
| XoVtpm
| XoSm
export type NonXapiXoRecord<
TActionsByResource extends XoAclSupportedActionsByResource = never,
TResource extends string = never,
> =
export type NonXapiXoRecord =
| AnyXoBackupArchive
| AnyXoJob
| AnyXoLog
@@ -905,12 +903,9 @@ export type NonXapiXoRecord<
| XoTask
| XoUser
| XoAclRole
| XoAclPrivilege<TActionsByResource, TResource>
| XoAclBasePrivilege
export type XoRecord<
TActionsByResource extends XoAclSupportedActionsByResource = never,
TResource extends string = never,
> = XapiXoRecord | NonXapiXoRecord<TActionsByResource, TResource>
export type XoRecord = XapiXoRecord | NonXapiXoRecord
export type AnyXoVm = XoVm | XoVmSnapshot | XoVmTemplate | XoVmController

View File

@@ -4,6 +4,7 @@
"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.5.0",
"version": "1.6.1",
"license": "AGPL-3.0-or-later",
"private": false,
"type": "module",
@@ -30,7 +30,7 @@
},
"devDependencies": {
"@eslint/js": "^9.19.0",
"@vates/types": "^1.30.1",
"@vates/types": "^2.0.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,This
* @template Item, Result, [This=Iterable<Item>]
* @param {Iterable<Item>} iterable
* @param {(this: This, item: Item) => (Item | PromiseLike<Item>)} mapFn
* @param {This} [thisArg]
* @returns {Promise<Item[]>}
* @param {(this: This, item: Item) => (Result | PromiseLike<Result>)} mapFn
* @param {This} [thisArg] defaults to `iterable`
* @returns {Promise<Result[]>}
*/
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,This
* @template Item, Result, [This=Iterable<Item>]
* @param {Iterable<Item>} iterable
* @param {(this: This, item: Item) => (Item | PromiseLike<Item>)} mapFn
* @param {This} [thisArg]
* @returns {Promise<Item[]>}
* @param {(this: This, item: Item) => (Result | PromiseLike<Result>)} mapFn
* @param {This} [thisArg] defaults to `iterable`
* @returns {Promise<Result[]>}
*/
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.3",
"version": "0.1.4",
"license": "ISC",
"description": "Promise.all + map for all iterables",
"keywords": [

View File

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

View File

@@ -0,0 +1,49 @@
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

@@ -0,0 +1,16 @@
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 = vdiDir
this.#vdiDir = normalize(vdiDir)
this.#opts = opts
}

View File

@@ -55,6 +55,8 @@ 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,11 +17,8 @@ import {
import { cleanOrphanDiskDirs } from '@xen-orchestra/backup-archive/disks'
import { asyncEach } from '@vates/async-each'
import { createLogger } from '@xen-orchestra/log'
import { promisify } from 'node:util'
import zlib from 'node:zlib'
const gzip = promisify(zlib.gzip)
const gunzip = promisify(zlib.gunzip)
import { readBackupCache, writeBackupCache } from './BackupCache.mjs'
import { unlinkTolerant } from './_unlinkTolerant.mjs'
const { info: logInfo, warn: logWarn } = createLogger('xo:backup-archive')
@@ -30,7 +27,7 @@ const FILES_TO_KEEP = ['cache.json.gz', 'vdis']
export class VmBackupDirectory implements VmBackupInterface {
handler: RemoteHandlerAbstract
rootPath: string
files: Array<string> = new Array()
files: Array<string> = []
orphans: Set<string> = new Set()
backupArchives: Map<string, VmBackupInterface> = new Map()
opts: ResolvedBackupCleanOptions
@@ -43,6 +40,9 @@ 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,21 +67,11 @@ export class VmBackupDirectory implements VmBackupInterface {
}
async #readCache(path: string): Promise<Record<string, unknown> | undefined> {
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 })
}
}
return readBackupCache(this.handler, path, logWarn)
}
async #writeCache(path: string, data: Record<string, unknown>): Promise<void> {
try {
await this.handler.writeFile(path, await gzip(JSON.stringify(data)), { flags: 'w' })
} catch (error) {
logWarn('failed to write cache', { error, path })
}
return writeBackupCache(this.handler, path, data, logWarn)
}
async init() {
@@ -90,9 +80,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 = undefined
let metadata: PartialBackupMetadata | undefined
try {
metadata = JSON.parse(await this.handler.readFile(fullPath)) satisfies PartialBackupMetadata
metadata = JSON.parse((await this.handler.readFile(fullPath)).toString()) satisfies PartialBackupMetadata
} catch (error) {
this.opts.logWarn(`Issue loading ${basename(fullPath)}`)
}
@@ -176,18 +166,35 @@ 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.values()),
async (archive: VmBackupInterface) => {
const { removedFiles } = await archive.clean({ remove, mergedSizes: allMergedSizes })
Array.from(this.backupArchives.entries()),
async ([metadataPath, archive]: [string, VmBackupInterface]) => {
const { removedFiles, changedFiles: archiveChangedFiles } = 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 }
)
if (allMergedSizes.size > 0 || cacheNeedsRegen || this.#cacheOutOfSync) {
// 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)) {
await this.#regenerateCache()
}
@@ -210,13 +217,50 @@ export class VmBackupDirectory implements VmBackupInterface {
)
}
const size = [...allMergedSizes.values()].reduce((total, merged) => total + merged, 0)
return { removedFiles: orphans, merge: someLineageMergedOrShouldBe, size: size }
// `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,
}
}
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)
const actual = existingCache === undefined ? 0 : Object.keys(existingCache).length
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 expected = this.backupArchives.size
this.#cacheOutOfSync = actual !== expected
if (this.#cacheOutOfSync) {
@@ -283,7 +327,6 @@ export class VmBackupDirectory implements VmBackupInterface {
const dir = new VmBackupDirectory(handler, vmBackupPath, cleanOpts)
await dir.init()
await dir.check()
const { merge, size } = await dir.clean({ remove: cleanOpts.remove, merge: cleanOpts.merge })
return { merge, size }
return await dir.clean({ remove: cleanOpts.remove, merge: cleanOpts.merge })
}
}

View File

@@ -10,8 +10,13 @@ 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}`
@@ -124,7 +129,10 @@ 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`, 'cache')
await handler.writeFile(
`${rootPath}/cache.json.gz`,
await gzip(JSON.stringify({ [`/${rootPath}/backup1.json`]: {} }))
)
await VmBackupDirectory.cleanVm(handler, rootPath)
@@ -133,6 +141,104 @@ 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 } from '@xen-orchestra/fs/path'
import { basename, normalize, resolveFromFile } from '@xen-orchestra/fs/path'
import assert from 'node:assert'
import { FileDescriptor } from '@xen-orchestra/fs'
import { FileDescriptor, RemoteHandlerAbstract } from '@xen-orchestra/fs'
import {
ArchiveCleanOptions,
CheckResult,
@@ -8,8 +8,10 @@ import {
VmBackupInterface,
PartialBackupMetadata,
ResolvedBackupCleanOptions,
DEFAULT_REMOVE_CONCURRENCY,
} from './VmBackup.types.mjs'
import { RemoteHandlerAbstract } from '@xen-orchestra/fs'
import { asyncEach } from '@vates/async-each'
import { unlinkTolerant } from './_unlinkTolerant.mjs'
const COMPRESSED_MAGIC_NUMBERS: Buffer[] = [
// https://tools.ietf.org/html/rfc1952.html#page-5
@@ -80,6 +82,29 @@ 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
@@ -158,12 +183,10 @@ export class VmFullBackupArchive implements VmBackupInterface {
files: this.getAssociatedFiles({ prefix: false }),
})
} else {
for (const file of removedFiles) {
try {
await this.handler.unlink(file)
} catch (error) {
this.opts.logWarn(`Issue removing ${file}`, { error })
}
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 })
}
}
}
@@ -173,7 +196,7 @@ export class VmFullBackupArchive implements VmBackupInterface {
}
getAssociatedFiles({ prefix = false }): Array<string> {
let validFiles = [this.metadataPath, this.xvaPath, `${this.xvaPath}.checksum`]
const validFiles = [this.metadataPath, this.xvaPath, `${this.xvaPath}.checksum`]
return prefix ? validFiles : validFiles.map(file => basename(file))
}
}

View File

@@ -6,10 +6,13 @@ import fs from 'fs-extra'
import * as uuid from 'uuid'
import { getHandler } from '@xen-orchestra/fs'
import { pFromCallback } from 'promise-toolbox'
// eslint-disable-next-line n/no-missing-import
// `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 */
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'
@@ -20,6 +23,7 @@ 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/'
@@ -205,8 +209,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 be regenerated after metadata deletion'
!(await handler.list(rootPath)).includes('cache.json.gz'),
'cache.json.gz should not be created when none existed before the clean'
)
})
@@ -364,7 +368,6 @@ 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: () => {} })
@@ -726,10 +729,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)
// cache.json.gz must be regenerated when metadata changes after a merge
// no cache.json.gz existed before this run, so a merge must not create one
assert.ok(
(await handler.list(rootPath)).includes('cache.json.gz'),
'cache.json.gz should be regenerated after a merge'
!(await handler.list(rootPath)).includes('cache.json.gz'),
'cache.json.gz should not be created when none existed before the merge'
)
// broken vhd, non referenced, abandoned should be deleted ( alias and data)
@@ -833,7 +836,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 regenerates the cache when its entry count is out of sync, even with nothing to merge/remove', async () => {
test('it does not create nor warn about the cache when none existed, even with a count mismatch', async () => {
// a referenced disk + its metadata, but no cache.json.gz on disk
await generateVhd(`${basePath}/diskA1.vhd`)
await handler.writeFile(
@@ -842,6 +845,79 @@ test('it regenerates the cache when its entry count is out of sync, even with no
)
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
@@ -857,3 +933,53 @@ test('it regenerates the cache when its entry count is out of sync, even with no
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,10 +5,27 @@ 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
@@ -132,6 +149,7 @@ export class VmIncrementalBackupArchive implements VmBackupInterface {
}
}
const changedFiles: string[] = []
let mergedSize = 0
if (mergedSizes !== undefined) {
for (const diskPath of this.diskPaths) {
@@ -139,10 +157,11 @@ export class VmIncrementalBackupArchive implements VmBackupInterface {
}
if (mergedSize > 0) {
await this.updateMetadata(mergedSize)
changedFiles.push(this.metadataPath)
}
}
return { removedFiles }
return { removedFiles, changedFiles }
}
/**

View File

@@ -0,0 +1,20 @@
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)
this.#state = JSON.parse(mergeStateContent.toString())
// 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))
const state = JSON.parse((await handler.readFile(filePath)).toString())
if (Array.isArray(state?.chain)) {
chain = state.chain.map((/** @type {string} */ relPath) => normalize(resolveFromFile(filePath, relPath)))
} else {

View File

@@ -2,14 +2,16 @@
/**
* @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 {Object} [options]
* @param {boolean} [options.force]
* @param {boolean} [options.ignoreBlockIndexes] skip reading the block index when the format allows it
* @returns {Promise<void>}
*/
async init(options = { force: false }) {
@@ -229,6 +231,22 @@ 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

@@ -0,0 +1,275 @@
// @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,6 +6,7 @@
* @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
*
*/
@@ -17,7 +18,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 { normalize } from '@xen-orchestra/fs/path'
import { isInDir, normalize } from '@xen-orchestra/fs/path'
export class RemoteVhdDisk extends RemoteDisk {
/**
@@ -81,12 +82,13 @@ 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()
}
@@ -433,6 +435,37 @@ 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
@@ -540,18 +573,15 @@ 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)) {
if (isInDir(this.#path, dir)) {
files.push(this.#path)
}
if (isVhdAlias(this.#path)) {
try {
const resolved = await resolveVhdAlias(this.#handler, this.#path)
if (isInDir(resolved)) {
if (isInDir(resolved, dir)) {
files.push(resolved)
}
} catch {

View File

@@ -3,17 +3,11 @@
/**
* @typedef {import('./RemoteVhdDisk.mjs').VhdFooter} VhdFooter
* @typedef {import('./RemoteVhdDisk.mjs').RemoteVhdDisk} RemoteVhdDisk
* @typedef {import('@xen-orchestra/disk-transform').DiskBlock} DiskBlock
*/
import { RemoteDisk } from './RemoteDisk.mjs'
export class RemoteVhdDiskChain extends RemoteDisk {
/**
* @type {RemoteVhdDisk[]}
*/
#disks
import { RemoteDiskChain } from './RemoteDiskChain.mjs'
export class RemoteVhdDiskChain extends RemoteDiskChain {
/**
* @type {number}
*/
@@ -39,55 +33,15 @@ export class RemoteVhdDiskChain extends RemoteDisk {
* @param {RemoteVhdDisk[]} params.disks
*/
constructor({ disks }) {
super()
this.#disks = disks
super({ disks })
}
/**
* Initializes the VHD chain
* @param {Object} options
* @param {boolean} options.force
* @returns {Promise<void>}
* The VHD disks of the chain, oldest first
* @returns {RemoteVhdDisk[]}
*/
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()
get disks() {
return /** @type {RemoteVhdDisk[]} */ (super.disks)
}
/**
@@ -107,36 +61,6 @@ export class RemoteVhdDiskChain extends RemoteDisk {
)
}
/**
* @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
*/
@@ -144,148 +68,24 @@ export class RemoteVhdDiskChain extends RemoteDisk {
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) {
for (const disk of [...this.#disks].reverse()) {
if (disk.hasBlock(index)) {
return disk.getBlockPath(index)
}
const disk = /** @type {RemoteVhdDisk | undefined} */ (this.newestDiskWith(index))
if (disk === undefined) {
throw new Error(`Block ${index} not found in chain`)
}
throw new Error(`Block ${index} not found in chain`)
return disk.getBlockPath(index)
}
/**
* @returns {VhdFooter}
*/
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 })
}
return /** @type {VhdFooter} */ (super.getMetadata())
}
/**
@@ -293,7 +93,7 @@ export class RemoteVhdDiskChain extends RemoteDisk {
* @returns {Promise<boolean>}
*/
async isDirectory() {
for (const disk of this.#disks) {
for (const disk of this.disks) {
if (!(await disk.isDirectory())) {
return false
}
@@ -301,23 +101,11 @@ export class RemoteVhdDiskChain extends RemoteDisk {
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 this.#disks[0]
return /** @type {RemoteVhdDisk|undefined} */ (super.getRootDisk())
}
}

View File

@@ -0,0 +1,119 @@
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

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

View File

@@ -0,0 +1,50 @@
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

@@ -0,0 +1,241 @@
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

@@ -0,0 +1,305 @@
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

@@ -0,0 +1,810 @@
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 })
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,231 @@
// 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

@@ -0,0 +1,7 @@
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

@@ -0,0 +1,86 @@
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

@@ -0,0 +1,93 @@
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

@@ -0,0 +1,198 @@
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,22 +1,16 @@
import { RemoteVhdDisk } from './RemoteVhdDisk.mjs'
import { instantiateDisk } from './instantiateDisk.mjs'
export { isDisk } from './instantiateDisk.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
@@ -27,7 +21,7 @@ export function isDisk(path) {
* @returns {Promise<Disposable<RemoteDisk>>}
*/
export async function openDisposableDisk({ handler, path, force = false, ignoreBlockIndexes = false }) {
const disk = new RemoteVhdDisk({ handler, path })
const disk = instantiateDisk(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).
@@ -50,7 +44,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 = new RemoteVhdDisk({ handler, path })
const disk = instantiateDisk(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

@@ -0,0 +1,24 @@
// @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,9 +4,28 @@
* @typedef {import('@xen-orchestra/fs').RemoteHandlerAbstract} RemoteHandlerAbstract
* @typedef {import('./RemoteDisk.mjs').RemoteDisk} RemoteDisk
*/
import { RemoteVhdDisk } from './RemoteVhdDisk.mjs'
import { defer } from 'golike-defer'
import { RemoteVhdDisk } from './RemoteVhdDisk.mjs'
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
@@ -20,15 +39,15 @@ import { RemoteVhdDiskChain } from './RemoteVhdDiskChain.mjs'
*/
async function _openDiskChain($defer, { handler, path, until, force = false, ignoreBlockIndexes = false }) {
/**
* @type {RemoteVhdDisk}
* @type {RemoteDisk}
*/
let disk
/**
* @type {Array<RemoteVhdDisk>}
* @type {Array<RemoteDisk>}
*/
const disks = []
$defer.onFailure(() => Promise.all(disks.map(disk => disk.close())))
disk = new RemoteVhdDisk({ handler, path })
disk = instantiateDisk(handler, path)
await disk.init({ force, ignoreBlockIndexes })
disks.push(disk)
@@ -40,15 +59,14 @@ 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 = /** @type {RemoteVhdDisk} */ (disk.instantiateParent())
disk = 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`)
}
// the root disk
return new RemoteVhdDiskChain({ disks })
return newChain(path, disks)
}
/**

View File

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

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.3",
"@xen-orchestra/backups": "^0.73.10",
"@xen-orchestra/async-map": "^0.1.4",
"@xen-orchestra/backups": "^0.74.2",
"@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.13",
"version": "1.1.14",
"license": "AGPL-3.0-or-later",
"author": {
"name": "Vates SAS",

View File

@@ -0,0 +1,488 @@
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,27 +1,35 @@
import { asyncEach } from '@vates/async-each'
import { asyncMap, asyncMapSettled } from '@xen-orchestra/async-map'
import { createLogger } from '@xen-orchestra/log'
import { VhdDirectory, VhdSynthetic } from 'vhd-lib'
import { stringify } from 'uuid'
import { decorateMethodsWith } from '@vates/decorate-with'
import { dirname, join, resolve } from 'node:path'
import { basename, 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 } from '@xen-orchestra/backup-archive'
import {
VmBackupDirectory,
deleteFullVmBackups as deleteFullVmBackupFiles,
deleteDeltaVmBackups as deleteDeltaVmBackupFiles,
deleteMetadataBackup as deleteMetadataBackupFiles,
readBackupCache,
writeBackupCache,
} 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 } from '@xen-orchestra/backup-archive/disks'
import { RemoteVhdDisk, openDiskChain, openDisposableDisk } 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'
@@ -36,8 +44,6 @@ 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') {
@@ -47,14 +53,10 @@ const createSafeReaddir = (handler, methodName) => (path, options) =>
})
export class RemoteAdapter {
constructor(
handler,
{ debounceResource = res => res, dirMode, vhdDirectoryCompression, useGetDiskLegacy = false } = {}
) {
constructor(handler, { debounceResource = res => res, dirMode, useGetDiskLegacy = false } = {}) {
this._debounceResource = debounceResource
this._dirMode = dirMode
this._handler = handler
this._vhdDirectoryCompression = vhdDirectoryCompression
this._readCacheListVmBackups = synchronized.withKey()(this._readCacheListVmBackups)
this._useGetDiskLegacy = useGetDiskLegacy
}
@@ -65,22 +67,29 @@ 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(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()
})
return await Disposable.use(openDisposableDisk({ handler: this.handler, path, ignoreBlockIndexes: true }), disk =>
disk.isMergeableParent(stringify(packedParentUid), { diskFormat: this.#diskFormat })
)
}
async #removeVmBackupsFromCache(backups) {
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) {
await asyncEach(
Object.entries(
groupBy(
@@ -97,27 +106,39 @@ 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 }
)
}
async deleteDeltaVmBackups(backups) {
const handler = this._handler
/**
* @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 asyncMapSettled(backups, ({ _filename }) => handler.unlink(_filename))
await deleteDeltaVmBackupFiles(
this._handler,
backups.map(({ _filename }) => ({ metadataPath: _filename }))
)
await this.#removeVmBackupsFromCache(backups)
await this.#forgetVmBackups(backups, reason)
}
async deleteMetadataBackup(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)
await deleteMetadataBackupFiles(this._handler, backupId)
}
async deleteOldMetadataBackups(dir, retention) {
@@ -128,26 +149,23 @@ export class RemoteAdapter {
await asyncMapSettled(list, timestamp => handler.rmtree(`${dir}/${timestamp}`))
}
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
}),
])
)
/**
* @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
}
})
await this.#removeVmBackupsFromCache(backups)
await this.#forgetVmBackups(backups, reason)
}
deleteVmBackup(file) {
@@ -186,13 +204,13 @@ export class RemoteAdapter {
}
const promises = []
if (delta !== undefined) {
promises.push(this.deleteDeltaVmBackups(delta))
promises.push(this.deleteDeltaVmBackups(delta, { reason: 'user' }))
}
if (full !== undefined) {
promises.push(this.deleteFullVmBackups(full))
promises.push(this.deleteFullVmBackups(full, { reason: 'user' }))
}
if (missingFiles.length) {
promises.push(this.#removeVmBackupsFromCache(missingFiles))
promises.push(this.#forgetVmBackups(missingFiles, 'user'))
}
await Promise.all(promises)
@@ -205,24 +223,24 @@ export class RemoteAdapter {
)
}
#getCompressionType() {
return this._vhdDirectoryCompression
}
useVhdDirectory() {
return this.handler.useVhdDirectory()
return this.handler.getConfig('diskFormat') === 'vhdDirectory'
}
#useAlias() {
return this.useVhdDirectory()
}
// if we use alias on this remote, we have to name the file alias.vhd
getVhdFileName(baseName) {
if (this.#useAlias()) {
return `${baseName}.alias.vhd`
// 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`
}
return `${baseName}.vhd`
}
async listAllVms() {
@@ -298,18 +316,18 @@ export class RemoteAdapter {
}
async _readCache(path) {
try {
return JSON.parse(await fromCallback(zlib.gunzip, await this.handler.readFile(path)))
} catch (error) {
if (error.code !== 'ENOENT') {
warn('#readCache', { error, path })
}
}
return readBackupCache(this.handler, path, warn)
}
_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)
@@ -324,11 +342,7 @@ export class RemoteAdapter {
}
async _writeCache(path, data) {
try {
await this.handler.writeFile(path, await fromCallback(zlib.gzip, JSON.stringify(data)), { flags: 'w' })
} catch (error) {
warn('#writeCache', { error, path })
}
return writeBackupCache(this.handler, path, data, warn)
}
async #getCacheableDataListVmBackups(dir) {
@@ -431,6 +445,16 @@ 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`
@@ -438,6 +462,19 @@ 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 })
@@ -453,33 +490,45 @@ export class RemoteAdapter {
return path
}
async writeVhd(path, disk, { validator = noop, writeBlockConcurrency, uuid, parentUuid, parentPath } = {}) {
async writeDisk(path, disk, { validator = noop, writeBlockConcurrency, uuid, parentUuid, parentPath } = {}) {
const handler = this._handler
if (this.useVhdDirectory()) {
return await writeToVhdDirectory({
disk,
target: {
handler,
path,
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,
concurrency: writeBlockConcurrency,
validator,
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
})
default:
throw new Error(`unknown disk format ${diskFormat} for ${path}`)
}
}
@@ -641,15 +690,51 @@ 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), () => {
return VmBackupDirectory.cleanVm(this._handler, vmBackupPath, cleanOpts)
})
return Disposable.use(this._handler.lock(vmBackupPath), run)
} else {
return VmBackupDirectory.cleanVm(this._handler, vmBackupPath, cleanOpts)
return run()
}
},
isValidXva,

View File

@@ -0,0 +1,408 @@
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

@@ -0,0 +1,272 @@
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

@@ -0,0 +1,66 @@
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,7 +230,6 @@ 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,42 +16,15 @@ import { toQcow2Stream } from '@xen-orchestra/qcow2'
const ensureArray = value => (value === undefined ? [] : Array.isArray(value) ? value : [value])
const orderedMemoryLimits = ['memory_static_min', 'memory_dynamic_min', 'memory_dynamic_max', 'memory_static_max']
// 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.
// 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 memoryValues = {}
for (const key of orderedMemoryLimits) {
memoryValues[key] = {
currentValue: targetVm[key],
newValue: vmRecord[key] ?? targetVm[key],
}
}
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
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
await xapi.call('VM.set_memory_limits', targetVm.$ref, staticMin, staticMax, dynamicMin, dynamicMax)
}
export async function exportIncrementalVm(

View File

@@ -1,122 +0,0 @@
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,7 +9,9 @@ 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
@@ -31,7 +33,9 @@ const DEFAULT_XAPI_VM_SETTINGS = {
nRetriesVmBackupFailures: 0,
offlineBackup: false,
offlineSnapshot: false,
snapshotConcurrency: 2,
snapshotRetention: 0,
synchronizedSnapshot: false,
timeout: 0,
useNbd: false,
unconditionalSnapshot: false,
@@ -47,6 +51,16 @@ 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
@@ -95,7 +109,81 @@ export const VmsXapi = class VmsXapiBackupRunner extends Abstract {
const allSettings = this._job.settings
const baseSettings = this._baseSettings
const queue = new Set(vmIds)
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 taskByVmId = {}
const nTriesByVmId = {}
@@ -155,21 +243,16 @@ 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,
}
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`)
}
}
const vmBackup = this._getVmBackup(job.mode, opts)
return vmBackup.run().catch(error => {
taskError = error
})

View File

@@ -1,13 +1,10 @@
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 {
@@ -34,22 +31,7 @@ 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

@@ -0,0 +1,19 @@
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

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

View File

@@ -2,13 +2,12 @@ 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 { openVhd } from 'vhd-lib'
import { openDisposableDisk } from '@xen-orchestra/backup-archive/disks'
import { getVmBackupDir } from '../../_getVmBackupDir.mjs'
import { SynchronizedDisk, ThrottledDisk } from '@xen-orchestra/disk-transform'
import { AggregatedIncrementalRemoteWriter } from '../_writers/AggregatedIncrementalRemoteWriter.mjs'
@@ -44,9 +43,12 @@ 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(openVhd(this._sourceRemoteAdapter._handler, path), vhd => {
baseUuidToSrcVdi.set(UUID.stringify(vhd.header.parentUuid), vdi.$snapshot_of$uuid)
})
await Disposable.use(
openDisposableDisk({ handler: this._sourceRemoteAdapter._handler, path, ignoreBlockIndexes: true }),
disk => {
baseUuidToSrcVdi.set(disk.getParentUuid(), vdi.$snapshot_of$uuid)
}
)
}
})

View File

@@ -13,7 +13,6 @@ 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'
@@ -68,7 +67,6 @@ export const IncrementalXapi = class IncrementalXapiVmBackupRunner extends Abstr
// @todo : reimplement throttle
const timestamp = Date.now()
await this._callWriters(
writer =>
writer.transfer({
@@ -78,7 +76,7 @@ export const IncrementalXapi = class IncrementalXapiVmBackupRunner extends Abstr
// clean; the tip's flag lets the next run skip re-probing
includeNonNbdQcow2Fix: true,
isVhdDifferencing,
timestamp,
timestamp: this.timestamp,
vm,
vmSnapshot: exportedVm,
}),
@@ -91,11 +89,6 @@ 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,6 +7,7 @@ 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'
@@ -16,9 +17,11 @@ import {
JOB_ID,
SCHEDULE_ID,
VM_UUID,
EXPORTED_SUCCESSFULLY,
resetVmOtherConfig,
setVmOtherConfig,
setVmSnapshotContentKeys,
markExportSuccessfull,
} from '../../_otherConfig.mjs'
const { warn, info } = createLogger('xo:backups:AbstractXapi')
@@ -36,6 +39,7 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
schedule,
settings,
srs,
synchronizedSnapshotTimestamp,
throttleGenerator,
throttleStream,
vm,
@@ -63,9 +67,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
@@ -180,6 +184,27 @@ 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
@@ -396,10 +421,25 @@ 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))
const disklessVmSnapshots = this._disklessJobSnapshotVms.map(vm => xapi.getObject(vm.$ref))
let disklessVmSnapshots = this._disklessJobSnapshotVms.map(vm => xapi.getObject(vm.$ref))
// get the datetime of the most recent snapshot across both VDI and diskless VM snapshots
const lastSnapshotDateTime = [...this._jobSnapshotVdis, ...disklessVmSnapshots]
// 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)
.map(({ other_config }) => other_config[DATETIME])
.sort()
.pop()
@@ -419,9 +459,13 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
}
const retention = settings.snapshotRetention ?? 0
await asyncMap(getOldEntries(retention, datetimes), async datetime => {
// keep the last snapshot across all schedules for delta
// keep the last exported snapshot across all schedules for delta
// since we'll need it to compute delta for next backup
if (this.job.mode === 'delta' && datetime === lastSnapshotDateTime) {
if (
this.job.mode === 'delta' &&
lastExportedSnapshotDateTime !== undefined &&
datetime === lastExportedSnapshotDateTime
) {
return
}
const vdis = snapshotPerDatetime[datetime]
@@ -464,7 +508,9 @@ 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(
@@ -490,9 +536,15 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
}
const retention = settings.snapshotRetention ?? 0
await asyncEach(getOldEntries(retention, datetimes), async datetime => {
if (this.job.mode === 'delta' && datetime === lastSnapshotDateTime) {
if (
this.job.mode === 'delta' &&
lastExportedSnapshotDateTime !== undefined &&
datetime === lastExportedSnapshotDateTime
) {
return
}
this._forgetExportedVm(snapshotPerDatetime[datetime])
await xapi.VM_destroy(snapshotPerDatetime[datetime])
})
})
@@ -504,6 +556,15 @@ 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
@@ -551,6 +612,11 @@ 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(
@@ -614,6 +680,10 @@ 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

@@ -0,0 +1,659 @@
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 { checkVhd } from './_checkVhd.mjs'
import { checkDisk } from './_checkDisk.mjs'
import { packUuid } from './_packUuid.mjs'
import { openDiskChain } from '@xen-orchestra/backup-archive/disks'
import { isDisk, 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] !== '.' && _.endsWith('.vhd'),
filter: _ => _[0] !== '.' && isDisk(_),
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$/, '')
const parentDate = basename(parentDestPath).replace(/\.(alias\.vhd|vhd|hbd)$/, '')
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.getVhdFileName(filenameDate)}`
}/${adapter.getDiskFileName(filenameDate)}`
)
let metadataContent = await this._isAlreadyTransferred(timestamp)
@@ -273,8 +273,11 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
parentPath = relativeFromFile(path, parentDestPath)
}
const transferred = await adapter.writeVhd(path, disk, {
validator: tmpPath => checkVhd(handler, tmpPath),
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),
writeBlockConcurrency: this._config.writeBlockConcurrency,
uuid: packUuid(vdi.uuid),
parentUuid,

View File

@@ -263,6 +263,7 @@ 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

@@ -0,0 +1,6 @@
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

@@ -1,6 +0,0 @@
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

@@ -0,0 +1,148 @@
# 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.73.10",
"version": "0.74.2",
"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.0",
"@vates/nbd-client": "^3.5.1",
"@vates/parse-duration": "^0.1.1",
"@vates/task": "^0.7.0",
"@vates/types": "^1.30.1",
"@xen-orchestra/async-map": "^0.1.3",
"@vates/types": "^2.0.1",
"@xen-orchestra/async-map": "^0.1.4",
"@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.1",
"@xen-orchestra/backup-archive": "^1.1.2",
"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.3",
"tar": "^7.5.19",
"uuid": "^9.0.0",
"value-matcher": "^0.2.0",
"vhd-lib": "^4.16.1",
"xen-api": "^4.8.0",
"xen-api": "^4.9.0",
"yazl": "^2.5.1"
},
"devDependencies": {
@@ -67,7 +67,7 @@
"typescript": "^5.9.3"
},
"peerDependencies": {
"@xen-orchestra/xapi": "^8.10.2"
"@xen-orchestra/xapi": "^8.10.5"
},
"license": "AGPL-3.0-or-later",
"author": {

View File

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

View File

@@ -1,10 +1,12 @@
```
$ 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)
```
@@ -97,6 +99,28 @@ $ 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,10 +19,12 @@ 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)
```
@@ -115,6 +117,28 @@ $ 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.0",
"version": "2.2.1",
"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.73.10",
"@xen-orchestra/backup-archive": "^1.1.1",
"@xen-orchestra/backups": "^0.74.2",
"@xen-orchestra/backup-archive": "^1.1.2",
"@xen-orchestra/disk-transform": "^1.3.3",
"@xen-orchestra/fs": "^4.9.3",
"@xen-orchestra/qcow2": "^1.3.1",

View File

@@ -0,0 +1,35 @@
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 = toQcow2Stream(disk)
stream = await toQcow2Stream(disk)
}
await pipeline(stream, process.stdout, { end: false })

View File

@@ -46,6 +46,21 @@ 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,6 +2,7 @@
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>
@@ -9,13 +10,19 @@ 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)',
}
@@ -24,6 +31,7 @@ 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}
@@ -33,20 +41,25 @@ 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, diskPath, ...extraArgs] = process.argv
const [, , command, handlerUrl, ...args] = process.argv
if (!command || command === '--help' || command === '-h') {
showHelp(0)
}
if (!handlerUrl || !diskPath) {
console.error('Error: handler-url and disk-path are required\n')
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')
showHelp(1)
}

View File

@@ -0,0 +1,130 @@
/**
* 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,6 +13,13 @@ 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,6 +16,13 @@ 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) => {
@@ -29,11 +36,18 @@ 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',
@@ -52,7 +66,9 @@ const WITH_RETRY = {
_closeFile: {},
_copy: {},
_getInfo: {},
_getLinkCount: {},
_getSize: {},
_link: {},
_list: {},
_mkdir: {},
_openFile: {},
@@ -78,7 +94,9 @@ const WITH_TIMEOUT = [
'_closeFile',
'_createReadStream',
'_getInfo',
'_getLinkCount',
'_getSize',
'_link',
'_list',
'_rename',
'_copy',
@@ -123,6 +141,10 @@ 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))
}
@@ -144,6 +166,15 @@ 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
@@ -165,7 +196,19 @@ export default class RemoteHandlerAbstract {
}
_conditionRetry(error) {
return !['EEXIST', 'EISDIR', 'ENOTEMPTY', 'ENOENT', 'ENOTDIR', 'SystemInUse', 'ERR_ASSERTION'].includes(error?.code)
return ![
'EEXIST',
'EISDIR',
'EMLINK',
'ENOTEMPTY',
'ENOENT',
'ENOTDIR',
'ENOTIMP',
'ENOTSUP',
'EPERM',
'SystemInUse',
'ERR_ASSERTION',
].includes(error?.code)
}
#applySafeGuards(options) {
@@ -223,7 +266,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 Error('Not implemented')
throw new NotImplementedError()
}
addPrefix(prefix) {
@@ -341,10 +384,36 @@ 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)
@@ -603,14 +672,8 @@ export default class RemoteHandlerAbstract {
}
}
// Methods that can be implemented by inheriting classes
useVhdDirectory() {
return this._remote.useVhdDirectory ?? false
}
async _closeFile(fd) {
throw new Error('Not implemented')
throw new NotImplementedError()
}
async _createOutputStream(file, { dirMode, ...options } = {}) {
@@ -627,13 +690,13 @@ export default class RemoteHandlerAbstract {
}
async _createReadStream(file, options) {
throw new Error('Not implemented')
throw new NotImplementedError()
}
// 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 Error('Not implemented')
throw new NotImplementedError()
}
// called to finalize the remote
@@ -647,16 +710,24 @@ export default class RemoteHandlerAbstract {
return () => Promise.resolve()
}
async _getLinkCount(path) {
throw new NotImplementedError()
}
async _getSize(file) {
throw new Error('Not implemented')
throw new NotImplementedError()
}
async _link(existingPath, newPath) {
throw new NotImplementedError()
}
async _list(dir) {
throw new Error('Not implemented')
throw new NotImplementedError()
}
async _mkdir(dir) {
throw new Error('Not implemented')
throw new NotImplementedError()
}
async _mktree(dir, { mode } = {}) {
@@ -673,7 +744,7 @@ export default class RemoteHandlerAbstract {
}
async _openFile(path, flags) {
throw new Error('Not implemented')
throw new NotImplementedError()
}
async _outputFile(file, data, { dirMode, flags }) {
@@ -711,7 +782,7 @@ export default class RemoteHandlerAbstract {
}
_read(file, buffer, position) {
throw new Error('Not implemented')
throw new NotImplementedError()
}
_readFile(file, options) {
@@ -719,14 +790,14 @@ export default class RemoteHandlerAbstract {
}
async _rename(oldPath, newPath) {
throw new Error('Not implemented')
throw new NotImplementedError()
}
async _copy(oldPath, newPath) {
throw new Error('Not implemented')
throw new NotImplementedError()
}
async _rmdir(dir) {
throw new Error('Not implemented')
throw new NotImplementedError()
}
async _rmtree(dir) {
@@ -766,7 +837,7 @@ export default class RemoteHandlerAbstract {
async _sync() {}
async _unlink(file) {
throw new Error('Not implemented')
throw new NotImplementedError()
}
async _write(file, buffer, position) {
@@ -784,11 +855,11 @@ export default class RemoteHandlerAbstract {
}
async _writeFd(fd, buffer, position) {
throw new Error('Not implemented')
throw new NotImplementedError()
}
async _writeFile(file, data, options) {
throw new Error('Not implemented')
throw new NotImplementedError()
}
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 from './abstract'
import AbstractHandler, { NotImplementedError } from './abstract'
import fs from 'fs-extra'
import tmp from 'tmp'
const TIMEOUT = 12e5
class TestHandler extends AbstractHandler {
constructor() {
constructor(remoteOverrides = {}) {
const options = { timeout: TIMEOUT, withRetry: [] }
super({ url: 'test://' }, options)
super({ url: 'test://', ...remoteOverrides }, options)
Object.defineProperty(this, 'isEncrypted', {
get: () => false, // encryption is tested separately
})
@@ -58,6 +58,47 @@ 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()
@@ -225,4 +266,17 @@ 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,6 +19,12 @@ 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)
@@ -313,8 +319,4 @@ export default class AzureHandler extends RemoteHandlerAbstract {
await blobBatchClient.submitBatch(batch)
}
}
useVhdDirectory() {
return true
}
}

View File

@@ -0,0 +1,41 @@
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,6 +110,30 @@ 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,6 +7,7 @@ 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,
@@ -38,5 +39,4 @@ 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