Compare commits

..

195 Commits

Author SHA1 Message Date
unel
abc3018b66 feat(uiObjectLink): replace all uiObjectLink by uiLink 2026-04-27 14:22:45 +02:00
unel
423f00fefa rebase 2026-04-27 14:22:45 +02:00
unel
7456ab9faf feedback 2026-04-27 14:22:02 +02:00
unel
4d30d43a66 add changelog 2026-04-27 14:22:01 +02:00
unel
d1f3efc57f feat(xo6): rebase and resolve comment 2026-04-27 14:22:01 +02:00
unel
1d881fe8cc feat(xo6/uiLink): wrap uiLink on side panel 2026-04-27 14:22:01 +02:00
unel
7a9de0de57 feat(xo6/uiLink): add text ellipsis on uiLink 2026-04-27 14:21:56 +02:00
Joris K
699fb196fb feat(xo6): add possibility to remove a snapshot (#9749) 2026-04-27 10:25:14 +02:00
Mathieu
00e0bee372 fix(xo-server): fix default-template still in xo after deletion (#9760)
When VM_destroy is called on a default template, it is first converted to a simple template (and then to a VM).

After converting a default template to a simple template, the object received after the xapiObjectToXo transformation has a different ID (the default template's ID = pool.uuid + template.uuid, and non default template ID = template.uuid).

Since this object does not already exist in the XO server cache(because the ID is new), XO treats it as a new object and not as an update, so the old object with ID pool.uuid + template.uuid stay in the cache
2026-04-27 08:39:51 +02:00
Florent BEAUCHAMP
da045e0de1 fix(backups): use a delta transfer even if the VM is modified (#9709)
* fix(backups): use a delta transfer even if the VM is modified
* test(backup): fix date test without timezone
* refactor(backups): extract method that check which snapshot can be reused for replica target
* reset before launching the replication
2026-04-24 19:30:51 +02:00
Bastien Nollet
fdb82ed68a feat: technical release (#9768) 2026-04-24 14:38:15 +02:00
Pierre Brunet
112c22e748 fix: add chainPhysicalUsage property in vdi object (#9708)
*add  chainPhysicalUsage property to vdi
2026-04-23 16:29:55 +02:00
Thomas Moraine
c540a49643 doc(users.md): recommend against using local users in prod environments (#9761) 2026-04-23 15:13:14 +02:00
Joris K
f6484a0695 feat(xo6): add possibility to delete a VBD (#9698) 2026-04-21 16:34:13 +02:00
Joris K
5593f27110 feat(xo6): add possibility to remove VDIs (#9689) 2026-04-21 15:41:15 +02:00
Joris K
81813c7e5b feat(xo6): add possibility to remove VIFs (#9601) 2026-04-21 15:19:06 +02:00
Mathieu
0bf0a468b5 fix(rest-api): fix other_config being ignored on VDI creation (#9695) 2026-04-21 12:35:33 +02:00
Pierre Brunet
e78275f046 docs: fix typo (#9739) 2026-04-21 11:39:49 +02:00
spacotte-vates
89c7551293 feat(rest-api): add connect/disconnect vif actions (#9643) 2026-04-21 10:25:24 +02:00
Mathieu
ed30291993 fix(rest-api): fix double slash in the href property (#9741)
Introduced by dd5f0cdaa9
2026-04-21 10:07:52 +02:00
Pierre Donias
9765435471 feat(xo-web/servers): remind users to only add pool masters (#9742) 2026-04-20 15:43:02 +02:00
spacotte-vates
e2a4bd2231 fix(changelog): add version 6.2.3 (#9743) 2026-04-20 15:10:02 +02:00
Florent BEAUCHAMP
c6ccd987e2 fix(xo-server): TLSSocket memory leak — stoppable + http-server-plus incompatibility (#9725)
xo-server uses two libraries for its web server:

    http-server-plus — a multi-protocol server facade that multiplexes HTTP and HTTPS listeners behind a single EventEmitter interface ( introduced here JsCommunity/http-server-plus@ec63f3f )
    stoppable — wraps the server to track open connections for graceful shutdown, using an internal reqsPerSocket Map (server._pendingSockets) (introduced here : 782505b )


Fix

@vates/http-server-plus (fork of JsCommunity/http-server-plus): add 'secureConnection' to the forwardedEvents list so that webServer.on('secureConnection', handler) is propagated to underlying https.Server instances at listen() time.

xo-server/src/index.mjs: register the missing handler that stoppable was supposed to add but never did:
2026-04-20 14:38:37 +02:00
Mathieu
45f810c044 feat(openmetrics): add VM status and uptime metrics (#9684)
* feat(openmetrics): add VM status and uptime metrics

* refactor(openmetrics): address review feedback on VM status/uptime
2026-04-20 14:09:28 +02:00
Bastien Nollet
fbba05bbde feat(backups): use XO Tasks (#9734)
Change the backups so they stop using their own task system, and use the same system as XO Tasks.

For the moment, it shouldn't affect the users, but when the previous backup logs will be old enough to be erased, this will allow us to have shorter loading times for backup logs.

XO-52
2026-04-17 17:49:18 +02:00
OlivierFL
9dc52f2e5b fix(xo-6/network-form): toRef causes TS error on build (#9736) 2026-04-17 17:33:06 +02:00
Mathieu
271d123395 fix(rest-api): SSE MiB limit instead percent (#9731) 2026-04-17 16:58:26 +02:00
Enée DI IORIO
88a89cc3a9 fix(changelog): fix PR link formatting in changelogs (#9732) 2026-04-17 11:46:47 +02:00
Florent BEAUCHAMP
5f7fab9d34 test(backups): replication and full mirror backups
* test(replication): test the new snapshot based replication

* fix(tests): use mergeBackupsSynchronously to ensure the backups don't fails with lock already heled error

* fix: ensure the repository that will be purged start empty

* test(backup): add test for full mirror backups
2026-04-17 11:25:38 +02:00
spacotte-vates
8df8ef0af8 feat(backups): log merge size (#9679)
XO-2050

Add the merged size in the cleanVm task log
2026-04-17 09:58:12 +02:00
Mathieu
6fbb961e7f fix(xo-server): fix 408 timeout when copying a VM with compression (#9699)
* fix compression not used on front whe copying a VM
* ensure the first bytes are ready before starting to import the VM 

---------

Co-authored-by: Florent BEAUCHAMP <florent.beauchamp@vates.tech>
2026-04-17 09:56:39 +02:00
Mathieu
6b1a2afc9c docs(@vates/types): document vm.videoram (#9694) 2026-04-16 16:05:28 +02:00
Pierre Donias
3ed8c7b689 feat(netbox): introduce sub-platforms with major version number (#9644)
Fixes #7773
See Zammad#53857

On Netbox >= 4.4 (which introduced platform hierarchies):
- If the major version number is available: create a versioned child platform (e.g. "Debian 12") with the distro-only platform (e.g. "Debian") as its parent, and assign the child to the VM
- Otherwise: keep previous behaviour and assign the VM to the distro-only platform
2026-04-16 10:31:32 +02:00
Mathieu
db9c4815b1 feat(openmetrics): add 9 missing host RRD metrics (#9696) 2026-04-15 19:27:03 +02:00
Mathieu
3e21edad4e chore: upgrade dependencies with known security vulnerabilities (#9640)
* chore: upgrade dependencies with known security vulnerabilities

* Update Node.js version in CI workflow

* chore: upgrade additional security dependencies

* chore: stabilize yarn.lock path-to-regexp entry

* chore: bump minimum version ranges for security-patched dependencies

* chore: update CHANGELOG.unreleased.md with security upgrades

* chore: revert vite upgrade to 6.4.1 (6.4.2 breaks vue-tsc)

* chore: fix vite upgrade and pin vue to 3.5.28
2026-04-15 16:56:43 +02:00
vates-bot
1b12aebb47 feat(web-stack/i18n): update Xen Orchestra 6 (#9649) 2026-04-15 14:43:26 +02:00
p-bo
2e009535aa fix(i18n): shutdown -> reboot in force reboot dialog (as in French) (#9683)
99d19012ad/%40xen-orchestra/web-core/lib/locales/fr.json (L485)
2026-04-15 14:36:13 +02:00
Elise-F
5af32683ce feat(web-core): update default tab functionality (#9651) 2026-04-15 12:40:20 +02:00
Mathieu
0fef765ce6 fix(rest-api): fix memory-leak on subscription (#9707) 2026-04-15 12:18:06 +02:00
Pierre Donias
4508e01644 fix(CHANGELOG): markdown, URLs, labels, ... (#9723) 2026-04-15 11:56:25 +02:00
Pierre Briffaux
f60203a927 fix(web): fix lost focus on vdi name input (#9685) 2026-04-15 11:29:11 +02:00
Mathieu
5ebefb0af2 feat(openmetrics): add VDI disk size and physical usage metrics (#9680)
Fixes XO-1995
2026-04-15 09:52:26 +02:00
Thomas Moraine
fa8844037f docs(xen-orchestra): upgrade docusaurus to v3.10.0 (#9682) 2026-04-15 09:40:19 +02:00
Bastien Nollet
2098c02e7f chore(xo-web): remove unused function (#9691) 2026-04-15 09:37:11 +02:00
Mathieu
c4763d5eec feat(rest-api,mcp): add ?markdown=true output format to REST API (#9624) 2026-04-15 09:30:20 +02:00
Elise-F
0b78cab0b3 fix(web-core): match npm package version (#9721)
web-core 0.49.0 was accidentally published to npm.
This commit bumps the version to match what is already on npm.
2026-04-14 18:18:38 +02:00
Elise-F
bbf3e1e446 feat: release 6.3.3 (#9720) 2026-04-14 17:19:55 +02:00
Elise-F
d94de6090b feat: technical release (#9716) 2026-04-14 15:31:22 +02:00
Bastien Nollet
816b60f11b docs(backups): extra details (#9693) 2026-04-14 14:20:07 +02:00
Florent BEAUCHAMP
6b36b41d68 fix(xo-web): toggle distributed replication (#9715)
introduced by #9433
2026-04-14 11:44:26 +02:00
spacotte-vates
e9caeafd7a fix(bakups): fix merge resume issue when child is disk chain (#9668)
* fix(bakups): fix merge resume issue when child is disk chain
2026-04-14 11:04:23 +02:00
Pierre Brunet
06c3933756 test(backups): add unit test to check #9667 (#9670) 2026-04-13 18:30:17 +02:00
Mathieu
30ff04d88a docs(mcp): add multi-instance configuration (#9705) 2026-04-13 18:25:27 +02:00
Florent BEAUCHAMP
43d86038b1 fix(backups): Fix "Storage_error ([S(Illegal_transition);[[S(Activated);S(RO)];[S(Activated);S(RW)]]])" (#9702)
* don't connect NBD server if we only want the block list
* wait for the disk to be disconnected from dom0 before trying to write into it
2026-04-13 16:46:23 +02:00
Thomas Moraine
415207d1ba docs(intro_backup.md): fix broken youtube embed (#9701) 2026-04-13 10:41:57 +02:00
spacotte-vates
b21e5e8c53 fix(backups): fix vhd directory merge speed regression (#9692)
* fix(backups): fix vhd directory merge speed regression

* add changelog
2026-04-13 09:35:40 +02:00
OlivierFL
aa605639e4 feat(xo-6): network creation forms (#9629) 2026-04-10 17:35:21 +02:00
Elise-F
8ecaa6d817 fix(xo6): increase SSE ping timeout (#9681)
Introduced by #9375
2026-04-09 10:14:54 +02:00
Mathieu
76655a9e05 fix(@xen-orchestra/immutable-backups): fix missing prepublishOnly entry (#9687)
See zammad#51952
2026-04-08 16:12:20 +02:00
Elise-F
58b56a0749 fix(XO6): 'please wait' page not displayed on dev pages (#9686) 2026-04-08 14:41:50 +02:00
Thomas Moraine
99d19012ad docs(xo): replace some XO5 screenshots with the XO6 versions (#9678) 2026-04-07 09:24:38 +02:00
Elise-F
c1e5f2e8d7 feat: release XO 6.3.2 (#9676) 2026-04-03 15:21:41 +02:00
Elise-F
372a2be21d feat: technical release (#9673) 2026-04-03 10:47:59 +02:00
Florent BEAUCHAMP
3acd35142c fix(backups): don't fail incremental replication when the VM has VTPM (#9671) 2026-04-03 10:06:44 +02:00
Florent BEAUCHAMP
28c5e5f138 fix(backups): schedule reference is missing (#9667)
introduced by #9635
2026-04-02 14:47:00 +02:00
Elise-F
a6c508be46 feat(lite): 0.20.0 (#9666) 2026-04-01 16:27:01 +02:00
Elise-F
875ceb7cab feat: release XO 6.3.1 (#9665) 2026-04-01 15:08:02 +02:00
Thomas Moraine
d98dd78168 docs(manage-infrastructure.md): fix formatting errors in info panels (#9664)
Signed-off-by: Thomas Moraine <thomas.moraine@vates.tech>
2026-04-01 13:07:04 +02:00
Elise-F
df0c69c023 feat: technical release (#9663) 2026-04-01 10:37:53 +02:00
Mathieu
df7ffbb90c fix(web-core): fix objects store not updated (#9660)
* fix(web-core): fix objects store not updated
2026-04-01 10:10:23 +02:00
Mathieu
8553f1cd08 fix(rest-api): fix no such VDI for /vms/:id/(dashboard|vdis) (#9662)
* fix(rest-api): fix no such VDI for /vms/:id/(dashboard|vdis)
2026-04-01 10:07:10 +02:00
Florent BEAUCHAMP
41de7528bf fix(backups): full when going from 6.2 to 6.3 (#9661) 2026-04-01 09:48:55 +02:00
Elise-F
bfb0a052ef feat: release XO 6.3.0 (#9658) 2026-03-31 16:37:31 +02:00
Elise-F
5bd04b0736 feat: technical release (#9656) 2026-03-31 14:52:50 +02:00
Mathieu
4015987b03 fix(web-core): fix performance issue when lot of new events (#9627) 2026-03-31 12:05:00 +02:00
Elise-F
25db113349 feat: technical release (#9654) 2026-03-31 10:00:56 +02:00
spacotte-vates
b8637097c2 fix(backups): fix double close on merge (#9636)
* fix(backups): fix double close on merge

* set dispose to promise instead of empty func
2026-03-31 09:20:06 +02:00
Mathieu
9226c51df7 fix(rest-api): cannot read properties of undefined for vms/:id/dashboard (#9650)
Fix forum#12031
2026-03-30 20:07:45 +02:00
Joris K
14328ad62a feat(web-core): add stepper component (#9569) 2026-03-30 17:19:29 +02:00
Florent BEAUCHAMP
ac8dfeb7f5 feat(backups): improve incremental replication (#9635) 2026-03-30 17:04:16 +02:00
OlivierFL
bce3c88915 fix(xo-core): wrong translation key on PT locale (#9652)
Introduced by 658de40
2026-03-30 15:55:53 +02:00
DustyArmstrong
658de40f9e fix(web-core): fix some grammar issues on the XO 6 Dashboard (#9647) 2026-03-30 15:31:16 +02:00
Pierre Donias
b413db14e7 fix(xo-server-netbox): avoid mutating TYPES_WITH_UUID constant (#9607) 2026-03-30 15:24:58 +02:00
Enée DI IORIO
e6e5031964 feat(xo6/lite): add bug tools download button (#9419) 2026-03-30 14:35:45 +02:00
Florent BEAUCHAMP
484b9a02a3 docs(openmetrics): add documentation for xo metrics (#9631)
introduced by 9535
2026-03-30 14:34:32 +02:00
OlivierFL
a7829414b0 chore(web-core/query-builder): add query builder documentation (#9541) 2026-03-30 10:56:05 +02:00
vates-bot
39acc6b3a0 feat(web-stack/i18n): update Xen Orchestra 6 (#9554) 2026-03-30 10:55:00 +02:00
Mathieu
465c00b71d fix(xo-stack): return null instead of 0 for every NaN stats (#9634) 2026-03-27 17:26:55 +01:00
Mathieu
6814f6b2ef feat(qa-test): migrate xo-qatest into monorepo as @xen-orchestra/qa-test (#9626)
* feat(qa-test): migrate xo-qatest into monorepo as @xen-orchestra/qa-test
2026-03-27 14:35:03 +01:00
Elise-F
cc4cc1796b feat: technical release (#9646) 2026-03-27 14:22:03 +01:00
Florent BEAUCHAMP
1d81c0b26e fix(xapi): add missing package to changelog (#9645)
introduced by #9596
2026-03-27 13:46:38 +01:00
Elise-F
04a6fb3805 feat: technical release (#9642) 2026-03-27 10:23:50 +01:00
Florent BEAUCHAMP
1302618f90 fix(backup): compute the restore size for incremental restore (#9632)
introduced by #8432
2026-03-26 11:48:44 +01:00
Elise-F
7a39e45ffb feat(xo6): add please wait page for first connection in xo server (#9568) 2026-03-26 11:27:16 +01:00
Florent BEAUCHAMP
4bbfa77ec8 feat(xo5/sr): add preferred-image-format field (#9596) 2026-03-26 10:43:52 +01:00
Elise-F
57414dafce feat(xo6): implement vm snapshot tab page (#9521) 2026-03-26 10:03:19 +01:00
Elise-F
e28e768c72 Fix(xo6): remove scrollbar from console tab (#9609) 2026-03-26 09:14:24 +01:00
Joris K
8e5809a675 feat(xo6): add backup replication on vm dashboard (#9545) 2026-03-25 14:55:54 +01:00
Mathieu
56b17ce7f6 feat(rest-api): expose create internal and bonded network (#9611) 2026-03-25 11:25:06 +01:00
Mathieu
27a119f037 refactor(mcp): split monolithic index.mts into modular file structure (#9621)
XO-2221
2026-03-25 11:14:48 +01:00
Elise-F
60ba5070c9 fix(XO6): update watch to avoid reset template select in new VM (#9603) 2026-03-24 17:33:01 +01:00
Florent BEAUCHAMP
0efa078190 fix(backups): vhd directory have empty names (#9633) 2026-03-24 17:05:49 +01:00
Mathieu
c3dcb8fd50 feat(mcp): add list_srs and get_sr_details tools for SR (#9599)
* feat(mcp): add list_srs and get_sr_details tools for storage
repositories

* docs(mcp): add list_srs and get_sr_details to documentation

* fix(mcp): extract expected tool names into a constant in tests

* docs(mcp): add link to live filter syntax documentation for all filter
parameters
2026-03-24 16:39:58 +01:00
Florent BEAUCHAMP
0286f7786a fix(immutable-backups): decrease resource consumption, add tests and typing (#9548) 2026-03-24 16:00:01 +01:00
Florent BEAUCHAMP
f2b1931408 feat(disk-cli): implement disk cli tooling (#9551)
* feat(disk-cli): implement disk cli tooling

* changelog

* fix test path

* fix following review

* fix following rebase

* ci

* fix following rebase

* more tests
2026-03-24 14:35:05 +01:00
Florent BEAUCHAMP
f546849494 feat(xo-server): use index for getAllUnhealthyVdiChainsLength (#9622) 2026-03-24 10:37:18 +01:00
Florent BEAUCHAMP
6ae70a424a fix(backups): correctly rename replicated VMs (#9606) 2026-03-24 09:16:43 +01:00
Florent BEAUCHAMP
41751a8599 fix(backups): use the snapshot of the source (#9612)
* fix(backups): use the snapshot of the source

introduced by 9524

use only the vdi from the source VM as the source on backup
this bug could only occurs if the replication was intra pool, if
not the different xapi was filtering the results
2026-03-24 09:16:16 +01:00
Joris K
7ea8640ad0 fix(xo6/lite): fixed duplicated ip addresses in vm networks tab (#9547) 2026-03-23 16:29:41 +01:00
Enée DI IORIO
2994761178 fix(xo-lite/header): Fix menu button on large screen (#9558) 2026-03-23 10:12:56 +01:00
Mathieu
d1736e01f7 feat(mcp): add list_networks and get_network_details tools (#9595) 2026-03-20 09:38:59 +01:00
Mathieu
a2e3343b6e fix(rest-api/dashboard): exlude ISO SRs from dashboard (#9608) 2026-03-19 14:07:54 +01:00
Bastien Nollet
e325c6af51 docs(load-balancer): add info on migration cooldown (#9604) 2026-03-18 10:09:40 +01:00
Florent BEAUCHAMP
598ab85446 feat(vmware-explorer): make V2V import cancellable (#9552) 2026-03-17 18:17:08 +01:00
Pierre Brunet
1591749a23 fix(fs/s3): add check before using DeleteObjectsCommand (#9598)
fallback to delete object by object on multiple delete error  to handle backends that can't handle this command
2026-03-16 16:56:33 +01:00
Mathieu
800fd97996 feat(openmetrics): add missing VBD and DCMI metrics (#9563)
XO-1491
2026-03-16 11:37:19 +01:00
Pierre Brunet
45aee36ae7 typescript: Add types in several packages (#9583)
* feat: add types for fs (#9515)

* feat: add types for fs

* fix: update from review

* fix: update devDep

* feat: add types from @xen-orchestra/fs/path

* feat: export types based on async-each

* fix: remove ts-expect-error because async-each is now typed

* fix: export backups types and packages

* fix: update tsconfig async-each and fix types in MergeRemoteDisk

* fix: extractIdsFromSimplePattern from backups

* fix: package.json

* feat: export vhd-lib types

* feat(disks): export types

* fix(backups/disks): make params optional

* fix(backups/disks): small update in jsdoc

* bump: update yarn.lock

* fix: update vhd-lib exports

* fix(vhd-lib): update package exports

* fix: revert to previous import

* fix: new approach without exports

* fix: revert types except for asyncEach, openDisk

* fix(disks): import in vhd-lib

* fix(remoteVhdDisk): update typedef
2026-03-16 10:55:18 +01:00
Mathieu
2aff87d6d6 feat(mcp): add list_vdis tool to list virtual disks (#9559) 2026-03-13 15:54:40 +01:00
Mathieu
449e79de21 feat(rest-api): add disable/enable action endpoints for hosts (#9532) 2026-03-13 10:03:56 +01:00
MlssFrncJrg
9d657ac7cc feat(@xen-orchestra/rest-api): expose forget SR (#9505) 2026-03-12 16:12:43 +01:00
Enée DI IORIO
f4cc40233c fix(xo6/backups): backupLog transfer size calculation (#9496) 2026-03-12 15:09:19 +01:00
MlssFrncJrg
2cd5ba0319 feat(@xen-orchestra/rest-api): expose vms/:id/actions/clone (#9453) 2026-03-11 15:58:18 +01:00
Mathieu
2444861082 fix(rest-api/xo6): cpu at VM creation was not working (#9591)
* fix(rest-api/xo6): cpu at VM creation was not working

* changelog
2026-03-11 15:07:56 +01:00
Florent BEAUCHAMP
7ddff121de feat(fs): make part size configurable for s3 (#9561)
from https://xcp-ng.org/forum/topic/10587/s3-backup-maximum-number-of-parts/
2026-03-11 09:54:08 +01:00
Florent BEAUCHAMP
c1e9b83adc feat(backups): symetrical backups (#9524) 2026-03-11 09:34:09 +01:00
Mathieu
18d9b33c87 feat(mcp): support token authentication via XO_TOKEN (#9577) 2026-03-11 09:20:40 +01:00
Bastien Nollet
673e729afe fix(xo-server): incorrect import (#9589) 2026-03-10 19:25:55 +01:00
Florent BEAUCHAMP
4e0655dc3d fix(backups): better handling of generator cleanup (#9557) 2026-03-10 15:55:59 +01:00
bleader
a78870b473 docs(sdn-controller): mention xapi plugin is in BETA (#9556) 2026-03-10 15:42:16 +01:00
Thomas Moraine
0bf309a4ad docs(sdn_controller.md): clarify requirements for regenerating certificates (#9584) 2026-03-10 09:54:01 +01:00
spacotte-vates
5bdd76a955 feat: release 6.2.2 (#9579) 2026-03-09 14:41:09 +01:00
Pierre Brunet
e11530ea7c feat: technical release (#9576) 2026-03-09 10:10:36 +01:00
Florent BEAUCHAMP
c70f911b5e fix(changelog): remove package from release list (#9575)
introduced during rebase by #9572
2026-03-09 09:56:22 +01:00
Mathieu
82f047ef9d fix(xo-server): proxy issue if hostname defined (#9572)
fix #9500
2026-03-09 09:49:24 +01:00
Mathieu
57aec1ab2d fix(xo-server): race condition on XOA WebSocket during plugin loading (#9402) 2026-03-09 09:42:53 +01:00
Pierre Donias
385fcf3810 fix(xo-server/vm): allocate resource set quotas when not using DMC (#9566)
When editing VM RAM, the high-level `memory` field dispatches to `memoryMax` or
`_memory` depending on whether the VM uses DMC. Both paths need `limitName:
'memory'` on their spec so the resource set quota counter is correctly updated,
but `_memory` was missing it, causing memory resizes on non-DMC VMs to silently
create a stale `_memory` counter instead of updating the actual memory quota.
2026-03-09 09:37:24 +01:00
Florent BEAUCHAMP
6699bd1f5d fix(backups): remove snapshot of vm with cdrommounted (#9571) 2026-03-06 17:28:50 +01:00
Pierre Brunet
844c07e166 feat: technical release (#9570) 2026-03-06 14:49:29 +01:00
spacotte-vates
7676978c78 fix(backups): fix out of range error on merge (#9567)
Fixes out of range error during merge that was happening on delta backups when the child disk was bigger than the parent disk but no blocks where written in the "new" space.

Also added a test for this error.
2026-03-06 14:17:17 +01:00
Elise-F
7054fefdbd Style(xo6): update color for status paused VM icon (#9562) 2026-03-05 11:21:06 +01:00
Enée DI IORIO
acd84649ed feat(xo6): add backupRuns and BackupArchives card on vm dashboard (#9303) 2026-03-05 10:32:07 +01:00
Florent BEAUCHAMP
7460bf93d1 feat(openmetrics): add XO related metrics (#9535) 2026-03-04 10:30:20 +01:00
Mathieu
61e4a77cab fix(openmetrics): convert latency from µs to seconds instead of ms (#9550) 2026-03-03 10:01:56 +01:00
vates-bot
55130311f3 feat(web-stack/i18n): update Xen Orchestra 6 (#9531) 2026-03-03 09:18:35 +01:00
Florent BEAUCHAMP
f0cbd1bd72 docs(backup): document distributed backups (#9528)
* docs(backup): document distributed backups

* Apply suggestions from MPT code review

Co-authored-by: Mathieu <goore.csmoviz@gmail.com>

---------

Co-authored-by: Mathieu <goore.csmoviz@gmail.com>
2026-03-03 09:11:36 +01:00
Enée DI IORIO
561e2349e9 feat(xo6-lite/dashboard): add reactivity on resize (#9378) 2026-03-02 14:59:51 +01:00
Enée DI IORIO
7c83ed63f1 fix(web-core/treeItemLabel): fix treeview tooltip overlap (#9319) 2026-03-02 10:41:26 +01:00
Enée DI IORIO
9525abdee5 feat(xo6/Lite): add secureBoot support (#9423) 2026-02-27 15:09:49 +01:00
spacotte-vates
c6172b7b74 feat: release 6.2.1 (#9546) 2026-02-27 14:42:27 +01:00
Pierre Brunet
1b865bbf89 feat: technical release (#9544)
* feat(@xen-orchestra/backups): 0.69.2

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

* feat(xo-server): 5.197.3

* chore(CHANGELOG): update next

* fix: update changelog
2026-02-27 11:56:10 +01:00
spacotte-vates
815f4be76c fix(backups): changelog (#9543) 2026-02-27 11:44:13 +01:00
spacotte-vates
53f5c63fa2 fix(backups): race condition on merge (#9542) 2026-02-27 11:29:42 +01:00
spacotte-vates
4ffd1b4e13 feat(lite): 0.19.0 (#9540) 2026-02-26 18:29:55 +01:00
spacotte-vates
d25d15efd7 feat: release 6.2.0 (#9539) 2026-02-26 17:46:07 +01:00
Pierre Brunet
322205d203 feat: technical release (#9537) 2026-02-26 14:57:42 +01:00
Mathieu
89494457a1 fix(mcp): use bin wrapper to fix npx permission denied (#9536)
Fix npx @xen-orchestra/mcp failing with "Permission denied".

tsc does not preserve the executable bit on compiled files, so bin pointing to ./dist/index.mjs (mode 644) caused the error. This adds a bin/xo-mcp.mjs wrapper tracked by git with mode 755, following the same pattern as other packages (@xen-orchestra/xapi, @xen-orchestra/proxy, etc.).
2026-02-26 13:34:08 +01:00
Pierre Briffaux
6bc2844092 feat(xo6/new-vm): add custom user-config to new VM creation (#9427) 2026-02-26 13:15:30 +01:00
Mathieu
53c15bc9e4 docs(mcp) : documentation (#9529)
docs(mcp): add README and Docusaurus documentation page
2026-02-25 17:19:38 +01:00
Pierre Brunet
1dd8c1603f Release (#9534) 2026-02-25 16:19:54 +01:00
Mathieu
52513fc898 feat(xo-server): add transient option to host.disable (#9503)
Add optional transient parameter (boolean) to host.disable API endpoint.

When transient=true, passes auto_enable=false to XAPI, keeping the host disabled across reboots and toolstack restarts (requires XAPI >= 25.31.0). Default behavior unchanged (backward compatible).

XAPI 25.31.0 introduced a new auto_enable parameter to Host.disable (xen-api#6652). When set to false, the host stays disabled regardless of toolstack restarts, host reboots, or consider_enabling_host calls. Only an explicit Host.enable can re-activate it.
2026-02-25 15:54:26 +01:00
spacotte-vates
ed508ec04f feat: technical release (#9533)
* feat(@xen-orchestra/backups): 0.69.1

* feat(complex-matcher): 1.1.0

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

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

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

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

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

* feat(xo-server): 5.197.1

* feat(xo-web): 5.194.0

* chore(CHANGELOG): update next

---------

Co-authored-by: Pierre Brunet <pierre.brunet@vates.tech>
Co-authored-by: Pierre Donias <pierre.donias@gmail.com>
2026-02-25 15:39:25 +01:00
MathieuRA
21823bf430 feat: add rest-api debug 2026-02-25 14:13:30 +01:00
Florent BEAUCHAMP
e36e1012e2 fix(xo-web): reducing polling for patches and license 2026-02-25 14:13:30 +01:00
Elise-F
3fcf582087 feat(new VM): add ssh key to vm creation form (#9413) 2026-02-25 10:24:29 +01:00
vates-bot
f1389cff6e feat(web-stack/i18n): update Xen Orchestra 6 (#9462) 2026-02-25 09:39:32 +01:00
Mathieu
438a7cc746 feat(mcp): add @xen-orchestra/mcp package (#9519)
This PR adds the new @xen-orchestra/mcp package — an MCP (Model Context Protocol) server that enables AI assistants (Claude Desktop, Claude Code, or any MCP-compatible client) to query a Xen Orchestra infrastructure in read-only mode.
2026-02-24 17:10:32 +01:00
Florent BEAUCHAMP
31e2ff1b02 feat(backups): only check size for full backups (#9527)
The size is computed from the blocksize * nb allocated blocks during the backups
which is not aligned with the real size on disk
Checking the file on disk is too costly for vhd directory
This will be eventually reimplemented by the next cleanVm rework
2026-02-24 17:04:58 +01:00
Thomas Moraine
44a23fb33f docs(sdn_controller.md): document openssl 3 + sdn upgrade path (#9525)
This pull request documents the manual steps that will be needed for the SDN controller, with the incoming March 2026 update of XCP-ng that will include OpenSSL3.
2026-02-24 13:21:26 +01:00
Pierre Donias
f8501c1a1e feat(xo-web/patches): warn about updating XOSTOR before installing patches (#9517) 2026-02-24 12:07:44 +01:00
spacotte-vates
6cab502260 feat(rest-api): sr scan route (#9514) 2026-02-24 11:05:18 +01:00
Pierre Donias
157e7fe757 feat(xo-web/licenses): display bundle name next to license name (#9512) 2026-02-23 16:20:46 +01:00
OlivierFL
0866a5db81 feat(xo-stack): implement Query Builder (#9488) 2026-02-23 15:35:23 +01:00
Pierre Donias
1c245acca5 feat(xo-web/network): reconfigure management PIF (#9510) 2026-02-23 14:36:18 +01:00
spacotte-vates
58c2c518a3 feat: technical release (#9523)
* feat(@xen-orchestra/fs): 4.6.7

* feat(@vates/types): 1.20.0

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

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

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

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

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

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

* feat(@xen-orchestra/vmware-explorer): 0.11.0

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

* feat(xo-server): 5.197.0

* feat(xo-server-load-balancer): 0.12.0

* feat(xo-server-netbox): 1.11.0

* feat(xo-server-openmetrics): 1.2.0

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

* feat(xo-web): 5.193.0

* chore(CHANGELOG): update next

---------

Co-authored-by: Pierre Brunet <pierre.brunet@vates.tech>
2026-02-23 10:23:57 +01:00
Elise-F
755ac108f2 feat(xo6): adds a banner when access to the xo server fails (#9375) 2026-02-20 17:12:29 +01:00
Bastien Nollet
f88c0e8be2 feat(rest-api): expose POST vdis (#9492) 2026-02-20 16:24:18 +01:00
Philippe Coval
109e37695c fix(sdn-controller): Support openssl-3 for ca/cert generation (#9507)
OpenSSL-3 (on xcp-ng) requires CA set to true in basicConstraints.

"All CAs should have the CA flag set to true."

For context, here are additional resources:

- https://docs.openssl.org/3.0/man1/openssl-verification-options/#basic-constraints
- https://docs.openssl.org/1.0.2/man1/x509v3_config/#basic-constraints
- https://datatracker.ietf.org/doc/html/rfc5280#section-4.2.1.9

To connect to OpenSSL 3, certificates should be re-generated if they
already exist (just remove xo-server/data/sdn-controller).

Renewed certs were tested on XCP-ng host on "OpenSSL 1.0.2k-fips"
without regression, so it is safe to assume those ext are designed to
be backward compatible.

Observed issue:

    openssl verify \
      -CAfile .../xo-server/data/sdn-controller/ca-cert.pem \
      .../xo-server/data/sdn-controller/client-cert.pem

    C=XX, L=Default City, O=Default Company LTD
    error 79 at 1 depth lookup: invalid CA certificate
    error .../xo-server/data/sdn-controller/client-cert.pem: \
      verification failed

The expected output is now:

    .../xo-server/data/sdn-controller/client-cert.pem: OK

The expected output is now:

    .../xo-server/data/sdn-controller/client-cert.pem: OK

It was tested along ovsdb-server (Open vSwitch) 2.17.7 :

    openssl s_client \
      -connect  10.1.75.62:6640 \
      -cert .../xo-server/data/sdn-controller/client-cert.pem \
      -key .../xo-server/data/sdn-controller/client-key.pem

    (...)
    CONNECTED(00000003)
    Can't use SSL_get_servername
    (...)
    verify error:num=18:self-signed certificate
    (...)
    SSL handshake has read 2713 bytes and written 3799 bytes
    Verification error: self-signed certificate
    (...)
    New, TLSv1.2, Cipher is AES128-GCM-SHA256
    (...)
    {"id":"echo","method":"echo","params":[]}

Extra info at:

- https://xapi-project.github.io/new-docs/design/pool-certificates/

Origin: https://github.com/vatesfr/xen-orchestra/pull/9507
Relate-to: XCPNG-2710
Relate-to: XO-1986
Signed-off-by: Philippe Coval <philippe.coval@vates.tech>
2026-02-20 09:34:13 +01:00
spacotte-vates
a4b480de4a feat(rest-api): add relaim_space action to sr (#9486) 2026-02-19 17:26:12 +01:00
spacotte-vates
db8addbc45 fix(backups): fix RemoteVhdDisk & DiskChain parent and directory issue (#9508)
* fix(backups): fix RemoteVhdDisk & DiskChain parent and directory issue
2026-02-18 14:06:05 +01:00
Sebastien Marie
9dbc090116 fix(xo-server-sdn-controller): communicate with enabled hosts only (#9442)
permit to have working traffic rules when a pool is in a 'degraded' mode (for
example, one host temporary down or unreachable).

currently, exceptions occurs and nothing happens (no rules added or deleted).
with it, unreachable hosts are ignored and reachable hosts properly updated.
2026-02-17 13:31:44 +01:00
OlivierFL
353678e754 feat(xo-6/internal-links): normalize internal links (#9276) 2026-02-17 08:20:01 +01:00
Florent BEAUCHAMP
a313986694 feat(backups): implements distributed backup and replications (#9433)
The deletion of old backups is done globally
For Full backups/replication:
 * retention is computed on the total of the target
 * choose the storage with the most free size ( if possible, since some backup repositories don't have any size used/ free )
 * one vm is written on the same target ( xva, index, checksum )
 * healthcheck ( if enabled ) will run only on the target that received the data
 * the cleanup of old backups/replication is done on the right target ( but considering the full lenght across all the targets )

For incremental: 
 * delta chain are continued on the same target 
 
For mirror : 
if a vm has multiple backups to transfer during the same run, then
they will all go to teh same remote
 
UX : 
* show a toggle on remote/sr selectors
* toggle is disabled if 1 or less targets are selected
* for backup and mirror backup forms
* show the details in the job list
  

More details on the PR page
2026-02-16 18:17:03 +01:00
Florent BEAUCHAMP
983ac2d2c9 docs(config): explain the config files priorities (#9463) 2026-02-16 18:11:50 +01:00
spacotte-vates
4e50858526 feat(@xen-orchestra/backups): refactor backup merge code (#9300)
this merge code leverage the new classes introduced to handle qcow2, improving our flexibility, and future uses.

this also improve the performance on "block mode" backups (s3/ azure and other storage with the option), since it reliably updates the block allocation table only at the end of the merge instead of each time a new block is detected
2026-02-16 18:04:12 +01:00
Mathieu
c497ae3d38 fix(web): use the store's object type and not type from vates/types (#9421) 2026-02-16 17:01:26 +01:00
spacotte-vates
9d9b5d5e33 feat(rest-api): add plug and unplug pbd routes to rest api (#9477) 2026-02-16 16:52:04 +01:00
OlivierFL
5834070e77 fix(xo-6/xo-lite): missing required prop for UiRadioButtonGroup in new VM creation form (#9504) 2026-02-16 16:50:40 +01:00
Enée DI IORIO
5c5f27f92b fix(xo-stack): fix VM creation on small screen (#9344) 2026-02-16 16:16:11 +01:00
Cyrille G.
8fc04bc03b fix(hub/recipe): remove DHCP option for the Kubernetes recipe (#9454) 2026-02-16 10:20:11 +01:00
Pierre Brunet
87135c7469 feat: add qcow2 support in vdi creation (#9493)
Add qcow2 image-format when size is higher than 2TB. It will still be a VHD if PBD.preferred-image-formats do not list qcow2
2026-02-16 09:56:08 +01:00
Mathieu
fb030a590e docs(openmetrics): update documentation for host uptime, host status and is_control_domain (#9497)
docs(openmetrics): update documentation for host uptime, host status and
is_control_domain
2026-02-16 09:55:02 +01:00
Florent BEAUCHAMP
0be2392519 feat(xo-server/V2V): automatically take a snapshot if needed (#9471) 2026-02-12 17:07:56 +01:00
Florent BEAUCHAMP
546d42427c feat(xo-web): remember V2V connections settings (#9490) 2026-02-12 15:42:47 +01:00
Mathieu
fc86fda13d fix(rest-api): exclude removable storage from top 5 SRs usage (#9495) 2026-02-12 14:04:12 +01:00
Elise-F
b44bed6d10 feat(web-core): new ui rich radio button component created (#9198) 2026-02-12 11:53:35 +01:00
875 changed files with 40135 additions and 7904 deletions

View File

@@ -251,6 +251,9 @@ module.exports = {
'ja',
'fi',
'pl',
'zh-Hans',
'sk',
'pt',
],
},
],
@@ -287,6 +290,17 @@ module.exports = {
'eslint-comments/no-unlimited-disable': 'off',
},
},
{
files: ['*.d.ts'],
parser: '@typescript-eslint/parser',
parserOptions: {
sourceType: 'module',
},
rules: {
'n/no-unsupported-features/es-syntax': 'off',
'no-unused-vars': 'off',
},
},
],
ignorePatterns: ['@vates/fatfs/'],

View File

@@ -25,7 +25,7 @@ jobs:
- name: Setup Node environment
uses: actions/setup-node@v4
with:
node-version: '20'
node-version: '24.14'
cache: 'yarn'
- name: Install project dependencies

5
@vates/async-each/index.d.ts vendored Normal file
View File

@@ -0,0 +1,5 @@
export function asyncEach<Item>(
iterable: Iterable<Item> | AsyncIterable<Item>,
iteratee: (item: Item, index: number, iterable: Iterable<Item> | AsyncIterable<Item>) => Promise<void>,
opts?: { concurrency?: number; signal?: AbortSignal; stopOnError?: boolean }
): Promise<void>

View File

@@ -67,20 +67,17 @@ describe('asyncEach', () => {
})
it('stops on first error when stopOnError is true', async () => {
const tracker = new assert.CallTracker()
const error = new Error()
const iteratee = tracker.calls((_, i) => {
const iteratee = spy((_, i) => {
if (i === 1) {
throw error
}
}, 2)
})
assert.deepStrictEqual(
await rejectionOf(asyncEach(iterable, iteratee, { concurrency: 1, stopOnError: true })),
error
)
tracker.verify()
assert.deepStrictEqual(iteratee.callCount, 2)
})
it('rejects AggregateError when stopOnError is false', async () => {
@@ -100,19 +97,16 @@ describe('asyncEach', () => {
})
it('can be interrupted with an AbortSignal', async () => {
const tracker = new assert.CallTracker()
const ac = new AbortController()
const iteratee = tracker.calls((_, i) => {
const iteratee = spy((_, i) => {
if (i === 1) {
ac.abort()
}
}, 2)
})
await assert.rejects(asyncEach(iterable, iteratee, { concurrency: 1, signal: ac.signal }), {
message: 'asyncEach aborted',
})
tracker.verify()
assert.deepStrictEqual(iteratee.callCount, 2)
})
it('handle error on iterable', async () => {

View File

@@ -24,7 +24,8 @@
"url": "https://vates.fr"
},
"license": "ISC",
"version": "1.0.1",
"types": "index.d.ts",
"version": "1.0.3",
"engines": {
"node": ">=8.10"
},

View File

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

View File

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

View File

@@ -1,6 +1,6 @@
{
"name": "@vates/generator-toolbox",
"version": "1.1.0",
"version": "1.1.2",
"main": "dist/index.mjs",
"license": "MIT",
"private": false,

View File

@@ -144,14 +144,7 @@ class Forked<T, TReturn, TNext> implements AsyncGenerator<T, TReturn, TNext> {
return this.#parent.remove(this.#uid, e)
}
async *[Symbol.asyncIterator](): AsyncGenerator<T> {
while (true) {
const res = await this.next()
if (res.done) {
break
}
yield res.value
}
[Symbol.asyncIterator](): AsyncGenerator<T, TReturn, TNext> {
return this
}
}

View File

@@ -2,8 +2,7 @@ import assert from 'node:assert'
import { suite, test } from 'node:test'
import { Synchronized } from './synchronized.mjs'
// eslint-disable-next-line @typescript-eslint/no-unused-vars
async function* makeRangeGenerator(end = Infinity, progress = { yielded: 0 }, onYielded = (val: unknown) => {}) {
async function* makeRangeGenerator(end = Infinity, progress = { yielded: 0 }, onYielded = (_val: unknown) => {}) {
for (let i = 0; i < end; i++) {
await new Promise(resolve => setTimeout(resolve, 10))
yield i
@@ -17,7 +16,7 @@ async function consume(
iterable: AsyncGenerator,
delay = 2500,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
onConsumed = (val: unknown, iterable: AsyncGenerator) => Promise.resolve(false)
onConsumed = (_val: unknown, _iterable: AsyncGenerator) => Promise.resolve(false)
) {
for await (const val of iterable) {
await new Promise(resolve => setTimeout(resolve, delay))
@@ -28,6 +27,30 @@ async function consume(
}
suite('success', () => {
test('for-await-of break stops the source generator', async () => {
let sourceClosed = false
const source = (async function* () {
try {
for (let i = 0; i < 10; i++) {
await new Promise(resolve => setTimeout(resolve, 10))
yield i
}
} finally {
sourceClosed = true
}
})()
const forker = new Synchronized(source)
const fork = forker.fork('first')
// for-await-of must call fork.return() on break, which propagates to the source
for await (const val of fork) {
if (val === 2) break
}
assert.strictEqual(sourceClosed, true)
})
test('if works with multiple consumer', async () => {
const progress = { yielded: 0 }
const generator = makeRangeGenerator(3, progress)

View File

@@ -1,4 +1,7 @@
import assert from 'node:assert'
const TIMEOUT = Symbol('timeout')
export class Timeout<T> implements AsyncGenerator {
#source: AsyncGenerator<T>
#timeout: number
@@ -8,21 +11,30 @@ export class Timeout<T> implements AsyncGenerator {
this.#timeout = timeout
}
async next(): Promise<IteratorResult<T>> {
let timeout: ReturnType<typeof setTimeout>
const promiseTimeout = new Promise((_, reject) => {
timeout = setTimeout(() => {
reject(new Error('Timeout reached '))
}, this.#timeout)
})
const promiseNext = new Promise((resolve, reject) => {
this.#source.next().then(res => {
// ensure timetout won't fire later
clearTimeout(timeout)
resolve(res)
}, reject)
})
// promiseTimeout will never resolve
return Promise.race([promiseNext, promiseTimeout]) as Promise<IteratorResult<T>>
let timeoutHandle: ReturnType<typeof setTimeout>
const sourceNext = this.#source.next()
const result = await Promise.race([
sourceNext.then(res => {
clearTimeout(timeoutHandle)
return res
}),
new Promise<typeof TIMEOUT>(resolve => {
timeoutHandle = setTimeout(() => resolve(TIMEOUT), this.#timeout)
}),
])
if (result === TIMEOUT) {
// stop the source once the in-flight next settles to avoid data loss on the next call
// we don't want to await for the end of timeouted code
sourceNext.then(
() => this.#source.return(undefined).catch(() => {}),
() => {} // source already errored, nothing to clean up
)
throw new Error('Timeout reached')
}
return result
}
return(): Promise<IteratorResult<T>> {
return this.#source.return(undefined)

View File

@@ -64,4 +64,24 @@ describe('Timeout class', () => {
await assert.rejects(timeout.throw(new Error('Test error')), 'Expected error was not thrown')
})
it('should close the source generator after a timeout', async () => {
let sourceClosed = false
const slowSource = (async function* () {
try {
// resolves after 100ms so the in-flight next() eventually settles
await new Promise(resolve => setTimeout(resolve, 100))
yield 1
} finally {
sourceClosed = true
}
})()
const timeout = new Timeout(slowSource, 10) // fires before source yields
await assert.rejects(() => timeout.next(), /Timeout reached/)
// wait for the in-flight next() to settle so source.return() can be called
await new Promise(resolve => setTimeout(resolve, 200))
assert.strictEqual(sourceClosed, true)
})
})

View File

@@ -0,0 +1,65 @@
### `create([opts], [requestListener])`
Creates a new server instance. `opts` may contain `createServer` and `createSecureServer` factories (defaults to `http.createServer` and `https.createServer`). `requestListener` is registered as a `request` event listener.
```js
import { create } from '@vates/http-server-plus'
const server = create(function onRequest(req, res) {
res.end('Hello')
})
```
### `server.listen(opts)`
Starts listening. Returns a promise that resolves to a human-readable address string, or rejects with `error.niceAddress` set.
```js
// HTTP on a specific port
await server.listen({ port: 8080 })
// HTTPS — detected automatically when cert+key are provided
await server.listen({
port: 443,
cert: fs.readFileSync('certificate.pem'),
key: fs.readFileSync('private_key.pem'),
})
// Unix socket
await server.listen({ socket: '/var/run/http.sock' })
// File descriptor
await server.listen({ fd: 3 })
// Systemd socket activation
await server.listen({ systemdSocket: 0 })
```
> As a convenience, if `hostname` is `'localhost'`, it will listen on both `127.0.0.1` and `::1`, similar to what Node does when no hostname is provided.
Multiple endpoints can be started on the same instance:
```js
const [httpAddr, httpsAddr] = await Promise.all([server.listen({ port: 80 }), server.listen({ port: 443, cert, key })])
console.log('listening on', httpAddr, httpsAddr)
```
### HTTP/2
Pass a custom `createSecureServer` factory to enable HTTP/2:
```js
import { createSecureServer } from 'node:http2'
import { create } from '@vates/http-server-plus'
const server = create({ createSecureServer }, app)
await server.listen({ port: 443, cert, key })
```
### `server.close()`
Closes all underlying servers. Returns a promise that resolves once the `close` event is emitted.
```js
await server.close()
```

View File

@@ -0,0 +1 @@
../../scripts/npmignore

View File

@@ -0,0 +1,91 @@
<!-- DO NOT EDIT MANUALLY, THIS FILE HAS BEEN GENERATED -->
# @vates/http-server-plus
> Augmented &#x60;http.Server&#x60;, HTTP/HTTPS/HTTP2 and multiple ports on the same instance
## Usage
### `create([opts], [requestListener])`
Creates a new server instance. `opts` may contain `createServer` and `createSecureServer` factories (defaults to `http.createServer` and `https.createServer`). `requestListener` is registered as a `request` event listener.
```js
import { create } from '@vates/http-server-plus'
const server = create(function onRequest(req, res) {
res.end('Hello')
})
```
### `server.listen(opts)`
Starts listening. Returns a promise that resolves to a human-readable address string, or rejects with `error.niceAddress` set.
```js
// HTTP on a specific port
await server.listen({ port: 8080 })
// HTTPS — detected automatically when cert+key are provided
await server.listen({
port: 443,
cert: fs.readFileSync('certificate.pem'),
key: fs.readFileSync('private_key.pem'),
})
// Unix socket
await server.listen({ socket: '/var/run/http.sock' })
// File descriptor
await server.listen({ fd: 3 })
// Systemd socket activation
await server.listen({ systemdSocket: 0 })
```
> As a convenience, if `hostname` is `'localhost'`, it will listen on both `127.0.0.1` and `::1`, similar to what Node does when no hostname is provided.
Multiple endpoints can be started on the same instance:
```js
const [httpAddr, httpsAddr] = await Promise.all([
server.listen({ port: 80 }),
server.listen({ port: 443, cert, key }),
])
console.log('listening on', httpAddr, httpsAddr)
```
### HTTP/2
Pass a custom `createSecureServer` factory to enable HTTP/2:
```js
import { createSecureServer } from 'node:http2'
import { create } from '@vates/http-server-plus'
const server = create({ createSecureServer }, app)
await server.listen({ port: 443, cert, key })
```
### `server.close()`
Closes all underlying servers. Returns a promise that resolves once the `close` event is emitted.
```js
await server.close()
```
## Contributions
Contributions are _very_ welcomed, either on the documentation or on
the code.
You may:
- report any [issue](https://github.com/vatesfr/xen-orchestra/issues)
you've encountered;
- fork and create a pull request.
## License
[ISC](https://spdx.org/licenses/ISC) © [Vates SAS](https://vates.fr)

View File

@@ -0,0 +1,268 @@
'use strict'
// ===================================================================
const EventEmitter = require('events').EventEmitter
const formatUrl = require('url').format
const fromEvent = require('promise-toolbox/fromEvent')
const inherits = require('util').inherits
const resolvePath = require('path').resolve
// ===================================================================
const forwardedEvents = [
'checkContinue',
'checkExpectation',
'clientError',
'connect',
'connection',
'listening',
'request',
'secureConnection',
'upgrade',
]
function extractProperty(obj, prop) {
const value = obj[prop]
if (value !== undefined) {
delete obj[prop]
return value
}
}
function forOwn(obj, cb) {
const keys = Object.keys(obj)
for (let i = 0, n = keys.length; i < n; ++i) {
cb(obj[keys[i]])
}
}
function getSystemdFd(index) {
if (process.pid !== +process.env.LISTEN_PID) {
throw new Error('systemd sockets are not meant for us (LISTEN_PID)')
}
const listenFds = process.env.LISTEN_FDS
if (listenFds == null) {
throw new Error('no systemd sockets found (LISTEN_FDS)')
}
const max = listenFds - 1
if (index > max) {
throw new Error('no such systemd socket found')
}
return index + 3 // 3 = SD_LISTEN_FDS_START
}
const isEmpty = obj => Object.keys(obj).length === 0
// ===================================================================
function onNewListener(event, listener) {
if (forwardedEvents.includes(event)) {
forOwn(this._servers, server => {
server.on(event, listener)
})
}
}
function onRemoveListener(event, listener) {
if (forwardedEvents.includes(event)) {
forOwn(this._servers, server => {
server.off(event, listener)
})
}
}
function Server(opts) {
EventEmitter.call(this)
this._createServer = (opts != null && opts.createServer) || require('http').createServer
this._createSecureServer = (opts != null && opts.createSecureServer) || require('https').createServer
this._servers = Object.create(null)
this._niceAddresses = Object.create(null)
this.on('removeListener', onRemoveListener).on('newListener', onNewListener)
}
inherits(Server, EventEmitter)
const proto = Server.prototype
function getAddress(serverId) {
return this[serverId].address()
}
proto.addresses = function Server$addresses() {
const servers = this._servers
return Object.keys(servers).map(getAddress, servers)
}
function getNiceAddress(serverId) {
return this[serverId]
}
proto.niceAddresses = function Server$niceAddresses() {
const niceAddresses = this._niceAddresses
return Object.keys(niceAddresses).map(getNiceAddress, niceAddresses)
}
function close(server) {
server.close()
}
proto.close = function Server$close(callback) {
if (callback) {
this.once('close', callback)
}
// Emit the close event even if there are no registered servers.
if (isEmpty(this._servers)) {
const self = this
setImmediate(function () {
self.emit('close')
})
return Promise.resolve()
}
// Closes each servers.
forOwn(this._servers, close)
return fromEvent(this, 'close')
}
let nextId = 0
proto.listen = function Server$listen(opts) {
opts = Object.assign({}, opts)
if (opts.hostname === 'localhost') {
return Promise.all([
this.listen(Object.assign(opts, { hostname: '::1' })),
this.listen(Object.assign(opts, { hostname: '127.0.0.1' })),
]).then(addresses => addresses[0])
}
const hostname = extractProperty(opts, 'hostname')
let port = extractProperty(opts, 'port')
const systemdSocket = extractProperty(opts, 'systemdSocket')
let fd = extractProperty(opts, 'fd')
let socket = extractProperty(opts, 'socket')
const servers = this._servers
const niceAddresses = this._niceAddresses
let server, protocol
if (opts.pfx || opts.SNICallback || (opts.cert && opts.key)) {
server = this._createSecureServer(opts)
protocol = 'https'
} else {
server = this._createServer(opts)
protocol = 'http'
}
const id = nextId++
servers[id] = server
if (systemdSocket != null) {
fd = getSystemdFd(systemdSocket)
}
// Compute a temporary nice address to display in case of error.
let niceAddress
if (fd != null) {
server.listen({ fd })
niceAddress = protocol + '://<fd:' + fd + '>'
} else if (socket != null) {
socket = resolvePath(socket)
server.listen(socket)
niceAddress = protocol + '://' + socket
} else {
if (port == null) {
port = protocol === 'https' ? 443 : 80
}
server.listen(port, hostname)
niceAddress = formatUrl({
protocol,
// Hostname default to localhost.
hostname: hostname || 'localhost',
// No port means random, unknown for now.
port: port || '<unknown>',
})
}
const emit = this.emit.bind(this)
server.once('close', function onClose() {
delete servers[id]
delete niceAddresses[id]
if (isEmpty(servers)) {
emit('close')
}
})
server.on('error', function onError() {
delete servers[id]
// FIXME: Should it be forwarded and be fatal if there are no
// listeners?
})
forwardedEvents.forEach(event => {
this.listeners(event).forEach(listener => {
server.on(event, listener)
})
})
return fromEvent(server, 'listening').then(
function () {
const address = server.address()
const niceAddress =
typeof address === 'string'
? protocol + '://' + address
: formatUrl({
protocol,
hostname: address.address,
port: address.port,
})
niceAddresses[id] = niceAddress
return niceAddress
},
function (error) {
error.niceAddress = niceAddress
throw error
}
)
}
function ref(server) {
server.ref()
}
proto.ref = function Server$ref() {
forOwn(this._servers, ref)
}
function unref(server) {
server.unref()
}
proto.unref = function Server$unref() {
forOwn(this._servers, unref)
}
// ===================================================================
module.exports = exports = Server
exports.create = function create(opts, requestListener) {
if (typeof opts === 'function') {
requestListener = opts
opts = undefined
}
const server = new Server(opts)
if (requestListener !== undefined) {
server.on('request', requestListener)
}
return server
}

View File

@@ -0,0 +1,303 @@
'use strict'
// ===================================================================
const assert = require('assert/strict')
const { EventEmitter } = require('events')
const resolvePath = require('path').resolve
const { describe, it } = require('node:test')
const HttpServerPlus = require('./')
// ===================================================================
// Creates a minimal mock server that can be used as a drop-in for http/https.Server.
// `address` is the value returned by mock.address() — use an object for TCP, a string for sockets.
function createMock(address) {
const mock = new EventEmitter()
mock.listen = function () {
setImmediate(() => this.emit('listening'))
}
mock.address = () => address
mock.close = function () {
setImmediate(() => this.emit('close'))
}
return mock
}
// ===================================================================
describe('HttpServerPlus', function () {
describe('#create()', function () {
it('creates a new instance', function () {
assert(HttpServerPlus.create() instanceof HttpServerPlus)
})
it('can register a `request` listener', function () {
const listener = function () {}
const server = HttpServerPlus.create(listener)
assert.deepEqual(server.listeners('request'), [listener])
})
})
describe('.addresses()', function () {
it('returns the list of addresses the server is listening at', function () {
const addr = { address: '127.0.0.1', port: 8080, family: 'IPv4' }
const mock = createMock(addr)
const server = HttpServerPlus.create({ createServer: () => mock })
return server.listen({ port: 8080 }).then(function () {
assert.deepEqual(server.addresses(), [addr])
return server.close()
})
})
})
describe('.niceAddresses()', function () {
it('returns the list of human readable addresses the server is listening at', function () {
const mock = createMock({ address: '127.0.0.1', port: 8080 })
const server = HttpServerPlus.create({ createServer: () => mock })
return server.listen({ hostname: '127.0.0.1', port: 8080 }).then(function (address) {
assert.deepEqual(server.niceAddresses(), [address])
return server.close()
})
})
})
describe('secureConnection event forwarding', function () {
function createMockHttpsServer() {
const server = new EventEmitter()
server.listen = function () {
setImmediate(() => this.emit('listening'))
}
server.address = () => ({ address: '127.0.0.1', port: 8443 })
server.close = function () {
setImmediate(() => this.emit('close'))
}
return server
}
function createServerWithMock() {
let mockServer
const server = HttpServerPlus.create({
createSecureServer: () => {
mockServer = createMockHttpsServer()
return mockServer
},
})
return {
server,
getMock: () => mockServer,
}
}
it('forwards secureConnection to listeners registered before listen()', function () {
const { server, getMock } = createServerWithMock()
const received = []
server.on('secureConnection', socket => received.push(socket))
const fakeSocket = {}
return server.listen({ cert: 'fake-cert', key: 'fake-key' }).then(function () {
getMock().emit('secureConnection', fakeSocket)
assert.deepEqual(received, [fakeSocket])
return server.close()
})
})
it('forwards secureConnection to listeners registered after listen()', function () {
const { server, getMock } = createServerWithMock()
return server.listen({ cert: 'fake-cert', key: 'fake-key' }).then(function () {
const received = []
server.on('secureConnection', socket => received.push(socket))
const fakeSocket = {}
getMock().emit('secureConnection', fakeSocket)
assert.deepEqual(received, [fakeSocket])
return server.close()
})
})
it('stops forwarding secureConnection after listener is removed', function () {
const { server, getMock } = createServerWithMock()
const received = []
const listener = socket => received.push(socket)
server.on('secureConnection', listener)
return server.listen({ cert: 'fake-cert', key: 'fake-key' }).then(function () {
server.off('secureConnection', listener)
getMock().emit('secureConnection', {})
assert.deepEqual(received, [])
return server.close()
})
})
})
describe('.listen()', function () {
it('can use a host:port', function () {
let listenArgs
const mock = createMock({ address: '127.0.0.1', port: 8080 })
mock.listen = function (...args) {
listenArgs = args
setImmediate(() => this.emit('listening'))
}
const server = HttpServerPlus.create({ createServer: () => mock })
return server.listen({ hostname: '127.0.0.1', port: 8080 }).then(function () {
assert.deepEqual(listenArgs, [8080, '127.0.0.1'])
return server.close()
})
})
it('can use a systemd socket', function () {
const SD_LISTEN_FDS_START = 3
const SOCKET_INDEX = 0
let listenArgs
const mock = createMock('http://<fd:3>')
mock.listen = function (...args) {
listenArgs = args
setImmediate(() => this.emit('listening'))
}
const server = HttpServerPlus.create({ createServer: () => mock })
const env = process.env
env.LISTEN_FDS = String(SOCKET_INDEX + 1)
env.LISTEN_PID = String(process.pid)
return server.listen({ systemdSocket: SOCKET_INDEX }).then(function () {
delete env.LISTEN_FDS
delete env.LISTEN_PID
assert.deepEqual(listenArgs, [{ fd: SOCKET_INDEX + SD_LISTEN_FDS_START }])
return server.close()
})
})
it('can use a socket', function () {
const socketPath = '/tmp/http-server-plus-test.sock'
let listenArgs
const mock = createMock(socketPath)
mock.listen = function (...args) {
listenArgs = args
setImmediate(() => this.emit('listening'))
}
const server = HttpServerPlus.create({ createServer: () => mock })
return server.listen({ socket: socketPath }).then(function () {
assert.deepEqual(listenArgs, [resolvePath(socketPath)])
return server.close()
})
})
it('can use a HTTPS certificate', function () {
let capturedOpts
const mock = createMock({ address: '127.0.0.1', port: 8443 })
const server = HttpServerPlus.create({
createSecureServer: opts => {
capturedOpts = opts
return mock
},
})
return server.listen({ cert: 'my-cert', key: 'my-key', port: 8443 }).then(function (address) {
assert.equal(capturedOpts.cert, 'my-cert')
assert.equal(capturedOpts.key, 'my-key')
assert.ok(address.startsWith('https://'), `expected https URL, got: ${address}`)
return server.close()
})
})
it('returns a promise which will resolve once listening', function () {
const mock = createMock({ address: '127.0.0.1', port: 8080 })
const server = HttpServerPlus.create({ createServer: () => mock })
return server.listen({ port: 8080 }).then(function (address) {
assert.equal(typeof address, 'string')
assert.ok(address.startsWith('http://'), `expected http URL, got: ${address}`)
return server.close()
})
})
it('returns a promise which will reject if failure', function () {
const listenError = new Error('EADDRINUSE')
const mock = createMock(null)
mock.listen = function () {
setImmediate(() => this.emit('error', listenError))
}
const server = HttpServerPlus.create({ createServer: () => mock })
return server.listen({ port: 8080 }).then(
function () {
assert.fail('should have rejected')
},
function (err) {
assert.equal(err, listenError)
assert.equal(typeof err.niceAddress, 'string')
}
)
})
})
describe('.close()', function () {
it('closes all servers', function () {
const closed = []
let callCount = 0
const server = HttpServerPlus.create({
createServer: () => {
const id = callCount++
const mock = createMock({ address: '127.0.0.1', port: id })
mock.close = function () {
closed.push(id)
setImmediate(() => this.emit('close'))
}
return mock
},
})
return Promise.all([server.listen({ port: 0 }), server.listen({ port: 0 })])
.then(function () {
return server.close()
})
.then(function () {
assert.equal(closed.length, 2)
})
})
it('emit the `close` event when all servers are closed', function () {
const mock = createMock({ address: '127.0.0.1', port: 8080 })
const server = HttpServerPlus.create({ createServer: () => mock })
let closeEmitted = false
server.on('close', () => {
closeEmitted = true
})
return server
.listen({ port: 8080 })
.then(function () {
return server.close()
})
.then(function () {
assert.ok(closeEmitted)
})
})
it('emit the `close` event even if there are no servers', function () {
const server = HttpServerPlus.create()
// close() with no servers returns Promise.resolve() immediately (before emitting
// 'close' via setImmediate), so we must wait for the event itself, not the promise.
return new Promise(function (resolve) {
server.close(resolve)
})
})
})
})

View File

@@ -0,0 +1,37 @@
{
"name": "@vates/http-server-plus",
"version": "2.0.0",
"license": "ISC",
"description": "Augmented `http.Server`, HTTP/HTTPS/HTTP2 and multiple ports on the same instance",
"keywords": [
"http",
"https",
"server",
"ports"
],
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/@vates/http-server-plus",
"bugs": "https://github.com/vatesfr/xen-orchestra/issues",
"repository": {
"directory": "@vates/http-server-plus",
"type": "git",
"url": "https://github.com/vatesfr/xen-orchestra.git"
},
"engines": {
"node": ">=20"
},
"dependencies": {
"promise-toolbox": "^0.21.0"
},
"devDependencies": {
"eslint-plugin-n": "^15.1.0"
},
"scripts": {
"pretest": "eslint .",
"test": "node --test index.spec.js"
},
"private": true,
"author": {
"name": "Vates SAS",
"url": "https://vates.fr"
}
}

View File

@@ -353,6 +353,7 @@ export default class NbdClient {
async readBlock(index, size = NBD_DEFAULT_BLOCK_SIZE) {
return pRetry(() => this.#readBlock(index, size), {
tries: this.#readBlockRetries,
when: error => error.code !== 'ERR_ABORTED',
onRetry: async err => {
warn('will retry reading block ', index, err)
await this.reconnect()
@@ -370,7 +371,7 @@ export default class NbdClient {
* - `length` — The size of the segment in bytes.
* - `type` — A numeric code indicating the segment type ( 0 means data).
*/
/* async */ getMap() {
/* async */ getMap(signal) {
return new Promise((resolve, reject) => {
const process = spawn('nbdinfo', [
'--json',
@@ -381,8 +382,17 @@ export default class NbdClient {
let errText = ''
process.stdout.on('data', data => (text += data))
process.stderr.on('data', data => (errText += data))
process.on('error', reject)
const onAbort = () => {
process.kill()
reject(signal.reason)
}
signal?.addEventListener('abort', onAbort, { once: true })
process.on('error', err => {
signal?.removeEventListener('abort', onAbort)
reject(err)
})
process.on('close', code => {
signal?.removeEventListener('abort', onAbort)
if (code !== 0) {
return reject(new Error(`Error during getMap (code: ${code}): ${errText}`))
}

View File

@@ -138,8 +138,8 @@ export default class MultiNbdClient {
* - `length` — The size of the segment in bytes.
* - `type` — A numeric code indicating the segment type (0 means no data).
*/
async getMap() {
async getMap(signal) {
// ask the map from one of the connected client
return this.#clients[Math.floor(this.#clients.length * Math.random())].getMap()
return this.#clients[Math.floor(this.#clients.length * Math.random())].getMap(signal)
}
}

View File

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

View File

@@ -1,6 +1,6 @@
{
"name": "@vates/node-vsphere-soap",
"version": "2.1.2",
"version": "2.1.3",
"description": "interface to vSphere SOAP/WSDL from node for interfacing with vCenter or ESXi, forked from node-vsphere-soap",
"main": "lib/client.mjs",
"author": "reedog117",
@@ -11,8 +11,8 @@
},
"bugs": "https://github.com/vatesfr/xen-orchestra/issues",
"dependencies": {
"@xen-orchestra/log": "^0.7.1",
"axios": "^1.8.0",
"@xen-orchestra/log": "^0.7.2",
"axios": "^1.15.0",
"soap": "^1.0.0",
"soap-cookie": "^0.10.1"
},

View File

@@ -23,7 +23,7 @@ exports.makeOnProgress = function ({ onRootTaskEnd = noop, onRootTaskStart = noo
Object.defineProperty(taskLog, '$root', { value: taskLog })
// start of a root task
onRootTaskStart(taskLog)
onRootTaskStart(taskLog, event)
} else {
// start of a subtask
const parent = taskLogs.get(parentId)
@@ -54,10 +54,10 @@ exports.makeOnProgress = function ({ onRootTaskEnd = noop, onRootTaskStart = noo
}
if (type === 'end' && taskLog.$root === taskLog) {
onRootTaskEnd(taskLog)
onRootTaskEnd(taskLog, event)
}
}
onTaskUpdate(taskLog)
onTaskUpdate(taskLog, event)
}
}

View File

@@ -7,6 +7,27 @@ function alreadyEnded() {
throw new Error('task has already ended')
}
const serializeErrors = errors => (Array.isArray(errors) ? errors.map(serializeError) : errors)
// Create a serializable object from an error.
//
// Otherwise some fields might be non-enumerable and missing from logs.
const serializeError = error => {
return error instanceof Error
? {
...error, // Copy enumerable properties.
cause: error.cause,
code: error.code,
errors: serializeErrors(error.errors), // supports AggregateError
message: error.message,
name: error.name,
stack: error.stack,
}
: error
}
exports.serializeError = serializeError
// define a read-only, non-enumerable, non-configurable property
function define(object, property, value) {
Object.defineProperty(object, property, { value })
@@ -72,7 +93,11 @@ class Task {
_onProgress
get id() {
return (this.id = Math.random().toString(36).slice(2))
// Use a compact, sortable, string representation of the creation date,
// and add a random part to differentiate tasks created at the same time
//
// Due to the padding, dates are sortable up to 5188-04-22T11:04:28.415Z
return (this.id = Date.now().toString(36).padStart(9, '0') + '-' + Math.random().toString(36).slice(2))
}
set id(value) {
define(this, 'id', value)
@@ -136,6 +161,10 @@ class Task {
assert.equal(this.#status, PENDING)
assert.equal(this.#running, false)
if (result instanceof Error && result.toJSON === undefined) {
result = serializeError(result)
}
this.#emit('end', { status, result })
this._onProgress = alreadyEnded
this.#status = status

View File

@@ -4,7 +4,7 @@ const assert = require('node:assert').strict
const { describe, it } = require('node:test')
const { makeOnProgress } = require('./combineEvents.js')
const { Task } = require('./index.js')
const { Task, serializeError } = require('./index.js')
const noop = Function.prototype
@@ -28,6 +28,36 @@ function createTask(opts) {
return task
}
describe('serializeError', function () {
it('serializes simple error', function () {
const err = new Error('test Error')
err.code = 404
const serialized = serializeError(err)
assert.equal(serialized.message, 'test Error')
assert.equal(serialized.name, 'Error')
assert.equal(serialized.code, 404)
assert.notEqual(serialized.stack, undefined)
})
it('serializes aggregate error', function () {
const err = new AggregateError([new Error('test error 1'), new Error('test error 2')], 'Error message', {
cause: 'broken',
})
const serialized = serializeError(err)
assert.equal(serialized.message, 'Error message')
assert.equal(serialized.name, 'AggregateError')
assert.equal(serialized.cause, 'broken')
assert.notEqual(serialized.stack, undefined)
assert.equal(serialized.errors.length, 2)
assert.equal(serialized.errors[0].name, 'Error')
assert.equal(serialized.errors[1].name, 'Error')
assert.equal(serialized.errors[0].message, 'test error 1')
assert.equal(serialized.errors[1].message, 'test error 2')
assert.notEqual(serialized.errors[0].stack, undefined)
assert.notEqual(serialized.errors[1].stack, undefined)
})
})
describe('Task', function () {
describe('constructor', function () {
it('data properties are passed to the start event', async function () {
@@ -106,7 +136,7 @@ describe('Task', function () {
assert.equal(task.$events.length, 3)
assertEvent(task, { type: 'start' }, 0)
assertEvent(task, { type: 'abortionRequested', reason }, 1)
assertEvent(task, { type: 'end', status: 'failure', result }, 2)
assertEvent(task, { type: 'end', status: 'failure', result: serializeError(result) }, 2)
})
it('does not abort if the task succeed', async function () {
@@ -176,7 +206,7 @@ describe('Task', function () {
assertEvent(task, {
status: 'failure',
result: error,
result: serializeError(error),
type: 'end',
})
})
@@ -475,7 +505,7 @@ describe('Task', function () {
assert.equal(task.status, 'failure')
assertEvent(task, {
status: 'failure',
result: e,
result: serializeError(e),
type: 'end',
})
})
@@ -511,7 +541,7 @@ describe('Task', function () {
assert.equal(task.status, 'failure')
assertEvent(task, {
status: 'failure',
result: e,
result: serializeError(e),
type: 'end',
})
})

View File

@@ -13,7 +13,7 @@
"url": "https://vates.fr"
},
"license": "ISC",
"version": "0.6.2",
"version": "0.7.0",
"engines": {
"node": ">=14"
},

View File

@@ -1,7 +1,7 @@
{
"name": "@vates/types",
"private": false,
"version": "1.19.0",
"version": "1.23.0",
"main": "./dist/index.mjs",
"exports": {
".": {

View File

@@ -1,6 +1,7 @@
import {
WrappedXenApiRecord,
XenApiHost,
XenApiHostWrapped,
XenApiNetwork,
XenApiNetworkWrapped,
XenApiRecord,
@@ -13,7 +14,15 @@ import {
XenApiVmWrapped,
XenApiVtpm,
} from '../xen-api.mjs'
import type { OPAQUE_REF_NULL, SUPPORTED_VDI_FORMAT, VBD_MODE, VBD_TYPE, VIF_LOCKING_MODE } from '../common.mjs'
import type {
BOND_MODE,
OPAQUE_REF_NULL,
SUPPORTED_VDI_FORMAT,
VBD_MODE,
VBD_TYPE,
VDI_TYPE,
VIF_LOCKING_MODE,
} from '../common.mjs'
import type { PassThrough, Readable } from 'node:stream'
import type {
XoGpuGroup,
@@ -68,6 +77,7 @@ export interface Xapi {
ref: T['$ref'],
field: K
): Promise<T[K]>
connectVif(vifId: XoVif['id']): Promise<void>
createNetwork(
params:
| {
@@ -84,8 +94,16 @@ export interface Xapi {
vlan: number
}
): Promise<XenApiNetworkWrapped>
createBondedNetwork(params: {
bondMode: BOND_MODE
pifIds: XoPif['id'][]
name: string
description?: string
mtu?: number
}): Promise<XenApiNetworkWrapped>
deleteNetwork(id: XoNetwork['id']): Promise<void>
deleteVif(vifId: XoVif['id']): Promise<void>
disconnectVif(vifId: XoVif['id']): Promise<void>
exportVmOva(vmRef: XenApiVm['$ref']): Promise<PassThrough>
migrateVm(
vmId: XoVm['id'],
@@ -104,6 +122,30 @@ export interface Xapi {
pool_emergencyShutdown(): Promise<void>
resumeVm(id: XoVm['id']): Promise<void>
unpauseVm(id: XoVm['id']): Promise<void>
cloneVm(
vmId: XoVm['id'],
opts?: {
nameLabel?: string
fast?: boolean
}
): Promise<XenApiVmWrapped>
copyVm(
vmId: XoVm['id'],
opts?: {
nameLabel?: string
srOrSrId?: XoSr['id'] | XoSr
}
): Promise<XenApiVmWrapped>
remoteCopyVm(
vmId: XoVm['id'],
targetXapi: Xapi,
targetSrId: XoSr['id'],
opts?: {
compress?: 'zstd' | 'gzip' | boolean
nameLabel?: string
}
): Promise<{ vm: XenApiVmWrapped }>
forgetSr(id: XoSr['id']): Promise<void>
SR_importVdi(
ref: XenApiSr['$ref'],
stream: Readable,
@@ -121,6 +163,7 @@ export interface Xapi {
xenstore_data?: Record<string, string>
}
): Promise<XenApiVdi['$ref']>
SR_reclaimSpace(ref: XenApiSr['$ref']): Promise<void>
startVm(
id: XoVm['id'],
opts?: {
@@ -150,6 +193,7 @@ export interface Xapi {
metadataVm: {
affinityHost?: XoHost['id']
autoPoweron?: boolean
cpus?: number
memory?: number
name_description?: string
name_label: string
@@ -218,6 +262,23 @@ export interface Xapi {
}): Promise<XenApiVbd['$ref']>
VBD_destroy(vbdRef: XenApiVbd['$ref']): Promise<void>
VBD_unplug(vbdRef: XenApiVbd['$ref']): Promise<void>
VDI_create(
options: {
name_description?: XoVdi['name_description']
name_label?: XoVdi['name_label']
other_config?: XoVdi['other_config']
read_only?: boolean
sharable?: boolean
SR?: XenApiSr['$ref']
tags?: XoVdi['tags']
type?: VDI_TYPE
virtual_size: XoVdi['size']
xenstore_data?: Record<string, string>
},
extraOptions?: {
sm_config?: Record<string, string>
}
): Promise<XenApiVdi['$ref']>
VDI_destroy(vdiRef: XenApiVdi['$ref']): Promise<void>
VDI_destroyCloudInitConfig(vdiRef: XenApiVdi['$ref'], opts?: { timeLimit?: number }): Promise<void>
VDI_exportContent(
@@ -265,6 +326,16 @@ export interface Xapi {
pathname: string,
params?: { host?: XenApiHost; query?: Record<string, unknown>; task?: boolean | XenApiTask['$ref'] }
): Promise<{ body: Readable }>
clearHost(host: Pick<XenApiHostWrapped, '$ref' | '$pool'>, force?: boolean): Promise<void>
disableHost(hostId: XoHost['id']): Promise<void>
enableHost(hostId: XoHost['id']): Promise<void>
getRecordByUuid<
Type extends WrappedXenApiRecord['$type'],
XenApiRecord extends WrappedXenApiRecord = Extract<WrappedXenApiRecord, { $type: Type }>,
>(
type: Type,
uuid: XenApiRecord['uuid']
): Promise<XenApiRecord>
isHyperThreadingEnabled(hostId: XoHost['id']): Promise<boolean | null>
VTPM_create(params: { VM: XenApiVm['$ref']; is_unique?: boolean; contents?: string }): Promise<XenApiVtpm['$ref']>
}

View File

@@ -82,6 +82,7 @@ type TagCallMethods = {
type WrapperXenApi<T, Type extends string, Fn = { (): void }> = T & {
$call: Fn
$callAsync: Fn
$pool: XenApiPool
$type: Type
$snapshot(params: {
cancelToken?: unknown
@@ -622,7 +623,9 @@ export interface XenApiHostCpu {
vendor: string
}
type XenApiNetworkCallMethods = TagCallMethods & {}
type XenApiNetworkCallMethods = TagCallMethods & {
(method: 'add_purpose', purpose: NETWORK_PURPOSE): Promise<void>
}
export interface XenApiNetwork {
$ref: Branded<'network'>

View File

@@ -93,7 +93,7 @@ type BaseXoVm = BaseXapiXo & {
notes?: string
os_version: Record<string, string> | null
other: Record<string, string>
parent?: XoVm['id']
parent?: XoVmSnapshot['id']
power_state: VM_POWER_STATE
pvDriversDetected?: boolean
pvDriversUpToDate?: boolean
@@ -106,6 +106,10 @@ type BaseXoVm = BaseXapiXo & {
suspendSr?: XoSr['id']
tags: string[]
vga?: string
/**
* Value in MiB.
* See: https://wiki.xenproject.org/wiki/XCP_PV_templates_start
*/
videoram?: number
viridian: boolean
virtualizationMode: DOMAIN_TYPE
@@ -725,6 +729,7 @@ type BaseXoVdi = BaseXapiXo & {
export type XoVdi = BaseXoVdi & {
id: Branded<'VDI'>
chainPhysicalUsage: number
type: 'VDI'
}

View File

@@ -1,7 +1,7 @@
{
"private": false,
"name": "@xen-orchestra/async-map",
"version": "0.1.2",
"version": "0.1.3",
"license": "ISC",
"description": "Promise.all + map for all iterables",
"keywords": [
@@ -28,7 +28,7 @@
"node": ">=6"
},
"dependencies": {
"lodash": "^4.17.4"
"lodash": "^4.18.0"
},
"scripts": {
"postversion": "npm publish",

View File

@@ -17,7 +17,7 @@
},
"dependencies": {
"@vates/decorate-with": "^2.1.0",
"@xen-orchestra/log": "^0.7.1",
"@xen-orchestra/log": "^0.7.2",
"golike-defer": "^0.5.1",
"object-hash": "^2.0.1"
},

View File

@@ -6,13 +6,13 @@
"preferGlobal": true,
"bugs": "https://github.com/vatesfr/xen-orchestra/issues",
"dependencies": {
"@vates/async-each": "^1.0.1",
"@xen-orchestra/async-map": "^0.1.2",
"@xen-orchestra/backups": "^0.68.2",
"@xen-orchestra/fs": "^4.6.6",
"@vates/async-each": "^1.0.3",
"@xen-orchestra/async-map": "^0.1.3",
"@xen-orchestra/backups": "^0.72.0",
"@xen-orchestra/fs": "^4.8.0",
"filenamify": "^6.0.0",
"getopts": "^2.2.5",
"lodash": "^4.17.15",
"lodash": "^4.18.0",
"promise-toolbox": "^0.21.0"
},
"engines": {
@@ -28,7 +28,7 @@
"scripts": {
"postversion": "npm publish --access public"
},
"version": "1.1.7",
"version": "1.1.11",
"license": "AGPL-3.0-or-later",
"author": {
"name": "Vates SAS",

View File

@@ -1,4 +1,4 @@
import { Task } from './Task.mjs'
import { Task } from '@vates/task'
export class HealthCheckVmBackup {
#restoredVm
@@ -14,7 +14,7 @@ export class HealthCheckVmBackup {
async run() {
return Task.run(
{
name: 'vmstart',
properties: { name: 'vmstart' },
},
async () => {
let restoredVm = this.#restoredVm

View File

@@ -2,9 +2,9 @@ import assert from 'node:assert'
import { formatFilenameDate } from './_filenameDate.mjs'
import { importIncrementalVm } from './_incrementalVm.mjs'
import { Task } from './Task.mjs'
import { watchStreamSize } from './_watchStreamSize.mjs'
import { decorateClass } from '@vates/decorate-with'
import { Task } from '@vates/task'
import { createLogger } from '@xen-orchestra/log'
import { dirname, join } from 'node:path'
import pickBy from 'lodash/pickBy.js'
@@ -244,7 +244,7 @@ export class ImportVmBackup {
return Task.run(
{
name: 'transfer',
properties: { name: 'transfer' },
},
async () => {
const xapi = this._xapi
@@ -255,6 +255,14 @@ export class ImportVmBackup {
: await importIncrementalVm(backup, await xapi.getRecord('SR', srRef), {
newMacAddresses,
})
let size = 0
if (isFull) {
size = sizeContainer.size
} else {
for (const disk of Object.values(backup.disks)) {
size += disk.getNbGeneratedBlock() * disk.getBlockSize()
}
}
const remoteName = adapter._handler._remote.name
let desc = `Restored on ${formatFilenameDate(+new Date())}`
if (remoteName !== undefined) {
@@ -275,7 +283,7 @@ export class ImportVmBackup {
])
return {
size: sizeContainer.size,
size,
id: await xapi.getField('VM', vmRef, 'uuid'),
}
}

View File

@@ -31,7 +31,7 @@ import { listPartitions, LVM_PARTITION_TYPE_MBR, LVM_PARTITION_TYPE_GPT } from '
import { lvs, pvs } from './_lvm.mjs'
import { watchStreamSize } from './_watchStreamSize.mjs'
import { RemoteVhd } from './disks/RemoteVhd.mjs'
import { RemoteVhdDisk } from './disks/RemoteVhdDisk.mjs'
import { openDiskChain } from './disks/openDiskChain.mjs'
import { toVhdStream, writeToVhdDirectory } from 'vhd-lib/disk-consumer/index.mjs'
import { ReadAhead } from '@xen-orchestra/disk-transform'
@@ -744,7 +744,7 @@ export class RemoteAdapter {
if (useChain) {
disk = await openDiskChain({ handler, path })
} else {
disk = new RemoteVhd({ handler, path })
disk = new RemoteVhdDisk({ handler, path })
await disk.init()
}
disk = new ReadAhead(disk)

View File

@@ -1,155 +0,0 @@
import CancelToken from 'promise-toolbox/CancelToken'
import Zone from 'node-zone'
const logAfterEnd = log => {
const error = new Error('task has already ended')
error.log = log
throw error
}
const noop = Function.prototype
const serializeErrors = errors => (Array.isArray(errors) ? errors.map(serializeError) : errors)
// Create a serializable object from an error.
//
// Otherwise some fields might be non-enumerable and missing from logs.
const serializeError = error =>
error instanceof Error
? {
...error, // Copy enumerable properties.
code: error.code,
errors: serializeErrors(error.errors), // supports AggregateError
message: error.message,
name: error.name,
stack: error.stack,
}
: error
const $$task = Symbol('@xen-orchestra/backups/Task')
export class Task {
static get cancelToken() {
const task = Zone.current.data[$$task]
return task !== undefined ? task.#cancelToken : CancelToken.none
}
static run(opts, fn) {
return new this(opts).run(fn, true)
}
static wrapFn(opts, fn) {
// compatibility with @decorateWith
if (typeof fn !== 'function') {
;[fn, opts] = [opts, fn]
}
return function () {
return Task.run(typeof opts === 'function' ? opts.apply(this, arguments) : opts, () => fn.apply(this, arguments))
}
}
#cancelToken
#id = Math.random().toString(36).slice(2)
#onLog
#zone
constructor({ name, data, onLog }) {
let parentCancelToken, parentId
if (onLog === undefined) {
const parent = Zone.current.data[$$task]
if (parent === undefined) {
onLog = noop
} else {
onLog = log => parent.#onLog(log)
parentCancelToken = parent.#cancelToken
parentId = parent.#id
}
}
const zone = Zone.current.fork('@xen-orchestra/backups/Task')
zone.data[$$task] = this
this.#zone = zone
const { cancel, token } = CancelToken.source(parentCancelToken && [parentCancelToken])
this.#cancelToken = token
this.cancel = cancel
this.#onLog = onLog
this.#log('start', {
data,
message: name,
parentId,
})
}
failure(error) {
this.#end('failure', serializeError(error))
}
info(message, data) {
this.#log('info', { data, message })
}
/**
* Run a function in the context of this task
*
* In case of error, the task will be failed.
*
* @typedef Result
* @param {() => Result} fn
* @param {boolean} last - Whether the task should succeed if there is no error
* @returns Result
*/
run(fn, last = false) {
return this.#zone.run(() => {
try {
const result = fn()
let then
if (result != null && typeof (then = result.then) === 'function') {
then.call(result, last && (value => this.success(value)), error => this.failure(error))
} else if (last) {
this.success(result)
}
return result
} catch (error) {
this.failure(error)
throw error
}
})
}
success(value) {
this.#end('success', value)
}
warning(message, data) {
this.#log('warning', { data, message })
}
wrapFn(fn, last) {
const task = this
return function () {
return task.run(() => fn.apply(this, arguments), last)
}
}
#end(status, result) {
this.#log('end', { result, status })
this.#onLog = logAfterEnd
}
#log(event, props) {
this.#onLog({
...props,
event,
taskId: this.#id,
timestamp: Date.now(),
})
}
}
for (const method of ['info', 'warning']) {
Task[method] = (...args) => Zone.current.data[$$task]?.[method](...args)
}

View File

@@ -14,10 +14,10 @@ import { decorateMethodsWith } from '@vates/decorate-with'
import { deduped } from '@vates/disposable/deduped.js'
import { getHandler } from '@xen-orchestra/fs'
import { parseDuration } from '@vates/parse-duration'
import { Task } from '@vates/task'
import { Xapi } from '@xen-orchestra/xapi'
import { RemoteAdapter } from './RemoteAdapter.mjs'
import { Task } from './Task.mjs'
createCachedLookup().patchGlobal()
@@ -178,8 +178,8 @@ process.on('message', async message => {
const result = message.runWithLogs
? await Task.run(
{
name: 'backup run',
onLog: data =>
properties: { name: 'backup run', ...message.data.jobData },
onProgress: data =>
emitMessage({
data,
type: 'log',

View File

@@ -212,6 +212,7 @@ test('it merges delta of non destroyed chain', async () => {
parentUnicodeName: 'orphan.vhd',
parentUuid: orphan.footer.uuid,
},
blocks: [0, 1],
})
// a grand child
await generateVhd(`${basePath}/grandchild.vhd`, {
@@ -229,13 +230,14 @@ test('it merges delta of non destroyed chain', async () => {
assert.equal(logged[0], `unexpected number of entries in backup cache`)
logged = []
await adapter.cleanVm(rootPath, { remove: true, merge: true, logInfo, logWarn: () => {}, lock: false })
const result = await adapter.cleanVm(rootPath, { remove: true, merge: true, logInfo, logWarn: () => {}, lock: false })
assert.ok(result.size > 0, `no merged size`)
const [merging] = logged
assert.equal(merging, `merging VHD chain`)
const metadata = JSON.parse(await handler.readFile(`${rootPath}/metadata.json`))
// size should be the size of children + grand children after the merge
assert.equal(metadata.size, 104960)
assert.equal(metadata.size, 4299776)
// merging is already tested in vhd-lib, don't retest it here (and theses vhd are as empty as my stomach at 12h12)
// only check deletion
@@ -286,6 +288,54 @@ test('it finish unterminated merge ', async () => {
assert.equal(remainingVhds.includes('child.vhd'), true)
})
test('it finishes unterminated merge when child is a disk chain', async () => {
// This test covers the case where a merge was interrupted and the child disk is a disk chain.
await handler.writeFile(
`${rootPath}/metadata.json`,
JSON.stringify({
mode: 'delta',
size: 209920,
vhds: [`${relativePath}/child.vhd`],
})
)
const ancestor = await generateVhd(`${basePath}/ancestor.vhd`)
const intermediate = await generateVhd(`${basePath}/intermediate.vhd`, {
header: {
parentUnicodeName: 'ancestor.vhd',
parentUuid: ancestor.footer.uuid,
},
})
await generateVhd(`${basePath}/child.vhd`, {
header: {
parentUnicodeName: 'intermediate.vhd',
parentUuid: intermediate.footer.uuid,
},
})
// merge state file with chain field
await handler.writeFile(
`${basePath}/.ancestor.vhd.merge.json`,
JSON.stringify({
parent: { uuid: '0' },
child: { uuid: '0' },
chain: ['ancestor.vhd', 'intermediate.vhd', 'child.vhd'],
currentBlock: 0,
mergedDataSize: 0,
step: 'mergeBlocks',
diskSize: 0,
})
)
await adapter.cleanVm(rootPath, { remove: true, merge: true, logWarn: () => {}, lock: false })
// ancestor should be renamed to child.vhd (replacing it), intermediate.vhd should be deleted
const remainingVhds = await handler.list(basePath)
assert.equal(remainingVhds.length, 1)
assert.equal(remainingVhds[0], 'child.vhd')
})
// each of the vhd can be a file, a directory, an alias to a file or an alias to a directory
// the message and resulting files should be identical to the output with vhd files which is tested independently
describe('tests multiple combination ', { concurrency: 1 }, () => {
@@ -402,13 +452,12 @@ 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, vhdMode === 'file' ? 6502400 : 6501888)
assert.deepEqual(metadata.size, 4404224)
// broken vhd, non referenced, abandoned should be deleted ( alias and data)
// ancestor and child should be merged
// grand child and clean vhd should not have changed
const survivors = await handler.list(basePath)
// console.log(survivors)
if (useAlias) {
const dataSurvivors = await handler.list(basePath + '/data')
// the goal of the alias : do not move a full folder

View File

@@ -1,40 +1,20 @@
import * as UUID from 'uuid'
import sum from 'lodash/sum.js'
import { asyncMap } from '@xen-orchestra/async-map'
import { Constants, openVhd, VhdAbstract, VhdFile } from 'vhd-lib'
import { Constants, openVhd, VhdAbstract } from 'vhd-lib'
import { isVhdAlias, resolveVhdAlias } from 'vhd-lib/aliases.js'
import { basename, dirname, resolve } from 'node:path'
import { isMetadataFile, isVhdFile, isVhdSumFile, isXvaFile, isXvaSumFile } from './_backupType.mjs'
import { limitConcurrency } from 'limit-concurrency-decorator'
import { mergeVhdChain } from 'vhd-lib/merge.js'
import { RemoteVhdDisk } from './disks/RemoteVhdDisk.mjs'
import { RemoteVhdDiskChain } from './disks/RemoteVhdDiskChain.mjs'
import { MergeRemoteDisk } from './disks/MergeRemoteDisk.mjs'
import { Task } from './Task.mjs'
import { Disposable } from 'promise-toolbox'
import { Task } from '@vates/task'
import handlerPath from '@xen-orchestra/fs/path'
const { DISK_TYPES } = Constants
// checking the size of a vhd directory is costly
// 1 Http Query per 1000 blocks
// we only check size of all the vhd are VhdFiles
function shouldComputeVhdsSize(handler, vhds) {
if (handler.isEncrypted) {
return false
}
return vhds.every(vhd => vhd instanceof VhdFile)
}
const computeVhdsSize = (handler, vhdPaths) =>
Disposable.use(
vhdPaths.map(vhdPath => openVhd(handler, vhdPath)),
async vhds => {
if (shouldComputeVhdsSize(handler, vhds)) {
const sizes = await asyncMap(vhds, vhd => vhd.getSize())
return sum(sizes)
}
}
)
// chain is [ ancestor, child_1, ..., child_n ]
async function _mergeVhdChain(handler, chain, { logInfo, remove, mergeBlockConcurrency }) {
logInfo(`merging VHD chain`, { chain })
@@ -51,7 +31,15 @@ async function _mergeVhdChain(handler, chain, { logInfo, remove, mergeBlockConcu
}
}, 10e3)
try {
return await mergeVhdChain(handler, chain, {
const parentDisk = new RemoteVhdDisk({ handler, path: chain.shift() })
const childDisks = []
for (const path of chain) {
childDisks.push(new RemoteVhdDisk({ handler, path }))
}
const childDiskChain = new RemoteVhdDiskChain({ disks: childDisks })
const mergeRemoteDisk = new MergeRemoteDisk(handler, {
logInfo,
mergeBlockConcurrency,
onProgress({ done: d, total: t }) {
@@ -60,6 +48,14 @@ async function _mergeVhdChain(handler, chain, { logInfo, remove, mergeBlockConcu
},
removeUnused: remove,
})
const isResumingMerge = await mergeRemoteDisk.isResuming(parentDisk)
await parentDisk.init({ force: isResumingMerge })
await childDiskChain.init({ force: isResumingMerge })
const result = await mergeRemoteDisk.merge(parentDisk, childDiskChain)
return result
} finally {
clearInterval(handle)
}
@@ -518,23 +514,27 @@ export async function cleanVm(
})
}
let totalMergedDataSize = 0
const metadataWithMergedVhd = {}
const doMerge = async () => {
await asyncMap(toMerge, async chain => {
const { finalVhdSize } = await limitedMergeVhdChain(handler, chain, {
const { finalDiskSize, mergedDataSize } = await limitedMergeVhdChain(handler, chain, {
logInfo,
logWarn,
remove,
mergeBlockConcurrency,
})
totalMergedDataSize += mergedDataSize
const metadataPath = vhdsToJSons[chain[chain.length - 1]] // all the chain should have the same metadata file
metadataWithMergedVhd[metadataPath] = (metadataWithMergedVhd[metadataPath] ?? 0) + finalVhdSize
metadataWithMergedVhd[metadataPath] = (metadataWithMergedVhd[metadataPath] ?? 0) + finalDiskSize
})
return { size: totalMergedDataSize }
}
await Promise.all([
...unusedVhdsDeletion,
toMerge.length !== 0 && (merge ? Task.run({ name: 'merge' }, doMerge) : () => Promise.resolve()),
toMerge.length !== 0 && (merge ? Task.run({ properties: { name: 'merge' } }, doMerge) : () => Promise.resolve()),
asyncMap(unusedXvas, path => {
logWarn('unused XVA', { path })
if (remove) {
@@ -562,7 +562,7 @@ export async function cleanVm(
let fileSystemSize
const mergedSize = metadataWithMergedVhd[metadataPath]
const { mode, size, vhds, xva } = metadata
const { mode, size, xva } = metadata
try {
if (mode === 'full') {
@@ -578,21 +578,7 @@ export async function cleanVm(
})
}
} catch (error) {
// can fail with encrypted remote
}
} else if (mode === 'delta') {
// don't warn if the size has changed after a merge
if (mergedSize === undefined) {
const linkedVhds = Object.keys(vhds).map(key => resolve('/', vmDir, vhds[key]))
fileSystemSize = await computeVhdsSize(handler, linkedVhds)
// the size is not computed in some cases (e.g. VhdDirectory)
if (fileSystemSize !== undefined && fileSystemSize !== size) {
logWarn('cleanVm: incorrect backup size in metadata', {
path: metadataPath,
actual: size ?? 'none',
expected: fileSystemSize,
})
}
// will fail with encrypted remote
}
}
} catch (error) {
@@ -637,5 +623,6 @@ export async function cleanVm(
return {
// boolean whether some VHDs were merged (or should be merged)
merge: toMerge.length !== 0,
size: totalMergedDataSize,
}
}

View File

@@ -127,19 +127,19 @@ describe('_getOldEntries() should succeed', () => {
args: [
0,
[
{ timestamp: +new Date('2024-08-31 09:01:00'), id: 1 }, // 4th day too old
{ timestamp: +new Date('2024-09-01 00:10:00'), id: 2 }, // third day
{ timestamp: +new Date('2024-09-01 14:20:00'), id: 3 }, // second day, oldest
{ timestamp: +new Date('2024-09-02 00:22:00'), id: 4 }, // second day
{ timestamp: +new Date('2024-09-03 14:00:00'), id: 5 }, // same day oldest
{ timestamp: +new Date('2024-09-04 00:09:00'), id: 6 }, // same day in NZ
{ timestamp: +new Date('2024-09-04 00:10:00'), id: 7 }, // most recent
{ timestamp: +new Date('2024-08-31T09:01:00Z'), id: 1 }, // 4th day too old
{ timestamp: +new Date('2024-09-01T00:10:00Z'), id: 2 }, // third day
{ timestamp: +new Date('2024-09-01T14:20:00Z'), id: 3 }, // second day, oldest
{ timestamp: +new Date('2024-09-02T00:22:00Z'), id: 4 }, // second day
{ timestamp: +new Date('2024-09-03T14:00:00Z'), id: 5 }, // same day oldest
{ timestamp: +new Date('2024-09-04T00:09:00Z'), id: 6 }, // same day in NZ
{ timestamp: +new Date('2024-09-04T00:10:00Z'), id: 7 }, // most recent
],
{
longTermRetention: {
daily: { retention: 3 },
},
timezone: 'Pacific/Auckland', // GMT +13
timezone: 'Pacific/Auckland', // GMT +12 (NZST in September)
},
],
expectedIds: [1, 4, 6, 7],

View File

@@ -4,11 +4,11 @@ import { asyncMap } from '@xen-orchestra/async-map'
import { CancelToken } from 'promise-toolbox'
import { compareVersions } from 'compare-versions'
import { defer } from 'golike-defer'
import { Task } from '@vates/task'
import { cancelableMap } from './_cancelableMap.mjs'
import { Task } from './Task.mjs'
import pick from 'lodash/pick.js'
import { BASE_DELTA_VDI, COPY_OF, VM_UUID } from './_otherConfig.mjs'
import { BASE_DELTA_VDI, CONTENT_KEY, COPY_OF, VM_UUID } from './_otherConfig.mjs'
import { VHD_MAX_SIZE, XapiDiskSource } from '@xen-orchestra/xapi'
import { toVhdStream } from 'vhd-lib/disk-consumer/index.mjs'
@@ -124,7 +124,7 @@ export const importIncrementalVm = defer(async function importIncrementalVm(
$defer,
incrementalVm,
sr,
{ cancelToken = CancelToken.none, newMacAddresses = false } = {}
{ cancelToken = CancelToken.none, newMacAddresses = false, targetRef = undefined } = {}
) {
const { version } = incrementalVm
if (compareVersions(version, '1.0.0') < 0) {
@@ -136,44 +136,106 @@ export const importIncrementalVm = defer(async function importIncrementalVm(
const vdiRecords = incrementalVm.vdis
// 0. Create suspend_VDI
// When targetRef is provided, update the existing VM instead of creating a new one.
const targetVm = targetRef !== undefined ? xapi.getObjectByRef(targetRef, undefined) : undefined
const isUpdate = targetVm !== undefined && !targetVm.is_a_snapshot && !targetVm.is_a_template
// 0. Create suspend_VDI (only when creating a new VM).
let suspendVdi
if (vmRecord.suspend_VDI !== undefined && vmRecord.suspend_VDI !== 'OpaqueRef:NULL') {
const vdi = vdiRecords[vmRecord.suspend_VDI]
if (vdi === undefined) {
Task.warning('Suspend VDI not available for this suspended VM', {
vm: pick(vmRecord, 'uuid', 'name_label', 'suspend_VDI'),
})
} else {
suspendVdi = await xapi.getRecord('VDI', await xapi.VDI_create(vdi))
$defer.onFailure(() => suspendVdi.$destroy())
if (!isUpdate) {
if (vmRecord.suspend_VDI !== undefined && vmRecord.suspend_VDI !== 'OpaqueRef:NULL') {
const vdi = vdiRecords[vmRecord.suspend_VDI]
if (vdi === undefined) {
Task.warning('Suspend VDI not available for this suspended VM', {
vm: pick(vmRecord, 'uuid', 'name_label', 'suspend_VDI'),
})
} else {
suspendVdi = await xapi.getRecord('VDI', await xapi.VDI_create(vdi))
$defer.onFailure(() => suspendVdi.$destroy())
}
}
}
// 1. Create the VM.
const vmRef = await xapi.VM_create(
{
...vmRecord,
affinity: undefined,
blocked_operations: {
...vmRecord.blocked_operations,
// 1. Create the VM or update the existing one.
let vmRef
if (isUpdate) {
vmRef = targetRef
await Promise.all([
xapi.setFields('VM', vmRef, {
actions_after_crash: vmRecord.actions_after_crash,
actions_after_reboot: vmRecord.actions_after_reboot,
actions_after_shutdown: vmRecord.actions_after_shutdown,
domain_type: vmRecord.domain_type,
ha_restart_priority: vmRecord.ha_restart_priority,
has_vendor_device: vmRecord.has_vendor_device,
HVM_boot_params: vmRecord.HVM_boot_params,
HVM_boot_policy: vmRecord.HVM_boot_policy,
HVM_shadow_multiplier: vmRecord.HVM_shadow_multiplier,
memory_dynamic_max: vmRecord.memory_dynamic_max,
memory_dynamic_min: vmRecord.memory_dynamic_min,
memory_static_max: vmRecord.memory_static_max,
memory_static_min: vmRecord.memory_static_min,
name_label: vmRecord.name_label,
name_description: vmRecord.name_description,
order: vmRecord.order,
other_config: vmRecord.other_config,
platform: vmRecord.platform,
PV_args: vmRecord.PV_args,
PV_bootloader: vmRecord.PV_bootloader,
PV_bootloader_args: vmRecord.PV_bootloader_args,
PV_kernel: vmRecord.PV_kernel,
PV_legacy_args: vmRecord.PV_legacy_args,
PV_ramdisk: vmRecord.PV_ramdisk,
recommendations: vmRecord.recommendations,
shutdown_delay: vmRecord.shutdown_delay,
start_delay: vmRecord.start_delay,
suspend_SR: vmRecord.suspend_SR,
tags: vmRecord.tags,
user_version: vmRecord.user_version,
VCPUs_at_startup: vmRecord.VCPUs_at_startup,
VCPUs_max: vmRecord.VCPUs_max,
VCPUs_params: vmRecord.VCPUs_params,
xenstore_data: vmRecord.xenstore_data,
}),
targetVm.update_blocked_operations({
start: 'Importing…',
start_on: 'Importing…',
}),
])
} else {
vmRef = await xapi.VM_create(
{
...vmRecord,
affinity: undefined,
blocked_operations: {
...vmRecord.blocked_operations,
start: 'Importing…',
start_on: 'Importing…',
},
ha_always_run: false,
is_a_template: false,
name_label: '[Importing…] ' + vmRecord.name_label,
},
ha_always_run: false,
is_a_template: false,
name_label: '[Importing…] ' + vmRecord.name_label,
},
{
bios_strings: vmRecord.bios_strings,
generateMacSeed: newMacAddresses,
suspend_VDI: suspendVdi?.$ref,
}
)
$defer.onFailure.call(xapi, 'VM_destroy', vmRef)
{
bios_strings: vmRecord.bios_strings,
generateMacSeed: newMacAddresses,
suspend_VDI: suspendVdi?.$ref,
}
)
$defer.onFailure.call(xapi, 'VM_destroy', vmRef)
}
// 2. Delete all VBDs which may have been created by the import.
await asyncMap(await xapi.getField('VM', vmRef, 'VBDs'), ref => ignoreErrors.call(xapi.call('VBD.destroy', ref)))
// In update mode, also collect the VDI refs so orphaned VDIs can be destroyed after new ones are created.
const existingVbdRefs = await xapi.getField('VM', vmRef, 'VBDs')
const oldVdiRefs = new Set(
isUpdate
? (await asyncMap(existingVbdRefs, ref => xapi.getField('VBD', ref, 'VDI'))).filter(
ref => ref !== undefined && ref !== 'OpaqueRef:NULL'
)
: []
)
await asyncMap(existingVbdRefs, ref => ignoreErrors.call(xapi.call('VBD.destroy', ref)))
// 3. Create VDIs & VBDs.
const vbdRecords = incrementalVm.vbds
@@ -184,10 +246,18 @@ export const importIncrementalVm = defer(async function importIncrementalVm(
let newVdi
if (vdi.baseVdi?.$ref !== undefined) {
newVdi = await xapi.getRecord('VDI', await xapi.VDI_clone(vdi.baseVdi.$ref))
$defer.onFailure(() => newVdi.$destroy())
if (isUpdate) {
// In update mode, reuse the existing target VDI directly — no clone needed.
newVdi = vdi.baseVdi
oldVdiRefs.delete(newVdi.$ref)
} else {
newVdi = await xapi.getRecord('VDI', await xapi.VDI_clone(vdi.baseVdi.$ref))
$defer.onFailure(() => newVdi.$destroy())
}
await newVdi.update_other_config(COPY_OF, vdi.uuid)
if (vdi.other_config[CONTENT_KEY] !== undefined) {
await newVdi.update_other_config(CONTENT_KEY, vdi.other_config[CONTENT_KEY])
}
if (vdi.virtual_size > newVdi.virtual_size) {
await newVdi.$callAsync('resize', vdi.virtual_size)
}
@@ -213,6 +283,16 @@ export const importIncrementalVm = defer(async function importIncrementalVm(
newVdis[vdiRef] = newVdi
})
// 3.5. Destroy old VDIs that are no longer attached to the VM.
// Uses ignoreErrors because some storage backends refuse to destroy a VDI that still has snapshot children;
// those VDIs will become truly orphaned once the old snapshot VMs are cleaned up by _deleteOldEntries.
await asyncMap([...oldVdiRefs], ref => ignoreErrors.call(xapi.call('VDI.destroy', ref)))
// 4. For updates, destroy existing VIFs before recreating them.
if (isUpdate) {
await asyncMap(await xapi.getField('VM', vmRef, 'VIFs'), ref => ignoreErrors.call(xapi.call('VIF.destroy', ref)))
}
const networksByNameLabelByVlan = {}
let defaultNetwork
Object.values(xapi.objects.all).forEach(object => {
@@ -285,12 +365,16 @@ export const importIncrementalVm = defer(async function importIncrementalVm(
}
}),
])
// recreate VTPMs
await Promise.all(
(incrementalVm.vtpms ?? []).map(async contents => {
await xapi.VTPM_create({ VM: vmRef, contents })
})
)
// recreate vtpm (note there is normally only one VTPM per VM at most)
const existingVtpmRefs = await xapi.getField('VM', vmRef, 'VTPMs')
for (const vtpmRef of existingVtpmRefs ?? []) {
await xapi.call('VTPM_destroy', vtpmRef)
}
for (const contents of incrementalVm.vtpms ?? []) {
await xapi.VTPM_create({ VM: vmRef, contents })
}
const vm = await xapi.getRecord('VM', vmRef)
await Promise.all([
vmRecord.ha_always_run && xapi.setField('VM', vmRef, 'ha_always_run', true),

View File

@@ -28,6 +28,11 @@ export const EXPORTED_SUCCESSFULLY = 'xo:backup:exported'
// the VM ( not the snapshot) uuid
export const VM_UUID = 'xo:backup:vm'
// in `other_config` of source snapshot VDIs and replicated target VDIs
// contains the UUID of the source snapshot VDI whose content this VDI represents
// allows direction-agnostic discovery of common base VDIs (e.g. for failback/reverse replication)
export const CONTENT_KEY = 'xo:backup:contentKey'
async function listVdiRefs(xapi, vmRef) {
return xapi.VM_getDisks(vmRef)
}
@@ -80,6 +85,7 @@ export async function getVmDeltaChainLength(xapi, vmRef) {
export function resetVmOtherConfig(xapi, vmRef) {
return applyToVmAndVdis(xapi, vmRef, (type, ref) => {
return xapi.setFieldEntries(type, ref, 'other_config', {
[COPY_OF]: null,
[DATETIME]: null,
[DELTA_CHAIN_LENGTH]: null,
[EXPORTED_SUCCESSFULLY]: null,
@@ -131,3 +137,24 @@ export async function markExportSuccessfull(xapi, vmRef) {
xapi.setFieldEntry(type, ref, 'other_config', EXPORTED_SUCCESSFULLY, 'true')
)
}
/**
* Set CONTENT_KEY on each VDI of a VM snapshot to its own UUID.
*
* This marks each snapshot VDI with a unique content identifier that can be
* propagated to replicated copies for direction-agnostic base VDI discovery
* (e.g. for failback / reverse replication).
*
* @param {Xapi} xapi
* @param {String} snapshotRef
* @returns {Promise}
*/
export async function setVmSnapshotContentKeys(xapi, snapshotRef) {
return applyToVmAndVdis(xapi, snapshotRef, async (type, ref) => {
if (type !== 'VDI') {
return
}
const uuid = await xapi.getField(type, ref, 'uuid')
return xapi.setFieldEntry(type, ref, 'other_config', CONTENT_KEY, uuid)
})
}

View File

@@ -1,4 +1,5 @@
import { asyncMap } from '@xen-orchestra/async-map'
import { Task } from '@vates/task'
import Disposable from 'promise-toolbox/Disposable'
import ignoreErrors from 'promise-toolbox/ignoreErrors'
@@ -6,9 +7,10 @@ import { extractIdsFromSimplePattern } from '../extractIdsFromSimplePattern.mjs'
import { PoolMetadataBackup } from './_PoolMetadataBackup.mjs'
import { XoMetadataBackup } from './_XoMetadataBackup.mjs'
import { DEFAULT_SETTINGS, Abstract } from './_Abstract.mjs'
import { runTask } from './_runTask.mjs'
import { getAdaptersByRemote } from './_getAdaptersByRemote.mjs'
const noop = Function.prototype
const DEFAULT_METADATA_SETTINGS = {
retentionPoolMetadata: 0,
retentionXoMetadata: 0,
@@ -55,13 +57,16 @@ export const Metadata = class MetadataBackupRunner extends Abstract {
poolIds.map(id =>
this._getRecord('pool', id).catch(error => {
// See https://github.com/vatesfr/xen-orchestra/commit/6aa6cfba8ec939c0288f0fa740f6dfad98c43cbb
runTask(
Task.run(
{
name: 'get pool record',
data: { type: 'pool', id },
properties: {
id,
name: 'get pool record',
type: 'pool',
},
},
() => Promise.reject(error)
)
).catch(noop)
})
)
),
@@ -81,11 +86,11 @@ export const Metadata = class MetadataBackupRunner extends Abstract {
if (pools.length !== 0 && settings.retentionPoolMetadata !== 0) {
promises.push(
asyncMap(pools, async pool =>
runTask(
Task.run(
{
name: `Starting metadata backup for the pool (${pool.$id}). (${job.id})`,
data: {
properties: {
id: pool.$id,
name: `Starting metadata backup for the pool (${pool.$id}). (${job.id})`,
pool,
poolMaster: await ignoreErrors.call(pool.$xapi.getRecord('host', pool.master)),
type: 'pool',
@@ -100,17 +105,17 @@ export const Metadata = class MetadataBackupRunner extends Abstract {
schedule,
settings,
}).run()
)
).catch(noop)
)
)
}
if (job.xoMetadata !== undefined && settings.retentionXoMetadata !== 0) {
promises.push(
runTask(
Task.run(
{
name: `Starting XO metadata backup. (${job.id})`,
data: {
properties: {
name: `Starting XO metadata backup. (${job.id})`,
type: 'xo',
},
},
@@ -122,7 +127,7 @@ export const Metadata = class MetadataBackupRunner extends Abstract {
schedule,
settings,
}).run()
)
).catch(noop)
)
}
await Promise.all(promises)

View File

@@ -1,9 +1,9 @@
import { asyncMapSettled } from '@xen-orchestra/async-map'
import Disposable from 'promise-toolbox/Disposable'
import { limitConcurrency } from 'limit-concurrency-decorator'
import { Task } from '@vates/task'
import { extractIdsFromSimplePattern } from '../extractIdsFromSimplePattern.mjs'
import { Task } from '../Task.mjs'
import { DEFAULT_SETTINGS, Abstract } from './_Abstract.mjs'
import { getAdaptersByRemote } from './_getAdaptersByRemote.mjs'
import { FullRemote } from './_vmRunners/FullRemote.mjs'
@@ -78,7 +78,7 @@ export const VmsRemote = class RemoteVmsBackupRunner extends Abstract {
}
nTriesByVmId[vmUuid]++
const taskStart = { name: 'backup VM', data: { type: 'VM', id: vmUuid } }
const taskStart = { properties: { id: vmUuid, name: 'backup VM', type: 'VM' } }
const vmSettings = { ...settings, ...allSettings[vmUuid] }
const isLastRun = nTriesByVmId[vmUuid] === vmSettings.nRetriesVmBackupFailures + 1
@@ -113,23 +113,27 @@ export const VmsRemote = class RemoteVmsBackupRunner extends Abstract {
taskByVmId[vmUuid] = new Task(taskStart)
}
const task = taskByVmId[vmUuid]
// error has to be caught in the task to prevent its failure, but handled outside the task to execute another task.run()
let taskError
return task
.run(async () => {
try {
const result = await vmBackup.run()
task.success(result)
return result
} catch (error) {
if (isLastRun) {
throw error
} else {
Task.warning(`Retry the VM mirror backup due to an error`, {
attempt: nTriesByVmId[vmUuid],
error: error.message,
})
queue.add(vmUuid)
}
.runInside(async () =>
vmBackup.run().catch(error => {
taskError = error
})
)
.then(result => {
if (taskError === undefined) {
return task.success(result)
}
if (isLastRun) {
return task.failure(taskError)
}
// don't end the task
task.warning(`Retry the VM mirror backup due to an error`, {
attempt: nTriesByVmId[vmUuid],
error: taskError.message,
})
queue.add(vmUuid)
})
.catch(noop)
}

View File

@@ -1,11 +1,10 @@
import { asyncMapSettled } from '@xen-orchestra/async-map'
import Disposable from 'promise-toolbox/Disposable'
import { limitConcurrency } from 'limit-concurrency-decorator'
import { Task } from '@vates/task'
import { extractIdsFromSimplePattern } from '../extractIdsFromSimplePattern.mjs'
import { Task } from '../Task.mjs'
import { DEFAULT_SETTINGS, Abstract } from './_Abstract.mjs'
import { runTask } from './_runTask.mjs'
import { getAdaptersByRemote } from './_getAdaptersByRemote.mjs'
import { IncrementalXapi } from './_vmRunners/IncrementalXapi.mjs'
import { FullXapi } from './_vmRunners/FullXapi.mjs'
@@ -65,13 +64,12 @@ export const VmsXapi = class VmsXapiBackupRunner extends Abstract {
Disposable.all(
extractIdsFromSimplePattern(job.srs).map(id =>
this._getRecord('SR', id).catch(error => {
runTask(
Task.run(
{
name: 'get SR record',
data: { type: 'SR', id },
properties: { id, name: 'get SR record', type: 'SR' },
},
() => Promise.reject(error)
)
).catch(noop)
})
)
),
@@ -108,11 +106,12 @@ export const VmsXapi = class VmsXapiBackupRunner extends Abstract {
}
return taskByVmId[vmUuid]
}
const vmBackupFailed = error => {
const vmBackupFailed = async (error, task) => {
if (isLastRun) {
throw error
return task.failure(error)
} else {
Task.warning(`Retry the VM backup due to an error`, {
// don't end the task
task.warning(`Retry the VM backup due to an error`, {
attempt: nTriesByVmId[vmUuid],
error: error.message,
})
@@ -126,19 +125,21 @@ export const VmsXapi = class VmsXapiBackupRunner extends Abstract {
nTriesByVmId[vmUuid]++
const vmSettings = { ...settings, ...allSettings[vmUuid] }
const taskStart = { name: 'backup VM', data: { type: 'VM', id: vmUuid } }
const taskStart = { properties: { id: vmUuid, name: 'backup VM', type: 'VM' } }
const isLastRun = nTriesByVmId[vmUuid] === vmSettings.nRetriesVmBackupFailures + 1
return this._getRecord('VM', vmUuid).then(
disposableVm =>
Disposable.use(disposableVm, async vm => {
if (taskStart.data.name_label === undefined) {
taskStart.data.name_label = vm.name_label
if (taskStart.properties.name_label === undefined) {
taskStart.properties.name_label = vm.name_label
}
const task = getVmTask()
// error has to be caught in the task to prevent its failure, but handled outside the task to execute another task.run()
let taskError
return task
.run(async () => {
.runInside(async () => {
const opts = {
baseSettings,
config,
@@ -164,21 +165,21 @@ export const VmsXapi = class VmsXapiBackupRunner extends Abstract {
throw new Error(`Job mode ${job.mode} not implemented`)
}
}
try {
const result = await vmBackup.run()
return vmBackup.run().catch(error => {
taskError = error
})
})
.then(result => {
if (taskError === undefined) {
task.success(result)
return result
} catch (error) {
vmBackupFailed(error)
} else {
// ending the task with error or not ending the task
vmBackupFailed(taskError, task)
}
})
.catch(noop) // errors are handled by logs
}),
error =>
getVmTask().run(() => {
vmBackupFailed(error)
})
error => vmBackupFailed(error, getVmTask())
)
}
const { concurrency } = settings

View File

@@ -1,8 +1,10 @@
import Disposable from 'promise-toolbox/Disposable'
import pTimeout from 'promise-toolbox/timeout'
import { compileTemplate } from '@xen-orchestra/template'
import { runTask } from './_runTask.mjs'
import { RemoteTimeoutError } from './_RemoteTimeoutError.mjs'
import { Task } from '@vates/task'
const noop = Function.prototype
export const DEFAULT_SETTINGS = {
getRemoteTimeout: 300e3,
@@ -36,13 +38,16 @@ export const Abstract = class AbstractRunner {
})
} catch (error) {
// See https://github.com/vatesfr/xen-orchestra/commit/6aa6cfba8ec939c0288f0fa740f6dfad98c43cbb
runTask(
Task.run(
{
name: 'get remote adapter',
data: { type: 'remote', id: remoteId },
properties: {
id: remoteId,
name: 'get remote adapter',
type: 'remote',
},
},
() => Promise.reject(error)
)
).catch(noop)
}
}
}

View File

@@ -1,9 +1,9 @@
import { asyncMap } from '@xen-orchestra/async-map'
import { Task } from '@vates/task'
import { DIR_XO_POOL_METADATA_BACKUPS } from '../RemoteAdapter.mjs'
import { forkStreamUnpipe } from './_forkStreamUnpipe.mjs'
import { formatFilenameDate } from '../_filenameDate.mjs'
import { Task } from '../Task.mjs'
export const PATH_DB_DUMP = '/pool/xmldbdump'
@@ -54,8 +54,8 @@ export class PoolMetadataBackup {
([remoteId, adapter]) =>
Task.run(
{
name: `Starting metadata backup for the pool (${pool.$id}) for the remote (${remoteId}). (${job.id})`,
data: {
properties: {
name: `Starting metadata backup for the pool (${pool.$id}) for the remote (${remoteId}). (${job.id})`,
id: remoteId,
type: 'remote',
},

View File

@@ -1,9 +1,9 @@
import { asyncMap } from '@xen-orchestra/async-map'
import { join } from '@xen-orchestra/fs/path'
import { Task } from '@vates/task'
import { DIR_XO_CONFIG_BACKUPS } from '../RemoteAdapter.mjs'
import { formatFilenameDate } from '../_filenameDate.mjs'
import { Task } from '../Task.mjs'
export class XoMetadataBackup {
constructor({ config, job, remoteAdapters, schedule, settings }) {
@@ -51,8 +51,8 @@ export class XoMetadataBackup {
([remoteId, adapter]) =>
Task.run(
{
name: `Starting XO metadata backup for the remote (${remoteId}). (${job.id})`,
data: {
properties: {
name: `Starting XO metadata backup for the remote (${remoteId}). (${job.id})`,
id: remoteId,
type: 'remote',
},

View File

@@ -1,5 +0,0 @@
import { Task } from '../Task.mjs'
const noop = Function.prototype
export const runTask = (...args) => Task.run(...args).catch(noop) // errors are handled by logs

View File

@@ -0,0 +1,45 @@
import assert from 'node:assert/strict'
import { describe, it } from 'node:test'
import { IncrementalRemote } from './IncrementalRemote.mjs'
const makeAdapter = () => ({
listVmBackups: async () => [],
_handler: { getInfo: async () => ({ available: 0 }), _remote: { id: 'remote-id' } },
})
const makeRunner = ({ distributeBackups = false, schedule } = {}) => {
const remoteId = 'remote-id'
return new IncrementalRemote({
config: {},
job: { id: 'job-id', mode: 'delta', remotes: { id: remoteId }, settings: {}, filter: undefined },
healthCheckSr: undefined,
remoteAdapters: { [remoteId]: makeAdapter() },
schedule,
settings: { distributeBackups, exportRetention: 1, deleteFirst: false, skipDeleteOldEntries: false },
sourceRemoteAdapter: {},
throttleGenerator: {},
throttleStream: {},
vmUuid: 'vm-uuid',
})
}
describe('IncrementalRemote prepare()', () => {
it('prepare() with IncrementalRemoteWriter (distributeBackups: false)', async () => {
const schedule = { id: 'schedule-id' }
const runner = makeRunner({ distributeBackups: false, schedule })
for (const writer of runner._writers) {
await writer.prepare({ isFull: false })
assert.equal(writer._schedule, schedule)
}
})
it('prepare() AggregatedIncrementalRemoteWriter (distributeBackups: true)', async () => {
const schedule = { id: 'schedule-id' }
const runner = makeRunner({ distributeBackups: true, schedule })
const [aggWriter] = runner._writers
await aggWriter.setupWriters()
await aggWriter.prepare({ isFull: false })
assert.equal(aggWriter.props.schedule, schedule)
})
})

View File

@@ -1,4 +1,5 @@
import { createLogger } from '@xen-orchestra/log'
import { Task } from '@vates/task'
import keyBy from 'lodash/keyBy.js'
import { AbstractXapi } from './_AbstractXapi.mjs'
@@ -6,7 +7,6 @@ import { forkDeltaExport } from './_forkDeltaExport.mjs'
import { exportIncrementalVm } from '../../_incrementalVm.mjs'
import { IncrementalRemoteWriter } from '../_writers/IncrementalRemoteWriter.mjs'
import { IncrementalXapiWriter } from '../_writers/IncrementalXapiWriter.mjs'
import { Task } from '../../Task.mjs'
import {
DATETIME,
DELTA_CHAIN_LENGTH,
@@ -135,16 +135,6 @@ export const IncrementalXapi = class IncrementalXapiVmBackupRunner extends Abstr
const deltaChainLength = Math.max(
...lastExportedVdis.map(({ other_config }) => Number(other_config[DELTA_CHAIN_LENGTH] ?? 0))
)
const fullInterval = this._settings.fullInterval
if (fullInterval !== 0 && fullInterval <= deltaChainLength + 1) {
debug('not using base VM because fullInterval reached', {
fullInterval,
deltaChainLength,
eq: fullInterval < deltaChainLength + 1,
dc1: deltaChainLength + 1,
})
return
}
const srcVdis = keyBy(await xapi.getRecords('VDI', await this._vm.$getDisks()), '$ref')
@@ -173,6 +163,20 @@ export const IncrementalXapi = class IncrementalXapiVmBackupRunner extends Abstr
debug('no base VM found')
return
}
// we do tafter checkbasevdis because we want the writer to know the target VM
// especially on replication when we alwayr update the same VM
const fullInterval = this._settings.fullInterval
if (fullInterval !== 0 && fullInterval <= deltaChainLength + 1) {
debug('not using base VM because fullInterval reached', {
fullInterval,
deltaChainLength,
eq: fullInterval < deltaChainLength + 1,
dc1: deltaChainLength + 1,
})
return
}
baseUuidToSrcVdiUuid.forEach((srcVdiUuid, baseUuid) => {
if (presentBaseVdis.has(baseUuid)) {
debug('found base VDI', {

View File

@@ -1,6 +1,6 @@
import { asyncMap } from '@xen-orchestra/async-map'
import { createLogger } from '@xen-orchestra/log'
import { Task } from '../../Task.mjs'
import { Task } from '@vates/task'
const { debug, warn } = createLogger('xo:backups:AbstractVmRunner')
@@ -83,7 +83,7 @@ export const Abstract = class AbstractVmBackupRunner {
// create a task to have an info in the logs and reports
return Task.run(
{
name: 'health check',
properties: { name: 'health check' },
},
() => {
Task.info(`This VM doesn't match the health check's tags for this schedule`)

View File

@@ -4,12 +4,12 @@ import { decorateMethodsWith } from '@vates/decorate-with'
import { defer } from 'golike-defer'
import { Disposable } from 'promise-toolbox'
import { createPredicate } from 'value-matcher'
import { Task } from '@vates/task'
import { getVmBackupDir } from '../../_getVmBackupDir.mjs'
import { Abstract } from './_Abstract.mjs'
import { extractIdsFromSimplePattern } from '../../extractIdsFromSimplePattern.mjs'
import { Task } from '../../Task.mjs'
export const AbstractRemote = class AbstractRemoteVmBackupRunner extends Abstract {
_filterPredicate
@@ -54,7 +54,7 @@ export const AbstractRemote = class AbstractRemoteVmBackupRunner extends Abstrac
config,
healthCheckSr,
job,
scheduleId: schedule.id,
schedule,
vmUuid,
settings,
})
@@ -72,7 +72,7 @@ export const AbstractRemote = class AbstractRemoteVmBackupRunner extends Abstrac
config,
healthCheckSr,
job,
scheduleId: schedule.id,
schedule,
vmUuid,
remoteId,
settings: targetSettings,

View File

@@ -6,11 +6,20 @@ import { asyncMap } from '@xen-orchestra/async-map'
import { asyncEach } from '@vates/async-each'
import { decorateMethodsWith } from '@vates/decorate-with'
import { defer } from 'golike-defer'
import { Task } from '@vates/task'
import { getOldEntries } from '../../_getOldEntries.mjs'
import { Task } from '../../Task.mjs'
import { Abstract } from './_Abstract.mjs'
import { DATETIME, JOB_ID, SCHEDULE_ID, VM_UUID, resetVmOtherConfig, setVmOtherConfig } from '../../_otherConfig.mjs'
import {
COPY_OF,
DATETIME,
JOB_ID,
SCHEDULE_ID,
VM_UUID,
resetVmOtherConfig,
setVmOtherConfig,
setVmSnapshotContentKeys,
} from '../../_otherConfig.mjs'
const { warn, info } = createLogger('xo:backups:AbstractXapi')
@@ -96,7 +105,7 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
config,
healthCheckSr,
job,
scheduleId: schedule.id,
schedule,
vmUuid: vm.uuid,
settings,
})
@@ -114,7 +123,7 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
config,
healthCheckSr,
job,
scheduleId: schedule.id,
schedule,
vmUuid: vm.uuid,
remoteId,
settings: targetSettings,
@@ -132,7 +141,7 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
healthCheckSr,
job,
ReplicationWriter,
scheduleId: schedule.id,
schedule,
vmUuid: vm.uuid,
srs,
settings,
@@ -150,7 +159,7 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
config,
healthCheckSr,
job,
scheduleId: schedule.id,
schedule,
vmUuid: vm.uuid,
sr,
settings: targetSettings,
@@ -165,11 +174,9 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
// ensure the VM itself does not have any backup metadata which would be
// copied on manual snapshots and interfere with the backup jobs
async _cleanMetadata() {
const vm = this._vm
if (JOB_ID in vm.other_config) {
await resetVmOtherConfig(this._xapi, vm.$ref)
}
await resetVmOtherConfig(this._xapi, this._vm.$ref)
}
async _snapshot() {
@@ -179,7 +186,7 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
const settings = this._settings
if (await this._mustDoSnapshot()) {
await Task.run({ name: 'snapshot' }, async () => {
await Task.run({ properties: { name: 'snapshot' } }, async () => {
if (!settings.bypassVdiChainsCheck) {
await vm.$assertHealthyVdiChains()
}
@@ -205,6 +212,7 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
scheduleId: this.scheduleId,
vmUuid: vm.uuid,
})
await setVmSnapshotContentKeys(xapi, snapshotRef)
const snapshot = await xapi.getRecord('VM', snapshotRef)
await snapshot.set_name_label(this._getSnapshotNameLabel(vm))
// reload data to ensure it is up to date with the new name label
@@ -233,11 +241,16 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
const xapi = this._xapi
const vdiCandidates = {}
const vdiUuids = this._vm.$VBDs.map(({ VDI }) => VDI)
Object.values(xapi.objects.indexes.type.VDI)
.filter(_ => !!_) // filter nullish
.filter(({ other_config, $snapshot_of }) => {
return $snapshot_of !== undefined && other_config[JOB_ID] === jobId && other_config[VM_UUID] === this._vm.uuid
.filter(({ other_config, snapshot_of }) => {
return (
vdiUuids.includes(snapshot_of) &&
other_config[JOB_ID] === jobId &&
other_config[VM_UUID] === this._vm.uuid &&
other_config[COPY_OF] === undefined
)
})
.forEach(vdi => {
vdiCandidates[vdi.uuid] = vdi
@@ -310,6 +323,7 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
// if not => remove it from the list to ensure we won't half destroy VM later
vm.$VBDs
.filter(({ $VDI }) => !!$VDI) // filter missing keys
.filter(({ $VDI }) => $VDI.$snapshot_of !== undefined) // skip non-snapshot VDIs (e.g., ISOs/CD-ROMs)
.filter(({ $VDI }) => $VDI && vdiCandidates[$VDI.uuid] === undefined)
.forEach(({ $VDI: outOfSnapshotsVdi, ...other }) => {
warn(

View File

@@ -1,6 +1,7 @@
import { Task } from '@vates/task'
import { formatFilenameDate } from '../../_filenameDate.mjs'
import { getOldEntries } from '../../_getOldEntries.mjs'
import { Task } from '../../Task.mjs'
import { MixinRemoteWriter } from './_MixinRemoteWriter.mjs'
import { AbstractFullWriter } from './_AbstractFullWriter.mjs'
@@ -9,11 +10,11 @@ export class FullRemoteWriter extends MixinRemoteWriter(AbstractFullWriter) {
constructor(props) {
super(props)
this.run = Task.wrapFn(
this.run = Task.wrap(
{
name: 'export',
data: {
properties: {
id: props.remoteId,
name: 'export',
type: 'remote',
// necessary?
@@ -27,7 +28,7 @@ export class FullRemoteWriter extends MixinRemoteWriter(AbstractFullWriter) {
async _run({ maxStreamLength, timestamp, sizeContainer, stream, streamLength, vm, vmSnapshot }) {
const settings = this._settings
const job = this._job
const scheduleId = this._scheduleId
const scheduleId = this._schedule.id
const adapter = this._adapter
let metadata = await this._isAlreadyTransferred(timestamp)
@@ -64,7 +65,7 @@ export class FullRemoteWriter extends MixinRemoteWriter(AbstractFullWriter) {
await deleteOldBackups()
}
await Task.run({ name: 'transfer' }, async () => {
await Task.run({ properties: { name: 'transfer' } }, async () => {
await adapter.outputStream(dataFilename, stream, {
maxStreamLength,
streamLength,

View File

@@ -1,9 +1,9 @@
import ignoreErrors from 'promise-toolbox/ignoreErrors'
import { asyncMap, asyncMapSettled } from '@xen-orchestra/async-map'
import { Task } from '@vates/task'
import { formatFilenameDate } from '../../_filenameDate.mjs'
import { getOldEntries } from '../../_getOldEntries.mjs'
import { Task } from '../../Task.mjs'
import { AbstractFullWriter } from './_AbstractFullWriter.mjs'
import { MixinXapiWriter } from './_MixinXapiWriter.mjs'
@@ -14,11 +14,11 @@ export class FullXapiWriter extends MixinXapiWriter(AbstractFullWriter) {
constructor(props) {
super(props)
this.run = Task.wrapFn(
this.run = Task.wrap(
{
name: 'export',
data: {
properties: {
id: props.sr.uuid,
name: 'export',
name_label: this._sr.name_label,
type: 'SR',
@@ -34,7 +34,7 @@ export class FullXapiWriter extends MixinXapiWriter(AbstractFullWriter) {
const sr = this._sr
const settings = this._settings
const job = this._job
const scheduleId = this._scheduleId
const scheduleId = this._schedule.id
const { uuid: srUuid, $xapi: xapi } = sr
@@ -52,7 +52,7 @@ export class FullXapiWriter extends MixinXapiWriter(AbstractFullWriter) {
}
let targetVmRef
await Task.run({ name: 'transfer' }, async () => {
await Task.run({ properties: { name: 'transfer' } }, async () => {
targetVmRef = await xapi.VM_import(stream, sr.$ref, vm =>
Promise.all([
!_warmMigration && vm.add_tags('Disaster Recovery'),

View File

@@ -7,10 +7,10 @@ import { createLogger } from '@xen-orchestra/log'
import { decorateClass } from '@vates/decorate-with'
import { defer } from 'golike-defer'
import { dirname, basename } from 'node:path'
import { Task } from '@vates/task'
import { formatFilenameDate } from '../../_filenameDate.mjs'
import { getOldEntries } from '../../_getOldEntries.mjs'
import { Task } from '../../Task.mjs'
import { MixinRemoteWriter } from './_MixinRemoteWriter.mjs'
import { AbstractIncrementalWriter } from './_AbstractIncrementalWriter.mjs'
@@ -72,25 +72,26 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
prepare({ isFull }) {
// create the task related to this export and ensure all methods are called in this context
const task = new Task({
name: 'export',
data: {
properties: {
id: this._remoteId,
isFull,
name: 'export',
type: 'remote',
},
})
this.transfer = task.wrapFn(this.transfer)
this.healthCheck = task.wrapFn(this.healthCheck)
this.cleanup = task.wrapFn(this.cleanup)
this.afterBackup = task.wrapFn(this.afterBackup, true)
this._prepare = task.wrapInside(this._prepare)
this.transfer = task.wrapInside(this.transfer)
this.healthCheck = task.wrapInside(this.healthCheck)
this.cleanup = task.wrapInside(this.cleanup)
this.afterBackup = task.wrap(this.afterBackup)
return task.run(() => this._prepare())
return this._prepare()
}
async _prepare() {
const adapter = this._adapter
const settings = this._settings
const scheduleId = this._scheduleId
const scheduleId = this._schedule.id
const vmUuid = this._vmUuid
const oldEntries = getOldEntries(
@@ -180,7 +181,7 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
async _transfer($defer, { isVhdDifferencing, timestamp, deltaExport, vm, vmSnapshot }) {
const adapter = this._adapter
const job = this._job
const scheduleId = this._scheduleId
const scheduleId = this._schedule.id
const settings = this._settings
const jobId = job.id
const handler = adapter.handler
@@ -223,7 +224,7 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
vtpms: deltaExport.vtpms,
}
let size = 0
await Task.run({ name: 'transfer' }, async () => {
await Task.run({ properties: { name: 'transfer' } }, async () => {
await asyncEach(
Object.entries(deltaExport.disks),
async ([diskRef, disk]) => {

View File

@@ -1,13 +1,15 @@
import humanFormat from 'human-format'
import { asyncMapSettled } from '@xen-orchestra/async-map'
import { Task } from '@vates/task'
import ignoreErrors from 'promise-toolbox/ignoreErrors'
import { getOldEntries } from '../../_getOldEntries.mjs'
import { importIncrementalVm } from '../../_incrementalVm.mjs'
import { Task } from '../../Task.mjs'
import { AbstractIncrementalWriter } from './_AbstractIncrementalWriter.mjs'
import { MixinXapiWriter } from './_MixinXapiWriter.mjs'
import { listReplicatedVms } from './_listReplicatedVms.mjs'
import { compareReplicatedVmDatetime, listReplicatedVms } from './_listReplicatedVms.mjs'
import {
COPY_OF,
setVmOtherConfig,
@@ -18,70 +20,206 @@ import {
DATETIME,
VM_UUID,
} from '../../_otherConfig.mjs'
import assert from 'node:assert'
import { formatFilenameDate } from '../../_filenameDate.mjs'
import { XapiDiskSource } from '@xen-orchestra/xapi'
import { asyncEach } from '@vates/async-each'
import { createLogger } from '@xen-orchestra/log'
const { debug } = createLogger('xo:backups:IncrementalXapiWriter')
export class IncrementalXapiWriter extends MixinXapiWriter(AbstractIncrementalWriter) {
// Map of source VDI UUID (COPY_OF) → validated active VDI on the target SR.
// Built by checkBaseVdis, consumed by #decorateVmMetadata to set baseVdi.
#baseVdisBySourceUuid = new Map()
async checkBaseVdis(baseUuidToSrcVdi) {
const sr = this._sr
this.#baseVdisBySourceUuid = new Map()
if (baseUuidToSrcVdi.size === 0) {
// searching for the vdis is expensive
// don't do it if there is nothing to find
return
}
// @todo use an index if possible
// @todo : this seems similar to decorateVmMetadata
const replicatedVdis = sr.$VDIs
.filter(vdi => {
// REPLICATED_TO_SR_UUID is not used here since we are already filtering from sr.$VDIs
return (
vdi?.managed &&
!vdi?.is_a_snapshot /* only look for real vdi */ &&
baseUuidToSrcVdi.has(vdi?.other_config[COPY_OF])
)
// look for the same snapshot
// ensure there are no data between the snapshot and the active disk
const snapshotCandidates = sr.$VDIs.filter(vdi => {
return (
vdi?.managed &&
vdi?.is_a_snapshot &&
vdi.other_config[JOB_ID] === this._job.id &&
vdi.other_config[VM_UUID] === this._vmUuid &&
baseUuidToSrcVdi.has(vdi?.other_config[COPY_OF])
)
})
debug('checkBaseVdis, got snapshot candidates,', snapshotCandidates.length)
if (snapshotCandidates.length > 0) {
// reset before searching for candidates
this.#baseVdisBySourceUuid = new Map()
this._targetVmRef = undefined
const { baseVdisBySourceUuid, targetVmRef } = await this.#validateSnapshotCandidates(snapshotCandidates)
for (const [sourceUuid, vdi] of baseVdisBySourceUuid) {
this.#baseVdisBySourceUuid.set(sourceUuid, vdi)
}
if (targetVmRef !== undefined) {
this._targetVmRef = targetVmRef
}
} else {
// Legacy fallback (upgrade from pre-6.3): no target snapshots exist yet,
// look for active (non-snapshot) VDIs with matching COPY_OF, like the old code did.
debug('checkBaseVdis, no snapshot candidates, falling back to legacy active VDI lookup')
const legacyVdis = sr.$VDIs.filter(vdi => {
return vdi?.managed && !vdi?.is_a_snapshot && baseUuidToSrcVdi.has(vdi?.other_config[COPY_OF])
})
.map(({ other_config }) => other_config?.[COPY_OF])
.filter(_ => !!_)
for (const vdi of legacyVdis) {
const sourceUuid = vdi.other_config[COPY_OF]
if (sourceUuid) {
this.#baseVdisBySourceUuid.set(sourceUuid, vdi)
}
}
}
for (const uuid of baseUuidToSrcVdi.keys()) {
if (!replicatedVdis.includes(uuid)) {
if (!this.#baseVdisBySourceUuid.has(uuid)) {
baseUuidToSrcVdi.delete(uuid)
}
}
}
/**
* 6.3+ snapshot-based validation: for each snapshot candidate, check whether
* the active VDI has diverged from the snapshot. Returns a baseVdisBySourceUuid
* map and, when all disks are clean, the targetVmRef to reuse.
*/
async #validateSnapshotCandidates(snapshotCandidates) {
const sr = this._sr
const baseVdisBySourceUuid = new Map()
let targetVmRef
let canChainToTargetVm = true
await asyncEach(
snapshotCandidates,
async snapshot => {
let diffDisk
let activeVdi
try {
activeVdi = sr.$xapi.getObject(snapshot.$snapshot_of)
const userVbds = activeVdi.$VBDs?.filter(vbd => vbd.$VM && !vbd.$VM.is_control_domain) ?? []
if (userVbds.length !== 1) {
debug('checkBaseVdis, shared vbd ', { ref: snapshot.$ref, userVbds })
// shared vdi ignore
return
}
const vm = userVbds[0].$VM
if (!('start' in vm.blocked_operations)) {
debug('checkBaseVdis, vm not blocked', { vmRef: vm.$ref })
// vm start unlocked
// not really an issue since we have check the delta
// but it indicates the users played with the blocked operations
return
}
diffDisk = new XapiDiskSource({
xapi: sr.$xapi,
vdiRef: activeVdi.$ref,
baseRef: snapshot.$ref,
onlyListChangedBlocks: true,
})
await diffDisk.init()
const sourceUuid = snapshot.other_config?.[COPY_OF]
if (diffDisk.getBlockIndexes().length === 0) {
// no block modification since the common snapshot, we can chain VM and disk
if (sourceUuid) {
baseVdisBySourceUuid.set(sourceUuid, activeVdi)
}
// Track the target VM (the replicated VM to update on the next transfer).
targetVmRef = vm.$ref
} else {
if (sourceUuid) {
baseVdisBySourceUuid.set(sourceUuid, snapshot)
}
// there are changed block since the snapshot
// we can reuse it to transfer a delta, but we will
// create a new VM
canChainToTargetVm = false
debug('checkBaseVdis, data between snapshot and active disk', {
vdiRef: snapshot.$ref,
nbBlocks: diffDisk.getBlockIndexes().length,
})
}
} catch (error) {
debug('checkBaseVdis, skipping snapshot', { ref: snapshot.$ref, error })
return
} finally {
await diffDisk?.close().catch(error => debug('checkBaseVdis, error closing', error))
await sr.$xapi.VDI_disconnectFromControlDomain(snapshot.$ref)
if (activeVdi !== undefined) {
await sr.$xapi.VDI_disconnectFromControlDomain(activeVdi.$ref)
}
}
},
{
concurrency: 4,
}
)
if (!canChainToTargetVm) {
// if at least one disk has new data, create a new VM
// instead of updating it
targetVmRef = undefined
} else if (targetVmRef !== undefined) {
debug('checkBaseVdis,got a valid vm target', targetVmRef)
}
return { baseVdisBySourceUuid, targetVmRef }
}
updateUuidAndChain() {
// nothing to do, the chaining is not modified in this case
}
prepare({ isFull }) {
// create the task related to this export and ensure all methods are called in this context
const task = new Task({
name: 'export',
data: {
properties: {
id: this._sr.uuid,
isFull,
name: 'export',
name_label: this._sr.name_label,
type: 'SR',
},
})
const hasHealthCheckSr = this._healthCheckSr !== undefined
this.transfer = task.wrapFn(this.transfer)
this.cleanup = task.wrapFn(this.cleanup, !hasHealthCheckSr)
this.healthCheck = task.wrapFn(this.healthCheck, hasHealthCheckSr)
this._prepare = task.wrapInside(this._prepare)
this.transfer = task.wrapInside(this.transfer)
if (this._healthCheckSr !== undefined) {
this.cleanup = task.wrapInside(this.cleanup)
this.healthCheck = task.wrap(this.healthCheck)
} else {
this.cleanup = task.wrap(this.cleanup)
}
return task.run(() => this._prepare(isFull))
return this._prepare(isFull)
}
async _prepare(isFull) {
const settings = this._settings
const { uuid: srUuid, $xapi: xapi } = this._sr
const vmUuid = this._vmUuid
const scheduleId = this._scheduleId
const scheduleId = this._schedule.id
// delete previous interrupted copies
ignoreErrors.call(asyncMapSettled(listReplicatedVms(xapi, scheduleId, undefined, vmUuid), vm => vm.$destroy))
this._oldEntries = getOldEntries(settings.copyRetention - 1, listReplicatedVms(xapi, scheduleId, srUuid, vmUuid))
const allEntries = listReplicatedVms(xapi, scheduleId, srUuid, vmUuid)
// In the snapshot-based flow a non-snapshot VM (the live target) coexists with its
// snapshots (one per transfer). That VM must not be subject to retention — only its
// snapshots are. Build the set of VM refs that already have snapshots in the list so
// we can exclude them, while keeping old-style non-snapshot VMs (no snapshots).
const vmRefsWithSnapshots = new Set(allEntries.filter(e => e.is_a_snapshot).map(e => e.snapshot_of))
const retentionEntries = allEntries.filter(e => e.is_a_snapshot || !vmRefsWithSnapshots.has(e.$ref))
retentionEntries.sort(compareReplicatedVmDatetime)
this._oldEntries = getOldEntries(settings.copyRetention - 1, retentionEntries)
if (settings.deleteFirst && settings.skipDeleteOldEntries) {
// we want to keep the baseVM when copying a delta
@@ -110,9 +248,8 @@ export class IncrementalXapiWriter extends MixinXapiWriter(AbstractIncrementalWr
const sr = this._sr
const vm = backup.vm
const job = this._job
const scheduleId = this._scheduleId
const scheduleId = this._schedule.id
vm.name_label = `${vm.name_label} - ${job.name} - (${formatFilenameDate(timestamp)})`
// update other_config data as soon as possible to ensure the next job
// will be able to detect any partial transfer and lean them
vm.other_config[COPY_OF] = vm.uuid
@@ -130,18 +267,6 @@ export class IncrementalXapiWriter extends MixinXapiWriter(AbstractIncrementalWr
if (!_warmMigration) {
vm.tags.push('Continuous Replication')
}
// extracting the uuid of each delta vdi on the source
// get all in one pass, since there is a lot of objects
const sourceVdiUuids = Object.values(backup.vdis)
.map(({ other_config }) => other_config[BASE_DELTA_VDI])
// full vdi don't have a base
.filter(_ => !!_)
// @todo use index ?
const replicatedVdis = sr.$VDIs.filter(vdi => {
// REPLICATED_TO_SR_UUID is not used here since we are already filtering from sr.$VDIs
return vdi?.managed && !vdi?.is_a_snapshot && sourceVdiUuids.includes(vdi?.other_config[COPY_OF])
})
Object.values(backup.vdis).forEach(vdi => {
vdi.other_config[COPY_OF] = vdi.uuid
@@ -150,18 +275,12 @@ export class IncrementalXapiWriter extends MixinXapiWriter(AbstractIncrementalWr
vdi.other_config[REPLICATED_TO_SR_UUID] = sr.uuid
vdi.other_config[VM_UUID] = vm.uuid
if (sourceVdiUuids.length > 0) {
const baseReplicatedTo = replicatedVdis.filter(
replicatedVdi => replicatedVdi.other_config[COPY_OF] === vdi.other_config[BASE_DELTA_VDI]
)
assert.ok(
baseReplicatedTo.length <= 1,
`Target of a replication must be unique, got ${baseReplicatedTo.length} candidates`
)
// baseReplicatedTo can be undefined if a new disk is added and other are already replicated
vdi.baseVdi = baseReplicatedTo[0]
const baseDeltaVdiUuid = vdi.other_config[BASE_DELTA_VDI]
if (baseDeltaVdiUuid !== undefined) {
// reuse the validated mapping built by checkBaseVdis
vdi.baseVdi = this.#baseVdisBySourceUuid.get(baseDeltaVdiUuid)
} else {
// first replication of this disk
// first replication of this disk (full, no base)
vdi.baseVdi = undefined
}
// ensure the VDI are created on the target SR
@@ -175,18 +294,43 @@ export class IncrementalXapiWriter extends MixinXapiWriter(AbstractIncrementalWr
const { _warmMigration } = this._settings
const sr = this._sr
const job = this._job
const scheduleId = this._scheduleId
const schedule = this._schedule
const scheduleId = schedule.id
const { uuid: srUuid, $xapi: xapi } = sr
let targetVmRef
await Task.run({ name: 'transfer' }, async () => {
targetVmRef = await importIncrementalVm(this.#decorateVmMetadata(deltaExport, timestamp), sr)
// size is mandatory to ensure the task have the right data
await Task.run({ properties: { name: 'transfer' } }, async () => {
targetVmRef = await importIncrementalVm(this.#decorateVmMetadata(deltaExport, timestamp), sr, {
targetRef: this._targetVmRef,
})
// this also ensure the data are up to date on the snapshot
await setVmOtherConfig(xapi, targetVmRef, {
timestamp, // updated at the end to mark the transfer as complete
jobId: job.id,
scheduleId,
vmUuid: vm.uuid,
srUuid,
})
const size = Object.values(deltaExport.disks).reduce(
(sum, disk) => sum + disk.getNbGeneratedBlock() * disk.getBlockSize(),
0
)
await xapi.setField(
'VM',
targetVmRef,
'name_description',
deltaExport.vm.name_description +
` -- last replication: ${formatFilenameDate(timestamp)} ${humanFormat.bytes(size)} read`
)
// take a snapshot to ensure these data are not modified until next snapshot
await Task.run({ properties: { name: 'target snapshot' } }, async () => {
await xapi.VM_snapshot(targetVmRef, {
name_label: `${vm.name_label} - ${job.name} / ${schedule.name} ${formatFilenameDate(timestamp)}`,
})
})
return {
size: Object.values(deltaExport.disks).reduce(
(sum, disk) => sum + disk.getNbGeneratedBlock() * disk.getBlockSize(),
0
),
size,
}
})
this._targetVmRef = targetVmRef
@@ -197,13 +341,6 @@ export class IncrementalXapiWriter extends MixinXapiWriter(AbstractIncrementalWr
!_warmMigration &&
targetVm.ha_restart_priority !== '' &&
Promise.all([targetVm.set_ha_restart_priority(''), targetVm.add_tags('HA disabled')]),
setVmOtherConfig(xapi, targetVmRef, {
timestamp, // updated at the end to mark the transfer as complete
jobId: job.id,
scheduleId,
vmUuid: vm.uuid,
srUuid,
}),
])
}
}

View File

@@ -107,7 +107,7 @@ export class AbstractAggregatedRemoteWriter {
}
async getEntriesPerAdapter(adapter) {
const scheduleId = this.#props.scheduleId
const scheduleId = this.#props.schedule.id
const vmUuid = this.#props.vmUuid
return (await adapter.listVmBackups(vmUuid, _ => _.scheduleId === scheduleId)).map(entry => ({
...entry,

View File

@@ -1,9 +1,9 @@
export class AbstractWriter {
constructor({ config, healthCheckSr, job, vmUuid, scheduleId, settings }) {
constructor({ config, healthCheckSr, job, vmUuid, schedule, settings }) {
this._config = config
this._healthCheckSr = healthCheckSr
this._job = job
this._scheduleId = scheduleId
this._schedule = schedule
this._settings = settings
this._vmUuid = vmUuid
}

View File

@@ -1,12 +1,12 @@
import { createLogger } from '@xen-orchestra/log'
import { join } from 'node:path'
import { Task } from '@vates/task'
import assert from 'node:assert'
import { formatFilenameDate } from '../../_filenameDate.mjs'
import { getVmBackupDir } from '../../_getVmBackupDir.mjs'
import { HealthCheckVmBackup } from '../../HealthCheckVmBackup.mjs'
import { ImportVmBackup } from '../../ImportVmBackup.mjs'
import { Task } from '../../Task.mjs'
import * as MergeWorker from '../../merge-worker/index.mjs'
import ms from 'ms'
import { getEntryStatus } from '../../_getOldEntries.mjs'
@@ -28,7 +28,7 @@ export const MixinRemoteWriter = (BaseClass = Object) =>
async _cleanVm(options) {
try {
return await Task.run({ name: 'clean-vm' }, () => {
return await Task.run({ properties: { name: 'clean-vm' } }, () => {
return this._adapter.cleanVm(this._vmBackupDir, {
...options,
fixMetadata: true,
@@ -50,7 +50,7 @@ export const MixinRemoteWriter = (BaseClass = Object) =>
async getLongTermRetentionTags(currentEntry) {
const settings = this._settings
const scheduleId = this._scheduleId
const scheduleId = this._schedule.id
const vmUuid = this._vmUuid
const adapter = this._adapter
@@ -100,7 +100,7 @@ export const MixinRemoteWriter = (BaseClass = Object) =>
}
return Task.run(
{
name: 'health check',
properties: { name: 'health check' },
},
async () => {
const xapi = sr.$xapi

View File

@@ -1,7 +1,7 @@
import assert from 'node:assert/strict'
import { Task } from '@vates/task'
import { HealthCheckVmBackup } from '../../HealthCheckVmBackup.mjs'
import { Task } from '../../Task.mjs'
import ms from 'ms'
export const MixinXapiWriter = (BaseClass = Object) =>
@@ -33,7 +33,7 @@ export const MixinXapiWriter = (BaseClass = Object) =>
// copy VM
return Task.run(
{
name: 'health check',
properties: { name: 'health check' },
},
async () => {
const { $xapi: xapi } = sr
@@ -47,12 +47,12 @@ export const MixinXapiWriter = (BaseClass = Object) =>
}
if (await this.#isAlreadyOnHealthCheckSr(baseVm)) {
healthCheckVmRef = await Task.run(
{ name: 'cloning-vm' },
{ properties: { name: 'cloning-vm' } },
async () => await xapi.callAsync('VM.clone', this._targetVmRef, `Health Check - ${baseVm.name_label}`)
)
} else {
healthCheckVmRef = await Task.run(
{ name: 'copying-vm' },
{ properties: { name: 'copying-vm' } },
async () =>
await xapi.callAsync(
'VM.copy',

View File

@@ -23,12 +23,13 @@ export function listReplicatedVms(xapi, scheduleOrJobId, srUuid, vmUuid) {
const oc = object.other_config
if (
object.$type === 'VM' &&
!object.is_a_snapshot &&
!object.is_a_template &&
'start' in object.blocked_operations &&
(oc[JOB_ID] === scheduleOrJobId || oc[SCHEDULE_ID] === scheduleOrJobId) &&
oc[REPLICATED_TO_SR_UUID] === srUuid &&
oc[VM_UUID] === vmUuid
oc[VM_UUID] === vmUuid &&
// Old-style replication: one VM per transfer (non-snapshot, start blocked)
// New-style replication: snapshots of the target VM represent each transfer
(!object.is_a_snapshot ? 'start' in object.blocked_operations : true)
) {
vms[object.$id] = object
}

View File

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

View File

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

File diff suppressed because it is too large Load Diff

View File

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

View File

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

View File

@@ -0,0 +1,304 @@
// @ts-check
/**
* @typedef {import('./RemoteVhdDisk.mjs').VhdFooter} VhdFooter
* @typedef {import('./RemoteVhdDisk.mjs').RemoteVhdDisk} RemoteVhdDisk
* @typedef {import('@xen-orchestra/disk-transform').DiskBlock} DiskBlock
* @typedef {import('@xen-orchestra/disk-transform').FileAccessor} FileAccessor
*/
import { RemoteDisk } from './RemoteDisk.mjs'
export class RemoteVhdDiskChain extends RemoteDisk {
/**
* @type {RemoteVhdDisk[]}
*/
#disks
/**
* @type {number}
*/
#blockSize = 2 * 1024 * 1024
/**
* @type {number}
*/
#headerSize = 1024
/**
* @type {number}
*/
#footerSize = 512
/**
* @type {number}
*/
#bitmapSize = 512
/**
* @param {Object} params
* @param {FileAccessor} params.handler
* @param {RemoteVhdDisk[]} params.disks
*/
constructor({ disks }) {
super()
this.#disks = disks
}
/**
* Initializes the VHD chain
* @param {Object} options
* @param {boolean} options.force
* @returns {Promise<void>}
*/
async init(options) {
try {
await Promise.all(this.#disks.map(disk => disk.init(options)))
let parentUuid = ''
for (const [index, disk] of this.#disks.entries()) {
if (index !== 0) {
if (!disk.isDifferencing()) {
throw Object.assign(new Error("Can't init vhd directory with non differencing child disks"), {
code: 'NOT_SUPPORTED',
})
}
if (disk.getParentUuid() !== parentUuid) {
throw Object.assign(new Error("Can't init vhd directory with incorrect parentage"), {
code: 'NOT_SUPPORTED',
})
}
}
parentUuid = disk.getUuid()
}
} catch (error) {
await this.close()
throw error
}
}
/**
* Closes the VHD.
* @returns {Promise<void>}
*/
async close() {
await Promise.all(this.#disks.map(disk => disk.close()))
}
/**
* @returns {number}
*/
getVirtualSize() {
return this.#disks[this.#disks.length - 1].getVirtualSize()
}
/**
* @returns {number} size
*/
getSizeOnDisk() {
const batEntrySize = 4
const sectorSize = 512
const batSize = Math.ceil((this.getMaxBlockCount() * batEntrySize) / sectorSize) * sectorSize
return (
this.#footerSize +
this.#headerSize +
batSize +
this.getBlockIndexes().length * (this.#blockSize + this.#bitmapSize) +
this.#footerSize
)
}
/**
* @returns {number}
*/
getBlockSize() {
return this.#disks[this.#disks.length - 1].getBlockSize()
}
/**
* @returns {string}
*/
getPath() {
return this.#disks[this.#disks.length - 1].getPath()
}
/**
* 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
*/
async canMergeConcurently() {
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)
}
}
throw new Error(`Block ${index} not found in chain`)
}
/**
* @returns {VhdFooter}
*/
getMetadata() {
return this.#disks[this.#disks.length - 1].getMetadata()
}
/**
* @param {RemoteVhdDisk} childDisk
* @returns {Promise<void>}
*/
async flushMetadata(childDisk) {
throw new Error(`Can't flush metadata on a disk chain`)
}
/**
* @param {RemoteVhdDisk} childDisk
* @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
*/
async unlink() {
for (const disk of this.#disks) {
await disk.unlink()
}
}
/**
* Check if all the disks in the chain are VHD directories.
* @returns {Promise<boolean>}
*/
async isDirectory() {
for (const disk of this.#disks) {
if (!(await disk.isDirectory())) {
return false
}
}
return true
}
}

View File

@@ -0,0 +1,49 @@
import { RemoteVhdDisk } from './RemoteVhdDisk.mjs'
export { RemoteDisk } from './RemoteDisk.mjs'
export { openDiskChain } from './openDiskChain.mjs'
/**
* @typedef {import('../../disk-transform/src/FileAccessor.mjs').FileAccessor} FileAccessor
* @typedef {import('./RemoteDisk.mjs').RemoteDisk} RemoteDisk
*/
/**
* @param {Object} params
* @param {FileAccessor} params.handler
* @param {string} params.path
* @returns {Promise<RemoteDisk>}
*/
export async function openDisk({ handler, path }) {
const disk = new RemoteVhdDisk({ handler, path })
await disk.init()
return disk
}
/**
*
* @param {Object} params
* @param {FileAccessor} params.handler
* @param {string} params.path
* @returns {Promise<Disposable<RemoteDisk>>}
*/
export async function openDisposableDisk({ handler, path }) {
const disk = new RemoteVhdDisk({ handler, path })
await disk.init()
return {
value: disk,
dispose: () => disk.close(),
}
}
const DISK_EXTENSIONS = ['.vhd']
/**
* Returns true if the path points to a supported disk format.
*
* @param {FileAccessor} _handler - Remote file handler (reserved for future use)
* @param {string} path - Path to check
* @returns {boolean}
*/
export function isDisk(_handler, path) {
return DISK_EXTENSIONS.some(ext => path.endsWith(ext))
}

View File

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

View File

@@ -0,0 +1,116 @@
# Incremental Replication (CR) - Target Selection
This document explains how incremental replication (Continuous Replication to a XAPI SR) selects its target VM and VDIs, and the resulting transfer modes.
## Overview
The goal is to maintain a replica VM on a target SR. On each run, the system decides:
1. **Target VM**: should we update an existing replicated VM, or create a new one?
2. **Target VDIs**: for each disk, should we transfer a delta (incremental) or a full copy?
These two decisions are independent: we can create a new VM but still chain disks to existing VDIs from a previous replica, reducing transfer size.
## Key metadata (`other_config`)
Replicated VDI snapshots on the target SR are tagged with:
| Key | Purpose |
| -------------------- | -------------------------------------------------- |
| `xo:copy_of` | UUID of the source VDI this is a copy of |
| `xo:backup:job` | Job ID that created it |
| `xo:backup:vm` | Source VM UUID |
| `xo:backup:schedule` | Schedule ID |
| `xo:backup:sr` | Target SR UUID |
| `xo:base_delta_vdi` | UUID of the source VDI used as base for this delta |
## Step-by-step flow
### 1. `_selectBaseVm` (runner)
Finds the last successfully exported snapshot VDIs on the source. Builds `baseUuidToSrcVdiUuid`: a map of `snapshotVdiUuid -> currentSrcVdiUuid` for each disk. Then calls `checkBaseVdis` on each writer with a shared copy of this map (`presentBaseVdis`).
Each writer removes entries from `presentBaseVdis` for disks it cannot handle as delta. Since writers are called sequentially on the same map, the result is an **intersection**: only disks that are valid across all writers survive. If any single writer (e.g. a remote writer) lacks a base for a disk, that disk is removed for everyone, and the runner will export it as full.
### 2. `checkBaseVdis` (writer)
Searches the target SR for VDI snapshots that match the source snapshot by `COPY_OF`, scoped to the current `JOB_ID` and `VM_UUID`. For each candidate, it validates:
1. **Active VDI exists**: the snapshot's `$snapshot_of` must resolve to a live VDI.
2. **Single user VM**: the active VDI must be attached to exactly one non-control-domain VM (shared VDIs are skipped).
3. **VM is blocked**: the VM must have `start` in `blocked_operations` (confirms it's a managed replica).
4. **No data written since snapshot**: a diff between the active VDI and the snapshot must be empty (no blocks changed).
This produces two results stored as instance state:
- **`#baseVdisBySourceUuid`**: a `Map<sourceVdiUuid, activeVdi>` of validated disk links, reused later by `#decorateVmMetadata`.
- **`_targetVmRef`**: the ref of the replicated VM to update, set only if **all** disks can chain to the same VM (`canChainToTargetVm`).
Any source VDI UUID not present in `#baseVdisBySourceUuid` is removed from `baseUuidToSrcVdi`, signaling the runner that no valid base exists for that disk.
### 3. `#decorateVmMetadata` (writer, called during transfer)
Sets `vdi.baseVdi` for each disk in the export by looking up `vdi.other_config[BASE_DELTA_VDI]` in `#baseVdisBySourceUuid`. This directly reuses the validated mapping from `checkBaseVdis` instead of re-querying the SR.
**Important**: a disk may arrive as a full export (no `BASE_DELTA_VDI`) even though this writer's `checkBaseVdis` had found a valid candidate for it. This happens when another writer in the job could not handle that disk as delta, causing the runner to remove it from the shared map and export it as full for all writers. In that case `BASE_DELTA_VDI` is absent, `#baseVdisBySourceUuid` is not consulted, and the disk is transferred as full.
### 4. `_transfer` (writer)
Calls `importIncrementalVm` with:
- `targetRef = this._targetVmRef` (may be `undefined` if no valid target VM)
- Each VDI's `baseVdi` set by `#decorateVmMetadata` (may be `undefined` per-disk)
## Decision matrix
### Target VM selection
| All VDI diffs empty | VM blocked | `_targetVmRef` set | Result |
| ---------------------- | ---------- | ------------------ | -------------------------------------------------------- |
| Yes | Yes | Yes | **Update existing VM** (incremental into the same VM) |
| No (some disk changed) | - | No | **Create new VM** (but may still chain individual disks) |
| - | No | No | **Create new VM** (target VM was tampered with) |
| No candidates found | - | No | **Create new VM** (first replication or target deleted) |
### Per-disk transfer mode
| `baseVdi` set | `BASE_DELTA_VDI` present | Result |
| ------------- | ------------------------ | ---------------------------------------------------------------------------- |
| Yes | Yes | **Delta transfer**: only changed blocks since the base are sent |
| No | Yes | **Full transfer for this disk**: base was not found or not valid on target |
| - | No | **Full transfer**: first replication of this disk (no base exists on source) |
### Combined scenarios
#### Scenario 1: Normal incremental run
All disks have valid bases on the target, diffs are empty. `_targetVmRef` is set. Transfer is fully incremental into the existing VM.
#### Scenario 2: One disk was modified on the target
Disk A's diff is empty, disk B has blocks written. `canChainToTargetVm = false`, so a new VM is created. But disk A still has a valid entry in `#baseVdisBySourceUuid`, so its transfer is incremental (chained to the existing active VDI). Disk B falls back to full.
#### Scenario 3: New disk added to source VM
Existing disks have valid bases. The new disk has no `BASE_DELTA_VDI`. Existing disks transfer as delta; the new disk transfers as full. If the existing disks' VM is valid, `_targetVmRef` is set and the new disk is added to that VM.
#### Scenario 4: Target VM deleted or first run
No snapshot candidates found. `#baseVdisBySourceUuid` is empty. All disks are full. A new VM is created.
#### Scenario 5: Disk valid on one writer but not another
A job replicates to both SR-A (XAPI writer) and Remote-B (remote writer). Disk X has a valid base on SR-A but the VHD chain is broken on Remote-B. Remote-B removes disk X from the shared `presentBaseVdis` map. The runner exports disk X as full. SR-A's `#decorateVmMetadata` receives a full disk (no `BASE_DELTA_VDI`), so `baseVdi` is `undefined` despite SR-A having a valid candidate locally. Both writers get a full transfer for that disk.
#### Scenario 6: Multiple jobs replicate the same VM to the same SR
`checkBaseVdis` scopes candidates by `JOB_ID` + `VM_UUID`, so each job only sees its own VDI snapshots. `#decorateVmMetadata` reuses this scoped mapping, avoiding cross-job conflicts.
## After transfer
Once the transfer completes:
1. `other_config` is updated on the target VM with the final timestamp.
2. A snapshot of the target VM is taken (to serve as the base for the next delta).
3. `other_config` is reset on the target VM (the snapshot retains the metadata).
4. Old entries beyond `copyRetention` are destroyed during cleanup.

View File

@@ -8,32 +8,34 @@
"type": "git",
"url": "https://github.com/vatesfr/xen-orchestra.git"
},
"version": "0.68.2",
"version": "0.72.0",
"engines": {
"node": ">=14.18"
},
"scripts": {
"postversion": "npm publish --access public",
"test": "node --test",
"test-integration": "node --test *.integ.mjs"
},
"dependencies": {
"@iarna/toml": "^2.2.5",
"@kldzj/stream-throttle": "^1.1.1",
"@vates/async-each": "^1.0.1",
"@vates/async-each": "^1.0.3",
"@vates/cached-dns.lookup": "^1.0.0",
"@vates/compose": "^2.1.0",
"@vates/decorate-with": "^2.1.0",
"@vates/disposable": "^0.1.6",
"@vates/fuse-vhd": "^2.1.2",
"@vates/generator-toolbox": "^1.1.0",
"@vates/nbd-client": "^3.2.3",
"@vates/generator-toolbox": "^1.1.2",
"@vates/nbd-client": "^3.4.0",
"@vates/parse-duration": "^0.1.1",
"@xen-orchestra/async-map": "^0.1.2",
"@xen-orchestra/disk-transform": "^1.2.1",
"@xen-orchestra/fs": "^4.6.6",
"@xen-orchestra/log": "^0.7.1",
"@xen-orchestra/qcow2": "^1.1.2",
"@xen-orchestra/template": "^0.1.0",
"@vates/task": "^0.7.0",
"@xen-orchestra/async-map": "^0.1.3",
"@xen-orchestra/disk-transform": "^1.2.3",
"@xen-orchestra/fs": "^4.8.0",
"@xen-orchestra/log": "^0.7.2",
"@xen-orchestra/qcow2": "^1.3.0",
"@xen-orchestra/template": "^0.1.1",
"app-conf": "^3.0.0",
"compare-versions": "^6.0.0",
"d3-time-format": "^4.1.0",
@@ -41,7 +43,7 @@
"golike-defer": "^0.5.1",
"human-format": "^1.2.0",
"limit-concurrency-decorator": "^0.6.0",
"lodash": "^4.17.20",
"lodash": "^4.18.0",
"moment-timezone": "^0.5.46",
"ms": "^2.1.3",
"node-zone": "^0.4.0",
@@ -51,8 +53,8 @@
"tar": "^7.5.3",
"uuid": "^9.0.0",
"value-matcher": "^0.2.0",
"vhd-lib": "^4.14.7",
"xen-api": "^4.7.6",
"vhd-lib": "^4.16.0",
"xen-api": "^4.7.7",
"yazl": "^2.5.1"
},
"devDependencies": {
@@ -62,11 +64,15 @@
"tmp": "^0.2.1"
},
"peerDependencies": {
"@xen-orchestra/xapi": "^8.6.6"
"@xen-orchestra/xapi": "^8.7.2"
},
"license": "AGPL-3.0-or-later",
"author": {
"name": "Vates SAS",
"url": "https://vates.fr"
},
"exports": {
"./disks": "./disks/index.mjs",
"./*": "./*"
}
}

View File

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

View File

@@ -1,7 +1,7 @@
{
"private": false,
"name": "@xen-orchestra/cron",
"version": "1.0.6",
"version": "1.0.7",
"license": "ISC",
"description": "Focused, well maintained, cron parser/scheduler",
"keywords": [
@@ -34,7 +34,7 @@
"node": ">=8.3"
},
"dependencies": {
"lodash": "^4.17.4",
"lodash": "^4.18.0",
"moment-timezone": "^0.5.14"
},
"scripts": {

View File

@@ -0,0 +1,79 @@
```
$ xo-disk-cli --help
Usage: xo-disk-cli <command> <handler-url> <path> [options]
Commands:
info Show disk info (virtual size, uid, parent uid, block size)
list List all disks at a path and display their properties in a table
transform Convert a disk to another format and write to stdout (raw | vhd | qcow2)
```
## Commands
### `info`
Display metadata for a single disk file.
```
xo-disk-cli info <handler-url> <disk-path>
```
Output includes: UID, parent UID (for differencing disks), virtual size, and block size.
```
$ xo-disk-cli info file:///mnt/backups /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/snapshot.vhd
Disk info: /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/snapshot.vhd
UID: <uuid>
Parent UID: <parent-uuid>
Virtual size: 8.00 GiB (8589934592 bytes)
Block size: 2.00 MiB (2097152 bytes)
```
### `list`
List all disk files found at a directory path and display their properties in a table. Disks are sorted so that each child appears directly after its parent. When a disk's parent is the row immediately above, the parent UID column shows `↑` for quick chain health assessment.
```
xo-disk-cli list <handler-url> <dir-path>
```
```
$ xo-disk-cli list file:///mnt/backups /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/
┌──────────────┬──────────────────────────────────────┬─────────────┬──────────────┬─────────────┬──────────────────────────────────────┐
│ File │ UID │ Size on disk│ Virtual size │ Differencing │ Parent UID │
├──────────────┼──────────────────────────────────────┼─────────────┼──────────────┼─────────────┼──────────────────────────────────────┤
│ base.vhd │ xxxxxxxx-... │ 1.20 GiB │ 8.00 GiB │ no │ (none) │
│ snapshot.vhd │ yyyyyyyy-... │ 128.00 MiB │ 8.00 GiB │ yes │ ↑ │
└──────────────┴──────────────────────────────────────┴─────────────┴──────────────┴─────────────┴──────────────────────────────────────┘
```
### `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.
```
xo-disk-cli transform <handler-url> <disk-path> <format>
```
Supported formats:
- `raw` — flat binary image; absent blocks are written as zeros
- `vhd` — VHD fixed/dynamic image
- `qcow2` — QCOW2 image
```
$ xo-disk-cli transform file:///mnt/backups /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/snapshot.vhd raw > disk.img
$ xo-disk-cli transform file:///mnt/backups /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/snapshot.vhd qcow2 > disk.qcow2
$ xo-disk-cli transform file:///mnt/backups /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/snapshot.vhd vhd > disk.vhd
```
## Handler URLs
The `<handler-url>` argument identifies the remote storage backend. Examples:
| Backend | URL format |
| ---------------- | ----------------------- |
| Local filesystem | `file:///absolute/path` |
| NFS | `nfs://host/export` |
| SMB | `smb://host/share` |
| S3 | `s3://bucket/prefix` |

View File

@@ -0,0 +1 @@
../../scripts/npmignore

View File

@@ -0,0 +1,112 @@
<!-- DO NOT EDIT MANUALLY, THIS FILE HAS BEEN GENERATED -->
# @xen-orchestra/disk-cli
[![Package Version](https://badgen.net/npm/v/@xen-orchestra/disk-cli)](https://npmjs.org/package/@xen-orchestra/disk-cli) ![License](https://badgen.net/npm/license/@xen-orchestra/disk-cli) [![PackagePhobia](https://badgen.net/bundlephobia/minzip/@xen-orchestra/disk-cli)](https://bundlephobia.com/result?p=@xen-orchestra/disk-cli) [![Node compatibility](https://badgen.net/npm/node/@xen-orchestra/disk-cli)](https://npmjs.org/package/@xen-orchestra/disk-cli)
> CLI tool to inspect and manage disks in backup repositories
## Install
Installation of the [npm package](https://npmjs.org/package/@xen-orchestra/disk-cli):
```sh
npm install --global @xen-orchestra/disk-cli
```
## Usage
```
$ xo-disk-cli --help
Usage: xo-disk-cli <command> <handler-url> <path> [options]
Commands:
info Show disk info (virtual size, uid, parent uid, block size)
list List all disks at a path and display their properties in a table
transform Convert a disk to another format and write to stdout (raw | vhd | qcow2)
```
## Commands
### `info`
Display metadata for a single disk file.
```
xo-disk-cli info <handler-url> <disk-path>
```
Output includes: UID, parent UID (for differencing disks), virtual size, and block size.
```
$ xo-disk-cli info file:///mnt/backups /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/snapshot.vhd
Disk info: /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/snapshot.vhd
UID: <uuid>
Parent UID: <parent-uuid>
Virtual size: 8.00 GiB (8589934592 bytes)
Block size: 2.00 MiB (2097152 bytes)
```
### `list`
List all disk files found at a directory path and display their properties in a table. Disks are sorted so that each child appears directly after its parent. When a disk's parent is the row immediately above, the parent UID column shows `↑` for quick chain health assessment.
```
xo-disk-cli list <handler-url> <dir-path>
```
```
$ xo-disk-cli list file:///mnt/backups /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/
┌──────────────┬──────────────────────────────────────┬─────────────┬──────────────┬─────────────┬──────────────────────────────────────┐
│ File │ UID │ Size on disk│ Virtual size │ Differencing │ Parent UID │
├──────────────┼──────────────────────────────────────┼─────────────┼──────────────┼─────────────┼──────────────────────────────────────┤
│ base.vhd │ xxxxxxxx-... │ 1.20 GiB │ 8.00 GiB │ no │ (none) │
│ snapshot.vhd │ yyyyyyyy-... │ 128.00 MiB │ 8.00 GiB │ yes │ ↑ │
└──────────────┴──────────────────────────────────────┴─────────────┴──────────────┴─────────────┴──────────────────────────────────────┘
```
### `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.
```
xo-disk-cli transform <handler-url> <disk-path> <format>
```
Supported formats:
- `raw` — flat binary image; absent blocks are written as zeros
- `vhd` — VHD fixed/dynamic image
- `qcow2` — QCOW2 image
```
$ xo-disk-cli transform file:///mnt/backups /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/snapshot.vhd raw > disk.img
$ xo-disk-cli transform file:///mnt/backups /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/snapshot.vhd qcow2 > disk.qcow2
$ xo-disk-cli transform file:///mnt/backups /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/snapshot.vhd vhd > disk.vhd
```
## Handler URLs
The `<handler-url>` argument identifies the remote storage backend. Examples:
| Backend | URL format |
| ---------------- | ----------------------- |
| Local filesystem | `file:///absolute/path` |
| NFS | `nfs://host/export` |
| SMB | `smb://host/share` |
| S3 | `s3://bucket/prefix` |
## Contributions
Contributions are _very_ welcomed, either on the documentation or on
the code.
You may:
- report any [issue](https://github.com/vatesfr/xen-orchestra/issues)
you've encountered;
- fork and create a pull request.
## License
[AGPL-3.0-or-later](https://spdx.org/licenses/AGPL-3.0-or-later) © [Vates SAS](https://vates.fr)

View File

@@ -0,0 +1,47 @@
{
"private": false,
"name": "@xen-orchestra/disk-cli",
"version": "2.0.0",
"description": "CLI tool to inspect and manage disks in backup repositories",
"type": "module",
"bin": {
"xo-disk-cli": "./dist/index.mjs"
},
"preferGlobal": true,
"engines": {
"node": ">=22.3"
},
"scripts": {
"build": "tsc",
"dev": "tsc --watch",
"clean": "rimraf dist/",
"test": "tsc && node --experimental-test-module-mocks --test './dist/**/*.test.mjs'",
"postversion": "npm publish --access public"
},
"dependencies": {
"@vates/async-each": "^1.0.3",
"@xen-orchestra/backups": "^0.72.0",
"@xen-orchestra/disk-transform": "^1.2.3",
"@xen-orchestra/fs": "^4.8.0",
"@xen-orchestra/qcow2": "^1.3.0",
"promise-toolbox": "^0.21.0",
"vhd-lib": "^4.16.0"
},
"devDependencies": {
"@types/node": "^22.3.0",
"rimraf": "^6.0.1",
"typescript": "~5.6"
},
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/@xen-orchestra/disk-cli",
"bugs": "https://github.com/vatesfr/xen-orchestra/issues",
"repository": {
"directory": "@xen-orchestra/disk-cli",
"type": "git",
"url": "https://github.com/vatesfr/xen-orchestra.git"
},
"license": "AGPL-3.0-or-later",
"author": {
"name": "Vates SAS",
"url": "https://vates.fr"
}
}

View File

@@ -0,0 +1,22 @@
import Disposable from 'promise-toolbox/Disposable'
import { getSyncedHandler } from '@xen-orchestra/fs'
import { openDisposableDisk } from '@xen-orchestra/backups/disks'
import { formatBytes } from '../utils.mjs'
export async function infoCommand(handlerUrl: string, diskPath: string, _extraArgs: string[]): Promise<void> {
await Disposable.use(getSyncedHandler({ url: handlerUrl }), async handler => {
await Disposable.use(openDisposableDisk({ handler, path: diskPath }), async disk => {
const isDifferencing = disk.isDifferencing()
const virtualSize = disk.getVirtualSize()
const blockSize = disk.getBlockSize()
const uid = disk.getUuid()
const parentUid = isDifferencing ? disk.getParentUuid() : null
console.log(`Disk info: ${diskPath}`)
console.log(` UID: ${uid}`)
console.log(` Parent UID: ${parentUid ?? '(none)'}`)
console.log(` Virtual size: ${formatBytes(virtualSize)} (${virtualSize} bytes)`)
console.log(` Block size: ${formatBytes(blockSize)} (${blockSize} bytes)`)
})
})
}

View File

@@ -0,0 +1,114 @@
import Disposable from 'promise-toolbox/Disposable'
import { getSyncedHandler } from '@xen-orchestra/fs'
import { isDisk, openDisposableDisk } from '@xen-orchestra/backups/disks'
import { formatBytes, renderTable } from '../utils.mjs'
import { asyncEach } from '@vates/async-each'
const HEADERS = ['File', 'UID', 'Size on disk', 'Virtual size', 'Differencing', 'Parent UID']
export type OkDiskInfo = {
ok: true
filename: string
uid: string
sizeOnDisk: string
virtualSize: string
differencing: boolean
parentUid: string | null
}
export type ErrDiskInfo = { ok: false; filename: string; error: string }
export type DiskInfo = OkDiskInfo | ErrDiskInfo
// Topological sort: each child appears directly after its parent.
// Disks whose parent is absent from the list are treated as roots.
// Errored disks are appended at the end.
export function sortDisks(disks: DiskInfo[]): DiskInfo[] {
const okDisks = disks.filter((d): d is OkDiskInfo => d.ok)
const errDisks = disks.filter((d): d is ErrDiskInfo => !d.ok)
const byUid = new Map(okDisks.map(d => [d.uid, d]))
const childOf = new Map(okDisks.filter(d => d.differencing && d.parentUid !== null).map(d => [d.parentUid!, d]))
const sorted: OkDiskInfo[] = []
const visited = new Set<string>()
// Roots: base disks or differencing disks whose parent is not in the list
const roots = okDisks.filter(d => !d.differencing || d.parentUid === null || !byUid.has(d.parentUid))
for (const root of roots) {
let current: OkDiskInfo | undefined = root
while (current !== undefined && !visited.has(current.uid)) {
sorted.push(current)
visited.add(current.uid)
current = childOf.get(current.uid)
}
}
// Append any orphaned differencing disks not reachable from a root
for (const disk of okDisks) {
if (!visited.has(disk.uid)) {
sorted.push(disk)
}
}
return [...sorted, ...errDisks]
}
export function toTableRow(disk: DiskInfo, prevDisk: DiskInfo | undefined): string[] {
if (!disk.ok) {
return [disk.filename, `(error: ${disk.error})`, '-', '-', '-', '-']
}
const parentIsAbove = disk.differencing && prevDisk?.ok && prevDisk.uid === disk.parentUid
return [
disk.filename,
disk.uid,
disk.sizeOnDisk,
disk.virtualSize,
disk.differencing ? 'yes' : 'no',
disk.differencing ? (parentIsAbove ? '↑' : (disk.parentUid ?? '')) : '(none)',
]
}
export async function listCommand(handlerUrl: string, dirPath: string, _extraArgs: string[]): Promise<void> {
await Disposable.use(getSyncedHandler({ url: handlerUrl }), async handler => {
const entries = await handler.list(dirPath, { prependDir: true })
const diskPaths = entries.filter(entry => isDisk(handler, entry))
if (diskPaths.length === 0) {
console.log(`No disks found at ${dirPath}`)
return
}
const disks: DiskInfo[] = []
await asyncEach(
diskPaths,
async (diskPath: string) => {
const filename = diskPath.slice(diskPath.lastIndexOf('/') + 1)
try {
const disk = await Disposable.use(openDisposableDisk({ handler, path: diskPath }), async disk => {
const differencing = disk.isDifferencing()
return {
ok: true as const,
filename,
uid: disk.getUuid(),
sizeOnDisk: formatBytes(disk.getSizeOnDisk()),
virtualSize: formatBytes(disk.getVirtualSize()),
differencing,
parentUid: differencing ? disk.getParentUuid() : null,
}
})
disks.push(disk)
} catch (err) {
disks.push({ ok: false as const, filename, error: err instanceof Error ? err.message : String(err) })
}
},
{ concurrency: 4 }
)
const sorted = sortDisks(disks)
const rows = sorted.map((disk, i) => toTableRow(disk, sorted[i - 1]))
console.log(renderTable(HEADERS, rows))
})
}

View File

@@ -0,0 +1,68 @@
import { pipeline } from 'node:stream/promises'
import { Readable } from 'node:stream'
import type { RandomAccessDisk } from '@xen-orchestra/disk-transform'
import Disposable from 'promise-toolbox/Disposable'
import { getSyncedHandler, type RemoteHandler } from '@xen-orchestra/fs'
import { openDisposableDisk, openDiskChain } from '@xen-orchestra/backups/disks'
import { toVhdStream } from 'vhd-lib/disk-consumer/index.mjs'
import { toQcow2Stream } from '@xen-orchestra/qcow2'
type OutputFormat = 'raw' | 'vhd' | 'qcow2'
const OUTPUT_FORMATS: OutputFormat[] = ['raw', 'vhd', 'qcow2']
export async function* rawGenerator(disk: RandomAccessDisk): AsyncGenerator<Buffer> {
const blockSize = disk.getBlockSize()
const virtualSize = disk.getVirtualSize()
// DiskChain has no getMaxBlockCount(); derive it from virtualSize
const maxBlockCount = Math.ceil(virtualSize / blockSize)
const lastBlockSize = virtualSize % blockSize || blockSize
for (let i = 0; i < maxBlockCount; i++) {
const size = i === maxBlockCount - 1 ? lastBlockSize : blockSize
if (disk.hasBlock(i)) {
const { data } = await disk.readBlock(i)
yield size < data.length ? data.subarray(0, size) : data
} else {
yield Buffer.alloc(size, 0)
}
}
}
// Returns a disposable for either a single disk or the full chain,
// depending on whether the leaf disk is differencing.
async function openDiskOrChain(handler: RemoteHandler, diskPath: string) {
const { value: leafDisk, dispose: disposeLeaf } = await openDisposableDisk({ handler, path: diskPath })
if (leafDisk.isDifferencing()) {
await disposeLeaf()
const chain = await openDiskChain({ handler, path: diskPath })
return { value: chain, dispose: () => chain.close() }
}
return { value: leafDisk, dispose: disposeLeaf }
}
export async function transformCommand(handlerUrl: string, diskPath: string, extraArgs: string[]): Promise<void> {
const format = extraArgs[0] as OutputFormat
if (!format || !OUTPUT_FORMATS.includes(format)) {
// this is a cli tool let's not use @xen-orchestra/log here
console.error(`Error: output format must be one of: ${OUTPUT_FORMATS.join(', ')}`)
process.exit(1)
}
await Disposable.use(getSyncedHandler({ url: handlerUrl }), async handler => {
await Disposable.use(openDiskOrChain(handler, diskPath), async disk => {
let stream: Readable
if (format === 'raw') {
stream = Readable.from(rawGenerator(disk), { objectMode: false })
} else if (format === 'vhd') {
stream = await toVhdStream(disk)
} else {
stream = toQcow2Stream(disk)
}
await pipeline(stream, process.stdout, { end: false })
})
})
}

View File

@@ -0,0 +1,74 @@
declare module 'promise-toolbox/Disposable' {
interface DisposableLike<T> {
value: T
dispose(): void | Promise<void>
}
const Disposable: {
use<T, R>(
disposable: DisposableLike<T> | PromiseLike<DisposableLike<T>>,
fn: (value: T) => R | Promise<R>
): Promise<R>
}
export default Disposable
}
declare module '@xen-orchestra/fs' {
export interface RemoteHandler {
list(dir: string, opts?: { prependDir?: boolean }): Promise<string[]>
[key: string]: unknown
}
export interface HandlerDisposable {
value: RemoteHandler
dispose: () => Promise<void>
}
export function getSyncedHandler(remote: { url: string }): Promise<HandlerDisposable>
}
declare module 'vhd-lib/disk-consumer/index.mjs' {
import type { Readable } from 'node:stream'
import type { RandomAccessDisk } from '@xen-orchestra/disk-transform'
export function toVhdStream(disk: RandomAccessDisk): Promise<Readable>
}
declare module '@xen-orchestra/backups/disks/openDiskChain.mjs' {
import type { RemoteHandler } from '@xen-orchestra/fs'
import type { RandomAccessDisk } from '@xen-orchestra/disk-transform'
export function openDiskChain(params: {
handler: RemoteHandler
path: string
until?: string
}): Promise<RandomAccessDisk>
}
declare module '@xen-orchestra/backups/disks' {
import type { RemoteHandler } from '@xen-orchestra/fs'
import type { RandomAccessDisk } from '@xen-orchestra/disk-transform'
export interface RemoteDisk extends RandomAccessDisk {
getSizeOnDisk(): number
getPath(): string
getUuid(): string
getParentUuid(): string
getMaxBlockCount(): number
}
export interface DiskDisposable {
value: RemoteDisk
dispose: () => Promise<void>
}
export function isDisk(handler: RemoteHandler, path: string): boolean
export function openDisposableDisk(params: { handler: RemoteHandler; path: string }): Promise<DiskDisposable>
export function openDiskChain(params: {
handler: RemoteHandler
path: string
until?: string
}): Promise<RandomAccessDisk>
}

View File

@@ -0,0 +1,63 @@
#!/usr/bin/env node
import { infoCommand } from './commands/info.mjs'
import { listCommand } from './commands/list.mjs'
import { transformCommand } from './commands/transform.mjs'
type CommandFn = (handlerUrl: string, path: string, extraArgs: string[]) => Promise<void>
const COMMANDS: Record<string, CommandFn> = {
info: infoCommand,
list: listCommand,
transform: transformCommand,
}
function showHelp(exitCode: number): never {
const commandDescriptions: Record<string, string> = {
info: 'Show disk info (virtual size, uid, parent uid, block size)',
list: 'List all disks at a path and display their properties in a table',
transform: 'Convert a disk to another format and write to stdout (raw | vhd | qcow2)',
}
const commandList = Object.keys(COMMANDS)
.map(name => ` ${name.padEnd(10)} ${commandDescriptions[name] ?? ''}`)
.join('\n')
process.stdout.write(`Usage: xo-disk-cli <command> <handler-url> <path> [options]
Commands:
${commandList}
Examples:
xo-disk-cli info file:///mnt/backups /xo-vm-backups/uuid/disk.alias.vhd
xo-disk-cli list file:///mnt/backups /xo-vm-backups/uuid/
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
if (!command || command === '--help' || command === '-h') {
showHelp(0)
}
if (!handlerUrl || !diskPath) {
console.error('Error: handler-url and disk-path are required\n')
showHelp(1)
}
const cmd = COMMANDS[command]
if (cmd === undefined) {
console.error(`Unknown command: ${command}`)
console.error(`Available commands: ${Object.keys(COMMANDS).join(', ')}\n`)
showHelp(1)
}
try {
await cmd(handlerUrl, diskPath, extraArgs)
} catch (error) {
console.error(error)
process.exit(1)
}

View File

@@ -0,0 +1,93 @@
/**
* Tests for the `info` command.
*
* Focus:
* - Handler and disk are always disposed, even when disk methods throw.
* - Errors from broken disks are propagated (not swallowed).
*
* Design: mock.module() is called once at the top level. The mock for openDisk
* reads `currentDisk` at call-time via closure, so individual tests can inject
* failure scenarios simply by reassigning the variable before calling the command.
*/
import { describe, test, mock, beforeEach } from 'node:test'
import assert from 'node:assert/strict'
import { openDisposableDisk } from '@xen-orchestra/backups/disks'
// ---------------------------------------------------------------------------
// Spies — created once and reused; reset in beforeEach.
// ---------------------------------------------------------------------------
const handlerDispose = mock.fn(() => Promise.resolve())
const diskDispose = mock.fn(() => Promise.resolve())
const baseDisk = {
isDifferencing: () => false,
getVirtualSize: () => 1024 * 1024 * 1024,
getBlockSize: () => 2 * 1024 * 1024,
getUuid: () => 'aaaa-bbbb',
getParentUuid: () => 'pppp-qqqq',
}
// Reassigned per-test to inject different disk behaviours.
let currentDisk: typeof baseDisk = { ...baseDisk }
// ---------------------------------------------------------------------------
// Module mocks — registered once. openDisk reads `currentDisk` at call-time
// so tests only need to reassign the variable, not re-mock the module.
// ---------------------------------------------------------------------------
mock.module('@xen-orchestra/fs', {
namedExports: {
getSyncedHandler: () => Promise.resolve({ value: {}, dispose: handlerDispose }),
},
})
mock.module('@xen-orchestra/backups/disks', {
namedExports: {
openDisposableDisk: () => Promise.resolve({ value: currentDisk, dispose: diskDispose }),
},
})
// Import the module under test AFTER mocks are registered so it receives the
// mocked implementations. The same infoCommand reference is reused for all tests.
const { infoCommand } = await import('../../commands/info.mjs')
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
describe('info command', () => {
beforeEach(() => {
handlerDispose.mock.resetCalls()
diskDispose.mock.resetCalls()
currentDisk = { ...baseDisk }
})
test('disposes handler and disk on success', async () => {
await infoCommand('file:///test', '/vdis/disk.vhd', [])
assert.strictEqual(handlerDispose.mock.callCount(), 1, 'handler must be disposed once')
assert.strictEqual(diskDispose.mock.callCount(), 1, 'disk must be disposed once')
})
test('disposes handler and disk when a disk method throws', async () => {
currentDisk = {
...baseDisk,
getUuid: () => {
throw new Error('corrupt header')
},
}
await assert.rejects(() => infoCommand('file:///test', '/vdis/disk.vhd', []))
assert.strictEqual(handlerDispose.mock.callCount(), 1, 'handler must be disposed even on error')
assert.strictEqual(diskDispose.mock.callCount(), 1, 'disk must be disposed even on error')
})
test('error from broken disk is not swallowed', async () => {
currentDisk = {
...baseDisk,
getVirtualSize: () => {
throw new Error('corrupt header')
},
}
await assert.rejects(() => infoCommand('file:///test', '/vdis/disk.vhd', []), /corrupt header/)
})
})

View File

@@ -0,0 +1,125 @@
/**
* Tests for the `list` command.
*
* Focus:
* - Handler is always disposed, even when handler.list() throws.
* - A broken disk produces an error row but does not abort the whole command.
* - Successfully opened disks are always disposed.
*
* Design: module mocks are registered once at the top level. Mutable variables
* (currentListImpl, brokenPaths) are reset in beforeEach and set per-test.
*/
import { describe, test, mock, beforeEach } from 'node:test'
import assert from 'node:assert/strict'
// ---------------------------------------------------------------------------
// Spies & mutable state
// ---------------------------------------------------------------------------
const handlerDispose = mock.fn(() => Promise.resolve())
const diskDispose = mock.fn(() => Promise.resolve())
const baseDisk = {
isDifferencing: () => false,
getSizeOnDisk: () => 1024 * 1024 * 1024,
getVirtualSize: () => 8 * 1024 * 1024 * 1024,
getUuid: () => 'disk-uuid',
getParentUuid: () => null as unknown as string,
}
// Reassigned per-test to control what handler.list() returns (or throws).
let currentListImpl: () => Promise<string[]> = async () => []
// Populated per-test to make specific paths fail to open.
const brokenPaths = new Set<string>()
// handler.list() delegates to currentListImpl so tests can change behaviour
// without re-mocking the module.
const mockHandler = {
list: async (_dir: string, _opts?: unknown) => currentListImpl(),
}
// ---------------------------------------------------------------------------
// Module mocks
// ---------------------------------------------------------------------------
mock.module('@xen-orchestra/fs', {
namedExports: {
getSyncedHandler: () => Promise.resolve({ value: mockHandler, dispose: handlerDispose }),
},
})
mock.module('@xen-orchestra/backups/disks', {
namedExports: {
isDisk: (_h: unknown, p: string) => p.endsWith('.vhd'),
openDisposableDisk: ({ path }: { path: string }) => {
if (brokenPaths.has(path)) throw new Error('disk header corrupted')
return Promise.resolve({ value: { ...baseDisk }, dispose: diskDispose })
},
},
})
const { listCommand } = await import('../../commands/list.mjs')
// ---------------------------------------------------------------------------
// Helper: capture console.log output without polluting test output.
// ---------------------------------------------------------------------------
async function captureLog(fn: () => Promise<void>): Promise<string> {
const lines: string[] = []
const orig = console.log
console.log = (...args: unknown[]) => lines.push(args.map(String).join(' '))
try {
await fn()
} finally {
console.log = orig
}
return lines.join('\n')
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
describe('list command', () => {
beforeEach(() => {
handlerDispose.mock.resetCalls()
diskDispose.mock.resetCalls()
brokenPaths.clear()
currentListImpl = async () => ['/dir/disk.vhd']
})
test('disposes handler on success', async () => {
await captureLog(() => listCommand('file:///test', '/dir', []))
assert.strictEqual(handlerDispose.mock.callCount(), 1, 'handler must be disposed once')
})
test('disposes handler when handler.list() throws', async () => {
currentListImpl = async () => {
throw new Error('network error')
}
await assert.rejects(() => listCommand('file:///test', '/dir', []))
assert.strictEqual(handlerDispose.mock.callCount(), 1, 'handler must be disposed even on list() error')
})
test('disposes each successfully opened disk', async () => {
currentListImpl = async () => ['/dir/a.vhd', '/dir/b.vhd']
await captureLog(() => listCommand('file:///test', '/dir', []))
assert.strictEqual(diskDispose.mock.callCount(), 2, 'every opened disk must be disposed')
})
test('broken disk produces an error row instead of aborting, dispose still ok', async () => {
currentListImpl = async () => ['/dir/good.vhd', '/dir/broken.vhd']
brokenPaths.add('/dir/broken.vhd')
const output = await captureLog(() => listCommand('file:///test', '/dir', []))
assert.ok(output.includes('error'), 'error row should appear in output')
assert.ok(output.includes('broken.vhd'), 'broken filename should appear in output')
assert.strictEqual(diskDispose.mock.callCount(), 1, 'good disk must still be disposed')
})
test('prints "No disks found" when directory contains no disk files', async () => {
currentListImpl = async () => []
const output = await captureLog(() => listCommand('file:///test', '/dir', []))
assert.ok(output.includes('No disks found'))
})
})

View File

@@ -0,0 +1,129 @@
/**
* Tests for the `transform` command.
*
* Focus:
* - Handler and disk are always disposed, even on pipeline error.
* - For a differencing disk, the leaf disk is disposed and the full chain
* is opened via openDiskChain; the chain is disposed at the end.
* - For a non-differencing disk, openDiskChain is never called.
* - Invalid format triggers a visible error (process.exit).
*
* Design: module mocks are registered once at the top level. `currentLeafDisk`
* is reassigned per-test; spies are reset in beforeEach.
* Tests use an empty disk (virtualSize=0, raw format) to avoid writing
* any data to stdout.
*/
import { describe, test, mock, beforeEach } from 'node:test'
import assert from 'node:assert/strict'
// ---------------------------------------------------------------------------
// Spies & mutable state
// ---------------------------------------------------------------------------
const handlerDispose = mock.fn(() => Promise.resolve())
const leafDispose = mock.fn(() => Promise.resolve())
const chainClose = mock.fn(() => Promise.resolve())
// Empty disk — rawGenerator produces 0 bytes, so pipeline completes instantly.
const emptyDisk = {
init: () => Promise.resolve(),
isDifferencing: () => false,
getBlockSize: () => 512,
getVirtualSize: () => 0,
hasBlock: () => false,
readBlock: async () => ({ data: Buffer.alloc(512) }),
close: () => Promise.resolve(),
}
// Reassigned per-test to control the leaf disk's behaviour.
let currentLeafDisk: typeof emptyDisk = { ...emptyDisk }
// Chain disk returned by openDiskChain — has a tracked close().
const chainDisk = { ...emptyDisk, close: chainClose }
// Declared after chainDisk so TypeScript infers the correct return type.
const openDiskChainSpy = mock.fn(async () => chainDisk)
// ---------------------------------------------------------------------------
// Module mocks
// ---------------------------------------------------------------------------
mock.module('@xen-orchestra/fs', {
namedExports: {
getSyncedHandler: () => Promise.resolve({ value: {}, dispose: handlerDispose }),
},
})
mock.module('@xen-orchestra/backups/disks', {
namedExports: {
// openDisk reads `currentLeafDisk` at call-time via closure.
openDisposableDisk: () => Promise.resolve({ value: currentLeafDisk, dispose: leafDispose }),
openDiskChain: openDiskChainSpy,
},
})
const { transformCommand } = await import('../../commands/transform.mjs')
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
describe('transform command', () => {
beforeEach(() => {
handlerDispose.mock.resetCalls()
leafDispose.mock.resetCalls()
chainClose.mock.resetCalls()
openDiskChainSpy.mock.resetCalls()
currentLeafDisk = { ...emptyDisk }
})
test('disposes handler and disk on success (raw format)', async () => {
await transformCommand('file:///test', '/vdis/disk.vhd', ['raw'])
assert.strictEqual(handlerDispose.mock.callCount(), 1, 'handler must be disposed once')
assert.strictEqual(leafDispose.mock.callCount(), 1, 'disk must be disposed once')
})
test('disposes handler and disk when pipeline throws', async () => {
// One present block whose readBlock throws → pipeline error.
currentLeafDisk = {
...emptyDisk,
getVirtualSize: () => 512,
hasBlock: () => true,
readBlock: async () => {
throw new Error('I/O error')
},
}
await assert.rejects(() => transformCommand('file:///test', '/vdis/disk.vhd', ['raw']))
assert.strictEqual(handlerDispose.mock.callCount(), 1, 'handler must be disposed even on pipeline error')
assert.strictEqual(leafDispose.mock.callCount(), 1, 'disk must be disposed even on pipeline error')
})
test('non-differencing disk: openDiskChain is never called', async () => {
await transformCommand('file:///test', '/vdis/disk.vhd', ['raw'])
assert.strictEqual(openDiskChainSpy.mock.callCount(), 0, 'openDiskChain must not be called for a base disk')
})
test('differencing disk: leaf disk is disposed and chain is opened', async () => {
currentLeafDisk = { ...emptyDisk, isDifferencing: () => true }
await transformCommand('file:///test', '/vdis/snapshot.vhd', ['raw'])
assert.strictEqual(leafDispose.mock.callCount(), 1, 'leaf disk must be disposed before chain is opened')
assert.strictEqual(openDiskChainSpy.mock.callCount(), 1, 'openDiskChain must be called for a differencing disk')
})
test('differencing disk: chain is closed after transform', async () => {
currentLeafDisk = { ...emptyDisk, isDifferencing: () => true }
await transformCommand('file:///test', '/vdis/snapshot.vhd', ['raw'])
assert.strictEqual(chainClose.mock.callCount(), 1, 'chain must be closed after transform')
})
test('invalid format triggers process.exit(1)', async () => {
const exitMock = mock.method(process, 'exit', (_code: number) => {
throw new Error(`EXIT:${_code}`)
})
try {
await assert.rejects(() => transformCommand('file:///test', '/vdis/disk.vhd', ['invalid']), /EXIT:1/)
} finally {
exitMock.mock.restore()
}
})
})

View File

@@ -0,0 +1,112 @@
import { describe, test } from 'node:test'
import assert from 'node:assert/strict'
import { rawGenerator } from '../commands/transform.mjs'
import type { RandomAccessDisk } from '@xen-orchestra/disk-transform'
// ---------------------------------------------------------------------------
// Helper: collect all chunks from rawGenerator into a single Buffer
// ---------------------------------------------------------------------------
async function collect(disk: RandomAccessDisk): Promise<Buffer> {
const chunks: Buffer[] = []
for await (const chunk of rawGenerator(disk)) {
chunks.push(chunk)
}
return Buffer.concat(chunks)
}
// ---------------------------------------------------------------------------
// Helper: build a minimal mock disk
// ---------------------------------------------------------------------------
function makeDisk(opts: {
blockSize: number
virtualSize: number
present?: Set<number>
fillByte?: number
}): RandomAccessDisk {
const { blockSize, virtualSize, present = new Set(), fillByte = 0xab } = opts
return {
getBlockSize: () => blockSize,
getVirtualSize: () => virtualSize,
hasBlock: (i: number) => present.has(i),
readBlock: async (i: number) => ({ data: Buffer.alloc(blockSize, fillByte + i) }),
} as unknown as RandomAccessDisk
}
// ---------------------------------------------------------------------------
// Tests
// ---------------------------------------------------------------------------
describe('rawGenerator', () => {
test('empty disk (virtualSize=0) yields nothing', async () => {
const disk = makeDisk({ blockSize: 512, virtualSize: 0 })
const out = await collect(disk)
assert.strictEqual(out.length, 0)
})
test('single present block yields its data', async () => {
const disk = makeDisk({ blockSize: 512, virtualSize: 512, present: new Set([0]), fillByte: 0x42 })
const out = await collect(disk)
assert.strictEqual(out.length, 512)
assert.ok(
out.every(b => b === 0x42),
'all bytes should be fill byte'
)
})
test('absent block yields zeros', async () => {
const disk = makeDisk({ blockSize: 512, virtualSize: 512 }) // present is empty
const out = await collect(disk)
assert.strictEqual(out.length, 512)
assert.ok(
out.every(b => b === 0),
'absent block should yield zeros'
)
})
test('mixed present/absent blocks', async () => {
// 3 blocks: block 0 present, block 1 absent, block 2 present
const disk = makeDisk({ blockSize: 512, virtualSize: 3 * 512, present: new Set([0, 2]), fillByte: 0x01 })
const out = await collect(disk)
assert.strictEqual(out.length, 3 * 512)
// block 0: fill byte 0x01
assert.ok(out.subarray(0, 512).every(b => b === 0x01))
// block 1: zeros (absent)
assert.ok(out.subarray(512, 1024).every(b => b === 0))
// block 2: fill byte 0x03 (0x01 + blockIndex 2)
assert.ok(out.subarray(1024).every(b => b === 0x03))
})
test('last block is trimmed when virtualSize is not a multiple of blockSize', async () => {
// virtualSize=768, blockSize=512 → last block should be 256 bytes
const disk = makeDisk({ blockSize: 512, virtualSize: 768, present: new Set([0, 1]), fillByte: 0x10 })
const out = await collect(disk)
assert.strictEqual(out.length, 768)
// First block: 512 bytes of 0x10
assert.ok(out.subarray(0, 512).every(b => b === 0x10))
// Second (last) block: only 256 bytes (trimmed), value 0x11
assert.ok(out.subarray(512).every(b => b === 0x11))
})
test('last block is NOT trimmed when virtualSize is an exact multiple of blockSize', async () => {
const disk = makeDisk({ blockSize: 512, virtualSize: 1024, present: new Set([0, 1]) })
const out = await collect(disk)
assert.strictEqual(out.length, 1024)
})
test('total output length equals virtualSize for all-present disk', async () => {
const virtualSize = 3 * 512 + 200 // not an exact multiple
const present = new Set([0, 1, 2])
const disk = makeDisk({ blockSize: 512, virtualSize, present })
const out = await collect(disk)
assert.strictEqual(out.length, virtualSize)
})
test('total output length equals virtualSize for all-absent disk', async () => {
const virtualSize = 2 * 512 + 100
const disk = makeDisk({ blockSize: 512, virtualSize }) // no blocks present
const out = await collect(disk)
assert.strictEqual(out.length, virtualSize)
})
})

View File

@@ -0,0 +1,161 @@
import { describe, test } from 'node:test'
import assert from 'node:assert/strict'
import { sortDisks, toTableRow, type DiskInfo } from '../commands/list.mjs'
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
function ok(uid: string, parentUid: string | null = null): DiskInfo & { ok: true } {
return {
ok: true,
filename: `${uid}.vhd`,
uid,
sizeOnDisk: '1.00 GiB',
virtualSize: '8.00 GiB',
differencing: parentUid !== null,
parentUid,
}
}
function err(filename: string): DiskInfo & { ok: false } {
return { ok: false, filename, error: 'disk header corrupted' }
}
function uids(disks: DiskInfo[]): (string | false)[] {
return disks.map(d => d.ok && d.uid)
}
// ---------------------------------------------------------------------------
// sortDisks
// ---------------------------------------------------------------------------
describe('sortDisks', () => {
test('empty list', () => {
assert.deepStrictEqual(sortDisks([]), [])
})
test('single base disk', () => {
assert.deepStrictEqual(uids(sortDisks([ok('a')])), ['a'])
})
test('base + child already in order', () => {
assert.deepStrictEqual(uids(sortDisks([ok('a'), ok('b', 'a')])), ['a', 'b'])
})
test('child before parent in input gets reordered', () => {
assert.deepStrictEqual(uids(sortDisks([ok('b', 'a'), ok('a')])), ['a', 'b'])
})
test('three-disk chain regardless of input order', () => {
assert.deepStrictEqual(uids(sortDisks([ok('c', 'b'), ok('a'), ok('b', 'a')])), ['a', 'b', 'c'])
})
test('child with missing parent is treated as a root', () => {
assert.deepStrictEqual(uids(sortDisks([ok('b', 'missing')])), ['b'])
})
test('multiple independent chains', () => {
const result = uids(sortDisks([ok('b', 'a'), ok('d', 'c'), ok('a'), ok('c')]))
// Each chain must be contiguous: a before b, c before d
const ai = result.indexOf('a')
const bi = result.indexOf('b')
const ci = result.indexOf('c')
const di = result.indexOf('d')
assert.ok(ai < bi, 'a must come before b')
assert.ok(ci < di, 'c must come before d')
assert.ok(bi === ai + 1, 'b must follow immediately after a')
assert.ok(di === ci + 1, 'd must follow immediately after c')
})
test('error disks are appended at the end', () => {
const result = sortDisks([err('bad.vhd'), ok('a'), err('bad2.vhd')])
const okCount = result.filter(d => d.ok).length
const errCount = result.filter(d => !d.ok).length
assert.strictEqual(okCount, 1)
assert.strictEqual(errCount, 2)
// All ok disks come before error disks
const firstErr = result.findIndex(d => !d.ok)
assert.ok(result.slice(0, firstErr).every(d => d.ok))
})
test('parent with multiple children: all children follow the parent directly', () => {
const sorted = sortDisks([ok('c2', 'a'), ok('a'), ok('c1', 'a')])
const parentIdx = sorted.findIndex(d => d.ok && d.uid === 'a')
const c1Idx = sorted.findIndex(d => d.ok && d.uid === 'c1')
const c2Idx = sorted.findIndex(d => d.ok && d.uid === 'c2')
assert.notStrictEqual(parentIdx, -1)
assert.notStrictEqual(c1Idx, -1)
assert.notStrictEqual(c2Idx, -1)
// Both children must occupy the two slots right after the parent
const childIndices = [c1Idx, c2Idx].sort()
assert.deepStrictEqual(
childIndices,
[parentIdx + 1, parentIdx + 2],
'both children must follow the parent directly'
)
})
})
// ---------------------------------------------------------------------------
// toTableRow
// ---------------------------------------------------------------------------
describe('toTableRow', () => {
test('base disk shows "(none)" in parent uid column', () => {
const row = toTableRow(ok('a'), undefined)
assert.strictEqual(row[5], '(none)')
})
test('differencing disk with no previous disk shows parentUid', () => {
const row = toTableRow(ok('b', 'a'), undefined)
assert.strictEqual(row[5], 'a')
})
test('differencing disk whose parent is not the previous row shows parentUid', () => {
const row = toTableRow(ok('b', 'a'), ok('x'))
assert.strictEqual(row[5], 'a')
})
test('differencing disk whose parent is immediately above shows ↑', () => {
const row = toTableRow(ok('b', 'a'), ok('a'))
assert.strictEqual(row[5], '↑')
})
test('error disk shows error message in second column', () => {
const row = toTableRow(err('bad.vhd'), undefined)
assert.ok(row[1].includes('error'))
assert.ok(row[1].includes('disk header corrupted'))
})
test('differencing column shows "yes" for differencing disk', () => {
assert.strictEqual(toTableRow(ok('b', 'a'), undefined)[4], 'yes')
})
test('differencing column shows "no" for base disk', () => {
assert.strictEqual(toTableRow(ok('a'), undefined)[4], 'no')
})
test('parent with multiple children: at least one child shows parent UID instead of ↑', () => {
const sorted = sortDisks([ok('c2', 'a'), ok('a'), ok('c1', 'a')])
const rows = sorted.map((disk, i) => toTableRow(disk, sorted[i - 1]))
// Find rows for the two children
const childRows = rows.filter((_row, i) => {
const d = sorted[i]
return d.ok && (d.uid === 'c1' || d.uid === 'c2')
})
assert.strictEqual(childRows.length, 2, 'both child rows must be present')
const arrowCount = childRows.filter(r => r[5] === '↑').length
const uidCount = childRows.filter(r => r[5] === 'a').length
assert.ok(arrowCount >= 1, 'at least one child should show ↑ (the one directly after parent)')
assert.ok(uidCount >= 1, 'at least one child must show the parent UID instead of ↑')
})
})

View File

@@ -0,0 +1,39 @@
import { describe, test } from 'node:test'
import assert from 'node:assert/strict'
import { formatBytes, renderTable } from '../utils.mjs'
describe('formatBytes', () => {
test('0 bytes', () => assert.strictEqual(formatBytes(0), '0 B'))
test('bytes', () => assert.strictEqual(formatBytes(512), '512.00 B'))
test('KiB', () => assert.strictEqual(formatBytes(1024), '1.00 KiB'))
test('MiB', () => assert.strictEqual(formatBytes(2 * 1024 * 1024), '2.00 MiB'))
test('GiB', () => assert.strictEqual(formatBytes(1024 ** 3), '1.00 GiB'))
test('TiB', () => assert.strictEqual(formatBytes(1024 ** 4), '1.00 TiB'))
test('fractional MiB', () => assert.strictEqual(formatBytes(1.5 * 1024 * 1024), '1.50 MiB'))
})
describe('renderTable', () => {
test('contains headers', () => {
const out = renderTable(['Name', 'Size'], [['foo', '1 GiB']])
assert.ok(out.includes('Name'))
assert.ok(out.includes('Size'))
})
test('contains all row values', () => {
const out = renderTable(['H'], [['alpha'], ['beta']])
assert.ok(out.includes('alpha'))
assert.ok(out.includes('beta'))
})
test('starts with top border and ends with bottom border', () => {
const out = renderTable(['H'], [['v']])
assert.ok(out.startsWith('┌'))
assert.ok(out.endsWith('┘'))
})
test('columns are wide enough for the longest value', () => {
const long = 'a very long value'
const out = renderTable(['H'], [[long]])
assert.ok(out.includes(long))
})
})

View File

@@ -0,0 +1,19 @@
export function formatBytes(bytes: number): string {
if (bytes === 0) return '0 B'
const units = ['B', 'KiB', 'MiB', 'GiB', 'TiB']
const i = Math.min(Math.floor(Math.log2(bytes) / 10), units.length - 1)
return `${(bytes / Math.pow(1024, i)).toFixed(2)} ${units[i]}`
}
export function renderTable(headers: string[], rows: string[][]): string {
const colWidths = headers.map((h, i) => Math.max(h.length, ...rows.map(r => (r[i] ?? '').length)))
const border = (left: string, mid: string, right: string) =>
left + colWidths.map(w => '─'.repeat(w + 2)).join(mid) + right
const row = (cells: string[]) => '│ ' + cells.map((c, i) => c.padEnd(colWidths[i])).join(' │ ') + ' │'
return [border('┌', '┬', '┐'), row(headers), border('├', '┼', '┤'), ...rows.map(row), border('└', '┴', '┘')].join(
'\n'
)
}

View File

@@ -0,0 +1,15 @@
{
"compilerOptions": {
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"module": "ESNext",
"moduleResolution": "bundler",
"target": "es2022",
"skipLibCheck": true,
"types": ["node"],
"declaration": true
},
"include": ["./src/**/*"],
"exclude": ["./node_modules", "./dist"]
}

View File

@@ -1,6 +1,6 @@
{
"name": "@xen-orchestra/disk-transform",
"version": "1.2.1",
"version": "1.2.3",
"main": "./dist/index.mjs",
"license": "MIT",
"private": false,
@@ -34,7 +34,6 @@
"node": ">=20.17"
},
"dependencies": {
"vhd-lib": "^4.14.7",
"@vates/generator-toolbox": "^1.1.0"
"@vates/generator-toolbox": "^1.1.2"
}
}

View File

@@ -48,17 +48,10 @@ export abstract class Disk {
abstract buildDiskBlockGenerator(): Promise<AsyncGenerator<DiskBlock>> | AsyncGenerator<DiskBlock>
async *diskBlocks(uid?: string): AsyncGenerator<DiskBlock> {
try {
// compute next block while the destination is consuming the current block
const blockGenerator = await this.buildDiskBlockGenerator()
let next = blockGenerator.next()
while (true) {
const res = await next
next = blockGenerator.next()
if (res.done) {
break
}
for await (const block of blockGenerator) {
this.#generatedDiskBlocks++
yield res.value
yield block
}
} finally {
await this.close()

View File

@@ -28,7 +28,7 @@ test('Disk class', async t => {
disk.blocks[key] = true
}
const foundKeys = []
const generator = disk.diskBlocks()
const generator = disk.diskBlocks()
for await (const block of generator) {
foundKeys.push(block.index)
assert.strictEqual(block.data.length, blockSize)
@@ -39,4 +39,24 @@ test('Disk class', async t => {
foundKeys.sort()
assert.deepStrictEqual(keys, foundKeys)
})
await t.test('diskBlocks calls progressHandler.done when consumer exits early', async () => {
let doneCalled = false
disk.progressHandler = {
setProgress: async () => {},
done: async () => {
doneCalled = true
},
}
disk.blocks[4] = true
disk.blocks[5] = true
disk.blocks[6] = true
// break after the first block — the inner generator's finally must still run
for await (const _ of disk.diskBlocks()) {
break
}
assert.strictEqual(doneCalled, true)
})
})

View File

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

View File

@@ -24,12 +24,14 @@ export class ReadAhead extends RandomDiskPassthrough {
const PRELOAD_SIZE = Math.max(Math.min(Math.floor((blockIndexes.length * maxPercent) / 100), maxNumber), 1)
let counter = 0
try{
try {
for (const index of blockIndexes) {
counter++
await self.progressHandler?.setProgress(counter/ blockIndexes.length)
await self.progressHandler?.setProgress(counter / blockIndexes.length)
if (preloaded.length < PRELOAD_SIZE) {
preloaded.push(self.source.readBlock(index))
const p = self.source.readBlock(index)
p.catch(() => {}) // suppress unhandled rejection; error still surfaces when awaited via shift()
preloaded.push(p)
}
if (preloaded.length === PRELOAD_SIZE) {
const next = (await preloaded.shift())!
@@ -40,10 +42,11 @@ export class ReadAhead extends RandomDiskPassthrough {
const next = (await preloaded.shift())!
yield next
}
}finally{
} finally {
await Promise.allSettled(preloaded) // wait for in-flight I/O & release resources
preloaded.length = 0
await self.progressHandler?.done()
}
}
return generator()
}

View File

@@ -1,7 +1,5 @@
// @ts-expect-error async-each is not typed
import { asyncEach } from '@vates/async-each'
import { Disk, DiskBlock } from '../Disk.mjs'
import { DebugDisk } from './DebugDisk.mjs'
/**
*
@@ -15,7 +13,7 @@ export async function consume(disk: Disk, { blockDelay = 20, concurrency = 8 } =
await asyncEach(
disk.diskBlocks(),
async (block: DiskBlock) => {
async block => {
consumed += block.data.length
nbBlocks++
await new Promise(resolve => setTimeout(resolve, blockDelay))

View File

@@ -1,7 +1,7 @@
{
"private": false,
"name": "@xen-orchestra/fs",
"version": "4.6.6",
"version": "4.8.0",
"license": "AGPL-3.0-or-later",
"description": "The File System for Xen Orchestra backups.",
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/@xen-orchestra/fs",
@@ -26,23 +26,23 @@
"@aws-sdk/middleware-apply-body-checksum": "^3.58.0",
"@aws-sdk/node-http-handler": "^3.54.0",
"@azure/storage-blob": "^12.26.0",
"@vates/async-each": "^1.0.1",
"@vates/async-each": "^1.0.3",
"@vates/coalesce-calls": "^0.1.0",
"@vates/decorate-with": "^2.1.0",
"@vates/read-chunk": "^1.2.1",
"@xen-orchestra/log": "^0.7.1",
"@xen-orchestra/log": "^0.7.2",
"bind-property-descriptor": "^2.0.0",
"decorator-synchronized": "^0.6.0",
"execa": "^5.0.0",
"fs-extra": "^11.1.0",
"get-stream": "^6.0.0",
"limit-concurrency-decorator": "^0.6.0",
"lodash": "^4.17.4",
"lodash": "^4.18.0",
"promise-toolbox": "^0.21.0",
"proper-lockfile": "^4.1.2",
"readable-stream": "^4.1.0",
"through2": "^4.0.2",
"xo-remote-parser": "^0.10.0"
"xo-remote-parser": "^0.10.1"
},
"devDependencies": {
"@babel/cli": "^7.0.0",

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