Compare commits

..

62 Commits

Author SHA1 Message Date
Thomas Moraine
bdacfd46b0 docs(auth-oidc): warn about lockout when relying on Keycloak for passkeys
Raised on the forum (https://xcp-ng.org/forum/topic/12577): the passkeys
section explains the Keycloak setup but not how to get back in when the
identity provider is down.

- Keep a built-in admin account with a password as a fallback: enabling
  auth-oidc doesn't disable password login on the sign-in page
- Don't host Keycloak only on the pool XOA manages, since a Rolling Pool
  Update or a host reboot can stop its VM
2026-12-02 10:37:31 +01:00
Marie Garde
c0e7843274 feat(xo6): fix style backup job form (#10940)
* wip

* fix style on form

* fix checkbox and radio button in DS

* fix pipeline

* fix tests

* remove version DS

* edit style

* fix tests

* fix build

* fix changelog
2026-12-02 10:23:22 +01:00
Marie Garde
c893471c5e fix(xo6): Fix header menu pool (#10897)
* fix(xo6): Fix header menu pool

* rebase ok

* fix changelog
2026-12-02 09:31:17 +01:00
Sebastien Marie
6f91a90299 fix(xo-server-sdn-controller): set up the SDN controller on network rules too (#10917) 2026-12-01 18:14:57 +01:00
Florent BEAUCHAMP
41b290f166 fix(backups): correctly cleanup snapshot of diskless VM with a CDROM (#10789)
* fix(backups): correctly cleanup snapshot of diskless VM with a CDROM
* fix: correctly cleanup the snapshots even when switching from vm based to vdi based retention
2026-12-01 16:14:07 +01:00
Alina D
2475403b11 feat(lite): add possibility to delete a VIF (#10726) 2026-12-01 13:21:55 +01:00
MikitaKavaliouVates
0ae5d39aa5 feat(@vates/task, xapi, backups, xo-server, backup-reports): abort backup jobs running in the main thread (#10875)
BREAKING CHANGE: a subtask created under an aborted task no longer runs, unless it is created with
`cleanup: true`.

🔗 XO-3352

With backups.disableWorkers, a backup job could not be stopped. It can now be aborted from its task, the "run schedule" action or job.cancel: the transfers stop, the cleanup still runs and the run ends interrupted.

@vates/task: the new root option skipSubtasksAfterAbort skips the steps of an aborted task, except cleanup: true ones. Only backups use it.
Fixes the VM directory lock not being released after a failed transfer.
2026-12-01 11:52:21 +01:00
Sylvère
77b00ff871 feat(lite): 0.28.0 (#10951) 2026-12-01 08:22:41 +01:00
Sylvère
ed86fbec17 feat: release 6.11 (#10949) 2026-11-30 17:01:05 +01:00
Sylvère
1e6a049072 feat: technical release (#10946) 2026-11-30 14:26:35 +01:00
Mathieu
032159a609 feat(rest-api): CSRF middleware protection (#10945)
* feat: add CSRF protection middleware

* feat: scope urlencode middleware to signin routes

* feat: cookie sameSite default to lax

* changelog

---------

Co-authored-by: MathieuRA <contact@mathieu-raisin.fr>
2026-11-30 13:50:38 +01:00
Mathieu
a5295c6731 fix(auth-ldap): block LDAP unauthenticated bind via null password in session.signIn (#10944)
A JSON `null` password sent to `session.signIn` reached the LDAP provider,
which passed it to `client.bind()`. ldapts turns this into an LDAP
unauthenticated bind (DN + empty password), which some directories, such as
Active Directory by default, accept as a successful login. Anyone knowing a
username could sign in without its password.

- xo-server-auth-ldap: only bind with non-empty string username and password
- xo-server: reject empty or non-string passwords in `authenticateUser`,
  before any provider is called
- xo-server: add a `params` schema to `session.signIn` so non-string
  credentials are rejected at the API layer

Co-authored-by: Pierre Donias <pierre.donias@vates.tech>
2026-11-30 13:42:17 +01:00
Alex Castillo González
c8260fb259 fix(rest-api): keep colons in the password of Basic authentication (#10801) 2026-11-30 12:07:47 +01:00
Sylvère
756d7fa940 fix(xo6): my tasks optimization (#10935) 2026-11-30 11:11:04 +01:00
Thierry Goettelmann
8f925cb605 chore(xo6,web-core): upgrade vitest to v5 (#10941)
With Node 26, most unit test suites of `@xen-orchestra/web` fail at
import: Node's native `localStorage` is enabled by default, is
`undefined` without `--localstorage-file`, and shadows the one provided
by the test environment. Vitest 5 handles it.

See XO-3517
2026-11-30 09:43:30 +01:00
Florent BEAUCHAMP
54051163e0 feat(vdi): implement resize online (#10845)
* refactor(xapi): extract VDI.resize method
* refactor(xapi): centralize size check
* feat(xapi): implement resize online
2026-11-27 15:05:51 +01:00
vates-bot
9ff4716ef1 feat(web-stack/i18n): update Xen Orchestra 6 (#10680) 2026-11-27 14:18:00 +01:00
Sylvère
810e342df2 feat: technical release (#10926)
* feat(xo-collection): 1.0.1

* feat(@vates/nbd-client): 3.7.2

* feat(@vates/types): 3.1.0

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

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

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

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

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

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

* feat(xo-server): 5.214.1

* chore(CHANGELOG): update next
2026-11-27 11:10:16 +01:00
Florent BEAUCHAMP
20e90b6d0f fix(xo-web): sanitize-html dependency (#10899)
Since 2.17.6, sanitize-html depends on htmlparser2 ^12, which is
ESM-only. Browserify cannot bundle it and the build fails with:

    'import' and 'export' may appear only with 'sourceType: module'

The dev setup is not affected because yarn.lock resolves 2.17.4, but
xoa-packager installs each package with `npm install` and no lockfile,
so `^2.17.4` resolves to the latest release as soon as xo-web's
node_modules is recreated.

Pin the exact version until xo-web's bundler can handle ESM-only
dependencies.
2026-11-27 10:00:36 +01:00
Joris K
c23587cbdc fix(xo6/site): stop displaying the site pages below the pools loader (#10923) 2026-11-27 09:46:51 +01:00
Mathieu
f67f94a60b feat(vmware-explorer): fall back to RSA key exchange on ESXi 6.5 data port (#10802)
feat(vmware-explorer): fall back to RSA key exchange on ESXi 6.5 data port (#10802)
2026-11-26 17:09:13 +01:00
Joris K
07722cd4f3 feat(web-core): update UiTag to v7 and rename UiTertiaryTag to UiLabelValueTag (#10920) 2026-11-26 15:29:29 +01:00
Marie Garde
b6d1387425 fix(xo6): remove target proxy for backup job mirror create form (#10914)
* fix(xo6): remove target proxy for backup job mirror create form

* fix changelog
2026-11-26 14:01:24 +01:00
Joris K
8f8c8ca405 feat(web-core): add UiRichCheckbox component (#10909) 2026-11-26 12:43:20 +01:00
Joris K
424f970cf9 feat(web-core): add UiRichRadioButton component (#10907)
* feat(web-core): add UiRichRadioButton component

- Rename the image-based `UiRichRadioButton` to `UiImageRadioButton`, as
  the design system renamed "Rich radio button" into "Image radio button"
- Add `UiRichRadioButton` (Rich radio button + Label v1): card radio with
  optional icon, tag, description and info, in brand/warning/danger
  accents
- Add `UiRichRadioButtonGroup` (Rich radio button group v1): label,
  vertical or horizontal layout, info and accent message, exposed as a
  radiogroup
- Update `UiRadioButton` to Radio button v7 (radio drawn with the
  `status:radio-button` icon, `txt` accent colors, white checked dot) and
  grey out its label when disabled (Radio button + Label v4)
- Use the same v7 radio in `UiImageRadioButton` and `UiRichRadioButton`,
  and apply the active border of the image radio button card

* feat(web-core): add UiRichRadioButton component changelog entry
2026-11-26 12:13:57 +01:00
Joris K
dfc298e40b feat(web-core): add UiGroupSubcategory component (#10906)
Design system component (Group subcategory v1) that splits a group of
choices into titled subcategories, with an optional text on the right.
2026-11-26 12:03:57 +01:00
Florent BEAUCHAMP
750c74beb1 chore(types): add types for xoa updates (#10843)
* chore(types): add types for xoa updates
2026-11-25 19:03:40 +01:00
Joris K
050c47079a fix(lite): display the default 4 MiB video RAM of HVM VMs (#10901) 2026-11-25 18:12:59 +01:00
Joris K
dca9d63799 fix(xo6/pif): prevent setting the management PIF on a network whose MTU is not 1500 (#10905) 2026-11-25 18:02:28 +01:00
Joris K
c42b46b833 fix(xo6/vdi): show the used space of the whole snapshot chain (#10902) 2026-11-25 17:58:25 +01:00
Joris K
77c24dacd7 fix(lite): apply each template disk's settings to its own disk (#10898) 2026-11-25 17:42:57 +01:00
Alina D
9bee5dc5b1 fix(lite/vdi): show the used space of the whole snapshot chain (#10116) 2026-11-25 17:39:26 +01:00
MlssFrncJrg
2313809c11 feat(rest-api): expose proxy updater state endpoint (#10773)
* feat(rest-api): expose proxy updater state endpoint
2026-11-25 14:54:08 +01:00
GeraldineFromVates
21d458cdd1 Feat/qa test/readable report mail (#10867)
* feat(qa-test): show status, Paris time and commit in report subject

* feat(qa-test): show test counts in report subject

* feat(qa-test): show test summary at the top of report body

* feat(qa-test): show run duration in report summary
2026-11-25 14:14:18 +01:00
OlivierFL
fa675eead1 chore(web-core): remove unused --color-logo variable (#10895) 2026-11-25 12:07:49 +01:00
OlivierFL
31c3f5bb20 feat(web-core): add data colors for charts (#10894) 2026-11-25 11:59:03 +01:00
OlivierFL
7e850aedaf fix(web-core): mix dark status backgrounds from their item color (#10888)
* fix(web-core): mix dark status backgrounds from their item color

In dark mode, the selected, hover and active backgrounds of success, warning and danger
mixed black with the text color, unlike brand and info which use the item color.
Only danger was affected (its text and item colors differ): its backgrounds were too
light and the tertiary danger button text failed WCAG 1.4.3 on hover (4.38:1).

* docs(changelog): add the PR number of the dark status backgrounds fix

* fix(web-core): mix dark danger backgrounds from the danger background base

The design system mixes the dark danger selected, hover and active backgrounds
from #e73642, like the light ones: #451014 / #5c161a / #741b21. The tertiary
danger button text still passes WCAG 1.4.3 (4.77:1 on hover, 5.12:1 when active).

* fix(web-core): declare the dark danger background base
2026-11-25 11:49:34 +01:00
OlivierFL
069cb2816a fix(web-core): align light danger background tints with the design system (#10891)
* fix(web-core): align light danger background tints with the design system

* docs(changelog): add the PR number of the light danger backgrounds fix
2026-11-25 11:38:08 +01:00
Alex Castillo González
7c63be3aaf fix(xo-collection): emit remove on the previous type when an indexed item changes type (#10884)
Fixes #10717
2026-11-25 11:11:23 +01:00
ayoub-el-kajji-v
9c68705932 fix(backups/merge): adding delay in background merge when ELOCKED (#10866)
* fix(backups/merge): adding delay in background merge when ELOCKED

* add changelog

* changing logs display and unblocking non-locked tasks

* reducing changes to not make code complicated
2026-11-25 10:40:40 +01:00
Mathieu
14ed5fd5b9 fix(nbd-client): report the stderr of a stdio server dying before the handshake (#10842)
* fix(nbd-client): report the stderr of a stdio server dying before the handshake

When vectura exits before the NBD greeting (unreachable host, disk the
host refuses...), the V2V import failed with only:

    stream has ended without data, was looking for 8 bytes

The end of its stdout makes the handshake read fail first, then
`_destroyTransport` marks the exit as expected and the exit handler
reports nothing. When the exit comes first, stderr may not be read yet.

`connect()` now waits for the `close` event of the server, which comes
after its standard streams end, and throws `NBD_SERVER_EXITED` with its
stderr as the message and the handshake error as `cause`. `reconnect()`
goes through `connect()`, so the retries of `readBlock()` get it too.

Introduced by #10381

* fix(nbd-client): attach stderr to the pre-handshake NBD_SERVER_EXITED error

Same shape as the error built by the exit handler.
2026-11-25 10:13:27 +01:00
OlivierFL
f7e476cd81 docs(v2v): document the XO 6 migration wizard (#10833)
* docs(v2v): document the XO 6 migration wizard

* docs(v2v): add the XO 6 prerequisite check screenshot

* docs(v2v): add a screenshot of each XO 6 migration wizard step

* docs(v2v): flag the guide as new and the XO 5 section as legacy
2026-11-25 09:52:27 +01:00
spacotte-vates
2a4491aeda fix(backup-jobs): fix issues on backup job creation from the REST API (#10779)
* fix(rest-api): backup-job schedule settings lost on creation
* fix(backup-jobs): fix mirror and metadata job failing due to targeting backup repo with expression
* feat(backup-jobs): add expression support for vms and pools
* fix(rest-api): add filter support to backup-jobs
2026-11-25 09:44:12 +01:00
Sylvère
e9760747f9 feat: technical release (#10896)
* feat(@xen-orchestra/log): 1.0.0

* feat(@vates/disposable): 0.1.7

* feat(@xen-orchestra/fs): 4.11.0

* feat(vhd-lib): 4.17.1

* feat(@vates/fuse-vhd): 2.1.4

* feat(@vates/iscsi): 0.4.1

* feat(@vates/obfuscate): 0.2.0

* feat(xo-collection): 1.0.0

* feat(xen-api): 6.0.0

* feat(@vates/nbd-client): 3.7.1

* feat(@vates/node-vsphere-soap): 2.2.1

* feat(@vates/syslog): 0.2.0

* feat(@vates/types): 3.0.0

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

* feat(@xen-orchestra/audit-core): 0.4.1

* feat(@xen-orchestra/autopilot-docking): 0.1.0

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

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

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

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

* feat(@xen-orchestra/cr-seed-cli): 1.0.4

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

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

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

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

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

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

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

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

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

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

* feat(xapi-explore-sr): 0.4.9

* feat(xo-server): 5.214.0

* feat(xo-server-audit): 0.16.0

* feat(xo-server-auth-ldap): 0.10.13

* feat(xo-server-backup-reports): 1.7.2

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

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

* feat(xo-server-netbox): 1.14.1

* feat(xo-server-openmetrics): 1.9.4

* feat(xo-server-perf-alert): 1.1.3

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

* feat(xo-server-transport-nagios): 1.0.4

* feat(xo-server-usage-report): 0.11.2

* feat(xo-server-web-hooks): 0.4.1

* feat(xo-web): 5.209.0

* chore(CHANGELOG): update next
2026-11-24 16:47:56 +01:00
Marie Garde
eae4e889b6 fix(xo6): fix mock backup job (#10893) 2026-11-24 15:26:59 +01:00
Marie Garde
fdbfa97002 Xo6/backup job create form (#10758)
* wip

* wip

* wip

* wip

* wip

* wip

* wip

* wip

* form andjob ok

* refacto for pr

* refacto

* fix errorMessage

* split use backup job target

* refacto

* refacto

* add tests utils

* add tests form

* add tests components

* add test composable

* fix build

* fix CI

* rebase ok

* rebase ok

* refacto with backend

* remove lite from changelog

* remove claude

* refacto for merge

* fix post back

* fix build

* fix build
2026-11-24 15:08:27 +01:00
Joris K
57c1865270 feat(xo6/vm): open the VM duplication form in a drawer (#10879) 2026-11-24 14:53:54 +01:00
Marie Garde
a0a11fdd48 feat(xo6): display dynamic selection in backup job side panel (#10757)
* feat(xo6): display dynamic selection in backup job side panel

* fix import and add changelog
2026-11-24 14:50:48 +01:00
Marie Garde
54fb7a33b8 feat(xo6/web-core): add query builder preview and resource query buil… (#10756)
feat(xo6/web-core): add query builder preview and resource query builders
2026-11-24 14:47:26 +01:00
Marie Garde
edbfe8c7e4 feat(xo6): add schedule cron editor components (#10755)
* feat(xo6): add schedule cron editor components

* fix build
2026-11-24 14:45:30 +01:00
Joris K
e97cea2dd6 feat(xo6/traffic-rules): open the traffic rule creation form in a drawer (#10880) 2026-11-24 14:39:40 +01:00
Joris K
467c0130fc feat(xo6/pool): open the pool connection form in a drawer (#10881) 2026-11-24 14:27:58 +01:00
Marie Garde
de62672a07 refactor(xo6): rename backup repository review components (#10754) 2026-11-24 14:22:48 +01:00
noritaka97
4b242221f3 feat(xo6/web-core): show storage in VM dashboard quick info (#10747) 2026-11-24 14:11:32 +01:00
Sylvère
0be66a2698 feat(xo6): replace the Quick Tasks popup with a new My Tasks sidebar (#10805)
* feat(xo6): add MyTasks view

* feat(xo6): new tasks list components + story, fixed UiCircleProgressBar

* grouped task types, added mock tasks for testing

* fix(xo6): align task tree lines with compact treeview, use real tasks in UI

* review fixes

* feat(xo6): expand and seek parent task when selecting subtask

* feat(xo6): add search to tasks sidebar, include subtasks in tasks table search

* feat(xo6): use new UiButtonIcon counter for tasks

* feat(xo6): show unread dot on task items in sidebar

* feat(xo6): removed now unused components and locale keys

* review fixes and tests

* feat(xo6): updated tasks button behaviour, added progress circle

* feat(xo6): my tasks - add mark all as read feature

* fix rebase

* review fixes
2026-11-24 13:52:10 +01:00
OlivierFL
82dabbf0cd test(web): import the VDI drawer select helpers from web-core (#10890)
Introduced by #10878, merged after f608a47d8f
2026-11-24 13:26:45 +01:00
OlivierFL
1fca20d82e test(web): read the host and VIF network selects with the shared helpers (#10889)
Introduced by f608a47d8f, merged after #10865 and #10877
2026-11-24 12:00:29 +01:00
Joris K
04de2031e6 feat(xo6/vdi): open the VDI creation and attach forms in a drawer (#10878) 2026-11-24 11:47:10 +01:00
Olivier Floch
7c6b48d139 test(web): read the backup repository selects with the shared helpers
- Drop the local findShownSelections, which shadowed the web-core one with
  another signature
- Add mountBrGeneralStep and createBrGeneralFormData (src/test), replacing
  the three mounts of BackupRepositoryGeneralStep and the empty form data
  built twice
- Forward attachTo in the XO 6 mountWithSetup, used by mountBrGeneralStep
2026-11-24 11:39:43 +01:00
Olivier Floch
06080bbec6 test(web-core): share the test setup helpers
- Add mountWithSetupResult (web-core, wrapped by XO 6): setup returns
  { result, render }, the mount returns { wrapper, result }; the SR, private
  network, new VM, JSON schema form, menu popup, menu list navigation and
  overlay focus tests no longer capture what their setup builds by hand
- Add mountComposableUnderSetup (web-core, wrapped by XO 6) and
  injectOrThrow: the tests running a composable under the component
  providing what it injects (new VM form, JSON schema form, V2V connection,
  VM migrate selects, tag select keyboard) share them
2026-11-24 11:39:43 +01:00
Olivier Floch
f608a47d8f feat(web-core): update VtsSelect to v7
- Add the success accent to VtsSelect, with the success icon before the
  chevron, also from a success message of its input wrapper
- Show the placeholder of a readonly UiInput without value, so that a
  VtsSelect without selection shows its placeholder; an empty placeholder
  renders nothing
- Share the input wrapper accents in INPUT_WRAPPER_ACCENTS, make required
  optional in useInputWrapperController and style the slotted right icons
  of UiInput
- Move the select test helpers (select.ts) from XO 6 to web-core/test, add
  mountWithSetup (web-core, wrapped by XO 6) replacing the XO 6
  mountWithSelect, renderSelect / mountSelect and isPlaceholderShown;
  migrate every caller and the docs
- Add VtsSelect unit tests
- Update the VtsSelect story and the form-select README to the current API
2026-11-24 11:39:43 +01:00
Joris K
543aebb302 feat(xo6/vif): open the VIF creation form in a drawer (#10877) 2026-11-24 11:23:27 +01:00
625 changed files with 26650 additions and 5154 deletions

View File

@@ -14,7 +14,7 @@
"url": "https://vates.fr"
},
"license": "ISC",
"version": "0.1.6",
"version": "0.1.7",
"engines": {
"node": ">=8.10"
},
@@ -25,7 +25,7 @@
"dependencies": {
"@vates/multi-key-map": "^0.2.0",
"@xen-orchestra/async-map": "^0.1.5",
"@xen-orchestra/log": "^0.7.2",
"@xen-orchestra/log": "^1.0.0",
"ensure-array": "^1.0.0"
},
"devDependencies": {

View File

@@ -1,6 +1,6 @@
{
"name": "@vates/fuse-vhd",
"version": "2.1.3",
"version": "2.1.4",
"license": "ISC",
"private": false,
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/@vates/fuse-vhd",
@@ -19,12 +19,12 @@
},
"main": "./index.mjs",
"dependencies": {
"@xen-orchestra/fs": "^4.10.0",
"@xen-orchestra/log": "^0.7.2",
"@xen-orchestra/fs": "^4.11.0",
"@xen-orchestra/log": "^1.0.0",
"fuse-native": "^2.2.6",
"lru-cache": "^7.14.0",
"promise-toolbox": "^0.21.0",
"vhd-lib": "^4.17.0"
"vhd-lib": "^4.17.1"
},
"bin": {
"xo-fuse-vhd": "./cli.mjs"

View File

@@ -1,6 +1,6 @@
{
"name": "@vates/iscsi",
"version": "0.4.0",
"version": "0.4.1",
"main": "dist/index.mjs",
"types": "dist/index.d.mts",
"bin": {
@@ -24,7 +24,7 @@
"@vates/async-each": "^1.0.3",
"@vates/read-chunk": "^1.2.1",
"@xen-orchestra/disk-transform": "^1.3.4",
"@xen-orchestra/log": "^0.7.2",
"@xen-orchestra/log": "^1.0.0",
"promise-toolbox": "^0.21.0"
},
"devDependencies": {

View File

@@ -1,6 +1,6 @@
import assert from 'node:assert'
import { spawn } from 'node:child_process'
import { pFromCallback } from 'promise-toolbox'
import { pFromCallback, pTimeout } from 'promise-toolbox'
import { createLogger } from '@xen-orchestra/log'
import AbstractNbdClient from './AbstractNbdClient.mjs'
@@ -9,6 +9,9 @@ const { warn } = createLogger('vates:nbd-client:stdio')
// only the tail is kept: it's the part describing why the server died
const STDERR_MAX_LENGTH = 4096
// how long a failed connection waits for the server to exit and its stderr to end
const CLOSE_TIMEOUT = 1e3
/**
* NBD client talking to a server through its standard streams, like
* `nbdkit -s` or `qemu-nbd` in `--fd` mode: the queries are written to the
@@ -28,7 +31,7 @@ export default class NbdStdioClient extends AbstractNbdClient {
#cwd
#env
/** @type {{ child: import('node:child_process').ChildProcess, closing: boolean, stderr: string }|undefined} */
/** @type {{ child: import('node:child_process').ChildProcess, closing: boolean, stderr: string, closed: Promise<unknown> }|undefined} */
#state
/**
@@ -68,6 +71,36 @@ export default class NbdStdioClient extends AbstractNbdClient {
return this.#state?.child.pid
}
/**
* A server dying before the handshake makes it fail with "stream has ended
* without data", and the exit handler, racing with the teardown, often
* reports nothing: what the server wrote on stderr is the only reason given,
* so it becomes the error.
*/
async connect() {
try {
return await super.connect()
} catch (error) {
const state = this.#state
const closed =
state !== undefined &&
(await pTimeout.call(state.closed, CLOSE_TIMEOUT).then(
() => true,
() => false
))
// exitCode is null when the process was killed, by us when it did not die by itself
if (closed && state.child.exitCode !== null && state.stderr !== '') {
const serverError = new Error(state.stderr.trim(), { cause: error })
serverError.code = 'NBD_SERVER_EXITED'
serverError.exitCode = state.child.exitCode
serverError.command = this.#command
serverError.stderr = state.stderr
throw serverError
}
throw error
}
}
async _openTransport() {
const child = spawn(this.#command, this.#args, {
cwd: this.#cwd,
@@ -75,7 +108,13 @@ export default class NbdStdioClient extends AbstractNbdClient {
// the protocol goes through stdin/stdout, stderr is only used for diagnostics
stdio: ['pipe', 'pipe', 'pipe'],
})
const state = { child, closing: false, stderr: '' }
const state = {
child,
closing: false,
stderr: '',
// 'close' comes after the exit and the end of the standard streams: stderr is complete
closed: new Promise(resolve => child.once('close', resolve)),
}
this.#state = state
child.stderr.setEncoding('utf8')

View File

@@ -0,0 +1,19 @@
import assert from 'node:assert/strict'
import { describe, it } from 'node:test'
import NbdStdioClient from './NbdStdioClient.mjs'
describe('NbdStdioClient', () => {
it('reports what the server wrote on stderr when it dies before the handshake', async () => {
// the end of stdout and the exit of the process come in either order: repeat
for (let i = 0; i < 20; i++) {
const client = new NbdStdioClient({ command: 'sh', args: ['-c', 'echo "the actual reason" >&2; exit 1'] })
await assert.rejects(client.connect(), {
code: 'NBD_SERVER_EXITED',
exitCode: 1,
message: 'the actual reason',
stderr: 'the actual reason\n',
})
}
})
})

View File

@@ -13,7 +13,7 @@
"url": "https://vates.fr"
},
"license": "ISC",
"version": "3.7.0",
"version": "3.7.2",
"engines": {
"node": ">=14.0"
},
@@ -23,9 +23,9 @@
"@vates/read-chunk": "^1.2.1",
"@xen-orchestra/async-map": "^0.1.5",
"@xen-orchestra/disk-transform": "^1.3.4",
"@xen-orchestra/log": "^0.7.2",
"@xen-orchestra/log": "^1.0.0",
"promise-toolbox": "^0.21.0",
"xen-api": "^5.1.0"
"xen-api": "^6.0.0"
},
"devDependencies": {
"tap": "^18.7.0",

View File

@@ -1,6 +1,6 @@
{
"name": "@vates/node-vsphere-soap",
"version": "2.2.0",
"version": "2.2.1",
"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,7 +11,7 @@
},
"bugs": "https://github.com/vatesfr/xen-orchestra/issues",
"dependencies": {
"@xen-orchestra/log": "^0.7.2",
"@xen-orchestra/log": "^1.0.0",
"axios": "^1.15.0",
"soap": "^1.0.0",
"soap-cookie": "^0.10.1"

View File

@@ -13,7 +13,7 @@
"url": "https://vates.fr"
},
"license": "ISC",
"version": "0.1.0",
"version": "0.2.0",
"engines": {
"node": ">=8.10"
},

View File

@@ -19,7 +19,7 @@
"url": "https://vates.fr"
},
"license": "ISC",
"version": "0.1.0",
"version": "0.2.0",
"engines": {
"node": ">=18"
},

View File

@@ -25,6 +25,17 @@ const task = new Task({
const { reason } = event
}
},
// only for a detached task, inherited by its subtasks
//
// if true, a subtask created after the abort of its parent is aborted, and ended, right away: running it rejects
// with the abort reason without calling its function, so the remaining steps of an aborted task are skipped
skipSubtasksAfterAbort: false,
// if true, this subtask does not follow the abort of its parent, so that it still runs after an abort
//
// meant for the cleanup steps of an aborted task
cleanup: false,
})
// this field is settable once before being observed
@@ -38,9 +49,12 @@ task.id
// - failure
task.status
// Triggers the abort signal associated to the task.
// Triggers the abort signal associated to the task, and the ones of its subtasks.
//
// This simply requests the task to abort, it will be up to the task to handle or not this signal.
// A running task is only requested to abort: it is up to its function to handle or not this signal.
//
// A task that is not running ends right away as failed, with `reason` as result, and running it afterwards rejects
// with `reason` without calling its function. See `skipSubtasksAfterAbort` for the subtasks created after the abort.
task.abort(reason)
// if fn rejects, the task will be marked as failed

View File

@@ -41,6 +41,17 @@ const task = new Task({
const { reason } = event
}
},
// only for a detached task, inherited by its subtasks
//
// if true, a subtask created after the abort of its parent is aborted, and ended, right away: running it rejects
// with the abort reason without calling its function, so the remaining steps of an aborted task are skipped
skipSubtasksAfterAbort: false,
// if true, this subtask does not follow the abort of its parent, so that it still runs after an abort
//
// meant for the cleanup steps of an aborted task
cleanup: false,
})
// this field is settable once before being observed
@@ -54,9 +65,12 @@ task.id
// - failure
task.status
// Triggers the abort signal associated to the task.
// Triggers the abort signal associated to the task, and the ones of its subtasks.
//
// This simply requests the task to abort, it will be up to the task to handle or not this signal.
// A running task is only requested to abort: it is up to its function to handle or not this signal.
//
// A task that is not running ends right away as failed, with `reason` as result, and running it afterwards rejects
// with `reason` without calling its function. See `skipSubtasksAfterAbort` for the subtasks created after the abort.
task.abort(reason)
// if fn rejects, the task will be marked as failed

View File

@@ -35,6 +35,17 @@ function define(object, property, value) {
const noop = Function.prototype
// aborts `controller` when `signal` is aborted, right away if it already is
//
// `signal.aborted` must be checked: the abort event of an already aborted signal is never dispatched again
function followSignal(signal, controller) {
if (signal.aborted) {
controller.abort(signal.reason)
} else {
signal.addEventListener('abort', () => controller.abort(signal.reason), { once: true })
}
}
const FAILURE = 'failure'
const PENDING = 'pending'
const SUCCESS = 'success'
@@ -86,11 +97,12 @@ class Task {
}
}
// These two properties should not be used outside the class
// These properties should not be used outside the class
//
// To ensure compatibility between multiple versions of this lib, they are kept public for now
_abortController = new AbortController()
_onProgress
_skipSubtasksAfterAbort = false
get id() {
// Use a compact, sortable, string representation of the creation date,
@@ -110,18 +122,26 @@ class Task {
return this.#status
}
constructor({ properties, onProgress } = {}) {
// `skipSubtasksAfterAbort` (root task only, inherited by its subtasks): a subtask created after the abort is
// aborted right away, so the steps of an aborted task are skipped.
//
// `cleanup`: this subtask does not follow the abort of its parent, so that it still runs after an abort.
constructor({ properties, onProgress, cleanup = false, skipSubtasksAfterAbort = false } = {}) {
this.#startData = { properties }
// the parent signal this task's abort follows, once its own listener is registered
let parentSignal
if (onProgress !== undefined) {
this._onProgress = onProgress
this._skipSubtasksAfterAbort = skipSubtasksAfterAbort
} else {
const parent = getTask()
if (parent !== undefined) {
const { signal } = parent._abortController
signal.addEventListener('abort', () => {
this._abortController.abort(signal.reason)
})
// `_skipSubtasksAfterAbort` is missing on a task created by an older version of this library
this._skipSubtasksAfterAbort = parent._skipSubtasksAfterAbort === true
if (!cleanup) {
parentSignal = parent._abortController.signal
}
this._onProgress = parent._onProgress
this.#startData.parentId = parent.id
@@ -138,10 +158,23 @@ class Task {
this.#emit('abortionRequested', { reason: signal.reason })
if (!this.#running) {
this.#endedByAbort = true
this.#end(FAILURE, signal.reason)
}
}
})
if (parentSignal !== undefined) {
if (this._skipSubtasksAfterAbort) {
// after the listener above: a task created under an aborted parent is aborted, and ended, right away (its
// `run()` then rejects without calling its function), as if its parent had been aborted just after its creation
followSignal(parentSignal, this._abortController)
} else {
parentSignal.addEventListener('abort', () => {
this._abortController.abort(parentSignal.reason)
})
}
}
}
abort(reason) {
@@ -192,8 +225,14 @@ class Task {
return result
}
#endedByAbort = false
#running = false
async runInside(fn) {
// aborted before it could run, either directly or because it was created under an aborted parent
if (this.#endedByAbort) {
throw this._abortController.signal.reason
}
assert.equal(this.status, PENDING)
assert.equal(this.#running, false)
this.#running = true

View File

@@ -175,6 +175,213 @@ describe('Task', function () {
})
})
describe('subtask of an aborted task', function () {
// events of `subtask`, in the order they were emitted to the root task
const subtaskEventTypes = (task, subtask) => task.$events.filter(_ => _.id === subtask.id).map(_ => _.type)
describe('without skipSubtasksAfterAbort', function () {
it('runs when created after the abort, as before this option existed', async function () {
const task = createTask()
await task.run(async () => {
task.abort()
assert.equal(
await Task.run(() => {
assert.equal(Task.abortSignal.aborted, false)
return 'done'
}),
'done'
)
})
})
it('is aborted when its parent is aborted while it runs', async function () {
const task = createTask()
await task.run(() =>
Task.run(() => {
task.abort()
assert.equal(Task.abortSignal.aborted, true)
})
)
})
})
describe('with skipSubtasksAfterAbort', function () {
it('does not run when created after the abort', async function () {
const task = createTask({ skipSubtasksAfterAbort: true })
const reason = {}
let called = false
let subtask
await task.run(async () => {
task.abort(reason)
subtask = new Task()
await assert.rejects(
subtask.run(() => {
called = true
}),
error => error === reason
)
})
assert.equal(called, false)
assert.equal(subtask.status, 'failure')
assert.deepEqual(subtaskEventTypes(task, subtask), ['start', 'abortionRequested', 'end'])
const end = task.$events.findLast(_ => _.id === subtask.id)
assert.equal(end.status, 'failure')
assert.equal(end.result, reason)
})
it('does not run a step started with Task.run() after the abort', async function () {
const task = createTask({ skipSubtasksAfterAbort: true })
let called = false
await task.run(async () => {
task.abort()
await assert.rejects(
Task.run({ properties: { name: 'step' } }, () => {
called = true
}),
{ name: 'AbortError' }
)
})
assert.equal(called, false)
})
it('does not run when created before the abort and run after it', async function () {
const task = createTask({ skipSubtasksAfterAbort: true })
const reason = {}
let called = false
let subtask
await task.run(async () => {
subtask = new Task()
task.abort(reason)
await assert.rejects(
subtask.run(() => {
called = true
}),
error => error === reason
)
})
assert.equal(called, false)
assert.equal(subtask.status, 'failure')
assert.deepEqual(subtaskEventTypes(task, subtask), ['start', 'abortionRequested', 'end'])
})
it('is inherited by the subtasks of the subtasks', async function () {
const task = createTask({ skipSubtasksAfterAbort: true })
let called = false
await task.run(() =>
Task.run(async () => {
task.abort()
await assert.rejects(
Task.run(() => {
called = true
}),
{ name: 'AbortError' }
)
}).catch(noop)
)
assert.equal(called, false)
})
it('is ignored on a subtask', async function () {
const task = createTask()
await task.run(async () => {
task.abort()
assert.equal(await Task.run({ skipSubtasksAfterAbort: true }, () => Task.run(() => 'done')), 'done')
})
})
})
it('still throws when run after it ended for another reason', async function () {
const task = createTask()
task.start()
task.success()
await assert.rejects(task.run(noop), { name: 'AssertionError' })
})
})
describe('cleanup subtask', function () {
it('runs when created after the abort', async function () {
const task = createTask({ skipSubtasksAfterAbort: true })
let subtask
await task.run(async () => {
task.abort()
subtask = new Task({ cleanup: true })
const result = await subtask.run(() => {
assert.equal(Task.abortSignal.aborted, false)
return 'cleaned'
})
assert.equal(result, 'cleaned')
})
assert.equal(subtask.status, 'success')
})
it('runs through Task.run() with the cleanup option', async function () {
const task = createTask({ skipSubtasksAfterAbort: true })
await task.run(async () => {
task.abort()
assert.equal(await Task.run({ properties: { name: 'clean-vm' }, cleanup: true }, () => 'cleaned'), 'cleaned')
})
})
it('is not aborted when its parent is aborted while it runs', async function () {
const task = createTask({ skipSubtasksAfterAbort: true })
await task.run(() =>
Task.run({ cleanup: true }, () => {
task.abort()
assert.equal(Task.abortSignal.aborted, false)
})
)
})
it('lets its own subtasks run normally', async function () {
const task = createTask({ skipSubtasksAfterAbort: true })
await task.run(async () => {
task.abort()
const result = await Task.run({ cleanup: true }, () => Task.run(() => 'done'))
assert.equal(result, 'done')
})
})
})
describe('without abort', function () {
it('emits the same events for a task and its subtasks', async function () {
const task = createTask()
await task.run(() => Task.run({ properties: { name: 'step' } }, () => Task.run(() => 'foo')))
assert.deepEqual(
task.$events.map(_ => _.type),
['start', 'start', 'start', 'end', 'end', 'end']
)
assert.equal(task.status, 'success')
})
})
describe('#failure()', function () {
const error = new Error()

View File

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

View File

@@ -22,6 +22,11 @@ export const BACKUP_EXPRESSION_CONTEXT = {
tags: { type: 'string[]' },
power_state: { type: 'string' },
},
pool: {
name_label: { type: 'string' },
description: { type: 'string' },
tags: { type: 'string[]' },
},
chainLength: { type: 'number' },
} as const
@@ -33,6 +38,8 @@ export const BACKUP_SETTING_CONTEXT = {
vmFilter: ['vm', 'run'],
srs: ['sr', 'run'],
remotes: ['backupRepository', 'run'],
vms: ['vm', 'run'],
pools: ['pool', 'run'],
} as const
export type BACKUP_SETTING_CONTEXT = (typeof BACKUP_SETTING_CONTEXT)[keyof typeof BACKUP_SETTING_CONTEXT]

View File

@@ -822,3 +822,16 @@ export type RPU_RECOVERY_STEP_NAME = (typeof RPU_RECOVERY_STEP_NAMES)[number]
export const COMMON_TAG = {
NOBAK: 'xo:no-bak',
} as const
/**
* a package of the XO appliance with another version available
*
* Returned by `xoa-updater` as `upgradablePackages` at the end of an update check.
*/
export type XoaPackageUpdate = {
name: string
/** version which will be installed */
version: string
/** undefined: the package is not installed yet */
installedVersion?: string
}

View File

@@ -462,6 +462,7 @@ export interface Xapi {
stream: Readable | Buffer,
opts: { signal?: AbortSignal; format: SUPPORTED_VDI_FORMAT }
): Promise<void>
VDI_resize(vdiRef: XenApiVdi['$ref'], size: number): Promise<void>
VIF_create(
options: {
currently_attached?: boolean

View File

@@ -472,10 +472,7 @@ export type XoApp = EventEmitter & {
getPlugin(id: XoPlugin['id']): Promise<XoPlugin>
getPlugins(): Promise<XoPlugin[]>
getProxy(id: XoProxy['id']): Promise<XoProxy>
updateProxy(
id: XoProxy['id'],
updates: { address?: string | null; authenticationToken?: string; name?: string; vmUuid?: XoVm['id'] | null }
): Promise<XoProxy>
getProxyApplianceUpdaterState(id: XoProxy['id']): Promise<{ level: string; message: string; state: string }>
getRemote(id: XoBackupRepository['id']): Promise<XoBackupRepository>
getAllRemotes(): Promise<XoBackupRepository[]>
removeRemote(id: XoBackupRepository['id']): Promise<void>
@@ -507,7 +504,10 @@ export type XoApp = EventEmitter & {
* `assertBrowserMediaInsertable` reports the predictable failures synchronously, e.g. before
* starting a task.
*/
insertBrowserMedia(params: { id: XoBrowserMediaSession['id']; vmId: XoVm['id'] }): Promise<{ vdiId: XoVdi['id'] }>
insertBrowserMedia(params: {
id: XoBrowserMediaSession['id']
vmId: XoVm['id']
}): Promise<{ vdiId: XoVdi['id'] }>
assertBrowserMediaInsertable(params: { id: XoBrowserMediaSession['id']; vmId: XoVm['id'] }): void
/** Eject the ISO of a browser media session, release its storage, and disconnect the browser */
ejectBrowserMedia(id: XoBrowserMediaSession['id']): Promise<void>

View File

@@ -646,7 +646,7 @@ export type XoVmBackupJob = BaseXoJob & {
proxy?: XoProxy['id']
mode: 'full' | 'delta'
remotes?: CMType.IdOr<XoBackupRepository['id']> | string
vms: CMType.IdOr<XoVm['id']> | Record<string, unknown>
vms: CMType.IdOr<XoVm['id']> | Record<string, unknown> | string
srs?: CMType.IdOr<XoSr['id']> | string
type: 'backup'
settings: {
@@ -663,7 +663,7 @@ export type XoMetadataBackupJobScheduleSettings = {
}
export type XoMetadataBackupJob = BaseXoJob & {
type: 'metadataBackup'
pools?: CMType.IdOr<XoPool['id']>
pools?: CMType.IdOr<XoPool['id']> | string
remotes: CMType.IdOr<XoBackupRepository['id']>
settings: {
''?: XoMetadataBackupJobGeneralSettings
@@ -696,6 +696,7 @@ export type XoMirrorBackupJob = BaseXoJob & {
sourceRemote: XoBackupRepository['id']
remotes: CMType.IdOr<XoBackupRepository['id']>
proxy?: XoProxy['id']
filter?: { vm: { uuid: { __or: XoVm['id'][] } } } | null
settings: {
'': XoMirrorBackupGeneralSettings
[scheduleId: XoSchedule['id']]: XoMirrorBackupScheduleSettings | undefined

View File

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

View File

@@ -1,6 +1,3 @@
export default {
read: true,
update: {
name: true,
},
}

View File

@@ -7,7 +7,7 @@
"type": "git",
"url": "https://github.com/vatesfr/xen-orchestra.git"
},
"version": "0.4.0",
"version": "0.4.1",
"engines": {
"node": ">=14"
},
@@ -17,7 +17,7 @@
},
"dependencies": {
"@vates/decorate-with": "^2.1.0",
"@xen-orchestra/log": "^0.7.2",
"@xen-orchestra/log": "^1.0.0",
"golike-defer": "^0.5.1",
"object-hash": "^2.0.1"
},

View File

@@ -1,7 +1,7 @@
{
"private": true,
"name": "@xen-orchestra/autopilot-docking",
"version": "0.0.0",
"version": "0.1.0",
"description": "Live ISO that prepares a VM imported from another hypervisor to boot on XCP-ng",
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/@xen-orchestra/autopilot-docking",
"bugs": "https://github.com/vatesfr/xen-orchestra/issues",

View File

@@ -1,6 +1,6 @@
{
"name": "@xen-orchestra/backup-archive",
"version": "1.2.0",
"version": "1.2.1",
"description": "Helper to handle generic backup archives",
"license": "ISC",
"author": "",
@@ -21,18 +21,18 @@
"tar-stream": "^3.1.8",
"@types/tar-stream": "^3.1.4",
"tmp": "^0.2.1",
"@vates/types": "^2.5.0"
"@vates/types": "^3.2.0"
},
"dependencies": {
"@xen-orchestra/log": "^0.7.1",
"@xen-orchestra/fs": "^4.10.0",
"@xen-orchestra/log": "^1.0.0",
"@xen-orchestra/fs": "^4.11.0",
"@xen-orchestra/disk-transform": "^1.3.4",
"@vates/task": "0.7.0",
"golike-defer": "0.5.1",
"uuid": "^9.0.0",
"promise-toolbox": "^0.21.0",
"@vates/async-each": "^1.0.1",
"vhd-lib": "^4.17.0"
"vhd-lib": "^4.17.1"
},
"scripts": {
"build": "yarn run clean && tsc",

View File

@@ -8,8 +8,8 @@
"dependencies": {
"@vates/async-each": "^1.0.3",
"@xen-orchestra/async-map": "^0.1.5",
"@xen-orchestra/backups": "^0.78.0",
"@xen-orchestra/fs": "^4.10.0",
"@xen-orchestra/backups": "^1.0.1",
"@xen-orchestra/fs": "^4.11.0",
"filenamify": "^6.0.0",
"getopts": "^2.2.5",
"lodash": "^4.18.0",
@@ -28,7 +28,7 @@
"scripts": {
"postversion": "npm publish --access public"
},
"version": "1.1.18",
"version": "1.1.19",
"license": "AGPL-3.0-or-later",
"author": {
"name": "Vates SAS",

View File

@@ -21,6 +21,9 @@ export class HealthCheckVmBackup {
const xapi = this.#xapi
const restoredId = restoredVm.uuid
// the health check stops waiting once the backup is aborted; the caller removes the restored VM
const signal = Task.abortSignal
// remove vifs
await Promise.all(restoredVm.$VIFs.map(vif => xapi.callAsync('VIF.destroy', vif.$ref)))
const waitForScript = restoredVm.tags.includes('xo-backup-health-check-xenstore')
@@ -33,6 +36,7 @@ export class HealthCheckVmBackup {
// start Vm
await xapi.callAsync(
signal,
'VM.start',
restoredVm.$ref,
false, // Start paused?
@@ -51,6 +55,7 @@ export class HealthCheckVmBackup {
// wait for the 'Running' event to be really stored in local xapi object cache
restoredVm = await xapi.waitObjectState(restoredVm.$ref, vm => vm.power_state === 'Running', {
signal,
timeout: remainingTimeout,
timeoutMessage: refOrUuid =>
`local xapi did not get Running state for VM ${refOrUuid} after ${timeout / 1000} second`,
@@ -61,6 +66,7 @@ export class HealthCheckVmBackup {
// wait for the guest tools to be detected
await xapi.waitObjectState(restoredVm.guest_metrics, gm => gm?.PV_drivers_detected, {
signal,
timeout: remainingTimeout,
timeoutMessage: refOrUuid =>
`timeout reached while waiting for ${refOrUuid} to report the driver version through the Xen tools. Please check or update the Xen tools.`,
@@ -77,6 +83,7 @@ export class HealthCheckVmBackup {
(vm.xenstore_data['vm-data/xo-backup-health-check'] === 'success' ||
vm.xenstore_data['vm-data/xo-backup-health-check'] === 'failure'),
{
signal,
timeout: remainingTimeout,
timeoutMessage: refOrUuid =>
`timeout reached while waiting for ${refOrUuid} to report the startup script execution.`,

View File

@@ -0,0 +1,52 @@
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { Task } from '@vates/task'
import { HealthCheckVmBackup } from './HealthCheckVmBackup.mjs'
describe('HealthCheckVmBackup#run() after an abort', () => {
it('stops waiting for the restored VM without waiting for its timeout', async () => {
// resolved once the restored VM is started
const { promise: pStarted, resolve: onStarted } = Promise.withResolvers()
const xapi = {
callAsync: async (...args) => {
if (args.includes('VM.start')) {
onStarted()
}
},
// the restored VM never reaches the expected state: only an abort can end the wait
waitObjectState: (ref, predicate, { signal } = {}) =>
new Promise((resolve, reject) => {
// as `Xapi#waitObjectState()` does, rejects right away when already aborted
if (signal?.aborted) {
reject(signal.reason)
} else {
signal?.addEventListener('abort', () => reject(signal.reason), { once: true })
}
}),
}
const healthCheck = new HealthCheckVmBackup({
restoredVm: { $ref: 'vm-ref', $VIFs: [], tags: [], uuid: 'vm-uuid' },
timeout: 60e3,
xapi,
})
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
const result = await vmTask
.run(async () => {
const pRun = healthCheck.run()
await pStarted
vmTask.abort()
return Promise.race([
pRun.then(
() => 'resolved',
error => error.name
),
new Promise(resolve => setTimeout(resolve, 1e3, 'still waiting')),
])
})
.catch(error => error.name)
assert.equal(result, 'AbortError')
})
})

View File

@@ -3,6 +3,7 @@ import assert from 'node:assert'
import { formatFilenameDate } from './_filenameDate.mjs'
import { importIncrementalVm } from './_incrementalVm.mjs'
import { liveMountXapiLabels } from './liveMountXapiLabels.mjs'
import { destroyOnAbort } from './_destroyOnAbort.mjs'
import { watchStreamSize } from './_watchStreamSize.mjs'
import { decorateClass } from '@vates/decorate-with'
import { Task } from '@vates/task'
@@ -425,6 +426,13 @@ export class ImportVmBackup {
}
backup = await adapter.readFullVmBackup(metadata)
watchStreamSize(backup, sizeContainer)
// the restore stops once aborted (e.g. the health check of an aborted backup): a full backup is a stream that
// `VM_import()` sends as is, destroying it fails the import, and XAPI drops the partial VM
//
// set up as soon as the stream exists, so that an abort landing before the import starts, or leaving the transfer
// subtask unable to run, still closes it (a file handle or an S3 request)
$defer(destroyOnAbort(backup, Task.abortSignal))
} else {
assert.strictEqual(metadata.mode, 'delta')
@@ -451,12 +459,21 @@ export class ImportVmBackup {
additionalVmTag !== undefined && vm.add_tags(additionalVmTag),
])
const vmRef = isFull
? await xapi.VM_import(backup, srRef, onVmCreation)
: await importIncrementalVm(backup, await xapi.getRecord('SR', srRef), {
newMacAddresses,
vmNamePrefix,
})
const signal = Task.abortSignal
let vmRef
try {
vmRef = isFull
? await xapi.VM_import(backup, srRef, onVmCreation)
: await importIncrementalVm(backup, await xapi.getRecord('SR', srRef), {
newMacAddresses,
signal,
vmNamePrefix,
})
} catch (error) {
// the error of the destroyed stream: report the abort instead
signal?.throwIfAborted()
throw error
}
let size = 0
if (isFull) {
size = sizeContainer.size

View File

@@ -304,3 +304,109 @@ describe('ImportVmBackup#_reuseNearestSnapshot()', () => {
await assert.rejects(() => importer._reuseNearestSnapshot(new Set([SYSTEM.uuid])), /would transfer the disk/)
})
})
describe('ImportVmBackup#run() after an abort', () => {
// a full restore whose steps `xapi` and `adapter` are controlled by the test: it reads `xva` and imports it with
// `VM_import()`, which, as the XAPI one does, reads its input until it ends and fails when the input fails
async function makeFullRestore({ onOpen, onSrLookup } = {}) {
const { PassThrough } = await import('node:stream')
const xva = new PassThrough()
// `importing` is resolved once `VM_import()` reads the stream
const { promise: importing, resolve: onImport } = Promise.withResolvers()
const state = { imported: false, importing }
const importer = new ImportVmBackup({
adapter: {
_handler: { _remote: {} },
readFullVmBackup: async () => {
await onOpen?.()
return xva
},
},
metadata: { ...makeMetadata(), mode: 'full' },
srUuid: DEFAULT_SR,
xapi: {
call: async () => {
await onSrLookup?.()
return 'OpaqueRef:sr'
},
VM_import: stream =>
new Promise((resolve, reject) => {
state.imported = true
onImport()
stream.on('error', () => reject(new Error('premature close'))).resume()
}),
},
})
return { importer, state, xva }
}
// the outcome of `run()`, `'still running'` if it does not settle within a second
const outcomeOf = pRun =>
Promise.race([
pRun.then(
() => 'resolved',
error => error.name
),
new Promise(resolve => setTimeout(resolve, 1e3, 'still running')),
])
it('stops the import of a full backup and fails with the abort', async () => {
const { Task } = await import('@vates/task')
const { importer, state } = await makeFullRestore()
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
const result = await vmTask
.run(async () => {
const pRun = importer.run()
await state.importing
vmTask.abort()
return outcomeOf(pRun)
})
.catch(error => error.name)
assert.equal(result, 'AbortError')
})
it('stops a full restore aborted before its import has started, and destroys its stream', async () => {
const { Task } = await import('@vates/task')
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
// the abort lands during the lookup of the SR, after the transfer subtask started
const { importer, xva } = await makeFullRestore({ onSrLookup: () => vmTask.abort() })
const result = await vmTask.run(() => outcomeOf(importer.run())).catch(error => error.name)
assert.equal(result, 'AbortError')
assert.equal(xva.destroyed, true)
})
it('destroys the stream of a full backup when the abort lands while it is opened', async () => {
const { Task } = await import('@vates/task')
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
// the transfer subtask is then created under an aborted task: it fails without running
const { importer, state, xva } = await makeFullRestore({ onOpen: () => vmTask.abort() })
const result = await vmTask.run(() => outcomeOf(importer.run())).catch(error => error.name)
assert.equal(result, 'AbortError')
assert.equal(state.imported, false)
assert.equal(xva.destroyed, true, 'the stream (a file handle or an S3 request) is not left open')
})
it('restores a full backup outside a task, as the proxy does', async t => {
// `golike-defer` logs the errors of the deferred functions instead of rejecting with them
const logError = t.mock.method(console, 'error', () => {})
const { importer, xva } = await makeFullRestore()
importer._xapi.VM_import = async stream => {
stream.resume()
throw new Error('stop after the import')
}
xva.end()
// the error of the import, not one of the abort handling, which has no signal to listen to
await assert.rejects(importer.run(), { message: 'stop after the import' })
assert.deepEqual(
logError.mock.calls.map(call => String(call.arguments[0])),
[]
)
})
})

View File

@@ -317,6 +317,34 @@ describe('RemoteAdapter#writeVhd validated by checkDisk', { concurrency: 1 }, ()
assert.deepEqual(await handler.list(basePath, { ignoreMissing: true }), useVhdDirectory ? ['data'] : [])
assert.deepEqual(await handler.list(`${basePath}/data`, { ignoreMissing: true }), [])
})
test(`${mode}: an aborted write stops and leaves no disk behind`, async () => {
const adapter = await getAdapter({ useVhdDirectory })
const path = `${basePath}/${adapter.getVhdFileName('base')}`
const controller = new AbortController()
const read = []
// the backup is aborted once the first block has been read
class AbortedDisk extends MockDisk {
async readBlock(index) {
read.push(index)
if (read.length === 1) {
controller.abort()
}
return super.readBlock(index)
}
}
await assert.rejects(
adapter.writeVhd(path, new AbortedDisk(8, [0, 1, 2, 3, 4, 5, 6, 7], 0x11), {
signal: controller.signal,
uuid: uniqueIdBuffer(),
}),
{ name: 'AbortError' }
)
assert.deepEqual(await handler.list(basePath, { ignoreMissing: true }), useVhdDirectory ? ['data'] : [])
assert.deepEqual(await handler.list(`${basePath}/data`, { ignoreMissing: true }), [])
})
}
})

View File

@@ -687,12 +687,14 @@ export class RemoteAdapter {
return path
}
async writeVhd(path, disk, { validator = noop, writeBlockConcurrency, uuid, parentUuid, parentPath } = {}) {
// `signal` stops the write once aborted: the partial disk is then removed
async writeVhd(path, disk, { signal, validator = noop, writeBlockConcurrency, uuid, parentUuid, parentPath } = {}) {
const handler = this._handler
if (this.useVhdDirectory()) {
return await writeToVhdDirectory({
disk,
signal,
target: {
handler,
path,
@@ -705,7 +707,11 @@ export class RemoteAdapter {
},
})
} else {
const stream = await toVhdStream(disk, { uuid, parentUuid, parentPath })
const stream = await toVhdStream(disk, { signal, uuid, parentUuid, parentPath })
// the stream starts reading the disk before the output stream is piped (`outputStream()` creates it first): an
// error in between (an abort, a read error) must not be emitted without listener, which would crash the process
// the pipeline still fails with this error, kept by the stream
stream.on('error', noop)
const size = await this.outputStream(path, stream, {
validator,
// no checksum for VHDs, because they will be invalidated by

View File

@@ -178,6 +178,8 @@ process.on('message', async message => {
? await Task.run(
{
properties: { name: 'backup run', ...message.data.jobData },
// the steps of an aborted backup are skipped, as when the backup runs in the main thread
skipSubtasksAfterAbort: true,
onProgress: data =>
emitMessage({
data,

View File

@@ -9,6 +9,7 @@ const { warn } = createLogger('xo:backups:buildContext')
/**
* @typedef {import('@vates/types/xen-api').XenApiVm} XenApiVm
* @typedef {import('@vates/types/xo').XoSr} XoSr
* @typedef {import('@vates/types/xo').XoPool} XoPool
* @typedef {import('@vates/types/xo').XoBackupRepository} XoBackupRepository
*
* @typedef {object} RunContext
@@ -30,6 +31,10 @@ const { warn } = createLogger('xo:backups:buildContext')
* @typedef {object} BackupRepositoryContext
* @property {{name: string, type: string | undefined, tags: string[]}} backupRepository
* @property {RunContext} run
*
* @typedef {object} PoolContext
* @property {{name_label: string, description: string, tags: string[]}} pool
* @property {RunContext} run
*/
/**
@@ -109,3 +114,19 @@ export function buildBackupRepositoryContext(backupRepository, run) {
run,
}
}
/**
* @param {XoPool} pool
* @param {RunContext} run
* @returns {PoolContext}
*/
export function buildPoolContext(pool, run) {
return {
pool: {
name_label: pool.name_label,
description: pool.name_description,
tags: Array.isArray(pool.tags) ? pool.tags : [],
},
run,
}
}

View File

@@ -1,7 +1,13 @@
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { buildRunContext, buildVmContext, buildSrContext, buildBackupRepositoryContext } from './_buildContext.mjs'
import {
buildRunContext,
buildVmContext,
buildSrContext,
buildBackupRepositoryContext,
buildPoolContext,
} from './_buildContext.mjs'
import { BACKUP_EXPRESSION_CONTEXT } from '@vates/types/backup-expression-context'
describe('buildContext', () => {
@@ -144,4 +150,39 @@ describe('buildContext', () => {
Object.keys(BACKUP_EXPRESSION_CONTEXT.backupRepository).sort()
)
})
it('buildPoolContext', () => {
const pool1 = {
name_label: 'name_label',
name_description: 'description',
ignored: 'ignored',
}
const poolContext1 = buildPoolContext(pool1, runContext)
assert.deepEqual(poolContext1, {
pool: {
name_label: 'name_label',
description: 'description',
tags: [],
},
run: expectedRunContext,
})
assert.deepEqual(Object.keys(poolContext1.pool).sort(), Object.keys(BACKUP_EXPRESSION_CONTEXT.pool).sort())
const pool2 = {
name_label: 'name_label',
name_description: 'description',
tags: ['tag'],
ignored: 'ignored',
}
const poolContext2 = buildPoolContext(pool2, runContext)
assert.deepEqual(poolContext2, {
pool: {
name_label: 'name_label',
description: 'description',
tags: ['tag'],
},
run: expectedRunContext,
})
assert.deepEqual(Object.keys(poolContext2.pool).sort(), Object.keys(BACKUP_EXPRESSION_CONTEXT.pool).sort())
})
})

View File

@@ -0,0 +1,28 @@
const noop = Function.prototype
/**
* Destroys `stream` with the reason of `signal` once it is aborted, right away if it already is.
*
* Nothing may be listening to the stream when it is destroyed: an error event without a listener would crash the
* process, so a noop listener is added.
*
* @param {import('node:stream').Readable} stream
* @param {AbortSignal} [signal] nothing is done without a signal, e.g. a restore run outside a task
* @returns {() => void} removes the abort listener
*/
export function destroyOnAbort(stream, signal) {
if (signal === undefined) {
return noop
}
stream.on('error', noop)
const onAbort = () => stream.destroy(signal.reason)
if (signal.aborted) {
onAbort()
return noop
}
signal.addEventListener('abort', onAbort, { once: true })
return () => signal.removeEventListener('abort', onAbort)
}

View File

@@ -0,0 +1,50 @@
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { PassThrough } from 'node:stream'
import { destroyOnAbort } from './_destroyOnAbort.mjs'
describe('destroyOnAbort()', () => {
it('does nothing without a signal', () => {
const stream = new PassThrough()
destroyOnAbort(stream, undefined)()
assert.equal(stream.destroyed, false)
assert.equal(stream.listenerCount('error'), 0)
})
it('destroys the stream right away when the signal is already aborted', () => {
const stream = new PassThrough()
const reason = new Error('aborted')
destroyOnAbort(stream, AbortSignal.abort(reason))
assert.equal(stream.destroyed, true)
assert.equal(stream.errored, reason)
})
it('destroys the stream once aborted, without crashing when nothing listens to it', async () => {
const stream = new PassThrough()
const controller = new AbortController()
const reason = new Error('aborted')
destroyOnAbort(stream, controller.signal)
controller.abort(reason)
// the error event is emitted on the next tick: an unhandled one would crash the test process
await new Promise(resolve => setImmediate(resolve))
assert.equal(stream.destroyed, true)
assert.equal(stream.errored, reason)
})
it('returns a function that stops listening to the signal', () => {
const stream = new PassThrough()
const controller = new AbortController()
destroyOnAbort(stream, controller.signal)()
controller.abort()
assert.equal(stream.destroyed, false)
})
})

View File

@@ -32,7 +32,9 @@ export async function exportIncrementalVm(vm, baseVdis = {}, { signal, nbdConcur
const disks = {}
const vdis = {}
const vbds = {}
await abortableMap(signal, vm.$VBDs, async (signal, vbd) => {
// the signal given to the callback stops the other initializations when one fails; the disks keep `signal`, which
// must keep reaching them once the export is built
await abortableMap(signal, vm.$VBDs, async (_initSignal, vbd) => {
let vdi
if (vbd.type !== 'Disk' || !(vdi = vbd.$VDI)) {
// Ignore this VBD.
@@ -68,6 +70,7 @@ export async function exportIncrementalVm(vm, baseVdis = {}, { signal, nbdConcur
baseRef: baseVdi?.$ref,
nbdConcurrency,
preferNbd,
signal,
})
await disks[vdiRef].init()
})
@@ -84,6 +87,7 @@ export async function exportIncrementalVm(vm, baseVdis = {}, { signal, nbdConcur
xapi: vm.$xapi,
nbdConcurrency,
preferNbd,
signal,
})
await disks[vdiRef].init()
}

View File

@@ -40,6 +40,9 @@ export const VmsRemote = class RemoteVmsBackupRunner extends Abstract {
}
async run() {
// abort signal of the backup run: once aborted, no new VM backup starts and no VM backup is retried
const signal = Task.abortSignal
const job = this._job
const schedule = this._schedule
const settings = this._settings
@@ -81,6 +84,10 @@ export const VmsRemote = class RemoteVmsBackupRunner extends Abstract {
const nTriesByVmId = {}
const handleVm = async vmUuid => {
if (signal?.aborted) {
return
}
if (nTriesByVmId[vmUuid] === undefined) {
nTriesByVmId[vmUuid] = 0
}
@@ -143,9 +150,10 @@ export const VmsRemote = class RemoteVmsBackupRunner extends Abstract {
nbVmsDone++
return task.success(result)
}
if (isLastRun) {
// once aborted, the VM backup is not retried: it failed because of the abort, whatever its error
if (isLastRun || signal?.aborted) {
nbVmsDone++
return task.failure(taskError)
return task.failure(signal?.aborted ? signal.reason : taskError)
}
Task.set('progress', Math.round((nbVmsDone * 100) / nbVms))
// don't end the task

View File

@@ -0,0 +1,73 @@
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { Task } from '@vates/task'
import { FullRemote } from './_vmRunners/FullRemote.mjs'
import { VmsRemote } from './VmsRemote.mjs'
// a VM backup that runs until the run is aborted, as a transfer does
const backupUntilAborted = () =>
new Promise((resolve, reject) => {
const signal = Task.abortSignal
if (signal.aborted) {
reject(signal.reason)
} else {
signal.addEventListener('abort', () => reject(signal.reason), { once: true })
}
})
function createRunner({ vms, settings = {} }) {
const sourceAdapter = {
listAllVms: async () => vms,
listVmBackups: async () => [{ mode: 'full', vm: {} }],
}
return new VmsRemote({
config: { snapshotNameLabelTpl: '[XO Backup {job.name}] {vm.name_label}' },
getAdapter: async remoteId => ({ value: remoteId === 'source' ? sourceAdapter : {}, dispose() {} }),
getConnectedRecord: async () => {
throw new Error('no record in these tests')
},
job: {
id: 'job',
mode: 'full',
name: 'job',
remotes: { id: { __or: ['source', 'target'] } },
settings: { '': { concurrency: 1, ...settings } },
sourceRemote: 'source',
},
schedule: { id: 'schedule' },
})
}
// runs the runner inside a root task, aborted once the first VM backup has started
async function runAndAbort(runner, calls) {
const events = []
const root = new Task({ skipSubtasksAfterAbort: true, onProgress: event => events.push(event) })
const pRun = root.run(() => runner.run())
while ((calls.vm1 ?? 0) === 0) {
await new Promise(resolve => setImmediate(resolve))
}
root.abort()
await pRun.catch(() => {})
return events.filter(_ => _.type === 'start' && _.properties?.type === 'VM').map(_ => _.properties.id)
}
describe('VmsRemote#run() after an abort', () => {
it('does not start the backup of the next VMs, nor retry the aborted one', async t => {
const calls = {}
t.mock.method(FullRemote.prototype, 'run', function () {
calls[this._vmUuid] = (calls[this._vmUuid] ?? 0) + 1
return this._vmUuid === 'vm1' ? backupUntilAborted() : Promise.resolve()
})
const vmTaskIds = await runAndAbort(
createRunner({ vms: ['vm1', 'vm2'], settings: { nRetriesVmBackupFailures: 2 } }),
calls
)
assert.deepEqual(calls, { vm1: 1 }, 'the aborted VM is not retried and the second VM is not backed up')
assert.deepEqual(vmTaskIds, ['vm1'], 'no task is created for the VMs not started')
})
})

View File

@@ -63,6 +63,9 @@ export const VmsXapi = class VmsXapiBackupRunner extends Abstract {
}
async run() {
// abort signal of the backup run: once aborted, no new VM backup starts and no VM backup is retried
const signal = Task.abortSignal
const job = this._job
// FIXME: proper SimpleIdPattern handling
@@ -143,6 +146,10 @@ export const VmsXapi = class VmsXapiBackupRunner extends Abstract {
await asyncEach(
[...vms].filter(vm => batchIds.has(vm.uuid)),
async vm => {
if (signal?.aborted) {
return
}
const { task } = getVmTask(vm.uuid, vm.name_label)
const vmSettings = { ...settings, ...allSettings[vm.uuid] }
@@ -205,9 +212,14 @@ export const VmsXapi = class VmsXapiBackupRunner extends Abstract {
const queue = new Set(snapshotedVmIds)
const handleVm = vmUuid => {
if (signal?.aborted) {
return
}
const vmBackupFailed = async (error, task) => {
if (isLastRun) {
return task.failure(error)
// once aborted, the VM backup is not retried: it failed because of the abort, whatever its error
if (isLastRun || signal?.aborted) {
return task.failure(signal?.aborted ? signal.reason : error)
} else {
// don't end the task
task.warning(`Retry the VM backup due to an error`, {

View File

@@ -0,0 +1,89 @@
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { Task } from '@vates/task'
import { VmsXapi } from './VmsXapi.mjs'
// a VM backup that runs until the run is aborted, as a transfer does
const backupUntilAborted = () =>
new Promise((resolve, reject) => {
const signal = Task.abortSignal
if (signal.aborted) {
reject(signal.reason)
} else {
signal.addEventListener('abort', () => reject(signal.reason), { once: true })
}
})
function createRunner({ backups, settings = {} }) {
const runner = new VmsXapi({
config: { snapshotNameLabelTpl: '[XO Backup {job.name}] {vm.name_label}' },
getAdapter: () => {
throw new Error('no remote in these tests')
},
getConnectedRecord: async (type, id) => ({ $type: type, uuid: id, name_label: id }),
job: {
id: 'job',
mode: 'full',
name: 'job',
settings: { '': { concurrency: 1, ...settings } },
srs: { id: 'sr' },
vms: { id: { __or: Object.keys(backups) } },
},
schedule: { id: 'schedule' },
})
const calls = Object.fromEntries(Object.keys(backups).map(id => [id, 0]))
runner._getVmBackup = (mode, { vm }) => ({
run: () => {
++calls[vm.uuid]
return backups[vm.uuid]()
},
})
return { runner, calls }
}
// runs the runner inside a root task, aborted once the first VM backup has started
async function runAndAbort(runner, calls) {
const events = []
const root = new Task({ skipSubtasksAfterAbort: true, onProgress: event => events.push(event) })
const pRun = root.run(() => runner.run())
while (calls.vm1 === 0) {
await new Promise(resolve => setImmediate(resolve))
}
root.abort()
await pRun.catch(() => {})
const vmTaskIds = events.filter(_ => _.type === 'start' && _.properties?.type === 'VM').map(_ => _.properties.id)
return { events, vmTaskIds }
}
describe('VmsXapi#run() after an abort', () => {
it('does not start the backup of the next VMs', async () => {
const { runner, calls } = createRunner({
backups: { vm1: backupUntilAborted, vm2: async () => {} },
})
const { vmTaskIds } = await runAndAbort(runner, calls)
assert.equal(calls.vm2, 0, 'the second VM is not backed up')
assert.deepEqual(vmTaskIds, ['vm1'], 'no task is created for the VMs not started')
})
it('does not retry the aborted VM', async () => {
const { runner, calls } = createRunner({
backups: { vm1: backupUntilAborted },
settings: { nRetriesVmBackupFailures: 2 },
})
const { events } = await runAndAbort(runner, calls)
assert.equal(calls.vm1, 1, 'the aborted VM backup is not run again')
const vmTaskId = events.find(_ => _.type === 'start' && _.properties?.id === 'vm1').id
const vmEnd = events.find(_ => _.type === 'end' && _.id === vmTaskId)
assert.equal(vmEnd.status, 'failure')
assert.equal(vmEnd.result.name, 'AbortError')
})
})

View File

@@ -3,6 +3,7 @@ import { createLogger } from '@xen-orchestra/log'
import { AbstractRemote } from './_AbstractRemote.mjs'
import { FullRemoteWriter } from '../_writers/FullRemoteWriter.mjs'
import { forkStreamUnpipe } from '../_forkStreamUnpipe.mjs'
import { destroyOnAbort } from '../../_destroyOnAbort.mjs'
import { watchStreamSize } from '../../_watchStreamSize.mjs'
import { AggregatedFullRemoteWriter } from '../_writers/AggregatedFullRemoteWriter.mjs'
import { Task } from '@vates/task'
@@ -23,6 +24,7 @@ export const FullRemote = class FullRemoteVmBackupRunner extends AbstractRemote
const nbTransferrableVms = transferList.length
let nbTransferredVms = 0
for (const metadata of transferList) {
Task.abortSignal?.throwIfAborted()
const stream = this._throttleStream(await this._sourceRemoteAdapter.readFullVmBackup(metadata))
const sizeContainer = watchStreamSize(stream)
let checksum
@@ -36,6 +38,9 @@ export const FullRemote = class FullRemoteVmBackupRunner extends AbstractRemote
// a single writer can consume the stream itself: no need to fork it
const isForked = this._writers.size > 1
// the source is a plain stream: destroying it stops the reading and makes the writers fail
const stopDestroyOnAbort = destroyOnAbort(stream, Task.abortSignal)
// @todo shouldn't transfer backup if it will be deleted by retention policy (higher retention on source than destination)
await this._callWriters(
writer =>
@@ -51,7 +56,7 @@ export const FullRemote = class FullRemoteVmBackupRunner extends AbstractRemote
sizeContainer,
}),
'writer.run()'
)
).finally(stopDestroyOnAbort)
// for healthcheck
this._vm = metadata.vm
nbTransferredVms++

View File

@@ -0,0 +1,119 @@
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { PassThrough } from 'node:stream'
import { Task } from '@vates/task'
import { FullRemote } from './FullRemote.mjs'
const makeRunner = props => Object.assign(Object.create(FullRemote.prototype), props)
describe('FullRemote#_run() after an abort', () => {
it('stops reading the source backup', async () => {
const source = new PassThrough()
// resolved once the writer reads the stream
const { promise: pWriting, resolve: onWriting } = Promise.withResolvers()
const runner = makeRunner({
_computeTransferList: async () => [{ timestamp: 0, vm: {}, vmSnapshot: {} }],
_sourceRemoteAdapter: {
readFullVmBackup: async () => source,
readFullVmBackupChecksum: async () => {
throw new Error('no checksum')
},
},
_throttleStream: stream => stream,
_writers: new Set([
{
// a writer which writes until its input ends or fails
run: ({ stream }) =>
new Promise((resolve, reject) => {
onWriting()
stream.on('error', reject).on('end', resolve).resume()
}),
},
]),
})
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
const result = await vmTask
.run(async () => {
const pRun = runner._run()
await pWriting
vmTask.abort()
return Promise.race([
pRun.then(
() => 'resolved',
error => error.name
),
new Promise(resolve => setTimeout(resolve, 1e3, 'still reading')),
])
})
.catch(error => error.name)
assert.equal(result, 'AbortError')
})
it('destroys the source stream when the abort came while the source was being opened', async () => {
// nothing listens to its errors: destroying it must not crash the process
const source = new PassThrough()
let written = false
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
const runner = makeRunner({
_computeTransferList: async () => [{ timestamp: 0, vm: {}, vmSnapshot: {} }],
_sourceRemoteAdapter: {
readFullVmBackup: async () => source,
readFullVmBackupChecksum: async () => {
// the abort lands during the awaits that precede the registration of the listener
vmTask.abort()
throw new Error('no checksum')
},
},
_throttleStream: stream => stream,
_writers: new Set([
{
run: async () => {
written = true
},
},
]),
})
// the writers do not consume the stream: only the abort handling can close it
await vmTask.run(() => runner._run()).catch(() => {})
assert.equal(source.destroyed, true)
assert.equal(written, true)
})
it('does not open the source of the next backup once aborted', async () => {
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
let opened = 0
const runner = makeRunner({
_computeTransferList: async () => [
{ timestamp: 0, vm: {}, vmSnapshot: {} },
{ timestamp: 1, vm: {}, vmSnapshot: {} },
],
_sourceRemoteAdapter: {
readFullVmBackup: async () => {
++opened
// nothing listens to its errors: destroying it must not crash the process
return new PassThrough()
},
readFullVmBackupChecksum: async () => 'checksum',
},
_throttleStream: stream => stream,
_writers: new Set([
{
run: async () => {
vmTask.abort()
},
},
]),
})
await assert.rejects(
vmTask.run(() => runner._run()),
{ name: 'AbortError' }
)
assert.equal(opened, 1)
})
})

View File

@@ -1,4 +1,5 @@
import { createLogger } from '@xen-orchestra/log'
import { Task } from '@vates/task'
import { forkStreamUnpipe } from '../_forkStreamUnpipe.mjs'
import { FullRemoteWriter } from '../_writers/FullRemoteWriter.mjs'
@@ -55,6 +56,8 @@ export const FullXapi = class FullXapiVmBackupRunner extends AbstractXapi {
(
await this._xapi.VM_export(exportedVm.$ref, {
compress: Boolean(compression) && (compression === 'native' ? 'gzip' : 'zstd'),
// the export stream fails once the backup is aborted, which stops the writers
signal: Task.abortSignal,
useSnapshot: false,
})
).body

View File

@@ -0,0 +1,68 @@
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { PassThrough } from 'node:stream'
import { Task } from '@vates/task'
import { FullXapi } from './FullXapi.mjs'
const makeRunner = props => Object.assign(Object.create(FullXapi.prototype), props)
describe('FullXapi#_copy() after an abort', () => {
it('stops the XAPI export, and settles only once its writers have settled', async () => {
let exportOpts
// resolved once the XAPI export is called
const { promise: pExport, resolve: onExport } = Promise.withResolvers()
let writerSettledAt
const body = new PassThrough()
const runner = makeRunner({
job: {},
_vm: { uuid: 'vm-uuid' },
_exportedVm: { $ref: 'snapshot-ref', $getDisks: async () => [] },
_throttleStream: stream => stream,
_xapi: {
// as the HTTP export does: the body fails once the signal is aborted
VM_export: async (ref, opts) => {
exportOpts = opts
onExport()
opts.signal?.addEventListener('abort', () => body.destroy(opts.signal.reason), { once: true })
return { body }
},
},
_writers: new Set([
{
// a writer that needs some time to clean up after its input failed
run: ({ stream }) =>
new Promise((resolve, reject) => {
stream.on('error', error =>
setTimeout(() => {
writerSettledAt = Date.now()
reject(error)
}, 100)
)
stream.resume()
}),
},
]),
})
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
let copyRejectedAt
await vmTask
.run(async () => {
const pCopy = runner._copy()
await pExport
assert.ok(exportOpts.signal instanceof AbortSignal, 'the export gets the abort signal')
vmTask.abort()
await assert.rejects(pCopy, { name: 'AbortError' })
copyRejectedAt = Date.now()
})
.catch(error => {
if (error.name !== 'AbortError') {
throw error
}
})
assert.ok(writerSettledAt <= copyRejectedAt, 'the copy settles after its writers')
})
})

View File

@@ -85,6 +85,8 @@ class IncrementalRemoteVmBackupRunner extends AbstractRemote {
const nbTransferrableVms = transferList.length
let nbTransferredVms = 0
for (const metadata of transferList) {
// an abort during the previous VM's writer steps: its disks would be opened and never closed
Task.abortSignal?.throwIfAborted()
assert.strictEqual(metadata.mode, 'delta')
const incrementalExport = await this._sourceRemoteAdapter.readIncrementalVmBackup(metadata, undefined, {
useChain: false,

View File

@@ -1,5 +1,6 @@
import assert from 'node:assert/strict'
import { describe, it } from 'node:test'
import { Task } from '@vates/task'
import { IncrementalRemote } from './IncrementalRemote.mjs'
@@ -43,3 +44,42 @@ describe('IncrementalRemote prepare()', () => {
assert.equal(aggWriter.props.schedule, schedule)
})
})
describe('IncrementalRemote#_run() after an abort', () => {
it('does not open the disks of the next backup once aborted', async () => {
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
let opened = 0
// a real instance: `_run()` uses a private method
const runner = Object.assign(makeRunner({ schedule: { id: 'schedule-id' } }), {
_computeTransferList: async () => [
{ mode: 'delta', timestamp: 0, vm: {}, vmSnapshot: {} },
{ mode: 'delta', timestamp: 1, vm: {}, vmSnapshot: {} },
],
_selectBaseVm: async () => {},
_sourceRemoteAdapter: {
getVhdDirectoryCompression: () => undefined,
readIncrementalVmBackup: async () => {
++opened
return { disks: {}, vbds: {}, vdis: {}, vifs: {}, vm: {}, vtpms: {} }
},
},
_writers: new Set([
{
getVhdDirectoryCompression: () => undefined,
prepare: async () => {},
transfer: async () => {},
// the abort lands during the writer steps of the first backup
cleanup: async () => {
vmTask.abort()
},
},
]),
})
await assert.rejects(
vmTask.run(() => runner._run()),
{ name: 'AbortError' }
)
assert.equal(opened, 1)
})
})

View File

@@ -55,6 +55,8 @@ export const IncrementalXapi = class IncrementalXapiVmBackupRunner extends Abstr
const deltaExport = await exportIncrementalVm(exportedVm, baseVdis, {
nbdConcurrency: this._settings.nbdConcurrency,
preferNbd: this._settings.preferNbd,
// the reads of the disks stop once the backup is aborted
signal: Task.abortSignal,
})
const isVhdDifferencing = {}

View File

@@ -233,6 +233,7 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
const snapshotRef = await vm[settings.checkpointSnapshot ? '$checkpoint' : '$snapshot']({
ignoredVdisTag: '[NOBAK]',
name_label: TEMP_SNAPSHOT_NAME,
signal: Task.abortSignal,
unplugVusbs: true,
})
this.timestamp = Date.now()
@@ -381,7 +382,9 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
const xapi = this._xapi
const vdiCandidates = {}
const vdiUuids = this._vm.$VBDs.map(({ VDI }) => VDI)
// only disks: an empty CD drive has an empty VDI ref, which would match the
// snapshot_of of every VDI that is not a snapshot
const vdiUuids = this._vm.$VBDs.filter(({ type }) => type === 'Disk').map(({ VDI }) => VDI)
Object.values(xapi.objects.indexes.type.VDI)
.filter(_ => !!_) // filter nullish
.filter(({ other_config, snapshot_of }) => {
@@ -400,21 +403,20 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
this._jobSnapshotVdis = Object.values(vdiCandidates)
// For VMs with no disks, retention must be tracked directly on VM snapshots
// since there are no VDIs to anchor the discovery.
if (vdiUuids.length === 0) {
this._disklessJobSnapshotVms = this._vm.$snapshots
.filter(Boolean)
.filter(
({ other_config, $snapshot_of }) =>
$snapshot_of !== undefined &&
other_config[JOB_ID] === jobId &&
other_config[VM_UUID] === this._vm.uuid &&
other_config[COPY_OF] === undefined
)
} else {
this._disklessJobSnapshotVms = []
}
// also harvest each of the snapshot chain without any disk
// a VBD missing from the cache may be a disk: such a snapshot is skipped
// here, since it could also be reachable (and destroyed) through its VDIs
const hasNoDisk = ({ $VBDs }) => $VBDs.every(vbd => vbd !== undefined && vbd.type !== 'Disk')
this._disklessJobSnapshotVms = this._vm.$snapshots
.filter(Boolean)
.filter(
snapshot =>
snapshot.$snapshot_of !== undefined &&
snapshot.other_config[JOB_ID] === jobId &&
snapshot.other_config[VM_UUID] === this._vm.uuid &&
snapshot.other_config[COPY_OF] === undefined &&
hasNoDisk(snapshot)
)
}
async _removeUnusedSnapshots() {
@@ -450,7 +452,13 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
.pop()
// remove older snapshot schedule per schedule
const snapshotsPerSchedule = groupBy(this._jobSnapshotVdis, _ => _.other_config[SCHEDULE_ID])
// a VM snapshot without any disk is not reachable via its VDIs: both kinds
// share the same retention, so they are grouped by datetime together
const jobSnapshots = [
...this._jobSnapshotVdis.map(vdi => ({ other_config: vdi.other_config, vdi })),
...disklessVmSnapshots.map(vm => ({ other_config: vm.other_config, vm })),
]
const snapshotsPerSchedule = groupBy(jobSnapshots, _ => _.other_config[SCHEDULE_ID])
await asyncMap(Object.entries(snapshotsPerSchedule), async ([scheduleId, snapshots]) => {
const snapshotPerDatetime = groupBy(snapshots, _ => _.other_config[DATETIME])
@@ -473,7 +481,18 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
) {
return
}
const vdis = snapshotPerDatetime[datetime]
const entries = snapshotPerDatetime[datetime]
await asyncEach(
// VM snapshots without any disk: nothing to resolve, destroy them directly
entries.filter(({ vm }) => vm !== undefined),
async ({ vm: { $ref } }) => {
this._forgetExportedVm($ref)
await xapi.VM_destroy($ref)
}
)
// snapshots reached through their VDIs: resolve the VM snapshot via the
// VBDs, or destroy the VDIs alone when no VM is attached (CBT, orphans)
const vdis = entries.filter(({ vdi }) => vdi !== undefined).map(({ vdi }) => vdi)
let vm
// if there is an attached VM => destroy the VM (Non CBT backups)
for (const vdi of vdis) {
@@ -527,34 +546,6 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
})
})
// Retention for VMs with no disks: VM snapshots are not reachable via VDIs
if (disklessVmSnapshots.length > 0) {
const snapshotsPerSchedule = groupBy(disklessVmSnapshots, _ => _.other_config[SCHEDULE_ID])
await asyncEach(Object.entries(snapshotsPerSchedule), async ([scheduleId, snapshots]) => {
// we only have one snapshot per date time since it's at the VM level
const snapshotPerDatetime = Object.fromEntries(snapshots.map(s => [s.other_config[DATETIME], s.$ref]))
const datetimes = Object.keys(snapshotPerDatetime).sort()
const settings = {
...baseSettings,
...allSettings[scheduleId],
...allSettings[this._vm.uuid],
}
const retention = settings.snapshotRetention ?? 0
await asyncEach(getOldEntries(retention, datetimes), async datetime => {
if (
this.job.mode === 'delta' &&
lastExportedSnapshotDateTime !== undefined &&
datetime === lastExportedSnapshotDateTime
) {
return
}
this._forgetExportedVm(snapshotPerDatetime[datetime])
await xapi.VM_destroy(snapshotPerDatetime[datetime])
})
})
}
// list and remove the snapshot were the jobs failed between
// makesnapshot and update_other_config
const snapshots = this._vm.$snapshots.filter(_ => !!_).filter(({ name_label }) => name_label === TEMP_SNAPSHOT_NAME)

View File

@@ -2,9 +2,10 @@ import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { formatDateTime } from '@xen-orchestra/xapi'
import { Task } from '@vates/task'
import { AbstractXapi } from './_AbstractXapi.mjs'
import { DATETIME, EXPORTED_SUCCESSFULLY, JOB_ID, SCHEDULE_ID } from '../../_otherConfig.mjs'
import { DATETIME, EXPORTED_SUCCESSFULLY, JOB_ID, SCHEDULE_ID, VM_UUID } from '../../_otherConfig.mjs'
// Build an AbstractXapi instance without running its heavy constructor, then
// assign only the fields the method under test reads.
@@ -657,3 +658,197 @@ describe('run() purges the snapshot data only while the snapshot exists', () =>
assert.deepEqual(calls.vmDestroyed, [], 'the live VM must never be destroyed')
})
})
describe('after an abort', () => {
it('_snapshot() passes the abort signal to the snapshot', async () => {
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
let received
const runner = makeRunner({
_settings: { bypassVdiChainsCheck: true },
_vm: {
$ref: 'vm-ref',
uuid: 'vm-uuid',
$snapshot: async opts => {
received = opts
// the backup is aborted while the snapshot is being taken
vmTask.abort()
throw new Error('stop after the snapshot call')
},
},
_xapi: {},
_mustDoSnapshot: async () => true,
})
await vmTask.run(() => assert.rejects(runner._snapshot(), /stop after the snapshot call/)).catch(() => {})
assert.ok(received.signal instanceof AbortSignal, 'the snapshot gets a signal')
assert.equal(received.signal.aborted, true, 'the snapshot gets the abort signal of the backup')
})
it('run() still applies the retention and restores the blocked operations, but skips the health check', async () => {
const calls = []
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
const runner = makeRunner({
_settings: { offlineBackup: false, snapshotRetention: 0 },
_vm: {
uuid: 'live-uuid',
power_state: 'Halted',
blocked_operations: {},
update_blocked_operations: async ops => {
calls.push(Object.values(ops).every(_ => _ === null) ? 'unblock' : 'block')
},
$call: async () => {},
},
_writers: new Set([{ beforeBackup: async () => {}, afterBackup: async () => calls.push('afterBackup') }]),
_xapi: {},
_cleanMetadata: async () => {},
_fetchJobSnapshots: async () => {},
_selectBaseVm: async () => {},
_removeUnusedSnapshots: async () => calls.push('removeUnusedSnapshots'),
_removeSnapshotData: async () => calls.push('removeSnapshotData'),
_healthCheck: async () => calls.push('healthCheck'),
_snapshot: async function () {
this._exportedVm = { $ref: 'snapshot-ref', is_a_snapshot: true }
},
// a transfer, aborted while it runs
_copy: () =>
new Promise((resolve, reject) => {
const signal = Task.abortSignal
signal.addEventListener('abort', () => reject(signal.reason), { once: true })
setImmediate(() => {
calls.push('abort')
vmTask.abort()
})
}),
})
await vmTask.run(() => assert.rejects(runner.run(), { name: 'AbortError' })).catch(() => {})
assert.deepEqual(calls, [
'block',
'removeUnusedSnapshots',
'abort',
'removeUnusedSnapshots',
'removeSnapshotData',
'unblock',
'afterBackup',
])
})
})
describe('_fetchJobSnapshots() diskless VM snapshot detection', () => {
const makeFetchRunner = ({ vmVbds, snapshotVbds }) => {
const jobSnapshot = {
$ref: 'snap-ref',
$snapshot_of: {},
$VBDs: snapshotVbds,
other_config: { [JOB_ID]: 'job-1', [VM_UUID]: 'vm-uuid', [DATETIME]: '20240101T00:00:00Z' },
}
return makeRunner({
_jobId: 'job-1',
_vm: { uuid: 'vm-uuid', $VBDs: vmVbds, $snapshots: [jobSnapshot] },
_xapi: { objects: { indexes: { type: { VDI: {} } } } },
})
}
const trackedSnapshotRefs = runner => runner._disklessJobSnapshotVms.map(({ $ref }) => $ref)
it('tracks VM snapshots of a VM with only an empty CD drive', async () => {
const cdDrive = { type: 'CD', VDI: 'OpaqueRef:NULL' }
const runner = makeFetchRunner({ vmVbds: [cdDrive], snapshotVbds: [cdDrive] })
await runner._fetchJobSnapshots()
assert.deepEqual(trackedSnapshotRefs(runner), ['snap-ref'], 'a CD drive must not prevent the diskless retention')
})
it('tracks VM snapshots of a VM whose only disk is [NOBAK]', async () => {
// the ignored disk is on the VM, but not on its snapshot
const runner = makeFetchRunner({ vmVbds: [{ type: 'Disk', VDI: 'nobak-vdi-ref' }], snapshotVbds: [] })
await runner._fetchJobSnapshots()
assert.deepEqual(trackedSnapshotRefs(runner), ['snap-ref'], 'a snapshot without disk must be tracked at VM level')
})
it('does not use the diskless retention for a snapshot with a disk', async () => {
const runner = makeFetchRunner({
vmVbds: [{ type: 'Disk', VDI: 'vdi-ref' }],
snapshotVbds: [{ type: 'Disk', VDI: 'snapshot-vdi-ref' }],
})
await runner._fetchJobSnapshots()
assert.deepEqual(trackedSnapshotRefs(runner), [], 'this snapshot is handled through its VDIs')
})
it('does not use the diskless retention when a VBD of the snapshot is not in the cache', async () => {
const runner = makeFetchRunner({ vmVbds: [{ type: 'Disk', VDI: 'vdi-ref' }], snapshotVbds: [undefined] })
await runner._fetchJobSnapshots()
assert.deepEqual(trackedSnapshotRefs(runner), [], 'an unknown VBD may be a disk')
})
})
describe('_removeUnusedSnapshots() applies one retention across VDI-reached and diskless snapshots', () => {
// A VM that switched between "no backed up disk" and "at least one disk"
// has snapshots of both kinds: the retention must apply to their union, not
// keep `snapshotRetention` snapshots of each kind.
const OLD_DATETIME = '20240101T00:00:00Z'
const NEW_DATETIME = '20240102T00:00:00Z'
const makeSwitchedRunner = ({ oldIsDiskless }) => {
const destroyed = []
const disklessSnapshot = datetime => ({
$ref: 'vm-diskless',
other_config: { [DATETIME]: datetime, [SCHEDULE_ID]: 'schedule-1' },
})
const snapshotVm = { $ref: 'vm-with-disk', is_control_domain: false, $snapshot_of: 'live-vm-ref', other_config: {} }
const vdiSnapshot = datetime => ({
$ref: 'vdi-with-disk',
other_config: { [DATETIME]: datetime, [SCHEDULE_ID]: 'schedule-1' },
$VBDs: [{ $VM: snapshotVm }],
})
const vm = disklessSnapshot(oldIsDiskless ? OLD_DATETIME : NEW_DATETIME)
const vdi = vdiSnapshot(oldIsDiskless ? NEW_DATETIME : OLD_DATETIME)
const registry = { [vm.$ref]: vm, [vdi.$ref]: vdi }
const runner = makeRunner({
_vm: { uuid: 'live-uuid', $snapshots: [] },
_baseSettings: { snapshotRetention: 1 },
_jobSnapshotVdis: [vdi],
_disklessJobSnapshotVms: [vm],
job: { mode: 'full', settings: {} },
_xapi: {
barrier: async () => {},
getObject: ref => registry[ref],
VM_destroy: async ref => {
destroyed.push(ref)
},
VDI_destroy: async ref => {
destroyed.push(ref)
},
},
})
return { runner, destroyed }
}
it('removes the older diskless snapshot once a disk was added', async () => {
const { runner, destroyed } = makeSwitchedRunner({ oldIsDiskless: true })
await runner._removeUnusedSnapshots()
assert.deepEqual(destroyed, ['vm-diskless'], 'only the older, diskless, snapshot should be removed')
})
it('removes the older snapshot with a disk once the VM became diskless', async () => {
const { runner, destroyed } = makeSwitchedRunner({ oldIsDiskless: false })
await runner._removeUnusedSnapshots()
assert.deepEqual(destroyed, ['vm-with-disk'], 'only the older snapshot, reached through its VDI, should be removed')
})
})

View File

@@ -161,8 +161,24 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
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)
// `cleanup()` applies the retention once the backup has been written: an abort that arrives after the transfer
// has already ended the task, the retention then runs in a cleanup subtask, which the abort does not stop
const cleanupInTask = task.wrapInside(this.cleanup)
const cleanup = this.cleanup
this.cleanup = function () {
return task.status === 'pending'
? cleanupInTask.apply(this, arguments)
: Task.run({ properties: { name: 'retention' }, cleanup: true }, () => cleanup.apply(this, arguments))
}
// `afterBackup()` cleans the VM directory and releases its lock: it must run even when the task has already
// ended because the transfer failed or was aborted, outside of it then
const afterBackupInTask = task.wrap(this.afterBackup)
const afterBackup = this.afterBackup
this.afterBackup = function () {
return task.status === 'pending' ? afterBackupInTask.apply(this, arguments) : afterBackup.apply(this, arguments)
}
return this._prepare()
}
@@ -265,6 +281,8 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
}
let size = 0
await Task.run({ properties: { name: 'transfer' } }, async () => {
// stops the writes once the backup is aborted
const signal = Task.abortSignal
await asyncEach(
Object.entries(deltaExport.disks),
async ([diskRef, disk]) => {
@@ -285,6 +303,7 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
// no checksum for VHDs, because they will be invalidated by
// merges and chains
checksum: false,
signal,
validator: tmpPath => checkDisk(handler, tmpPath),
writeBlockConcurrency: this._config.writeBlockConcurrency,
uuid: packUuid(vdi.uuid),
@@ -300,6 +319,11 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
return { size }
})
// the metadata makes the backup restorable: it is not written for an aborted backup, whose disks are removed by
// the clean-vm of `afterBackup()`
Task.abortSignal?.throwIfAborted()
metadataContent.tags = await this.getLongTermRetentionTags(metadataContent)
metadataContent.size = size // @todo return exactly the size written by this writer
this._metadataFileName = await adapter.writeVmBackupMetadata(vm.uuid, metadataContent)

View File

@@ -0,0 +1,266 @@
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { Task } from '@vates/task'
import { IncrementalRemoteWriter } from './IncrementalRemoteWriter.mjs'
// a writer on a fake remote, whose transfer fails as an aborted transfer does
function createWriter() {
const calls = { cleanVm: 0, cleanVmOptions: [], deletedEntries: [], lockDisposed: false }
const writer = new IncrementalRemoteWriter({
adapter: {
deleteDeltaVmBackups: async backups => {
calls.deletedEntries.push(...backups.map(_ => _._filename))
},
handler: {
mktree: async () => {},
lock: async () => ({
dispose: async () => {
calls.lockDisposed = true
},
}),
},
cleanVm: async (vmDir, options) => {
++calls.cleanVm
calls.cleanVmOptions.push(options)
return {}
},
},
config: { disableMergeWorker: true },
job: { id: 'job', mode: 'delta' },
remoteId: 'remote',
schedule: { id: 'schedule' },
settings: {},
vmUuid: 'vm',
})
// what `prepare()` wraps in its "export" task
writer._prepare = async () => {
// the backups past the retention
writer._oldEntries = [{ _filename: 'old1.json' }, { _filename: 'old2.json' }]
}
writer.transfer = () =>
new Promise((resolve, reject) => {
const signal = Task.abortSignal
if (signal.aborted) {
reject(signal.reason)
} else {
signal.addEventListener('abort', () => reject(signal.reason), { once: true })
}
})
return { calls, writer }
}
// the steps of a VM backup for this writer, in the order `_AbstractXapi#run()` calls them
async function runSteps(writer, { abort, afterTransfer = () => {} }) {
const events = []
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress: event => events.push(event) })
let afterBackupError
await vmTask
.run(async () => {
await writer.beforeBackup()
try {
await writer.prepare({ isFull: true })
const pTransfer = writer.transfer()
abort(vmTask)
await pTransfer
afterTransfer(vmTask)
await writer.cleanup()
} finally {
// `$defer` of `_AbstractXapi#run()`
await writer.afterBackup().catch(error => {
afterBackupError = error
})
}
})
.catch(() => {})
return { afterBackupError, events }
}
describe('IncrementalRemoteWriter#afterBackup()', () => {
it('cleans the VM directory and releases the lock after a failed transfer', async () => {
const { calls, writer } = createWriter()
const { afterBackupError } = await runSteps(writer, {
// a transfer that fails for another reason than an abort
abort: vmTask => setImmediate(() => vmTask._abortController.abort(new Error('target unreachable'))),
})
assert.equal(afterBackupError, undefined)
assert.equal(calls.cleanVm, 2, 'clean-vm runs before and after the backup')
assert.equal(calls.lockDisposed, true)
})
it('cleans the VM directory and releases the lock after an abort, in a clean-vm subtask', async () => {
const { calls, writer } = createWriter()
const { afterBackupError, events } = await runSteps(writer, {
abort: vmTask => setImmediate(() => vmTask.abort()),
})
assert.equal(afterBackupError, undefined)
assert.equal(calls.cleanVm, 2, 'clean-vm runs before and after the backup')
assert.equal(calls.lockDisposed, true)
const cleanVmIds = events.filter(_ => _.type === 'start' && _.properties?.name === 'clean-vm').map(_ => _.id)
assert.equal(cleanVmIds.length, 2)
const lastCleanVmEnd = events.find(_ => _.type === 'end' && _.id === cleanVmIds[1])
assert.equal(lastCleanVmEnd.status, 'success')
})
it('releases the lock when the clean-vm after the backup fails', async () => {
const { calls, writer } = createWriter()
writer.transfer = async () => {}
const cleanVm = writer._cleanVm
writer._cleanVm = function (options) {
return options.cleanup ? Promise.reject(new Error('clean-vm failed')) : cleanVm.call(this, options)
}
const { afterBackupError } = await runSteps(writer, { abort: () => {} })
assert.equal(afterBackupError?.message, 'clean-vm failed')
assert.equal(calls.lockDisposed, true)
})
})
describe('IncrementalRemoteWriter clean-vm and abort', () => {
it('merges before and after the backup when it is not aborted', async () => {
const { calls, writer } = createWriter()
writer.transfer = async () => {}
await runSteps(writer, { abort: () => {} })
assert.deepEqual(
calls.cleanVmOptions.map(_ => _.merge),
[true, true]
)
})
it('still merges in the cleanup made after an abort, which is not stopped (level 1)', async () => {
const { calls, writer } = createWriter()
await runSteps(writer, { abort: vmTask => setImmediate(() => vmTask.abort()) })
assert.deepEqual(
calls.cleanVmOptions.map(_ => _.merge),
[true, true]
)
})
it('aborts the clean-vm made before the transfer with the backup', async () => {
const { calls, writer } = createWriter()
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
let signal
writer._adapter.cleanVm = async () => {
signal = Task.abortSignal
vmTask.abort()
++calls.cleanVm
return {}
}
await vmTask.run(() => writer.beforeBackup())
assert.equal(signal.aborted, true)
})
})
describe('IncrementalRemoteWriter#cleanup() and abort', () => {
it('applies the retention in the export task when the backup is not aborted', async () => {
const { calls, writer } = createWriter()
writer.transfer = async () => {}
const { events } = await runSteps(writer, { abort: () => {} })
assert.deepEqual(calls.deletedEntries, ['old2.json', 'old1.json'])
assert.equal(
events.some(_ => _.type === 'start' && _.properties?.name === 'retention'),
false,
'no retention subtask'
)
})
it('still applies the retention when the abort arrives after the transfer, in a retention subtask', async () => {
const { calls, writer } = createWriter()
writer.transfer = async () => {}
const { afterBackupError, events } = await runSteps(writer, {
abort: () => {},
afterTransfer: vmTask => vmTask.abort(),
})
assert.equal(afterBackupError, undefined)
assert.deepEqual(calls.deletedEntries, ['old2.json', 'old1.json'])
const retentionStart = events.find(_ => _.type === 'start' && _.properties?.name === 'retention')
assert.notEqual(retentionStart, undefined)
const retentionEnd = events.find(_ => _.type === 'end' && _.id === retentionStart.id)
assert.equal(retentionEnd.status, 'success')
})
it('does not apply the retention when the transfer is aborted', async () => {
const { calls, writer } = createWriter()
await runSteps(writer, { abort: vmTask => setImmediate(() => vmTask.abort()) })
assert.deepEqual(calls.deletedEntries, [])
})
})
describe('IncrementalRemoteWriter#transfer() after an abort', () => {
it('stops writing the disks and writes no metadata', async () => {
const writes = []
let metadataWritten = false
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
const writer = new IncrementalRemoteWriter({
adapter: {
getVhdFileName: basename => `${basename}.vhd`,
handler: { readFile: async () => Promise.reject(new Error('no such file')) },
listVmBackups: async () => [],
writeVhd: async (path, disk, { signal }) => {
if (signal?.aborted) {
throw signal.reason
}
writes.push(path)
// the backup is aborted once the first disk has been written
vmTask.abort()
return 1
},
writeVmBackupMetadata: async () => {
metadataWritten = true
},
},
config: {},
job: { id: 'job', mode: 'delta' },
remoteId: 'remote',
schedule: { id: 'schedule' },
settings: { diskPerVmConcurrency: 1 },
vmUuid: 'vm',
})
const disk = { close: async () => {} }
const deltaExport = {
disks: { vdi1: disk, vdi2: disk },
vbds: {},
vdis: { vdi1: { uuid: 'uuid1', $snapshot_of$uuid: 'src1' }, vdi2: { uuid: 'uuid2', $snapshot_of$uuid: 'src2' } },
vifs: {},
vm: { uuid: 'vm' },
vtpms: {},
}
await vmTask
.run(() =>
writer.transfer({
deltaExport,
isVhdDifferencing: { vdi1: false, vdi2: false },
timestamp: 0,
vm: { uuid: 'vm' },
vmSnapshot: {},
})
)
.catch(() => {})
assert.equal(writes.length, 1, 'the second disk is not written')
assert.equal(metadataWritten, false, 'no metadata is written for an aborted backup')
})
})

View File

@@ -327,11 +327,20 @@ export class IncrementalXapiWriter extends MixinXapiWriter(AbstractIncrementalWr
})
this._prepare = task.wrapInside(this._prepare)
this.transfer = task.wrapInside(this.transfer)
// `cleanup()` applies the retention once the backup has been written: an abort that arrives after the transfer
// has already ended the task, the retention then runs in a cleanup subtask, which the abort does not stop
let cleanupInTask
if (this._healthCheckSr !== undefined) {
this.cleanup = task.wrapInside(this.cleanup)
cleanupInTask = task.wrapInside(this.cleanup)
this.healthCheck = task.wrap(this.healthCheck)
} else {
this.cleanup = task.wrap(this.cleanup)
cleanupInTask = task.wrap(this.cleanup)
}
const cleanup = this.cleanup
this.cleanup = function () {
return task.status === 'pending'
? cleanupInTask.apply(this, arguments)
: Task.run({ properties: { name: 'retention' }, cleanup: true }, () => cleanup.apply(this, arguments))
}
return this._prepare(isFull)
@@ -504,6 +513,8 @@ export class IncrementalXapiWriter extends MixinXapiWriter(AbstractIncrementalWr
let targetVmRef
await Task.run({ properties: { name: 'transfer' } }, async () => {
targetVmRef = await importIncrementalVm(this.#decorateVmMetadata(deltaExport, timestamp), sr, {
// the import is stopped once the backup is aborted, and the VM and VDIs it created are destroyed
signal: Task.abortSignal,
targetRef: this._targetVmRef,
})
// this also ensure the data are up to date on the snapshot

View File

@@ -0,0 +1,83 @@
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { Task } from '@vates/task'
import { IncrementalXapiWriter } from './IncrementalXapiWriter.mjs'
// a writer whose retention is recorded instead of destroying the old replicas
function createWriter({ healthCheckSr } = {}) {
const calls = { deleteOldEntries: 0, deleteOrphanVdis: 0 }
const writer = new IncrementalXapiWriter({
config: {},
healthCheckSr,
job: { id: 'job' },
schedule: { id: 'schedule' },
settings: {},
sr: { name_label: 'sr', uuid: 'sr' },
vmUuid: 'vm',
})
// what `prepare()` wraps in its "export" task
writer._prepare = async () => {}
writer.transfer = async () => {}
writer._deleteOldEntries = async () => {
++calls.deleteOldEntries
}
writer._deleteOrphanVdis = async () => {
++calls.deleteOrphanVdis
}
return { calls, writer }
}
// the steps of a VM backup for this writer, in the order `IncrementalXapi#_copy()` calls them
async function runSteps(writer, { afterTransfer = () => {} } = {}) {
const events = []
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress: event => events.push(event) })
let cleanupError
await vmTask
.run(async () => {
await writer.prepare({ isFull: true })
await writer.transfer()
afterTransfer(vmTask)
await writer.cleanup().catch(error => {
cleanupError = error
})
})
.catch(() => {})
return { cleanupError, events }
}
const retentionTaskOf = events => events.find(_ => _.type === 'start' && _.properties?.name === 'retention')
for (const [label, healthCheckSr] of [
['without health check', undefined],
['with health check', { uuid: 'health-check-sr' }],
]) {
describe(`IncrementalXapiWriter#cleanup() and abort, ${label}`, () => {
it('applies the retention in the export task when the backup is not aborted', async () => {
const { calls, writer } = createWriter({ healthCheckSr })
const { cleanupError, events } = await runSteps(writer)
assert.equal(cleanupError, undefined)
assert.deepEqual(calls, { deleteOldEntries: 1, deleteOrphanVdis: 1 })
assert.equal(retentionTaskOf(events), undefined, 'no retention subtask')
})
it('still applies the retention when the abort arrives after the transfer, in a retention subtask', async () => {
const { calls, writer } = createWriter({ healthCheckSr })
const { cleanupError, events } = await runSteps(writer, { afterTransfer: vmTask => vmTask.abort() })
assert.equal(cleanupError, undefined)
assert.deepEqual(calls, { deleteOldEntries: 1, deleteOrphanVdis: 1 })
const retentionStart = retentionTaskOf(events)
assert.notEqual(retentionStart, undefined)
const retentionEnd = events.find(_ => _.type === 'end' && _.id === retentionStart.id)
assert.equal(retentionEnd.status, 'success')
})
})
}

View File

@@ -26,9 +26,12 @@ export const MixinRemoteWriter = (BaseClass = Object) =>
this._vmBackupDir = getVmBackupDir(rest.vmUuid)
}
async _cleanVm(options) {
// `cleanup`: the clean-vm is a cleanup subtask, it also runs after the backup has been aborted. Otherwise it is
// not started once the backup is aborted, but a merge already running is not interrupted: `cleanVm()` does not
// read the signal
async _cleanVm({ cleanup = false, ...options }) {
try {
return await Task.run({ properties: { name: 'clean-vm' } }, () => {
return await Task.run({ properties: { name: 'clean-vm' }, cleanup }, () => {
return this._adapter.cleanVm(this._vmBackupDir, {
...options,
logInfo: info,
@@ -72,8 +75,13 @@ export const MixinRemoteWriter = (BaseClass = Object) =>
const { handler } = this._adapter
const synchronousMerge = this._settings.mergeBackupsSynchronously
const willMergeInWorker = !synchronousMerge && !disableMergeWorker && typeof handler.getRealPath === 'function'
const { merge } = await this._cleanVm({ remove: true, merge: !willMergeInWorker })
await this.#lock.dispose()
let merge
try {
// part of the cleanup: it also runs after an abort, merge included (skipping it is a level 2 abort)
;({ merge } = await this._cleanVm({ cleanup: true, remove: true, merge: !willMergeInWorker }))
} finally {
await this.#lock.dispose()
}
if (merge && willMergeInWorker) {
const taskFile =

View File

@@ -48,13 +48,20 @@ export const MixinXapiWriter = (BaseClass = Object) =>
if (await this.#isAlreadyOnHealthCheckSr(baseVm)) {
healthCheckVmRef = await Task.run(
{ properties: { name: 'cloning-vm' } },
async () => await xapi.callAsync('VM.clone', this._targetVmRef, `Health Check - ${baseVm.name_label}`)
async () =>
await xapi.callAsync(
Task.abortSignal,
'VM.clone',
this._targetVmRef,
`Health Check - ${baseVm.name_label}`
)
)
} else {
healthCheckVmRef = await Task.run(
{ properties: { name: 'copying-vm' } },
async () =>
await xapi.callAsync(
Task.abortSignal,
'VM.copy',
this._targetVmRef,
`Health Check - ${baseVm.name_label}`,

View File

@@ -0,0 +1,43 @@
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import { Task } from '@vates/task'
import { FullXapiWriter } from './FullXapiWriter.mjs'
describe('MixinXapiWriter#healthCheck() after an abort', () => {
it('passes the abort signal to the copy of the replica', async () => {
const vmTask = new Task({ skipSubtasksAfterAbort: true, onProgress() {} })
const calls = []
const xapi = {
getObject: ref => ({ $ref: ref, $xapi: xapi, name_label: 'replica' }),
VM_getDisks: async () => [],
callAsync: async (...args) => {
calls.push(args)
// the backup is aborted while the replica is being copied
vmTask.abort()
throw new Error('stop after the copy call')
},
}
const writer = new FullXapiWriter({
config: {},
healthCheckSr: { $ref: 'OpaqueRef:health-check-sr', uuid: 'health-check-sr' },
job: { id: 'job' },
schedule: { id: 'schedule' },
settings: { healthCheckTimeout: '10m' },
sr: { $xapi: xapi, name_label: 'sr', uuid: 'sr' },
vmUuid: 'vm',
})
writer._targetVmRef = 'OpaqueRef:replica'
// the replica is not on the health check SR: it is copied there
xapi.VM_getDisks = async () => ['OpaqueRef:vdi']
xapi.getObject = ref =>
ref === 'OpaqueRef:vdi' ? { $SR: { uuid: 'sr' } } : { $ref: ref, $xapi: xapi, name_label: 'replica' }
await vmTask.run(() => assert.rejects(writer.healthCheck(), /stop after the copy call/)).catch(() => {})
const [[signal, method]] = calls
assert.ok(signal instanceof AbortSignal, 'the copy gets a signal')
assert.equal(signal.aborted, true, 'the copy gets the abort signal of the backup')
assert.equal(method, 'VM.copy')
})
})

View File

@@ -13,6 +13,7 @@
- [Of created VMs](#of-created-vms-and-their-associated-vdis)
- [Task logs](#task-logs)
- [During backup](#during-backup)
- [Aborted backup](#aborted-backup)
- [During restoration](#during-restoration)
- [API](#api)
- [Run description object](#run-description-object)
@@ -240,6 +241,41 @@ job.start(data: { mode: Mode, reportWhen: ReportWhen })
└─ job.end
```
### Aborted backup
When the backup runs in the xo-server process (`backups.disableWorkers`), it can be aborted from its task. The abort is
always an `AbortError`, and it changes the task log above as follows:
```
job.start(data: { mode: Mode, reportWhen: ReportWhen })
├─ task.info(message: 'abort requested', data: { type: 'abortRequested', userId: string }) // when requested by a user
├─ task.abortionRequested(reason: AbortError)
├─ task.start(data: { type: 'VM', id: string, name_label?: string }) // VM being backed up
│ ├─ task.abortionRequested(reason: AbortError)
│ ├─ task.start(message: 'export', data: { … })
│ │ ├─ task.start(message: 'transfer')
│ │ │ └─ task.end(status: 'failure', result: AbortError) // the transfer stops
│ │ └─ task.end(status: 'failure', result: AbortError)
│ ├─ task.start(message: 'clean-vm') // cleanup subtask, still run
│ │ └─ task.end
│ └─ task.end(status: 'failure', result: AbortError)
│ // no task for the VMs not started yet, no retry, no health check
└─ job.end(status: 'failure', result: AbortError)
```
- A step started as a subtask once the run is aborted fails right away, without running (the root task of the run
is created with `skipSubtasksAfterAbort: true` in `@vates/task`).
- The cleanup still runs: snapshot retention, removal of the snapshot data, restore of the VM's blocked operations,
and the writers' `afterBackup()`. `clean-vm` (and the merge it runs) is a cleanup subtask (`cleanup: true` in
`@vates/task`), which the abort does not stop.
- The metadata of an incremental backup is not written, so the aborted backup is never listed as restorable; its disks
are removed by `clean-vm`.
- The retention of the backups (or replicas) only applies once the new one has been written. When the abort arrives
after the transfer, the `export` task has already ended: the retention runs in a `retention` cleanup subtask of the VM
task, before `clean-vm`.
- In the backup logs and reports, a task that failed after an abort was requested on it (`abortionRequested`) has the
status `interrupted`, and does not make its parent `failure`.
### During restoration
```

View File

@@ -83,6 +83,7 @@ const main = Disposable.wrap(async function* main(args) {
handler.unlink(taskFile).catch(error => warn('deleting task failure', { error }))
} catch (error) {
warn('failure handling task', { error })
if (error.code === 'ELOCKED') await new Promise(resolve => setTimeout(resolve, 5 * 60e3))
}
},
{ concurrency }

View File

@@ -8,7 +8,7 @@
"type": "git",
"url": "https://github.com/vatesfr/xen-orchestra.git"
},
"version": "0.78.0",
"version": "1.0.1",
"engines": {
"node": ">=22.19"
},
@@ -24,20 +24,20 @@
"@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.3",
"@vates/disposable": "^0.1.7",
"@vates/fuse-vhd": "^2.1.4",
"@vates/generator-toolbox": "^1.1.3",
"@vates/nbd-client": "^3.7.0",
"@vates/nbd-client": "^3.7.2",
"@vates/parse-duration": "^0.1.1",
"@vates/task": "^0.7.0",
"@vates/types": "^2.5.0",
"@vates/types": "^3.2.0",
"@xen-orchestra/async-map": "^0.1.5",
"@xen-orchestra/disk-transform": "^1.3.4",
"@xen-orchestra/fs": "^4.10.0",
"@xen-orchestra/log": "^0.7.2",
"@xen-orchestra/fs": "^4.11.0",
"@xen-orchestra/log": "^1.0.0",
"@xen-orchestra/qcow2": "^1.4.1",
"@xen-orchestra/template": "^0.1.1",
"@xen-orchestra/backup-archive": "^1.2.0",
"@xen-orchestra/backup-archive": "^1.2.1",
"app-conf": "^3.0.0",
"compare-versions": "^6.0.0",
"complex-matcher": "^1.1.1",
@@ -56,8 +56,8 @@
"tar": "^7.5.19",
"uuid": "^9.0.0",
"value-matcher": "^0.2.0",
"vhd-lib": "^4.17.0",
"xen-api": "^5.1.0",
"vhd-lib": "^4.17.1",
"xen-api": "^6.0.0",
"xo-common": "^0.11.0",
"xo-remote-parser": "^2.0.0",
"yazl": "^2.5.1"
@@ -70,7 +70,7 @@
"typescript": "^5.9.3"
},
"peerDependencies": {
"@xen-orchestra/xapi": "^9.1.0"
"@xen-orchestra/xapi": "^10.1.0"
},
"license": "AGPL-3.0-or-later",
"author": {

View File

@@ -1,7 +1,7 @@
{
"private": false,
"name": "@xen-orchestra/cr-seed-cli",
"version": "1.0.3",
"version": "1.0.4",
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/@xen-orchestra/cr-seed-cli",
"bugs": "https://github.com/vatesfr/xen-orchestra/issues",
"repository": {
@@ -18,7 +18,7 @@
"preferGlobal": true,
"dependencies": {
"golike-defer": "^0.5.1",
"xen-api": "^5.1.0"
"xen-api": "^6.0.0"
},
"scripts": {
"postversion": "npm publish"

View File

@@ -1,7 +1,7 @@
{
"private": false,
"name": "@xen-orchestra/disk-cli",
"version": "2.2.5",
"version": "2.2.6",
"description": "CLI tool to inspect and manage disks in backup repositories",
"type": "module",
"bin": {
@@ -20,13 +20,13 @@
},
"dependencies": {
"@vates/async-each": "^1.0.3",
"@xen-orchestra/backups": "^0.78.0",
"@xen-orchestra/backup-archive": "^1.2.0",
"@xen-orchestra/backups": "^1.0.1",
"@xen-orchestra/backup-archive": "^1.2.1",
"@xen-orchestra/disk-transform": "^1.3.4",
"@xen-orchestra/fs": "^4.10.0",
"@xen-orchestra/fs": "^4.11.0",
"@xen-orchestra/qcow2": "^1.4.1",
"promise-toolbox": "^0.21.0",
"vhd-lib": "^4.17.0"
"vhd-lib": "^4.17.1"
},
"devDependencies": {
"@types/node": "^22.3.0",

View File

@@ -1,7 +1,7 @@
{
"private": false,
"name": "@xen-orchestra/fs",
"version": "4.10.0",
"version": "4.11.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",
@@ -30,7 +30,7 @@
"@vates/coalesce-calls": "^0.1.0",
"@vates/decorate-with": "^2.1.0",
"@vates/read-chunk": "^1.2.1",
"@xen-orchestra/log": "^0.7.2",
"@xen-orchestra/log": "^1.0.0",
"bind-property-descriptor": "^2.0.0",
"decorator-synchronized": "^0.6.0",
"execa": "^5.0.0",

View File

@@ -16,14 +16,14 @@
"xo-immutable-remote": "./dist/protectRemotes.mjs"
},
"license": "AGPL-3.0-or-later",
"version": "3.0.9",
"version": "3.0.10",
"engines": {
"node": ">=20.0.0"
},
"dependencies": {
"@vates/async-each": "^1.0.3",
"@xen-orchestra/backups": "^0.78.0",
"@xen-orchestra/log": "^0.7.2",
"@xen-orchestra/backups": "^1.0.1",
"@xen-orchestra/log": "^1.0.0",
"app-conf": "^3.0.0",
"execa": "^5.0.0",
"ms": "^2.1.3"

View File

@@ -2,6 +2,11 @@
## **next**
- [VM/Network] Add possibility to delete a VIF (PR [#10726](https://github.com/vatesfr/xen-orchestra/pull/10726))
## **0.28.0** (2026/12/01)
- [VDIs] The used space of a VDI now includes its whole snapshot chain instead of only its last layer, which showed almost 0% for disks with snapshots. It is shown as a size, without usage bar or free space (PR [#10116](https://github.com/vatesfr/xen-orchestra/pull/10116))
- [Web-Core/UiCircleProgressBar] Add a brand accent and an option to hide the value (PR [#10849](https://github.com/vatesfr/xen-orchestra/pull/10849))
- [Tables] Cells fit on one line: long names are cut in the middle, extra tags go under "+N" and long texts end with "…" (PR [#10850](https://github.com/vatesfr/xen-orchestra/pull/10850))
- [Pages] The page header and tabs now stay in place on every page: dashboards, System tabs, consoles, tasks, settings and creation forms scroll under them instead of scrolling with them (PR [#10822](https://github.com/vatesfr/xen-orchestra/pull/10822))
@@ -16,6 +21,8 @@
- [Side panels] Fix the double scrollbar when the side panel content is taller than the screen: the page header now stays in place, and the list and the side panel each scroll on their own. All scrollbars are now thin, like the side panel one (PR [#10807](https://github.com/vatesfr/xen-orchestra/pull/10807))
- [Mobile] Searchable dropdown lists no longer overflow the screen (PR [#10854](https://github.com/vatesfr/xen-orchestra/pull/10854))
- [New/VM] Fix the storage table overflowing horizontally, which hid part of the delete button (PR [#10851](https://github.com/vatesfr/xen-orchestra/pull/10851))
- [New/VM] Fix template disk settings being applied to every disk of the new VM: each disk now keeps its own name, description and SR (PR [#10898](https://github.com/vatesfr/xen-orchestra/pull/10898))
- [VM/System] Display the default 4 MiB video RAM for HVM VMs that don't define it, as XO 6 does (PR [#10901](https://github.com/vatesfr/xen-orchestra/pull/10901))
## **0.27.0** (2026-10-29)

View File

@@ -1,6 +1,6 @@
{
"name": "@xen-orchestra/lite",
"version": "0.27.0",
"version": "0.28.0",
"type": "module",
"scripts": {
"dev": "GIT_HEAD=$(git rev-parse HEAD) vite",
@@ -27,13 +27,13 @@
"@types/file-saver": "^2.0.7",
"@types/lodash-es": "^4.17.12",
"@types/node": "^18.19.80",
"@vates/types": "^2.5.0",
"@vates/types": "^3.2.0",
"@vitejs/plugin-vue": "^6.0.0",
"@vue/tsconfig": "^0.9.0",
"@vueuse/core": "^14.0.0",
"@vueuse/math": "^14.0.0",
"@vueuse/shared": "^14.0.0",
"@xen-orchestra/web-core": "^0.65.0",
"@xen-orchestra/web-core": "^0.67.0",
"complex-matcher": "^1.1.1",
"d3-time-format": "^4.1.0",
"decorator-synchronized": "^0.6.0",

View File

@@ -42,7 +42,7 @@ const progress = computed(() => {
.progress-circle-fill {
animation: progress 1s ease-out forwards;
fill: none;
stroke: var(--color-success-item-base);
stroke: var(--color-success-data);
stroke-width: 1.2;
stroke-linecap: round;
stroke-dasharray: v-bind(progress), 100;

View File

@@ -68,11 +68,11 @@ const hasError = computed(() => hostStoreHasError.value || vmStoreHasError.value
<style lang="postcss" scoped>
.progress-item {
--progress-bar-height: 1.2rem;
--progress-bar-color: var(--color-brand-item-base);
--progress-bar-color: var(--color-brand-data);
--progress-bar-background-color: var(--color-neutral-background-disabled);
&.warning {
--progress-bar-color: var(--color-warning-item-base);
--progress-bar-color: var(--color-warning-data);
--footer-value-color: var(--color-warning-item-base);
}

View File

@@ -56,7 +56,7 @@ const inactive = computed(() => props.total - props.active)
width: 1.3rem;
height: 1.3rem;
border-radius: 0.65rem;
background-color: var(--color-success-item-base);
background-color: var(--color-success-data);
&.inactive {
background-color: var(--color-neutral-background-disabled);

View File

@@ -143,7 +143,7 @@ const state = useTableState({
})
const { HeadCells, BodyCells } = useVmColumns({
exclude: ['actions', 'checkbox'],
exclude: ['actions', 'checkbox', 'lastBackupDate'],
body: (vm: XenApiVm) => {
const guestMetrics = computed(() => getGuestMetrics(vm.guest_metrics))
const vmMetrics = computed(() => getVmMetrics(vm.metrics))

View File

@@ -57,6 +57,7 @@
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import { getHostIcon } from '@/modules/host/utils/host.util.ts'
import { useVmUtils } from '@/modules/vm/composables/vm-utils.composable.ts'
import { getVmDomainType } from '@/modules/vm/utils/vm.util.ts'
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
import { useVmGuestMetricsStore } from '@/stores/xen-api/vm-guest-metrics.store.ts'
@@ -133,16 +134,7 @@ const ram = computed(() => formatSizeRaw(vm.memory_dynamic_max, 0))
const osVersion = computed(() => guestMetrics.value?.os_version.name)
const domainType = computed(() => {
if (
vm.domain_type !== undefined && // XS < 7.5
vm.domain_type !== 'unspecified' // detection failed
) {
return vm.domain_type
}
return vm.HVM_boot_policy === '' ? 'pv' : 'hvm'
})
const domainType = computed(() => getVmDomainType(vm))
const virtualizationType = computed(() =>
domainType.value === 'hvm' && guestMetrics.value?.PV_drivers_detected ? 'pvhvm' : domainType.value

View File

@@ -10,8 +10,8 @@
</template>
</VtsTabularKeyValueRow>
<VtsTabularKeyValueRow :label="t('video-ram')">
<template v-if="vm.platform.videoram" #value>
{{ `${vm.platform.videoram} ${t('bytes:mi')}` }}
<template v-if="videoRam" #value>
{{ `${videoRam} ${t('bytes:mi')}` }}
</template>
</VtsTabularKeyValueRow>
</VtsTabularKeyValueList>
@@ -20,14 +20,18 @@
<script setup lang="ts">
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import { getVmDomainType } from '@/modules/vm/utils/vm.util.ts'
import VtsStatus from '@core/components/status/VtsStatus.vue'
import VtsTabularKeyValueList from '@core/components/tabular-key-value-list/VtsTabularKeyValueList.vue'
import VtsTabularKeyValueRow from '@core/components/tabular-key-value-row/VtsTabularKeyValueRow.vue'
import UiCard from '@core/components/ui/card/UiCard.vue'
import UiTitle from '@core/components/ui/title/UiTitle.vue'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
defineProps<{ vm: XenApiVm }>()
const { vm } = defineProps<{ vm: XenApiVm }>()
const { t } = useI18n()
const videoRam = computed(() => (getVmDomainType(vm) === 'hvm' ? Number(vm.platform.videoram ?? 4) : undefined))
</script>

View File

@@ -35,6 +35,7 @@
<script setup lang="ts">
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import { getVmDomainType } from '@/modules/vm/utils/vm.util.ts'
import { useHostStore } from '@/stores/xen-api/host.store.ts'
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
import { useVtpmStore } from '@/stores/xen-api/vtpm.store.ts'
@@ -55,16 +56,7 @@ const { pool } = usePoolStore().subscribe()
const { getByOpaqueRef: getHostOpaqueRef } = useHostStore().subscribe()
const { getByOpaqueRef: getVtpmOpaqueRef } = useVtpmStore().subscribe()
/**
* @see `packages/xo-server/src/xapi/utils.mjs`:57
**/
const virtualizationMode = computed(() =>
vm.domain_type !== undefined && vm.domain_type !== 'unspecified'
? vm.domain_type
: vm.HVM_boot_policy === ''
? 'pv'
: 'hvm'
)
const virtualizationMode = computed(() => getVmDomainType(vm))
const isNestedVirtualizationEnabled = computed(() => {
const poolMaster = pool.value !== undefined ? getHostOpaqueRef(pool.value.master) : undefined

View File

@@ -24,6 +24,7 @@
<script lang="ts" setup>
import type { XenApiVbd, XenApiVdi } from '@/libs/xen-api/xen-api.types.ts'
import { getVdiFormat, getVdiIcon } from '@/modules/vdi/utils/vdi.util.ts'
import { useVdiStore } from '@/stores/xen-api/vdi.store.ts'
import VtsRow from '@core/components/table/VtsRow.vue'
import VtsTable from '@core/components/table/VtsTable.vue'
import UiQuerySearchBar from '@core/components/ui/query-search-bar/UiQuerySearchBar.vue'
@@ -43,6 +44,7 @@ const { vdis, vbds, busy, error } = defineProps<{
error?: boolean
}>()
const { t } = useI18n()
const { getChainPhysicalUsage } = useVdiStore().subscribe()
const selectedVdiId = useRouteQuery('id')
const { items: filteredVdis, searchBindings } = useSearchFilter(() => vdis)
const state = useTableState({
@@ -56,6 +58,7 @@ const { HeadCells, BodyCells } = useVdiColumns({
exclude: ['actions'],
body: (vdi: XenApiVdi) => {
const vdiVbds = computed(() => vbds.filter(vbd => vbd.VDI === vdi.$ref))
const usedSpace = computed(() => formatSizeRaw(getChainPhysicalUsage(vdi), 2))
const size = computed(() => formatSizeRaw(vdi.virtual_size, 2))
const format = computed(() => getVdiFormat(vdi.sm_config['image-format']))
return {
@@ -65,7 +68,7 @@ const { HeadCells, BodyCells } = useVdiColumns({
icon: getVdiIcon(vdiVbds.value),
}),
description: r => r(vdi.name_description),
usedSpace: r => r(vdi.physical_utilisation, vdi.virtual_size),
usedSpace: r => r(usedSpace.value.value, usedSpace.value.prefix),
size: r => r(size.value.value, size.value.prefix),
format: r => r(format.value),
selectItem: r => r(() => (selectedVdiId.value = vdi.uuid)),

View File

@@ -1,12 +1,48 @@
<template>
<VtsSpaceCard :used="vdi.physical_utilisation" :total="vdi.virtual_size" :label="vdi.name_label" />
<UiPanelCard>
<UiPanelCardTitle size="medium" :label="t('space')" />
<VtsCardRowList>
<VtsCardRowKeyValue>
<template #key>{{ t('used-space') }}</template>
<template #value>{{ usedSpace }}</template>
<template v-if="chainPhysicalUsage > 0" #addons>
<VtsCopyButton :value="usedSpace" />
</template>
</VtsCardRowKeyValue>
<VtsCardRowKeyValue>
<template #key>{{ t('size') }}</template>
<template #value>{{ size }}</template>
<template v-if="vdi.virtual_size > 0" #addons>
<VtsCopyButton :value="size" />
</template>
</VtsCardRowKeyValue>
</VtsCardRowList>
</UiPanelCard>
</template>
<script setup lang="ts">
import type { XenApiVdi } from '@/libs/xen-api/xen-api.types.ts'
import VtsSpaceCard from '@core/components/space-card/VtsSpaceCard.vue'
import { useVdiStore } from '@/stores/xen-api/vdi.store.ts'
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
import VtsCardRowList from '@core/components/card/VtsCardRowList.vue'
import VtsCopyButton from '@core/components/copy-button/VtsCopyButton.vue'
import UiPanelCard from '@core/components/ui/panel-card/UiPanelCard.vue'
import UiPanelCardTitle from '@core/components/ui/panel-card-title/UiPanelCardTitle.vue'
import { formatSize } from '@core/utils/size.util.ts'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
defineProps<{
const { vdi } = defineProps<{
vdi: XenApiVdi
}>()
const { t } = useI18n()
const { getChainPhysicalUsage } = useVdiStore().subscribe()
const chainPhysicalUsage = computed(() => getChainPhysicalUsage(vdi))
const usedSpace = computed(() => formatSize(chainPhysicalUsage.value, 2))
const size = computed(() => formatSize(vdi.virtual_size, 2))
</script>

View File

@@ -25,6 +25,7 @@
<script lang="ts" setup>
import type { XenApiNetwork, XenApiVif, XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import { useVifConnection } from '@/modules/vif/composables/use-vif-connection.composable.ts'
import { useVifDelete } from '@/modules/vif/composables/use-vif-delete.composable.ts'
import { useVifEdit } from '@/modules/vif/composables/use-vif-edit.composable.ts'
import { useNetworkStore } from '@/stores/xen-api/network.store.ts'
import { useVifStore } from '@/stores/xen-api/vif.store.ts'
@@ -106,6 +107,8 @@ const { HeadCells, BodyCells } = useVifColumns({
vm: () => vm,
})
const { deleteVifs, canDeleteVifs, isDeletingVifs, deleteVifsErrorMessage } = useVifDelete(() => [vif])
const connectionAction = useMapper(
() => (vif.currently_attached ? CONNECTION_ACTION.DISCONNECT : CONNECTION_ACTION.CONNECT),
() => ({
@@ -143,6 +146,15 @@ const { HeadCells, BodyCells } = useVifColumns({
actions: [
{ label: t('action:edit'), icon: 'action:edit', onClick: () => goToVifEdit(vif) } satisfies ActionItem,
connectionAction.value,
{
label: t('action:delete'),
icon: 'action:delete',
onClick: () => deleteVifs(),
disabled: !canDeleteVifs.value,
busy: isDeletingVifs.value,
hint: canDeleteVifs.value ? undefined : deleteVifsErrorMessage.value,
accent: 'danger',
} satisfies ActionItem,
],
}),
}

View File

@@ -0,0 +1,20 @@
<template>
<VtsDeleteButton
:hint="deleteVifsErrorMessage"
:disabled="!canDeleteVifs"
:busy="isDeletingVifs"
@click="deleteVifs()"
/>
</template>
<script lang="ts" setup>
import type { XenApiVif } from '@/libs/xen-api/xen-api.types.ts'
import { useVifDelete } from '@/modules/vif/composables/use-vif-delete.composable.ts'
import VtsDeleteButton from '@core/components/delete-button/VtsDeleteButton.vue'
const { vif } = defineProps<{
vif: XenApiVif
}>()
const { deleteVifs, canDeleteVifs, isDeletingVifs, deleteVifsErrorMessage } = useVifDelete(() => [vif])
</script>

View File

@@ -3,6 +3,7 @@
<template v-if="vif" #actions>
<VifEditButton :vif />
<VifConnectionToggleButton v-if="vm" :vif :vm />
<VifDeleteButton :vif />
</template>
<template v-if="vif" #default>
<!-- VIF -->
@@ -110,6 +111,7 @@
<script setup lang="ts">
import type { XenApiVif } from '@/libs/xen-api/xen-api.types.ts'
import VifConnectionToggleButton from '@/modules/vif/components/actions/connection/VifConnectionToggleButton.vue'
import VifDeleteButton from '@/modules/vif/components/actions/delete/VifDeleteButton.vue'
import VifEditButton from '@/modules/vif/components/actions/edit/VifEditButton.vue'
import { isTxChecksummingEnabled } from '@/modules/vif/utils/vif-tx-checksumming.util.ts'
import { useNetworkStore } from '@/stores/xen-api/network.store.ts'

View File

@@ -0,0 +1,51 @@
import type { XenApiVif } from '@/libs/xen-api/xen-api.types.ts'
import { useVifDeleteJob } from '@/modules/vif/jobs/vif-delete.job.ts'
import { useDeleteModal } from '@core/composables/modals/use-delete-modal.ts'
import { useRouteQuery } from '@core/composables/route-query.composable.ts'
import { toComputed } from '@core/utils/to-computed.util.ts'
import type { MaybeRefOrGetter } from 'vue'
import { useI18n } from 'vue-i18n'
export function useVifDelete(rawVifs: MaybeRefOrGetter<XenApiVif[]>) {
const vifs = toComputed(rawVifs)
const { t } = useI18n()
const selectedVifId = useRouteQuery('id')
const {
run,
canRun: canDeleteVifs,
isRunning: isDeletingVifs,
errorMessage: deleteVifsErrorMessage,
} = useVifDeleteJob(vifs)
const { open } = useDeleteModal()
function deleteVifs() {
const count = vifs.value.length
return open({
props: {
subject: t('n-vifs', { n: count }),
confirmLabel: t('action:delete-n-vifs', { n: count }),
},
events: {
onConfirm: () => {
const isSelectedVifDeleted = vifs.value.some(vif => vif.uuid === selectedVifId.value)
run({
detached: true,
onSuccess: () => {
if (isSelectedVifDeleted) {
selectedVifId.value = ''
}
},
})
},
},
})
}
return { deleteVifs, canDeleteVifs, isDeletingVifs, deleteVifsErrorMessage }
}

View File

@@ -0,0 +1,37 @@
import { vifsArg } from '@/modules/vif/jobs/vif-args.ts'
import { useXenApiStore } from '@/stores/xen-api.store.ts'
import { defineJob, JobError, JobRunningError } from '@core/packages/job'
import { useI18n } from 'vue-i18n'
export const useVifDeleteJob = defineJob('vif.delete', [vifsArg], () => {
const xapi = useXenApiStore().getXapi()
const { t } = useI18n()
return {
async run(vifs) {
const results = await Promise.allSettled(vifs.map(vif => xapi.vif.delete(vif.$ref)))
results.forEach((result, index) => {
if (result.status === 'rejected') {
console.error(`Failed to delete VIF ${vifs[index].uuid}:`, result.reason)
}
})
return results
},
validate: (isRunning, vifs) => {
if (vifs.length === 0) {
throw new JobError(t('job:vif-delete:missing-vif'))
}
if (isRunning) {
throw new JobRunningError(t('job:delete:in-progress'))
}
if (vifs.some(vif => vif.currently_attached)) {
throw new JobError(t('vif-connected'))
}
},
}
})

View File

@@ -43,6 +43,20 @@ export function areVmToolsDetected(guestMetrics: XenApiVmGuestMetrics | undefine
return managementAgentDetected && pvDriversDetected
}
/**
* @see `packages/xo-server/src/xapi/utils.mjs`:57
**/
export function getVmDomainType(vm: XenApiVm) {
if (
vm.domain_type !== undefined && // XS < 7.5
vm.domain_type !== 'unspecified' // detection failed
) {
return vm.domain_type
}
return vm.HVM_boot_policy === '' ? 'pv' : 'hvm'
}
export type VmPowerStateAction =
| 'start'
| 'pause'

View File

@@ -512,6 +512,7 @@ const getExistingVdis = (template: XenApiVm) => {
acc.push({
id: vdi.$ref,
userdevice: vbd.userdevice,
name_label: vdi.name_label,
name_description: vdi.name_description,
size: bytesToGiB(vdi.virtual_size),
@@ -698,6 +699,7 @@ const _createVm = defer(async ($defer: Defer) => {
const vdiRef = await xapi.getField<XenApiVdi['$ref']>('VBD', vbdRef, 'VDI')
const type = await xapi.getField<VBD_TYPE>('VBD', vbdRef, 'type')
const bootable = await xapi.getField<boolean>('VBD', vbdRef, 'bootable')
const userdevice = await xapi.getField<XenApiVbd['userdevice']>('VBD', vbdRef, 'userdevice')
if (!hasBootableDisk) {
hasBootableDisk = bootable
@@ -707,45 +709,49 @@ const _createVm = defer(async ($defer: Defer) => {
continue
}
for (const vdi of existingVdis) {
const srRef = await xapi.getField<XenApiSr['$ref']>('VDI', vdiRef, 'SR')
const vbdRefs = await xapi.getField<XenApiVbd['$ref'][]>('VDI', vdiRef, 'VBDs')
const vdi = existingVdis.find(vdi => vdi.userdevice === userdevice)
await xapi.vdi.setNameLabel(vdiRef, vdi.name_label)
await xapi.vdi.setNameDescription(vdiRef, vdi.name_description)
if (vdi === undefined) {
continue
}
// EDIT SR: Migrate VDI or create new one
if (vdi.SR !== srRef) {
try {
await xapi.vdi.poolMigrate(vdiRef, vdi.SR)
} catch (error) {
if (!(error instanceof Error)) {
throw error
}
const srRef = await xapi.getField<XenApiSr['$ref']>('VDI', vdiRef, 'SR')
const vbdRefs = await xapi.getField<XenApiVbd['$ref'][]>('VDI', vdiRef, 'VBDs')
const { message } = error
await xapi.vdi.setNameLabel(vdiRef, vdi.name_label)
await xapi.vdi.setNameDescription(vdiRef, vdi.name_description)
if (
message !== 'NO_HOSTS_AVAILABLE' &&
message !== 'LICENCE_RESTRICTION' &&
message !== 'VDI_NEEDS_VM_FOR_MIGRATE'
) {
throw error
}
const newVdiRef = await xapi.vdi.copy(vdiRef, vdi.SR)
if (vbdRefs) {
for (const vbdRef of vbdRefs) {
const vbd = await xapi.getField<XenApiVbd>('VBD', vbdRef, 'record')
await xapi.vbd.delete(vbdRef)
await xapi.vbd.create({ ...vbd, vmRefs, vdiRef: newVdiRef[0] })
}
}
await xapi.vdi.delete(vdiRef)
// EDIT SR: Migrate VDI or create new one
if (vdi.SR !== srRef) {
try {
await xapi.vdi.poolMigrate(vdiRef, vdi.SR)
} catch (error) {
if (!(error instanceof Error)) {
throw error
}
const { message } = error
if (
message !== 'NO_HOSTS_AVAILABLE' &&
message !== 'LICENCE_RESTRICTION' &&
message !== 'VDI_NEEDS_VM_FOR_MIGRATE'
) {
throw error
}
const newVdiRef = await xapi.vdi.copy(vdiRef, vdi.SR)
if (vbdRefs) {
for (const vbdRef of vbdRefs) {
const vbd = await xapi.getField<XenApiVbd>('VBD', vbdRef, 'record')
await xapi.vbd.delete(vbdRef)
await xapi.vbd.create({ ...vbd, vmRefs, vdiRef: newVdiRef[0] })
}
}
await xapi.vdi.delete(vdiRef)
}
}
}

View File

@@ -653,6 +653,13 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/task/vts-task-list': RouteRecordInfo<
'/story/web-core/task/vts-task-list',
'/story/web-core/task/vts-task-list',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/tree/vts-tree-item': RouteRecordInfo<
'/story/web-core/tree/vts-tree-item',
'/story/web-core/tree/vts-tree-item',
@@ -884,6 +891,13 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/ui/group-subcategory/ui-group-subcategory': RouteRecordInfo<
'/story/web-core/ui/group-subcategory/ui-group-subcategory',
'/story/web-core/ui/group-subcategory/ui-group-subcategory',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/ui/head-bar/ui-head-bar': RouteRecordInfo<
'/story/web-core/ui/head-bar/ui-head-bar',
'/story/web-core/ui/head-bar/ui-head-bar',
@@ -891,6 +905,13 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/ui/image-radio-button/ui-image-radio-button': RouteRecordInfo<
'/story/web-core/ui/image-radio-button/ui-image-radio-button',
'/story/web-core/ui/image-radio-button/ui-image-radio-button',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/ui/info/ui-info': RouteRecordInfo<
'/story/web-core/ui/info/ui-info',
'/story/web-core/ui/info/ui-info',
@@ -1045,6 +1066,20 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/ui/rich-checkbox/ui-rich-checkbox': RouteRecordInfo<
'/story/web-core/ui/rich-checkbox/ui-rich-checkbox',
'/story/web-core/ui/rich-checkbox/ui-rich-checkbox',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/ui/rich-checkbox-group/ui-rich-checkbox-group': RouteRecordInfo<
'/story/web-core/ui/rich-checkbox-group/ui-rich-checkbox-group',
'/story/web-core/ui/rich-checkbox-group/ui-rich-checkbox-group',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/ui/rich-radio-button/ui-rich-radio-button': RouteRecordInfo<
'/story/web-core/ui/rich-radio-button/ui-rich-radio-button',
'/story/web-core/ui/rich-radio-button/ui-rich-radio-button',
@@ -1052,6 +1087,13 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/ui/rich-radio-button-group/ui-rich-radio-button-group': RouteRecordInfo<
'/story/web-core/ui/rich-radio-button-group/ui-rich-radio-button-group',
'/story/web-core/ui/rich-radio-button-group/ui-rich-radio-button-group',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/ui/stacked-bar/ui-stacked-bar': RouteRecordInfo<
'/story/web-core/ui/stacked-bar/ui-stacked-bar',
'/story/web-core/ui/stacked-bar/ui-stacked-bar',
@@ -1108,6 +1150,13 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/ui/tag/ui-label-value-tag': RouteRecordInfo<
'/story/web-core/ui/tag/ui-label-value-tag',
'/story/web-core/ui/tag/ui-label-value-tag',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/ui/tag/ui-tag': RouteRecordInfo<
'/story/web-core/ui/tag/ui-tag',
'/story/web-core/ui/tag/ui-tag',
@@ -1122,13 +1171,6 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/ui/tag/ui-tertiary-tag': RouteRecordInfo<
'/story/web-core/ui/tag/ui-tertiary-tag',
'/story/web-core/ui/tag/ui-tertiary-tag',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/ui/task-item/ui-task-item': RouteRecordInfo<
'/story/web-core/ui/task-item/ui-task-item',
'/story/web-core/ui/task-item/ui-task-item',
@@ -1136,13 +1178,6 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/ui/task-list/ui-task-list': RouteRecordInfo<
'/story/web-core/ui/task-list/ui-task-list',
'/story/web-core/ui/task-list/ui-task-list',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/ui/title/ui-title': RouteRecordInfo<
'/story/web-core/ui/title/ui-title',
'/story/web-core/ui/title/ui-title',
@@ -1834,6 +1869,12 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/stories/web-core/task/vts-task-list.story.vue': {
routes:
| '/story/web-core/task/vts-task-list'
views:
| never
}
'src/stories/web-core/tree/vts-tree-item.story.vue': {
routes:
| '/story/web-core/tree/vts-tree-item'
@@ -2032,12 +2073,24 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/stories/web-core/ui/group-subcategory/ui-group-subcategory.story.vue': {
routes:
| '/story/web-core/ui/group-subcategory/ui-group-subcategory'
views:
| never
}
'src/stories/web-core/ui/head-bar/ui-head-bar.story.vue': {
routes:
| '/story/web-core/ui/head-bar/ui-head-bar'
views:
| never
}
'src/stories/web-core/ui/image-radio-button/ui-image-radio-button.story.vue': {
routes:
| '/story/web-core/ui/image-radio-button/ui-image-radio-button'
views:
| never
}
'src/stories/web-core/ui/info/ui-info.story.vue': {
routes:
| '/story/web-core/ui/info/ui-info'
@@ -2170,12 +2223,30 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/stories/web-core/ui/rich-checkbox/ui-rich-checkbox.story.vue': {
routes:
| '/story/web-core/ui/rich-checkbox/ui-rich-checkbox'
views:
| never
}
'src/stories/web-core/ui/rich-checkbox-group/ui-rich-checkbox-group.story.vue': {
routes:
| '/story/web-core/ui/rich-checkbox-group/ui-rich-checkbox-group'
views:
| never
}
'src/stories/web-core/ui/rich-radio-button/ui-rich-radio-button.story.vue': {
routes:
| '/story/web-core/ui/rich-radio-button/ui-rich-radio-button'
views:
| never
}
'src/stories/web-core/ui/rich-radio-button-group/ui-rich-radio-button-group.story.vue': {
routes:
| '/story/web-core/ui/rich-radio-button-group/ui-rich-radio-button-group'
views:
| never
}
'src/stories/web-core/ui/stacked-bar/ui-stacked-bar.story.vue': {
routes:
| '/story/web-core/ui/stacked-bar/ui-stacked-bar'
@@ -2224,6 +2295,12 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/stories/web-core/ui/tag/ui-label-value-tag.story.vue': {
routes:
| '/story/web-core/ui/tag/ui-label-value-tag'
views:
| never
}
'src/stories/web-core/ui/tag/ui-tag.story.vue': {
routes:
| '/story/web-core/ui/tag/ui-tag'
@@ -2236,24 +2313,12 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/stories/web-core/ui/tag/ui-tertiary-tag.story.vue': {
routes:
| '/story/web-core/ui/tag/ui-tertiary-tag'
views:
| never
}
'src/stories/web-core/ui/task-item/ui-task-item.story.vue': {
routes:
| '/story/web-core/ui/task-item/ui-task-item'
views:
| never
}
'src/stories/web-core/ui/task-list/ui-task-list.story.vue': {
routes:
| '/story/web-core/ui/task-list/ui-task-list'
views:
| never
}
'src/stories/web-core/ui/title/ui-title.story.vue': {
routes:
| '/story/web-core/ui/title/ui-title'

View File

@@ -1,9 +1,37 @@
import type { XenApiVdi } from '@/libs/xen-api/xen-api.types.ts'
import { createXapiStoreConfig } from '@/stores/xen-api/create-xapi-store-config.ts'
import { createSubscribableStoreContext } from '@core/utils/create-subscribable-store-context.util.ts'
import { defineStore } from 'pinia'
export const useVdiStore = defineStore('xen-api-vdi', () => {
const config = createXapiStoreConfig('vdi')
const { context: baseContext, ...configRest } = createXapiStoreConfig('vdi')
return createSubscribableStoreContext(config, {})
const getChainPhysicalUsage = (vdi: XenApiVdi) => {
if (vdi.is_a_snapshot || !vdi.managed) {
return vdi.physical_utilisation
}
let total = vdi.physical_utilisation
let parentUuid = vdi.sm_config['vhd-parent'] as XenApiVdi['uuid'] | undefined
while (parentUuid !== undefined) {
const parent = baseContext.getByUuid(parentUuid)
if (parent === undefined) {
break
}
total += parent.physical_utilisation
parentUuid = parent.sm_config['vhd-parent'] as XenApiVdi['uuid'] | undefined
}
return total
}
const context = {
...baseContext,
getChainPhysicalUsage,
}
return createSubscribableStoreContext({ context, ...configRest }, {})
})

View File

@@ -2,36 +2,32 @@
<ComponentStory
v-slot="{ properties }"
:params="[
prop('accent').required().enum('neutral', 'warning', 'danger').preset('neutral').widget(),
prop('options').required().arr('FormOption<TEntry, TValue>').widget().preset(options),
prop('selectedLabel').str(),
prop('required').bool().widget(),
prop('placeholder').str().widget().preset('Choose colors'),
prop('searchPlaceholder').str().widget().preset('Search colors'),
prop('loading').bool().widget(),
model('search'),
prop('accent').required().enum('neutral', 'success', 'warning', 'danger').preset('neutral').widget(),
prop('id').required().obj('FormSelectId').preset(id),
slot(),
]"
>
<VtsSelect v-bind="properties" v-model:search="searchTerm" :selected-label />
<VtsSelect v-bind="properties" />
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { model, prop, slot } from '@/libs/story/story-param.ts'
import { prop, slot } from '@/libs/story/story-param.ts'
import VtsSelect from '@core/components/select/VtsSelect.vue'
import { useFormSelect } from '@core/packages/form-select'
import { upperFirst } from 'lodash-es'
const colors = ['blue', 'yellow', 'red', 'green', 'orange', 'purple', 'white', 'grey', 'black']
const { options, searchTerm, selectedLabel } = useFormSelect(colors, {
properties: color => ({
value: color,
label: `${upperFirst(color)} color`,
disabled: color === 'blue' || color === 'orange' || color === 'black',
}),
const { id } = useFormSelect(colors, {
option: {
label: color => `${upperFirst(color)} color`,
disabled: color => color === 'blue' || color === 'orange' || color === 'black',
},
multiple: true,
searchable: true,
placeholder: 'Choose colors',
searchPlaceholder: 'Search colors',
})
</script>

View File

@@ -0,0 +1,33 @@
<template>
<ComponentStory
v-slot="{ properties }"
:params="[
prop('tasks').type('Task[]').required().preset(allTasks),
prop('selectedTaskId').str().widget(),
prop('showEyeIcon').bool().widget(),
prop('autoCollapseCompleted').bool().widget(),
prop('expandAll')
.bool()
.widget()
.help('Shows every task expanded; turning it off restores the tasks expanded before'),
prop('unreadTaskIds').type('ReadonlySet<string>').help('Shows an unread dot column, with a dot for these tasks'),
event('select').args({ id: 'string' }),
]"
:presets="{
'Unread tasks': {
props: {
unreadTaskIds: new Set(['1', '1-2', '4', '9', '9-2', '9-2-1']),
},
},
}"
>
<VtsTaskList v-bind="properties" />
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { event, prop } from '@/libs/story/story-param.ts'
import { allTasks } from '@/stories/web-core/ui/task-item/mock-tasks.ts'
import VtsTaskList from '@core/components/task/VtsTaskList.vue'
</script>

View File

@@ -3,6 +3,7 @@
v-slot="{ properties, settings }"
:params="[
prop('accent').type('CheckboxAccent').required().enum('brand', 'warning', 'danger').preset('brand').widget(),
prop('value').str().help('Used when the model is an array'),
prop('disabled').bool().widget(),
slot(),
slot('info'),
@@ -10,7 +11,7 @@
setting('defaultSlot').widget(text()).preset('Label'),
setting('info').widget(text()).preset('Lorem ipsum dolor sit amet, consectetur adipiscing elit.'),
setting('message').widget(text()).preset('Lorem ipsum dolor sit amet, consectetur adipiscing elit.'),
model().type('boolean').preset(undefined),
model().type('boolean | undefined | string[]').preset(undefined).help('undefined means partly checked'),
]"
>
<UiCheckbox v-bind="properties">

View File

@@ -0,0 +1,23 @@
<template>
<ComponentStory
v-slot="{ settings }"
:params="[
slot().help('Meant to receive the subcategory title'),
slot('info').help('Meant to receive a short text displayed on the right'),
setting('defaultSlot').widget(text()).preset('Into a pool'),
setting('info').widget(text()).preset('Writes to a pool'),
]"
>
<UiGroupSubcategory>
{{ settings.defaultSlot }}
<template v-if="settings.info" #info>{{ settings.info }}</template>
</UiGroupSubcategory>
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { setting, slot } from '@/libs/story/story-param.ts'
import { text } from '@/libs/story/story-widget.ts'
import UiGroupSubcategory from '@core/components/ui/group-subcategory/UiGroupSubcategory.vue'
</script>

View File

@@ -0,0 +1,39 @@
<template>
<ComponentStory
v-slot="{ properties, settings }"
:params="[
prop('accent').required().enum('brand', 'warning', 'danger').preset('brand').widget(),
prop('size').required().enum('small', 'medium').preset('medium').widget(),
prop('disabled').bool().widget(),
prop('src').required().str().help('Image URL for rich mode'),
prop('alt').required().str().help('Alt text for image'),
model().type('string').preset(''),
setting('defaultSlot').widget(text()).preset('Label'),
]"
>
<div class="radio">
<UiImageRadioButton v-model="selectedRadio" value="1" v-bind="properties" :src="imageUrl" :alt="properties.alt">
{{ settings.defaultSlot }}
</UiImageRadioButton>
</div>
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { model, prop, setting } from '@/libs/story/story-param.ts'
import { text } from '@/libs/story/story-widget.ts'
import UiImageRadioButton from '@core/components/ui/image-radio-button/UiImageRadioButton.vue'
import { ref } from 'vue'
import imageUrl from '../../../../assets/color-mode-dark.svg'
const selectedRadio = ref('')
</script>
<style lang="postcss" scoped>
.radio {
display: flex;
gap: 1.6rem;
flex-wrap: wrap;
}
</style>

View File

@@ -10,16 +10,16 @@
slot().help('Meant to receive a list of radio button components'),
slot('label').help('Meant to receive a label UiLabel component or another component'),
slot('info').help('Meant to receive a message info or UiInfo component or another component'),
setting('richRadioButton').widget(boolean()),
setting('imageRadioButton').widget(boolean()),
]"
>
<UiRadioButtonGroup v-bind="properties">
<component
:is="settings.richRadioButton === true ? UiRichRadioButton : UiRadioButton"
:is="settings.imageRadioButton === true ? UiImageRadioButton : UiRadioButton"
v-for="(label, index) in labels"
:key="index"
v-model="selectedRadio"
v-bind="richButtonProps(properties, settings.richRadioButton)"
v-bind="imageButtonProps(properties, settings.imageRadioButton)"
:value="`radio-${index}`"
>
{{ label }}
@@ -32,9 +32,9 @@
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { prop, setting, slot } from '@/libs/story/story-param.ts'
import { boolean } from '@/libs/story/story-widget.ts'
import UiImageRadioButton from '@core/components/ui/image-radio-button/UiImageRadioButton.vue'
import UiRadioButton from '@core/components/ui/radio-button/UiRadioButton.vue'
import UiRadioButtonGroup from '@core/components/ui/radio-button-group/UiRadioButtonGroup.vue'
import UiRichRadioButton from '@core/components/ui/rich-radio-button/UiRichRadioButton.vue'
import { ref } from 'vue'
import imageUrl from '../../../../assets/color-mode-dark.svg'
@@ -42,8 +42,8 @@ const selectedRadio = ref('')
const labels = ref(['Label 1', 'Label 2', 'Label 3'])
const richButtonProps = (properties: any, richRadioButton: boolean) => {
if (richRadioButton) {
const imageButtonProps = (properties: any, imageRadioButton: boolean) => {
if (imageRadioButton) {
return {
...properties,
src: imageUrl,

View File

@@ -0,0 +1,75 @@
<template>
<ComponentStory
v-slot="{ properties }"
:params="[
prop('accent').type('RichCheckboxAccent').required().enum('brand', 'warning', 'danger').preset('brand').widget(),
prop('label').str().widget().preset('Backup repositories'),
prop('info').str().widget(),
prop('message').str().widget().help('Only displayed when the accent is not brand'),
prop('vertical').bool().widget().preset(true),
slot().help('Meant to receive UiRichCheckbox components, and UiGroupSubcategory components in vertical mode'),
slot('label').help('Meant to receive a UiLabel component or another component'),
slot('info').help('Meant to receive a UiInfo component or another component'),
slot('message').help('Meant to receive a UiInfo component or another component'),
]"
>
<UiRichCheckboxGroup v-bind="properties">
<template v-for="category of properties.vertical ? categories : horizontalCategories" :key="category.title">
<UiGroupSubcategory v-if="properties.vertical">
{{ category.title }}
<template v-if="category.info" #info>{{ category.info }}</template>
</UiGroupSubcategory>
<UiRichCheckbox
v-for="option of category.options"
:key="option.value"
v-model="selectedRepositories"
:accent="properties.accent"
:value="option.value"
:tag="option.tag"
:description="option.description"
:disabled="option.disabled"
icon="fa:server"
>
{{ option.label }}
</UiRichCheckbox>
</template>
</UiRichCheckboxGroup>
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { prop, slot } from '@/libs/story/story-param.ts'
import UiGroupSubcategory from '@core/components/ui/group-subcategory/UiGroupSubcategory.vue'
import UiRichCheckbox from '@core/components/ui/rich-checkbox/UiRichCheckbox.vue'
import UiRichCheckboxGroup from '@core/components/ui/rich-checkbox-group/UiRichCheckboxGroup.vue'
import { ref } from 'vue'
type StoryOption = {
value: string
label: string
description: string
tag?: string
disabled?: boolean
}
const selectedRepositories = ref(['nfs-backups', 'smb-archive'])
const categories: { title: string; info?: string; options: StoryOption[] }[] = [
{
title: 'Category 1',
options: [
{ value: 'rd-s3', label: 'RD - S3', description: '3.1 TiB free', tag: 'Source' },
{ value: 'nfs-backups', label: 'NFS backups', description: '4.2 TiB free' },
{ value: 'local-backups', label: 'Local backups', description: '120 GiB free', disabled: true },
],
},
{
title: 'Category 2',
info: 'Info',
options: [{ value: 'smb-archive', label: 'SMB archive', description: '900 GiB free' }],
},
]
const horizontalCategories = categories.slice(0, 1)
</script>

View File

@@ -0,0 +1,41 @@
<template>
<ComponentStory
v-slot="{ properties, settings }"
:params="[
prop('accent').type('RichCheckboxAccent').required().enum('brand', 'warning', 'danger').preset('brand').widget(),
prop('value').str().help('Used when the model is an array'),
iconProp(),
prop('tag').str().widget().preset('Label'),
prop('description').str().widget().preset('Description'),
prop('info').str().widget(),
prop('message').str().widget().help('Only displayed when the accent is not brand'),
prop('disabled').bool().widget(),
model().type('boolean | undefined | string[]').preset(undefined).help('undefined means partly checked'),
slot().help('Meant to receive the label'),
slot('tag').help('Meant to receive a UiTag component, to use another accent than the default info one'),
slot('description'),
slot('info'),
slot('message'),
setting('defaultSlot').widget(text()).preset('Label'),
]"
>
<div class="checkbox">
<UiRichCheckbox v-bind="properties">
{{ settings.defaultSlot }}
</UiRichCheckbox>
</div>
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { iconProp, model, prop, setting, slot } from '@/libs/story/story-param.ts'
import { text } from '@/libs/story/story-widget.ts'
import UiRichCheckbox from '@core/components/ui/rich-checkbox/UiRichCheckbox.vue'
</script>
<style lang="postcss" scoped>
.checkbox {
max-width: 40rem;
}
</style>

View File

@@ -0,0 +1,125 @@
<template>
<ComponentStory
v-slot="{ properties }"
:params="[
prop('accent')
.type('RichRadioButtonAccent')
.required()
.enum('brand', 'warning', 'danger')
.preset('brand')
.widget(),
prop('label').str().widget().preset('Restore type'),
prop('info').str().widget(),
prop('message').str().widget().help('Only displayed when the accent is not brand'),
prop('vertical').bool().widget().preset(true),
slot().help('Meant to receive UiRichRadioButton components, and UiGroupSubcategory components in vertical mode'),
slot('label').help('Meant to receive a UiLabel component or another component'),
slot('info').help('Meant to receive a UiInfo component or another component'),
slot('message').help('Meant to receive a UiInfo component or another component'),
]"
>
<UiRichRadioButtonGroup v-bind="properties">
<template v-for="category of properties.vertical ? categories : horizontalCategories" :key="category.title">
<UiGroupSubcategory v-if="properties.vertical">
{{ category.title }}
<template #info>{{ category.info }}</template>
</UiGroupSubcategory>
<UiRichRadioButton
v-for="option of category.options"
:key="option.value"
v-model="selectedRadio"
:accent="properties.accent"
:value="option.value"
:icon="option.icon"
:description="option.description"
:disabled="option.disabled"
>
{{ option.label }}
<template v-if="option.tag" #tag>
<UiTag :accent="option.tag.accent" variant="secondary">{{ option.tag.label }}</UiTag>
</template>
</UiRichRadioButton>
</template>
</UiRichRadioButtonGroup>
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { prop, slot } from '@/libs/story/story-param.ts'
import type { IconName } from '@core/icons'
import UiGroupSubcategory from '@core/components/ui/group-subcategory/UiGroupSubcategory.vue'
import UiRichRadioButton from '@core/components/ui/rich-radio-button/UiRichRadioButton.vue'
import UiRichRadioButtonGroup from '@core/components/ui/rich-radio-button-group/UiRichRadioButtonGroup.vue'
import UiTag, { type TagAccent } from '@core/components/ui/tag/UiTag.vue'
import { ref } from 'vue'
type StoryOption = {
value: string
label: string
description: string
icon: IconName
tag?: { label: string; accent: TagAccent }
disabled?: boolean
}
const selectedRadio = ref('copy-then-start')
const categories: { title: string; info: string; options: StoryOption[] }[] = [
{
title: 'Into a pool',
info: 'Writes to a pool',
options: [
{
value: 'copy-then-start',
label: 'Copy, then start',
description:
'Copy the disks to a storage of the pool, then start the VM. When a snapshot of the VM is still in the pool, only the blocks that differ are transferred, if possible.',
icon: 'action:copy',
tag: { label: 'Default', accent: 'info' },
},
{
value: 'start-now',
label: 'Start now',
description: 'Start the VM right away from the backup. What it writes goes to a cache storage.',
icon: 'status:running',
tag: { label: 'Live restore', accent: 'neutral' },
},
{
value: 'attach-disk',
label: 'Attach a disk to a running VM',
description: 'Serve a disk of the backup, read-only, to an existing VM. Nothing is copied.',
icon: 'action:attach',
},
],
},
{
title: 'Out of the backup',
info: 'Nothing written to a pool',
options: [
{
value: 'download-files',
label: 'Download files',
description:
'Browse a partition of a disk and download individual files or folders. Best for a small amount of data.',
icon: 'action:download',
},
{
value: 'export-disk',
label: 'Export a disk',
description: 'Convert one disk to qcow2, vmdk, vhd or raw, then download it.',
icon: 'action:download',
},
{
value: 'export-vm',
label: 'Export the VM',
description: 'Build an XVA from the backup, to import into XCP-ng or XenServer.',
icon: 'action:download',
disabled: true,
},
],
},
]
const horizontalCategories = categories.slice(0, 1)
</script>

View File

@@ -2,17 +2,30 @@
<ComponentStory
v-slot="{ properties, settings }"
:params="[
prop('accent').required().enum('brand', 'warning', 'danger').preset('brand').widget(),
prop('size').required().enum('small', 'medium').preset('medium').widget(),
prop('accent')
.type('RichRadioButtonAccent')
.required()
.enum('brand', 'warning', 'danger')
.preset('brand')
.widget(),
iconProp(),
prop('tag').str().widget().preset('Label'),
prop('description').str().widget().preset('Description'),
prop('info').str().widget(),
prop('disabled').bool().widget(),
prop('src').required().str().help('Image URL for rich mode'),
prop('alt').required().str().help('Alt text for image'),
model().type('string').preset(''),
model().type('string'),
slot().help('Meant to receive the label'),
slot('tag').help('Meant to receive a UiTag component, to use another accent than the default info one'),
slot('description'),
slot('info'),
setting('defaultSlot').widget(text()).preset('Label'),
]"
>
<div class="radio">
<UiRichRadioButton v-model="selectedRadio" value="1" v-bind="properties" :src="imageUrl" :alt="properties.alt">
<div class="radios">
<UiRichRadioButton v-model="selectedRadio" v-bind="properties" value="1">
{{ settings.defaultSlot }}
</UiRichRadioButton>
<UiRichRadioButton v-model="selectedRadio" v-bind="properties" value="2">
{{ settings.defaultSlot }}
</UiRichRadioButton>
</div>
@@ -21,19 +34,19 @@
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { model, prop, setting } from '@/libs/story/story-param.ts'
import { iconProp, model, prop, setting, slot } from '@/libs/story/story-param.ts'
import { text } from '@/libs/story/story-widget.ts'
import UiRichRadioButton from '@core/components/ui/rich-radio-button/UiRichRadioButton.vue'
import { ref } from 'vue'
import imageUrl from '../../../../assets/color-mode-dark.svg'
const selectedRadio = ref('')
</script>
<style lang="postcss" scoped>
.radio {
.radios {
display: flex;
gap: 1.6rem;
flex-wrap: wrap;
flex-direction: column;
gap: 0.8rem;
max-width: 40rem;
}
</style>

View File

@@ -20,12 +20,15 @@
setting('maxWidth').widget(number()).help('Maximum width, in rem'),
]"
>
<UiTertiaryTag v-bind="properties" :style="{ maxWidth: settings.maxWidth ? `${settings.maxWidth}rem` : undefined }">
<UiLabelValueTag
v-bind="properties"
:style="{ maxWidth: settings.maxWidth ? `${settings.maxWidth}rem` : undefined }"
>
{{ settings.slot }}
<template #term>
{{ settings.term }}
</template>
</UiTertiaryTag>
</UiLabelValueTag>
</ComponentStory>
</template>
@@ -33,5 +36,5 @@
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { prop, setting, slot } from '@/libs/story/story-param.ts'
import { number } from '@/libs/story/story-widget.ts'
import UiTertiaryTag from '@core/components/ui/tag/UiTertiaryTag.vue'
import UiLabelValueTag from '@core/components/ui/tag/UiLabelValueTag.vue'
</script>

View File

@@ -9,6 +9,7 @@
.enum('brand', 'info', 'neutral', 'success', 'warning', 'danger', 'muted')
.widget(),
prop('variant').type('TagVariant').required().preset('primary').enum('primary', 'secondary').widget(),
iconProp(),
slot(),
setting('slot').preset('Label').widget(),
]"
@@ -21,6 +22,6 @@
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { prop, setting, slot } from '@/libs/story/story-param.ts'
import { iconProp, prop, setting, slot } from '@/libs/story/story-param.ts'
import UiTag from '@core/components/ui/tag/UiTag.vue'
</script>

View File

@@ -8,18 +8,18 @@
<UiTag accent="success" variant="primary">{{ settings.slot }}</UiTag>
<UiTag accent="warning" variant="secondary">{{ settings.slot }}</UiTag>
<UiTag accent="danger" variant="secondary">{{ settings.slot }}</UiTag>
<UiTertiaryTag accent="info">
<UiLabelValueTag accent="info">
{{ settings.slot }}
<template #term>
{{ settings.slot }}
</template>
</UiTertiaryTag>
<UiTertiaryTag accent="success">
</UiLabelValueTag>
<UiLabelValueTag accent="success">
{{ settings.slot }}
<template #term>
{{ settings.slot }}
</template>
</UiTertiaryTag>
</UiLabelValueTag>
</UiTagsList>
</ComponentStory>
</template>
@@ -27,7 +27,7 @@
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { setting, slot } from '@/libs/story/story-param.ts'
import UiLabelValueTag from '@core/components/ui/tag/UiLabelValueTag.vue'
import UiTag from '@core/components/ui/tag/UiTag.vue'
import UiTagsList from '@core/components/ui/tag/UiTagsList.vue'
import UiTertiaryTag from '@core/components/ui/tag/UiTertiaryTag.vue'
</script>

View File

@@ -67,10 +67,107 @@ export const deepNestedTask: Task = {
],
}
export const pendingWithoutProgressTask: Task = {
id: '6',
name: 'Queued replication',
status: 'pending',
start: Date.now() - 2 * 60_000,
}
export const pendingFullProgressTask: Task = {
id: '7',
name: 'Finalize export',
status: 'pending',
progress: 100,
start: Date.now() - 60_000,
infos: [{ message: 'Waiting for cleanup', data: null }],
}
export const infosAndWarningsTask: Task = {
id: '8',
name: 'Rolling pool update',
status: 'pending',
progress: 50,
start: Date.now() - 3 * 60 * 60_000,
infos: [{ message: 'Hosts updated', data: { hosts: 4, done: 2 } }],
warnings: [{ message: 'Reboot required after update', data: { host: 'host-3' } }],
subtasks: [
{ id: '8-1', name: 'host-1', status: 'success', progress: 100, end: Date.now() - 2 * 60 * 60_000 },
{ id: '8-2', name: 'host-2', status: 'success', progress: 100, end: Date.now() - 60 * 60_000 },
{ id: '8-3', name: 'host-3', status: 'pending', progress: 30, start: Date.now() - 15 * 60_000 },
],
}
export const failedNestedTask: Task = {
id: '9',
name: 'Disaster recovery drill',
status: 'failure',
progress: 100,
start: Date.now() - 8 * 60 * 60_000,
end: Date.now() - 7 * 60 * 60_000,
subtasks: [
{ id: '9-1', name: 'Provision VM', status: 'success', progress: 100, end: Date.now() - 7.5 * 60 * 60_000 },
{
id: '9-2',
name: 'Restore data',
status: 'failure',
progress: 100,
end: Date.now() - 7 * 60 * 60_000,
warnings: [{ message: 'Missing backup files', data: { missing: 3 } }],
subtasks: [
{ id: '9-2-1', name: 'Mount SR', status: 'failure', progress: 100, end: Date.now() - 7.1 * 60 * 60_000 },
],
},
],
}
export const interruptedTask: Task = {
id: '10',
name: 'Storage migration',
status: 'interrupted',
progress: 10,
start: Date.now() - 2 * 60 * 60_000,
infos: [
{ message: 'Rows migrated before interruption', data: { rows: 1200 } },
{ message: 'Task manually aborted', data: null },
],
}
export const longNameTask: Task = {
id: '11',
name: 'Very long task name that should wrap gracefully in the task list UI when space is limited',
status: 'pending',
progress: 8,
start: Date.now() - 2 * 60 * 60_000,
}
export const longNameWithEverythingTask: Task = {
id: '12',
name: 'Very long task name for a full backup job that also has subtasks, infos, warnings and an end time to display',
to: '#',
status: 'failure',
progress: 100,
start: Date.now() - 5 * 60 * 60_000,
end: Date.now() - 4 * 60 * 60_000,
infos: [{ message: 'Transferred 120 GiB', data: { size: 120 } }],
warnings: [{ message: 'Some VDIs were skipped', data: { skipped: 2 } }],
subtasks: [
{ id: '12-1', name: 'Snapshot', status: 'success', progress: 100, end: Date.now() - 4.5 * 60 * 60_000 },
{ id: '12-2', name: 'Transfer', status: 'failure', progress: 100, end: Date.now() - 4 * 60 * 60_000 },
],
}
export const allTasks: Task[] = [
pendingBackupTask,
completedWithRootLinkTask,
failedWithWarningsTask,
migrationNamePartsTask,
deepNestedTask,
pendingWithoutProgressTask,
pendingFullProgressTask,
infosAndWarningsTask,
failedNestedTask,
interruptedTask,
longNameTask,
longNameWithEverythingTask,
]

View File

@@ -4,27 +4,22 @@
:presets
:params="[
prop('task').type('object').required().widget().preset(pendingBackupTask),
prop('depth').type('number').required().preset(1),
model('expanded').prop(p => p.type('boolean').widget(boolean()).preset(false)),
prop('selected').type('boolean').widget(boolean()).preset(false),
prop('showEyeIcon').type('boolean').widget(boolean()).preset(true),
event('expand'),
prop('showUnread').bool().widget().help('Reserves the unread dot column'),
prop('unread').bool().widget(),
event('select').args({ id: 'string' }),
]"
>
<ul>
<UiTaskItem v-bind="properties" @expand="properties['onUpdate:expanded']?.(!properties.expanded)" />
</ul>
<UiTaskItem v-bind="properties" />
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { event, model, prop } from '@/libs/story/story-param.ts'
import { event, prop } from '@/libs/story/story-param.ts'
import { boolean } from '@/libs/story/story-widget.ts'
import {
completedWithRootLinkTask,
deepNestedTask,
failedWithWarningsTask,
migrationNamePartsTask,
pendingBackupTask,
@@ -40,45 +35,24 @@ const presets: Record<
'Pending backup': {
props: {
task: pendingBackupTask,
depth: 1,
expanded: false,
selected: false,
showEyeIcon: true,
},
},
'Completed + root link': {
props: {
task: completedWithRootLinkTask,
depth: 1,
expanded: false,
selected: false,
showEyeIcon: true,
},
},
'Failed + warnings': {
props: {
task: failedWithWarningsTask,
depth: 1,
expanded: false,
selected: false,
showEyeIcon: true,
},
},
'Migration (nameParts)': {
props: {
task: migrationNamePartsTask,
depth: 1,
expanded: false,
selected: false,
showEyeIcon: true,
},
},
'Deep nested': {
props: {
task: deepNestedTask,
depth: 1,
expanded: true,
selected: false,
showEyeIcon: true,
},
},

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