Compare commits

..

69 Commits

Author SHA1 Message Date
Sebastien Marie
f342186876 docs: CHANGELOG.unreleased.md
Add user-facing bug fix entries for the xo-server-sdn-controller
private networks fixes (host joining a pool, host ejected from a pool)
and mark xo-server-sdn-controller for a patch release.
2026-11-25 14:10:35 +01:00
Sebastien Rodot
b1ddc3fa70 fix(xo-server-sdn-controller): rewire private networks when a host leaves the pool
When a host is ejected from a pool, the VXLAN legs created by the SDN
controller on the remaining hosts (in particular on the star center) are
never removed: XAPI only destroys the tunnel records of the ejected host
itself, so the center keeps an active tunnel port toward the host's underlay
IP until the plugin is reloaded.

On the removal of a non-center host, re-run the network registration of its
pool (resetForNetwork then addHost for each host), as done on plugin load,
to remove the stale ports and rewire the remaining hosts.
2026-11-25 13:43:54 +01:00
Sebastien Rodot
76ae982a48 fix(xo-server-sdn-controller): log "Host added" only when the port is (re)created
Since the tunnel index fix (_addHostToPrivateNetworks reading `tunnel`
instead of the nonexistent `SDN_tunnel`), the host wiring runs on every host
metrics event (the reconcile), and addHost unconditionally logged
"Host added" at info level, spamming the log once per host per private
network every ~10 s even when nothing changed.

addInterfaceAndPort now reports whether it created the port ({name, added})
instead of only the bridge name, and addHost logs only when the host or the
center side was actually (re)wired. The bridge name is still returned so
the tunnel status key is restored, and the OVSDB operations are unchanged.
2026-11-25 13:43:54 +01:00
Sebastien Rodot
ba73b578f2 test(xo-server-sdn-controller): cover wiring a host that joins with private networks
Add tests that a just-joined host gets its OVSDB client created once it
becomes enabled, and that _addHostToPrivateNetworks only processes the tunnels
whose access PIF belongs to that host.
2026-11-25 13:43:54 +01:00
Sebastien Rodot
5a5f780441 fix(xo-server-sdn-controller): read the tunnel index by its real class name
_addHostToPrivateNetworks iterated the host's tunnels from
`indexes.type.SDN_tunnel`, a class name that does not exist in the XAPI data
model (the IDL calls it `tunnel`). The lookup always returned nothing, so the
per-network host wiring was a silent no-op and tunnels were never activated on
a newly added host.

Read `indexes.type.tunnel` instead.
2026-11-25 13:43:54 +01:00
Sebastien Rodot
5a411d2448 fix(xo-server-sdn-controller): create the OVSDB client when a host becomes enabled
A host that joins a pool while the SDN controller is already running never
got its OVSDB client created: it is only attempted on the host `add` event,
which bails out while the host is not yet `enabled`, and the later `enabled`
update (_hostUpdated) never retried it. With no client, the VXLAN tunnel leg
is never programmed and a VM migrated to that host is isolated at L2 until a
plugin reload.

Create the client once the host passes the join guard (enabled and recorded
as new), just before the pool certificates are synced.
2026-11-25 13:43:54 +01:00
Sebastien Rodot
37cf301562 test(xo-server-sdn-controller): cover a missing OVSDB Controller row
Add a test that setBridgeControllerForNetwork returns without throwing (and
without sending a transaction) when the host's Controller row does not exist
yet.
2026-11-25 13:43:54 +01:00
Sebastien Rodot
a92d89890b fix(xo-server-sdn-controller): handle a missing OVSDB Controller row
setBridgeControllerForNetwork resolved the host's controller UUID by selecting
the OVSDB `Controller` row and dereferencing the result unconditionally. For a
host that just joined the pool that row does not exist yet (setBridgeController()
has not run), so the select came back empty and undefined._uuid threw a
TypeError, surfacing as an unhandled rejection (the call is fire-and-forget).

Return early when the row is not found: the join flow creates the controller
right after, and later PIF events pick it up.

While here, remove now dead code assert.
2026-11-25 13:43:54 +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
Marie Garde
6f9c0f3466 feat(xo6): add connect host to pool (#10865)
* feat(xo6): add connect host to pool

* add tests

* add tests and loader

* fix build

* fix refacto

* add arg file

* remove useless com
2026-11-24 10:51:06 +01:00
Joris K
e4c8fbf211 feat(xo6/network): open the network creation forms in a drawer (#10876) 2026-11-24 09:45:27 +01:00
Joris K
e2c724d5fe fix(web-core): stop the treeview resize handle from covering its scrollbar (#10886) 2026-11-24 09:32:03 +01:00
Joris K
98cd148db7 fix(web-core): make Discard the primary button of the discard changes modal (#10883) 2026-11-23 18:21:51 +01:00
MlssFrncJrg
dbd8a14001 feat(rest-api): expose proxy health endpoint (#10752)
* feat(rest-api): migrate proxy health endpoint

* changelog entry

* handle unreachable proxy errors

* map all unreachable proxy errors to 502 and test health endpoint

* share proxy unreachable mapping and response descriptor

---------

Co-authored-by: Mathieu <mathieu.piton@vates.tech>
2026-11-23 15:52:06 +01:00
Elise-F
d3e8ec3458 feat(xo6/traffic-rules): show private network info in the traffic rue side panel (#10874) 2026-11-23 15:49:13 +01:00
Joris K
7104d235ef fix(web-core): pin the show more/less button to the top right of truncated text cells (#10873) 2026-11-23 15:45:18 +01:00
amouillard-vates
c3a4039aae fix(xo6/web-core): fix VM tags horizontal squeezing (#10871) 2026-11-23 14:24:25 +01:00
Joris K
5175915b1c fix(xo6/web-core): stop syncing the side panel open state between browser tabs (#10869) 2026-11-23 11:03:40 +01:00
MlssFrncJrg
dea99db937 feat(xo-web/licenses): add airgap data pack upload (#10254) 2026-11-23 10:47:55 +01:00
amouillard-vates
75c5696bef feat(xo6): add VM tags edition (#10804) 2026-11-23 10:18:51 +01:00
Sylvère
f376c130ee feat(xo6): add SR create form (#10251) 2026-11-23 10:15:41 +01:00
OlivierFL
3df5ba46d1 feat(web-core): update UiTextarea to v6 (#10862) 2026-11-23 09:50:19 +01:00
Mathieu
6d84ec9b20 feat(xo-server): resume a failed or interrupted rolling pool update (#10860)
* feat(xo-server): resume a failed or interrupted rolling pool update (#10474)
2026-11-23 09:31:04 +01:00
OlivierFL
525b72e00a feat(web-core): update UiInput to v10 (#10861) 2026-11-23 08:58:08 +01:00
Joris K
651f4e8aee fix(xo6/vdi): open the XO 6 storage repository page from the VDI storage link (#10864) 2026-11-20 18:18:05 +01:00
OlivierFL
334002cba5 test(web): run the unit tests about 7 times faster (#10841) 2026-11-20 17:42:19 +01:00
Joris K
6faeae4a2f fix(xo6/new-vm): add a default network interface to templates without one (#10863) 2026-11-20 17:40:44 +01:00
Mathieu
5eab6643a1 fix(xo-server): require admin authentication for updater access (#10857)
The XOA updater WebSocket proxied by xo-server did not check the caller's session. xo-server now requires a valid XO session with admin permission before it proxies an updater WebSocket connection.

    Every path starting with /api/updater or /v5/api/updater is protected, including the generic /v5/api proxy path.
    Missing, invalid and non-admin credentials get a 403. The rejection is logged without the request headers, so the session token never ends up in the logs.
    The upgrade handler moves to createProxyUpgradeHandler (_updaterProxy.mjs) so the wiring is covered by tests.
    The updater localhost target is no longer rewritten to http.listen.hostname: the updater only listens on loopback.
    xo-web only starts the updater client for admin users. On Free XOA, the rejected connection would otherwise put non-admin users in an error state that blocks their access.

This must ship together with the matching xoa-updater change.
Verification

    xo-server build and test suite pass, including the new _updaterProxy tests.
    Tested on a disposable XOA: unauthenticated, invalid-token and non-admin handshakes on every updater path get a 403, the admin update workflow and the local xoa-updater CLI keep working, and a non-admin user on Free XOA keeps access to the UI.

Same change as #10856, which targets release-6.10.
2026-11-20 16:53:20 +01:00
Killian
639fdee531 docs: log in to XOA and proxies with an SSH key, deprecate the XenStore password (#10852)
* docs: log in to XOA and proxies with an SSH key, deprecate the XenStore password

The xoa account can now get an SSH public key through
vm-data/system-account-xoa-ssh-key. Document it as the recommended way, and
mark the XenStore password as deprecated: it will be removed in a future
version.

* docs: fold the deprecated XenStore password method

Requested by julienXOvates: readers should not be led to the deprecated
method. The password command and its warning now sit in a collapsed
details block in the XOA, proxy and troubleshooting pages; the SSH key
method stays the only one shown by default.
2026-11-20 16:47:11 +01:00
Florent BEAUCHAMP
f556f77363 fix(proxy): stop exposing proxy token out of xo (#10810)
* fix(proxy): stop exposing proxy token out of xo, remove copy proxy url feature. 
* mark method and field as deprecated
2026-11-20 16:09:07 +01:00
Thierry Goettelmann
c40f0bac73 feat(web-core/validated-form): add markStepUntouched to multi-step forms (#10855)
When a form changes the values of a step itself, they are handled as
edited by the user and their errors are displayed right away, before the
user does anything on the step.

`markStepUntouched` hides the errors and warnings of a step until the
user edits or validates it again. Its values are not changed.

See XO-3469
2026-11-20 16:08:34 +01:00
Joris K
26767fccfc feat(xo6/vm): update the VM creation form into a 3-step workflow (#10851) 2026-11-20 15:51:44 +01:00
ayoub-el-kajji-v
cb206a4512 feat(rest-api): import VDI from URL (#10751) 2026-11-20 15:24:12 +01:00
Killian
bd91b65cef fix(deps): fix some critical vulnerabilities (#10853) 2026-11-20 13:49:40 +01:00
Elise-F
d0e88ad88c feat(xo6): add possibility to create a new private network (#10820) 2026-11-20 12:22:10 +01:00
Florent BEAUCHAMP
4dfd4e4035 fix(xo-server): improve in depth defense of legacy api (#10858) 2026-11-20 11:11:33 +01:00
Florent BEAUCHAMP
90a9d5c27d fix(proxy): refresh authentication token in memory as soon as config is updated 2026-11-20 11:04:45 +01:00
Sylvère
dd717dbf25 fix(xo6/lite/web-core): fix wider-than-viewport dropdowns (#10854)
fix(xo6/lite/web-core): fix searchable dropdowns taking more than viewport width on mobile
2026-11-20 08:50:49 +01:00
Joris K
a9ff407d78 feat(xo6/lite/web-core): keep table cells on one line (#10850) 2026-11-19 19:50:44 +01:00
Sylvère
2093c640dd feat(web-core/lite): updated UiCircleProgressBar component (#10849) 2026-11-19 16:40:35 +01:00
Killian
65156b81ca Feat(sdn-controller): add private networks rest routes (#10708)
Description

Adds POST /rest/v0/plugins/sdn-controller/pools/actions/create_private_network. Before this, a Global Private Network could only be created with the JSON-RPC method sdnController.createPrivateNetwork. Both APIs now go through _createPrivateNetwork. With sync=true the route answers 201 { networkIds }, the id of the network created on each pool.

Defaults, the same as the JSON-RPC method's: encrypted: false, mtu: 0 (left to XAPI), no preferred center. The route is admin-only and isn't exposed to MCP. Without sync=true it answers 202 with a task.

Side effects

    XO becomes the SDN controller of every pool in the network. This isn't new, but a REST client can now trigger it.
    Networks are created one pool at a time, so if XAPI fails on one pool, the networks already created on earlier pools stay.
    Bad parameters are now refused before the first network is created:
        invalidParameters for an empty poolIds, a pool given twice, a pool with no PIF, or a preferred center outside the pools
        404 for an unknown PIF
    The JSON-RPC method now returns the ids of the networks it created. XO 5 ignores them.
    Fix: a preferred center outside the first pool made the creation fail, and left an untracked network with no tunnels. Introduced by fix(xo-server-sdn-controller): correctly find preferred center's pool #5080.

XO-3337
2026-11-19 15:47:22 +01:00
Mathieu
ca1bb83672 docs(updater): fix broken link to the Replace your XOA guide (#10846)
#10471 linked to `migrate_to_new_xoa.md`, which #10575 had removed in
favor of the Vates knowledge base. Docusaurus fails on broken relative
Markdown links, so the docs build on master broke. Point to the KB
article that the existing redirect already targets.
2026-11-19 13:01:25 +01:00
Joris K
cce68035ca feat(web-core): add UiOverridden component (#10840) 2026-11-19 11:37:38 +01:00
Thomas Moraine
948d4a23e5 docs(updater.md): link to replace your xoa from the updater page (#10471)
* docs(updater): link to Replace your XOA for getting a newer OS

The updater keeps Xen Orchestra up to date but doesn't refresh the
appliance's underlying OS/kernel/runtime; point readers to the
"Replace your XOA" guide for that.

* docs(updater): turn OS updates note into a warning

Stress that keeping XOA's OS up to date is critical given its privileged
access, and that reboots shouldn't be postponed but scheduled outside
backup windows.

* docs(updater): make OS warning title actionable

* docs(updater): emphasize not postponing XOA reboots
2026-11-19 11:29:56 +01:00
OlivierFL
68634c8c01 test(web): map @core-test to the web-core test helpers (#10831) 2026-11-19 10:29:44 +01:00
Killian
36cb16e508 fix(xen-api,xo-server): reconnect a pool whose event loop failed (#10814)
After a short network interruption, a pool could disappear from XO and its server stay in "connecting" until it was disabled and enabled again.

The cause is a chain of three things:

    xo-server processed the metrics of a VM, host or PIF whose owner had been removed in the meantime (the cached records are refreshed type by type), and threw Cannot read properties of undefined (reading '$type') from the flush of the objects collection. The owner is already gone from XO, so the metrics are now skipped.
    xo-collection stopped flushing when a listener threw: the remaining batches and finish were never emitted and the buffer was emitted again at the next flush. Every batch and finish are now emitted whatever the listeners do, then the first failure is rethrown.
    xen-api swallowed the rejection of its event loop, so nothing restarted it and the cache froze on a connection which still looked alive; the session stayed open, disconnected was never emitted and the auto-reconnection never started. It now logs the error and disconnects, so the owner of the connection reconnects with a fresh cache.
2026-11-19 10:05:07 +01:00
1141 changed files with 52123 additions and 15403 deletions

View File

@@ -59,6 +59,33 @@ module.exports = {
'n/no-unpublished-import': 'off',
},
},
// The XO 6 test files share their modules (no isolation): mocking or resetting a module from one file would leak
// into the others. See @xen-orchestra/web/docs/tests/mocking.md
{
files: ['@xen-orchestra/web/src/**/*.unit.test.ts'],
rules: {
'no-restricted-syntax': [
'error',
{
selector: "CallExpression[callee.object.name='vi'][callee.property.name=/^(mock|doMock|unmock|doUnmock)$/]",
message: 'Mock a module with `mockModule` from `@/test/spy-on-module.ts`, never `vi.mock`.',
},
{
selector: "CallExpression[callee.object.name='vi'][callee.property.name='resetModules']",
message: 'The test files share their modules: never reset them.',
},
{
selector: "CallExpression[callee.object.name='vi'][callee.property.name='hoisted']",
message: '`mockModule` is not hoisted: declare the stubs as plain constants.',
},
{
selector: "CallExpression[callee.object.name='vi'][callee.property.name='resetAllMocks']",
message:
'Reset the stubs with `resetStubs` from `@/test/reset-stubs.ts`: `vi.resetAllMocks()` also resets the module mocks.',
},
],
},
},
{
files: ['@xen-orchestra/{web-core,lite,web}/**/*.{vue,ts}'],
parser: 'vue-eslint-parser',

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.1",
"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

@@ -1,7 +1,7 @@
{
"name": "@vates/types",
"private": false,
"version": "2.5.0",
"version": "3.0.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

@@ -759,6 +759,10 @@ export type TrafficRuleProtocol = (typeof TRAFFIC_RULE_PROTOCOLS)[number]
export const SDN_CONTROLLER_OF_RULES_KEY = 'xo:sdn-controller:of-rules'
export const SDN_CONTROLLER_OF_METHOD_KEY = 'xo:sdn-controller:of-method'
export const SDN_CONTROLLER_OF_FORMAT_KEY = 'xo:sdn-controller:of-format'
export const SDN_CONTROLLER_PRIVATE_NETWORK_UUID_KEY = 'xo:sdn-controller:private-network-uuid'
export const SDN_CONTROLLER_ENCRYPTED_KEY = 'xo:sdn-controller:encrypted'
export const SDN_CONTROLLER_ENCAPSULATION_KEY = 'xo:sdn-controller:encapsulation'
export const SDN_CONTROLLER_PREFERRED_CENTER_KEY = 'xo:sdn-controller:preferred-center'
export const TRAFFIC_RULE_PROTOCOLS = ['ARP', 'ICMP', 'IP', 'TCP', 'UDP'] as const
export const TRAFFIC_RULE_PROTOCOLS_WITH_PORT: readonly TrafficRuleProtocol[] = ['TCP', 'UDP']

View File

@@ -155,26 +155,80 @@ export type PoolRollingUpdateRecoveryError = {
}
export type PoolRollingUpdateRecoveryHost = {
status: 'pending' | 'running' | 'succeeded' | 'failed' | 'not-needed'
/** `interrupted`: left in progress by a run that is over */
status: 'pending' | 'running' | 'interrupted' | 'succeeded' | 'failed' | 'not-needed'
steps: Record<RPU_RECOVERY_STEP_NAME, PoolRollingUpdateRecoveryStep>
lastError: PoolRollingUpdateRecoveryError | null
}
/** a VM the last migrate back of the run could not bring to its original host */
export type PoolRollingUpdateRecoveryVmConflict = {
vmId: string
/** unknown for a VM deleted before the run could read it */
vmName?: string
/** UUID of the host the VM was running on before the run */
hostId: string
/** `stopped` and `deleted`: left to the operator; `migration-failed`: retried by a resume */
reason: 'stopped' | 'deleted' | 'migration-failed'
/** XAPI error of the last migration, `migration-failed` only */
message?: string
}
/** what an operator changed, since the run, on a setting the run left changed or on an object of the run */
export type PoolRollingUpdateRecoveryOperatorChange = {
/** `haHeartbeatSr`: a heartbeat SR needed to enable HA again no longer exists */
type: 'ha' | 'autoPowerOn' | 'wlb' | 'schedule' | 'haHeartbeatSr' | 'host' | 'vm'
/** pool, schedule, SR, host or VM UUID */
id: string
/** schedules enabled again only */
name?: string
/** `disabled` as the run left it, `present` for a heartbeat SR, a host or a VM */
expected: 'disabled' | 'present'
/** `missing` for a deleted schedule, heartbeat SR, host or VM */
observed: 'enabled' | 'missing'
}
/** hosts resumes added to the plan of the run: patches released since it started, or hosts new to the pool */
export type PoolRollingUpdateRecoveryPlanChange = {
/** the last resume which added hosts */
attempt: number
/** UUIDs of hosts the run did not plan to update, or had finished, added by any resume */
addedHostIds: string[]
}
export type PoolRollingUpdateRecoveryRun = {
runId: string
poolId: string
status: 'preparing' | 'running' | 'interrupted' | 'resuming' | 'failed' | 'cleaning' | 'succeeded'
/** `awaiting-acceptance`: a resume found operator changes and waits for them to be accepted */
status:
| 'preparing'
| 'running'
| 'interrupted'
| 'resuming'
| 'failed'
| 'cleaning'
| 'succeeded'
| 'awaiting-acceptance'
startedAt: string
updatedAt: string
finishedAt?: string
interruptedAt?: string
taskId?: string
variant?: 'xcp' | 'xs-cdn'
/** 1 for the first attempt, incremented by each resume of the run */
attempt?: number
/** whether a resume would be accepted: run failed, interrupted or awaiting the acceptance of operator changes */
resumable?: boolean
hostOrder?: string[]
hosts: Record<string, PoolRollingUpdateRecoveryHost>
lastError: PoolRollingUpdateRecoveryError | null
/** VM UUID -> UUID of the host it must be started on */
haltedPinnedVms: Record<string, string>
vmConflicts: PoolRollingUpdateRecoveryVmConflict[]
/** found by the last resume, the run stays `awaiting-acceptance` until they are accepted */
operatorChanges: PoolRollingUpdateRecoveryOperatorChange[]
/** absent when no resume changed the plan */
planChange?: PoolRollingUpdateRecoveryPlanChange
}
/** record unreadable or of an unknown schema version: recovery needs a human */
@@ -303,6 +357,8 @@ export type XoApp = EventEmitter & {
checkFeatureAuthorization(featureCode: FeatureCode): Promise<void>
/* whether this machine can run the tools of an import from VMware */
checkEsxiDependencies(): Promise<XoV2vStatus>
/* Throw if the proxy cannot be reached */
checkProxyHealth(id: XoProxy['id']): Promise<void>
/* validate, apply and persist the configuration of a plugin */
configurePlugin(id: string, configuration: unknown, mergeWithExisting?: boolean): Promise<void>
/* connect a server (XCP-ng/XenServer) */
@@ -617,6 +673,10 @@ export type XoApp = EventEmitter & {
): Promise<void>
getRollingUpdateRecovery(poolId: XoPool['id']): Promise<PoolRollingUpdateRecovery | undefined>
finalizeRollingUpdate(pool: XoPool, opts?: { force?: boolean; parentTask?: VatesTask }): Promise<void>
resumeRollingPoolUpdate(
pool: XoPool,
opts?: { acceptOperatorChanges?: boolean; bypassBackupCheck?: boolean; parentTask?: VatesTask }
): Promise<void>
setVmResourceSet(vmId: XoVm['id'], resourceSetId: string | null, force?: boolean): Promise<void>
shareVmResourceSet(vmId: XoVm['id']): Promise<void>
removeUserFromGroup(userId: XoUser['id'], id: XoGroup['id']): Promise<void>

View File

@@ -579,6 +579,9 @@ export type XoBrowserMediaSession = {
export type XoProxy = {
id: Branded<'proxy'>
/**
* @deprecated no replacement for this field
*/
url: string
version?: string
name: string
@@ -643,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: {
@@ -660,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
@@ -693,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.0.0",
"rimraf": "^6.0.1",
"typescript": "~5.6",
"typescript-eslint": "^8.61.0"

View File

@@ -3,7 +3,16 @@ export default {
delete: true,
forget: true,
import: {
vdi: true,
vdi: {
upload: true,
/**
* Warning: lets the holder make XO send a GET request to any HTTP(S) URL, including internal addresses
* reachable from the XO server (localhost, management network, etc.).
*
* Covered by `import:vdi`, `import` and `*`: only grant these to trusted users.
*/
url: true,
},
vm: true,
},
'migrate-receive': true,

View File

@@ -38,33 +38,10 @@ export class Privilege<T extends SupportedResource> {
}
#matchAction<Resource extends SupportedResource = T>(action: SupportedActions<Resource>) {
// read:name_label - read:name_label
if (this.#action === action) {
return true
}
const [namespaceToMatch, actionToMatch] = action.split(':')
const [thisNamespace, thisAction] = this.#action.split(':')
if (thisNamespace === '*') {
return true
}
// update:vm - read:name_label
if (thisNamespace !== namespaceToMatch) {
return false
}
// read - read:name_label
if (thisAction === undefined) {
return true
}
// read:name_decription - read:name_label
if (thisAction !== actionToMatch) {
return false
}
throw new Error(`Unable to verify if ${this.#action} match ${action} `)
// A privilege allows its own action and every action below it in the tree:
// e.g. `*`, `import`, `import:vdi` and `import:vdi:url` all allow `import:vdi:url`,
// but `import:vdi:upload` does not (it is a sibling, not a parent)
return this.#action === '*' || this.#action === action || action.startsWith(`${this.#action}:`)
}
#matchSelector(object: object) {

View File

@@ -27,6 +27,12 @@ suite('Privilege.checkActionIsValid behavior', () => {
test('should work', () => {
assert.doesNotThrow(() => Privilege.checkActionIsValid('vm', 'read'))
})
test('should work with 3-level actions', () => {
assert.doesNotThrow(() => Privilege.checkActionIsValid('sr', 'import:vdi:url'))
// @ts-expect-error test invalid action
assert.throws(() => Privilege.checkActionIsValid('sr', 'import:vdi:foo'))
})
})
suite('Privilege.match behavior', () => {
@@ -59,6 +65,22 @@ suite('Privilege.match behavior', () => {
const cleanShutdownPrivilege = new Privilege({ action: 'shutdown:clean', resource: 'vm', effect: 'allow' })
assert.strictEqual(cleanShutdownPrivilege.match({ resource: 'vm', action: 'shutdown', object }), false)
})
test('Should match 3-level actions with any parent action', () => {
for (const action of ['*', 'import', 'import:vdi', 'import:vdi:url'] as const) {
const srPrivilege = new Privilege({ action, resource: 'sr', effect: 'allow' })
assert.strictEqual(srPrivilege.match({ resource: 'sr', action: 'import:vdi:url', object }), true, action)
}
})
test('Should not match 3-level actions with a sibling or a child action', () => {
const uploadPrivilege = new Privilege({ action: 'import:vdi:upload', resource: 'sr', effect: 'allow' })
assert.strictEqual(uploadPrivilege.match({ resource: 'sr', action: 'import:vdi:url', object }), false)
assert.strictEqual(uploadPrivilege.match({ resource: 'sr', action: 'import:vdi', object }), false)
const vmImportPrivilege = new Privilege({ action: 'import:vm', resource: 'sr', effect: 'allow' })
assert.strictEqual(vmImportPrivilege.match({ resource: 'sr', action: 'import:vdi:url', object }), false)
})
})
suite('ACL V2 behavior', async () => {
@@ -258,6 +280,23 @@ suite('ACL V2 behavior', async () => {
false
)
})
test('Should allow VDI upload but not URL import with import:vdi allowed and import:vdi:url denied', () => {
const sr = { id: 'sr-id' }
const userPrivileges = [
{ id: privilegeId, action: 'import:vdi', resource: 'sr', effect: 'allow', roleId },
{ id: privilegeId, action: 'import:vdi:url', resource: 'sr', effect: 'deny', roleId },
] satisfies TPrivilege<'sr'>[]
assert.strictEqual(
hasPrivilegeOn({ user, action: 'import:vdi:upload', resource: 'sr', objects: sr, userPrivileges }),
true
)
assert.strictEqual(
hasPrivilegeOn({ user, action: 'import:vdi:url', resource: 'sr', objects: sr, userPrivileges }),
false
)
})
})
suite('getMissingPrivileges behavior', () => {
@@ -375,4 +414,12 @@ suite('getActionStrings', () => {
assert.ok(actions.includes('shutdown:clean'))
assert.ok(actions.includes('shutdown:hard'))
})
test('3-level actions are included alongside their parents', () => {
const actions = getActionStrings('sr')
assert.ok(actions.includes('import'))
assert.ok(actions.includes('import:vdi'))
assert.ok(actions.includes('import:vdi:upload'))
assert.ok(actions.includes('import:vdi:url'))
})
})

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.0.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.0",
"@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

@@ -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

@@ -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.0",
"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.1",
"@vates/parse-duration": "^0.1.1",
"@vates/task": "^0.7.0",
"@vates/types": "^2.5.0",
"@vates/types": "^3.0.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.0.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.0",
"@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.0",
"@xen-orchestra/log": "^1.0.0",
"app-conf": "^3.0.0",
"execa": "^5.0.0",
"ms": "^2.1.3"

View File

@@ -2,6 +2,8 @@
## **next**
- [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))
- [VM/Host] Main actions (shutdown, reboot, start, resume, migrate, snapshot) are shown as buttons in the VM and host headers and move one by one into "More actions" when space runs out; "More actions" groups them under "Change state" and "Actions" sections, and VMs without guest tools get force shutdown and force reboot instead (PR [#10815](https://github.com/vatesfr/xen-orchestra/pull/10815))
- [Web-Core/UiButtonIcon] Update icon buttons design, with a counter replacing the notification dot (PR [#10799](https://github.com/vatesfr/xen-orchestra/pull/10799))
@@ -12,6 +14,8 @@
- [Web-Core/UiDropdownButton] Update dropdown buttons design (PR [#9850](https://github.com/vatesfr/xen-orchestra/pull/9850))
- [Tables] Tables are filtered as you type, half a second after the last keystroke, or right away with Enter; the "Search" button is removed (PR [#10797](https://github.com/vatesfr/xen-orchestra/pull/10797))
- [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))
## **0.27.0** (2026-10-29)

View File

@@ -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.0.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.66.0",
"complex-matcher": "^1.1.1",
"d3-time-format": "^4.1.0",
"decorator-synchronized": "^0.6.0",

View File

@@ -2,12 +2,12 @@
<div class="collection-filter-row">
<span class="or">{{ t('or') }}</span>
<div class="inputs">
<UiInput v-if="newFilter.isAdvanced" v-model="filterContent" accent="brand" class="advanced-input" />
<UiInput v-if="newFilter.isAdvanced" v-model="filterContent" accent="neutral" class="advanced-input" />
<template v-else>
<VtsSelect :id="builderPropertySelectId" accent="brand" />
<VtsSelect v-if="hasComparisonSelect" :id="builderComparisonSelectId" accent="brand" />
<VtsSelect v-if="currentFilter?.type === 'enum'" :id="builderValueSelectId" accent="brand" />
<UiInput v-else-if="hasValueInput" v-model="newFilter.builder.value" accent="brand" />
<VtsSelect :id="builderPropertySelectId" accent="neutral" />
<VtsSelect v-if="hasComparisonSelect" :id="builderComparisonSelectId" accent="neutral" />
<VtsSelect v-if="currentFilter?.type === 'enum'" :id="builderValueSelectId" accent="neutral" />
<UiInput v-else-if="hasValueInput" v-model="newFilter.builder.value" accent="neutral" />
</template>
</div>
<div class="buttons">

View File

@@ -1,5 +1,5 @@
<template>
<VtsSelect v-if="isSelectWidget(widget)" :id="selectId" accent="brand" />
<VtsSelect v-if="isSelectWidget(widget)" :id="selectId" accent="neutral" />
<UiRadioButtonGroup v-else-if="isRadioWidget(widget)" accent="brand" gap="wide">
<UiRadioButton
v-for="choice in widget.choices"

View File

@@ -1,7 +1,7 @@
<template>
<VtsInputGroup>
<UiInput v-model.number="sizeInput" accent="brand" type="number" :max-decimals="3" />
<VtsSelect :id="prefixSelectId" accent="brand" />
<UiInput v-model.number="sizeInput" accent="neutral" type="number" :max-decimals="3" />
<VtsSelect :id="prefixSelectId" accent="neutral" />
</VtsInputGroup>
</template>

View File

@@ -2,8 +2,8 @@
<UiModal accent="info" @dismiss="emit('cancel')" @confirm="handleSubmit()">
<template #content>
<div class="form-selects">
<VtsSelect :id="sortPropertySelectId" accent="brand" />
<VtsSelect :id="isAscendingSelectId" accent="brand" />
<VtsSelect :id="sortPropertySelectId" accent="neutral" />
<VtsSelect :id="isAscendingSelectId" accent="neutral" />
</div>
</template>

View File

@@ -7,7 +7,7 @@
@dismiss="emit('cancel')"
>
<template #content>
<UiTextarea v-model="editedJson" accent="brand" class="modal-textarea" />
<UiTextarea v-model="editedJson" accent="neutral" class="modal-textarea" />
<VtsOverlayButton variant="tertiary" @click="formatJson()">
{{ t('action:reformat') }}
</VtsOverlayButton>

View File

@@ -8,7 +8,7 @@
:label="t('select-compression')"
learn-more-url="https://xcp-ng.org/blog/2018/12/19/zstd-compression-for-xcp-ng/"
>
<VtsSelect :id="compressionSelectId" accent="brand" />
<VtsSelect :id="compressionSelectId" accent="neutral" />
</VtsInputWrapper>
</template>
<template #buttons>

View File

@@ -7,7 +7,7 @@
<template #content>
<div>
<VtsInputWrapper :label="t('select-destination-host')">
<VtsSelect :id="hostSelectId" accent="brand" />
<VtsSelect :id="hostSelectId" accent="neutral" />
</VtsInputWrapper>
</div>
</template>

View File

@@ -45,6 +45,7 @@ const emit = defineEmits<{
const { t } = useI18n()
const { HeadCells, BodyCells, colspan } = useNewVmNetworkColumns({
exclude: ['rank'],
body: ({ networkInterface, onRemove }: { networkInterface: NetworkInterface; onRemove: () => void }) => {
const { id: interfaceSelectId } = useFormSelect(networks, {
model: toRef(networkInterface, 'interface'),

View File

@@ -1,5 +1,5 @@
<template>
<VtsTable>
<VtsTable class="new-vm-sr-table" fixed>
<thead>
<tr>
<HeadCells />
@@ -49,6 +49,7 @@ const emit = defineEmits<{
const { t } = useI18n()
const { HeadCells, BodyCells, colspan } = useNewVmSrColumns({
exclude: ['rank'],
body: ({ vdi, onRemove }: { vdi: Vdi; onRemove?: () => void }) => {
const { id: srSelectId } = useFormSelect(() => srs, {
model: toRef(vdi, 'SR'),
@@ -76,3 +77,9 @@ const { HeadCells, BodyCells, colspan } = useNewVmSrColumns({
},
})
</script>
<style lang="postcss" scoped>
.new-vm-sr-table {
--vts-table-min-width: 80rem;
}
</style>

View File

@@ -59,7 +59,7 @@ const useTaskColumns = defineColumns(() => {
const { t } = useI18n()
return {
name: useTextColumn({ headerLabel: t('name') }),
name: useTextColumn({ headerLabel: t('name'), flexible: true }),
host: useLinkColumn({ headerLabel: t('host') }),
progress: useProgressBarColumn({ headerLabel: t('progress') }),
started: useDateColumn({ headerLabel: t('started') }),

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

@@ -1,6 +1,6 @@
<template>
<VtsInputWrapper :label :message="error">
<VtsSelect :id accent="brand" />
<VtsSelect :id accent="neutral" />
</VtsInputWrapper>
</template>

View File

@@ -1,6 +1,6 @@
<template>
<VtsInputWrapper :label :message="error">
<UiInput v-model.trim="model" accent="brand" :required :disabled />
<UiInput v-model.trim="model" accent="neutral" :required :disabled />
</VtsInputWrapper>
</template>

View File

@@ -1,5 +1,5 @@
<template>
<UiTextarea v-model.trim="model" accent="brand">
<UiTextarea v-model.trim="model" accent="neutral">
{{ t('description') }}
</UiTextarea>
</template>

View File

@@ -1,5 +1,5 @@
<template>
<UiTextarea v-model.trim="model" :accent="errorMessage !== undefined ? 'danger' : 'brand'">
<UiTextarea v-model.trim="model" :accent="errorMessage !== undefined ? 'danger' : 'neutral'">
{{ t('allowed-ips') }}
<template #info>{{ t('allowed-ips-example') }}</template>

View File

@@ -1,6 +1,11 @@
<template>
<VtsInputWrapper :label="t('mac-address')" :message="messages" wrap-message>
<UiInput v-model.trim="model" accent="brand" :required :placeholder="required ? undefined : t('auto-generated')" />
<UiInput
v-model.trim="model"
accent="neutral"
:required
:placeholder="required ? undefined : t('auto-generated')"
/>
</VtsInputWrapper>
</template>

View File

@@ -1,6 +1,6 @@
<template>
<VtsInputWrapper :label="t('network')" :message="error">
<VtsSelect :id accent="brand">
<VtsSelect :id accent="neutral">
<template v-if="slots.option" #default="slotProps">
<slot name="option" v-bind="slotProps" />
</template>

View File

@@ -1,6 +1,6 @@
<template>
<VtsInputWrapper :label="t('rate-limit')" :message="error">
<UiInput v-model.number="model" accent="brand" type="number">
<UiInput v-model.number="model" accent="neutral" type="number">
<template #right-icon>
<span class="unit typo-body-regular">{{ t('bytes:kbs') }}</span>
</template>

View File

@@ -103,7 +103,7 @@
<VtsKeyValueList>
<VtsKeyValueRow>
<template #label>
<VtsSelect :id="localeSelectId" accent="brand" />
<VtsSelect :id="localeSelectId" accent="neutral" />
</template>
<template #value>
<UiLink size="medium" href="https://translate.vates.tech/engage/xen-orchestra/">

View File

@@ -10,7 +10,7 @@
<UiTitle>{{ t('template') }}</UiTitle>
<div class="template-container">
<VtsInputWrapper :label="t('action:pick-template')">
<VtsSelect :id="templateSelectId" accent="brand" />
<VtsSelect :id="templateSelectId" accent="neutral" />
</VtsInputWrapper>
</div>
<div v-if="vmState.new_vm_template" class="form-container">
@@ -30,7 +30,7 @@
{{ t('iso-dvd') }}
</UiRadioButton>
</UiRadioButtonGroup>
<VtsSelect v-if="vmState.installMode === 'ISO'" :id="vdiIsoSelectId" accent="brand" />
<VtsSelect v-if="vmState.installMode === 'ISO'" :id="vdiIsoSelectId" accent="neutral" />
</div>
<div v-else class="install-settings-container">
<UiRadioButtonGroup
@@ -45,7 +45,7 @@
{{ t('pxe') }}
</UiRadioButton>
</UiRadioButtonGroup>
<VtsSelect v-if="vmState.installMode === 'ISO'" :id="vdiIsoSelectId" accent="brand" />
<VtsSelect v-if="vmState.installMode === 'ISO'" :id="vdiIsoSelectId" accent="neutral" />
</div>
</div>
<!-- SYSTEM SECTION -->
@@ -54,11 +54,11 @@
<div class="system-container">
<div class="column">
<VtsInputWrapper :label="t('new-vm:name')">
<UiInput v-model.trim="vmState.name" accent="brand" />
<UiInput v-model.trim="vmState.name" accent="neutral" />
</VtsInputWrapper>
<VtsInputWrapper :label="t('tags')">
<!-- TODO Change input text into select when Thierry's component is available -->
<UiInput v-model.trim="vmState.tag" accent="brand" @keydown.enter.prevent="addTag" />
<UiInput v-model.trim="vmState.tag" accent="neutral" @keydown.enter.prevent="addTag" />
</VtsInputWrapper>
<div v-if="vmState.tags.length > 0" class="chips">
<UiChip v-for="(tag, index) in vmState.tags" :key="index" accent="info" @remove="removeTag(index)">
@@ -66,7 +66,7 @@
</UiChip>
</div>
<VtsInputWrapper :label="t('boot-firmware')">
<VtsSelect :id="bootFirmwareSelectId" accent="brand" />
<VtsSelect :id="bootFirmwareSelectId" accent="neutral" />
</VtsInputWrapper>
<div
v-if="vmState.boot_firmware !== 'uefi'"
@@ -93,11 +93,11 @@
</UiCheckboxGroup>
</div>
<div class="column">
<UiTextarea v-model="vmState.description" accent="brand">
<UiTextarea v-model="vmState.description" accent="neutral">
{{ t('new-vm:description') }}
</UiTextarea>
<VtsInputWrapper :label="t('affinity-host')">
<VtsSelect :id="affinityHostSelectId" accent="brand" />
<VtsSelect :id="affinityHostSelectId" accent="neutral" />
</VtsInputWrapper>
</div>
</div>
@@ -105,15 +105,15 @@
<UiTitle>{{ t('resource-management') }}</UiTitle>
<div class="resource-management-container">
<VtsInputWrapper :label="t('vcpus')">
<UiInput v-model.number="vmState.vCPU" type="number" accent="brand" />
<UiInput v-model.number="vmState.vCPU" type="number" accent="neutral" />
</VtsInputWrapper>
<!-- TODO remove (GB) when we can use new selector -->
<VtsInputWrapper :label="`${t('ram')} (GB)`">
<UiInput v-model.number="ramFormatted" type="number" accent="brand" />
<UiInput v-model.number="ramFormatted" type="number" accent="neutral" />
</VtsInputWrapper>
<VtsInputWrapper :label="t('topology')">
<div class="topology">
<VtsSelect :id="topologySelectId" accent="brand" />
<VtsSelect :id="topologySelectId" accent="neutral" />
</div>
</VtsInputWrapper>
</div>

View File

@@ -62,12 +62,12 @@
<FormSection :label="t('configuration')">
<div class="row">
<VtsInputWrapper :label="t('storage')" :message="t('n-gb-required', { n: REQUIRED_GB })">
<VtsSelect :id="srSelectId" accent="brand" />
<VtsSelect :id="srSelectId" accent="neutral" />
</VtsInputWrapper>
</div>
<div class="row">
<VtsInputWrapper :label="t('network')">
<VtsSelect :id="networkSelectId" accent="brand" />
<VtsSelect :id="networkSelectId" accent="neutral" />
</VtsInputWrapper>
<VtsInputWrapper
:label="t('deploy-xoa-custom-ntp-servers')"

View File

@@ -492,6 +492,13 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/middle-ellipsis/vts-middle-ellipsis': RouteRecordInfo<
'/story/web-core/middle-ellipsis/vts-middle-ellipsis',
'/story/web-core/middle-ellipsis/vts-middle-ellipsis',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/number-input/vts-number-input': RouteRecordInfo<
'/story/web-core/number-input/vts-number-input',
'/story/web-core/number-input/vts-number-input',
@@ -555,6 +562,13 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/select/vts-detailed-option': RouteRecordInfo<
'/story/web-core/select/vts-detailed-option',
'/story/web-core/select/vts-detailed-option',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/select/vts-select': RouteRecordInfo<
'/story/web-core/select/vts-select',
'/story/web-core/select/vts-select',
@@ -618,6 +632,20 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/tag/vts-tag': RouteRecordInfo<
'/story/web-core/tag/vts-tag',
'/story/web-core/tag/vts-tag',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/tag-select/vts-tag-select': RouteRecordInfo<
'/story/web-core/tag-select/vts-tag-select',
'/story/web-core/tag-select/vts-tag-select',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/tags-input/vts-tags-input': RouteRecordInfo<
'/story/web-core/tags-input/vts-tags-input',
'/story/web-core/tags-input/vts-tags-input',
@@ -625,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',
@@ -961,6 +996,13 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/ui/overridden/ui-overridden': RouteRecordInfo<
'/story/web-core/ui/overridden/ui-overridden',
'/story/web-core/ui/overridden/ui-overridden',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/ui/panel/ui-panel': RouteRecordInfo<
'/story/web-core/ui/panel/ui-panel',
'/story/web-core/ui/panel/ui-panel',
@@ -1101,13 +1143,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',
@@ -1661,6 +1696,12 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/stories/web-core/middle-ellipsis/vts-middle-ellipsis.story.vue': {
routes:
| '/story/web-core/middle-ellipsis/vts-middle-ellipsis'
views:
| never
}
'src/stories/web-core/number-input/vts-number-input.story.vue': {
routes:
| '/story/web-core/number-input/vts-number-input'
@@ -1715,6 +1756,12 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/stories/web-core/select/vts-detailed-option.story.vue': {
routes:
| '/story/web-core/select/vts-detailed-option'
views:
| never
}
'src/stories/web-core/select/vts-select.story.vue': {
routes:
| '/story/web-core/select/vts-select'
@@ -1769,12 +1816,30 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/stories/web-core/tag/vts-tag.story.vue': {
routes:
| '/story/web-core/tag/vts-tag'
views:
| never
}
'src/stories/web-core/tag-select/vts-tag-select.story.vue': {
routes:
| '/story/web-core/tag-select/vts-tag-select'
views:
| never
}
'src/stories/web-core/tags-input/vts-tags-input.story.vue': {
routes:
| '/story/web-core/tags-input/vts-tags-input'
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'
@@ -2063,6 +2128,12 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/stories/web-core/ui/overridden/ui-overridden.story.vue': {
routes:
| '/story/web-core/ui/overridden/ui-overridden'
views:
| never
}
'src/stories/web-core/ui/panel/ui-panel.story.vue': {
routes:
| '/story/web-core/ui/panel/ui-panel'
@@ -2183,12 +2254,6 @@ declare module 'vue-router/auto-routes' {
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

@@ -4,7 +4,7 @@
<div class="row">
Choose a component
<VtsSelect :id="componentSelectId" accent="brand" />
<VtsSelect :id="componentSelectId" accent="neutral" />
</div>
<div class="row">

View File

@@ -4,7 +4,7 @@
<template #content>
<div class="demo-rename-modal-content">
<VtsInputWrapper label="New name">
<UiInput v-model.trim="newName" accent="brand" required />
<UiInput v-model.trim="newName" accent="neutral" required />
</VtsInputWrapper>
<p>
Tip: name the VM "fail" to make the fake API call fail: the confirmation modal closes and this modal stays

View File

@@ -0,0 +1,24 @@
<template>
<ComponentStory
v-slot="{ properties, settings }"
:params="[
prop('text')
.str()
.required()
.preset('prod-web-frontend-eu-west-01')
.widget()
.help('Rendered as is when it fits, cut in the middle otherwise, with the full text in a tooltip'),
prop('tailLength').num().default(10).widget().help('Number of characters kept visible at the end of a cut text'),
setting('width').widget(number()).preset(15).help('Available width, in rem'),
]"
>
<VtsMiddleEllipsis v-bind="properties" :style="{ width: `${settings.width}rem` }" />
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { prop, setting } from '@/libs/story/story-param.ts'
import { number } from '@/libs/story/story-widget.ts'
import VtsMiddleEllipsis from '@core/components/middle-ellipsis/VtsMiddleEllipsis.vue'
</script>

View File

@@ -0,0 +1,53 @@
<template>
<ComponentStory
v-slot="{ properties }"
:params="[
prop('option')
.required()
.obj('FormOption<{ accent?: DropdownAccent }>')
.help('Given by the default slot of VtsSelect'),
iconProp().preset('object:network'),
prop('iconTooltip').str().widget(),
prop('details').str().widget().preset('eth0').help('Displayed after a dash'),
]"
:presets="{
'PIF with VLAN': {
props: {
icon: 'object:network',
details: 'eth1, VLAN 20',
},
},
'Disabled VM': {
props: {
icon: 'object:vm:running',
iconTooltip: 'Running',
details: 'No VIF detected',
},
},
'Without details': {
props: {
icon: 'object:network',
details: undefined,
},
},
}"
>
<VtsSelect :id="optionSelectId" accent="neutral">
<template #default="{ option }">
<VtsDetailedOption v-bind="properties" :option />
</template>
</VtsSelect>
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { iconProp, prop } from '@/libs/story/story-param.ts'
import VtsDetailedOption from '@core/components/select/VtsDetailedOption.vue'
import VtsSelect from '@core/components/select/VtsSelect.vue'
import { useFormSelect } from '@core/packages/form-select'
const optionLabels = ['Pool-wide network associated with eth0', 'Storage network']
const { id: optionSelectId } = useFormSelect(optionLabels)
</script>

View File

@@ -2,36 +2,32 @@
<ComponentStory
v-slot="{ properties }"
:params="[
prop('accent').required().enum('brand', 'warning', 'danger').preset('brand').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,46 @@
<template>
<ComponentStory
v-slot="{ properties }"
:params="[
prop('tags').arr('string').required().help('Currently selected tags. The component never mutates it'),
prop('suggestions').arr('TagSelectSuggestion').preset(suggestions).widget(),
prop('iconOnly').bool().widget().help('Displays the `Add`/`Edit` trigger as an icon with a tooltip'),
prop('busy').bool().widget().help('Displays the trigger as busy, e.g. while the tags are being saved'),
event('save')
.args({ changes: 'TagSelectChanges' })
.help('Emitted with the added and removed tags when clicking `Save`. `Cancel` discards the changes'),
]"
>
<UiTagsList>
<VtsTag v-for="tag of tags" :key="tag" :value="tag" accent="brand" />
<VtsTagSelect v-bind="properties" :tags @save="changes => saveTags(changes)" />
</UiTagsList>
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { event, prop } from '@/libs/story/story-param.ts'
import VtsTag from '@core/components/tag/VtsTag.vue'
import VtsTagSelect, {
type TagSelectChanges,
type TagSelectSuggestion,
} from '@core/components/tag-select/VtsTagSelect.vue'
import UiTagsList from '@core/components/ui/tag/UiTagsList.vue'
import { ref } from 'vue'
const tags = ref(['production', 'env=prod'])
const suggestions: TagSelectSuggestion[] = [
{ tag: 'production' },
{ tag: 'staging' },
{ tag: 'env=prod' },
{ tag: 'env=dev' },
{ tag: 'xo:no-bak', info: 'Excludes the VM from backups' },
{ tag: 'xo:notify-on-snapshot', info: 'Notifies when a snapshot is created' },
]
function saveTags({ added, removed }: TagSelectChanges) {
tags.value = [...tags.value.filter(tag => !removed.includes(tag)), ...added]
}
</script>

View File

@@ -0,0 +1,36 @@
<template>
<ComponentStory
v-slot="{ properties }"
:params="[
prop('value')
.str()
.required()
.preset('env=prod')
.widget()
.help('Tags in the `term=label` form are displayed as a tertiary tag'),
prop('accent')
.type('TagAccent')
.enum('brand', 'info', 'neutral', 'success', 'warning', 'danger', 'muted')
.default('info')
.widget(),
prop('variant')
.type('TagVariant')
.enum('primary', 'secondary')
.default('secondary')
.widget()
.help('Ignored when the tag is displayed as a tertiary tag'),
prop('wrap')
.bool()
.widget()
.help('Stacks the term above the value when they do not fit on one line (tertiary tag only)'),
]"
>
<VtsTag v-bind="properties" />
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { prop } from '@/libs/story/story-param.ts'
import VtsTag from '@core/components/tag/VtsTag.vue'
</script>

View File

@@ -9,6 +9,6 @@ The label comes from the surrounding `VtsInputWrapper`.
```vue-template
<VtsInputWrapper label="Values">
<VtsTagsInput v-model="values" accent="brand" placeholder="Add a value" />
<VtsTagsInput v-model="values" accent="neutral" placeholder="Add a value" />
</VtsInputWrapper>
```

View File

@@ -3,7 +3,7 @@
v-slot="{ properties }"
:params="[
model().type('string[]').preset(['alpha', 'beta']).help('Enter or comma adds the typed value'),
prop('accent').enum('brand', 'warning', 'danger').required().preset('brand').widget(),
prop('accent').enum('neutral', 'warning', 'danger').required().preset('neutral').widget(),
prop('placeholder').str().preset('Add a value').widget(),
]"
>

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

@@ -7,7 +7,7 @@
prop('accent')
.type('CircleProgressBarAccent')
.required()
.enum('info', 'warning', 'danger')
.enum('brand', 'info', 'warning', 'danger')
.preset('info')
.widget(),
prop('size')
@@ -16,6 +16,7 @@
.enum('extra-small', 'small', 'medium', 'large')
.preset('large')
.widget(),
prop('noValue').bool().widget(),
]"
:presets
>
@@ -35,6 +36,7 @@ const presets = {
maxValue: 500,
size: 'medium',
accent: 'info',
noValue: false,
},
},
'75% of 300': {
@@ -43,6 +45,34 @@ const presets = {
maxValue: 300,
size: 'medium',
accent: 'info',
noValue: false,
},
},
'Value above max (success)': {
props: {
value: 150,
maxValue: 100,
size: 'medium',
accent: 'info',
noValue: false,
},
},
'Value above max (warning)': {
props: {
value: 150,
maxValue: 100,
size: 'medium',
accent: 'warning',
noValue: false,
},
},
'Brand ring without value': {
props: {
value: 1,
maxValue: 3,
size: 'small',
accent: 'brand',
noValue: true,
},
},
}

View File

@@ -3,7 +3,7 @@
v-slot="{ properties }"
:params="[
model().type('string | number').preset(''),
prop('accent').enum('brand', 'warning', 'danger').required().preset('brand').widget(),
prop('accent').enum('neutral', 'success', 'warning', 'danger').required().preset('neutral').widget(),
prop('id').str().widget(),
prop('required').bool().widget(),
prop('selected').bool().widget(),

View File

@@ -3,7 +3,7 @@
v-slot="{ properties, settings }"
:params="[
model().type('string').preset(''),
prop('accent').enum('brand', 'warning', 'danger').required().preset('brand').widget(),
prop('accent').enum('neutral', 'warning', 'danger').required().preset('neutral').widget(),
prop('disabled').bool().widget(),
prop('href').str().widget(),
prop('max-characters').num().help('When used, it will display the character count under the input').widget(),

View File

@@ -0,0 +1,19 @@
<template>
<ComponentStory
v-slot="{ settings }"
:params="[
slot().help('Label displayed next to the dot, leave empty to only display the dot'),
setting('defaultSlot').widget(text()).preset('Overridden'),
]"
>
<UiOverridden v-if="settings.defaultSlot">{{ settings.defaultSlot }}</UiOverridden>
<UiOverridden v-else />
</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 UiOverridden from '@core/components/ui/overridden/UiOverridden.vue'
</script>

View File

@@ -6,7 +6,7 @@
.type('TagAccent')
.required()
.preset('info')
.enum('info', 'neutral', 'success', 'warning', 'danger', 'muted')
.enum('brand', 'info', 'neutral', 'success', 'warning', 'danger', 'muted')
.widget(),
prop('variant').type('TagVariant').required().preset('primary').enum('primary', 'secondary').widget(),
slot(),

View File

@@ -6,15 +6,21 @@
.type('TagAccent')
.required()
.preset('info')
.enum('info', 'neutral', 'success', 'warning', 'danger', 'muted')
.enum('brand', 'info', 'neutral', 'success', 'warning', 'danger', 'muted')
.widget(),
prop('truncate')
.bool()
.widget()
.help('Keeps the tag on one line: the longer part ends with an ellipsis first, the shorter one stays whole'),
prop('wrap').bool().widget().help('Stacks the term above the value when they do not fit on one line'),
slot(),
slot('term'),
setting('slot').preset('Label').widget(),
setting('term').preset('term').widget(),
setting('maxWidth').widget(number()).help('Maximum width, in rem'),
]"
>
<UiTertiaryTag v-bind="properties">
<UiTertiaryTag v-bind="properties" :style="{ maxWidth: settings.maxWidth ? `${settings.maxWidth}rem` : undefined }">
{{ settings.slot }}
<template #term>
{{ settings.term }}
@@ -26,5 +32,6 @@
<script lang="ts" setup>
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'
</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,
},
},

View File

@@ -1,15 +0,0 @@
<template>
<ComponentStory
v-slot="{ properties }"
:params="[prop('tasks').type('Task[]').required().preset(allTasks), event('select')]"
>
<UiTaskList 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 UiTaskList from '@core/components/ui/task-list/UiTaskList.vue'
</script>

View File

@@ -1,7 +1,7 @@
{
"private": false,
"name": "@xen-orchestra/log",
"version": "0.7.2",
"version": "1.0.0",
"license": "ISC",
"description": "Logging system with decoupled producers/consumer",
"keywords": [

View File

@@ -1,7 +1,7 @@
{
"private": false,
"name": "@xen-orchestra/mcp",
"version": "1.4.3",
"version": "1.4.4",
"description": "MCP server for Xen Orchestra — allows AI assistants to query and manage XO infrastructure",
"type": "module",
"main": "./dist/index.mjs",
@@ -34,7 +34,7 @@
"devDependencies": {
"@eslint/js": "^9.19.0",
"@types/node": "^22.3.0",
"@vates/types": "^2.5.0",
"@vates/types": "^3.0.0",
"rimraf": "^6.0.0",
"typescript": "~5.6.3",
"typescript-eslint": "^8.61.0"

View File

@@ -14,18 +14,18 @@
"url": "https://vates.fr"
},
"license": "AGPL-3.0-or-later",
"version": "0.23.0",
"version": "0.24.0",
"engines": {
"node": ">=15.6"
},
"dependencies": {
"@vates/async-each": "^1.0.3",
"@vates/event-listeners-manager": "^1.0.1",
"@vates/iscsi": "^0.4.0",
"@vates/iscsi": "^0.4.1",
"@vates/parse-duration": "^0.1.1",
"@vates/task": "^0.7.0",
"@xen-orchestra/backup-archive": "^1.2.0",
"@xen-orchestra/log": "^0.7.2",
"@xen-orchestra/backup-archive": "^1.2.1",
"@xen-orchestra/log": "^1.0.0",
"acme-client": "^5.0.0",
"app-conf": "^3.0.0",
"fast-xml-parser": "^4.0.0",
@@ -36,7 +36,7 @@
"xo-common": "^0.11.0"
},
"devDependencies": {
"@vates/types": "^2.5.0"
"@vates/types": "^3.0.0"
},
"scripts": {
"postversion": "npm publish --access public",

View File

@@ -11,14 +11,15 @@ const { warn } = createLogger('xo:proxy:authentication')
const isValidToken = t => typeof t === 'string' && t.length !== 0
export default class Authentication {
#app
// kept in memory because the config is not reloaded when the token is written at construction
#token
constructor(app, { appName, config: { authenticationToken: token } }) {
this.#app = app
const setToken = ({ token }) => {
assert(isValidToken(token), 'invalid authentication token: ' + token)
this.#token = token
// save this token in the automatically handled conf file
fse.outputFileSync(
// this file must take precedence over normal user config
@@ -38,6 +39,13 @@ export default class Authentication {
}
}
// follow config changes (including the ones made by setToken)
app.config.watch('authenticationToken', token => {
if (isValidToken(token)) {
this.#token = token
}
})
app.api.addMethod('authentication.setToken', setToken, {
description: 'change the authentication token used by this XO Proxy',
params: {
@@ -50,7 +58,9 @@ export default class Authentication {
}
async findProfile(credentials) {
if (credentials?.token === this.#app.config.get('authenticationToken')) {
const token = credentials?.token
// never match an empty/missing token, even if no valid token is known
if (isValidToken(token) && token === this.#token) {
return new Profile()
}
}

View File

@@ -1,7 +1,7 @@
{
"private": true,
"name": "@xen-orchestra/proxy",
"version": "0.34.0",
"version": "0.35.0",
"license": "AGPL-3.0-or-later",
"description": "XO Proxy used to remotely execute backup jobs",
"keywords": [
@@ -31,16 +31,16 @@
"@vates/cached-dns.lookup": "^1.0.0",
"@vates/compose": "^2.1.0",
"@vates/decorate-with": "^2.1.0",
"@vates/disposable": "^0.1.6",
"@vates/disposable": "^0.1.7",
"@vates/task": "^0.7.0",
"@xen-orchestra/async-map": "^0.1.5",
"@xen-orchestra/backups": "^0.78.0",
"@xen-orchestra/fs": "^4.10.0",
"@xen-orchestra/log": "^0.7.2",
"@xen-orchestra/backups": "^1.0.0",
"@xen-orchestra/fs": "^4.11.0",
"@xen-orchestra/log": "^1.0.0",
"@xen-orchestra/mixin": "^0.2.1",
"@xen-orchestra/mixins": "^0.23.0",
"@xen-orchestra/mixins": "^0.24.0",
"@xen-orchestra/self-signed": "^0.2.1",
"@xen-orchestra/xapi": "^9.1.0",
"@xen-orchestra/xapi": "^10.0.0",
"ajv": "^8.0.3",
"app-conf": "^3.0.0",
"async-iterator-to-stream": "^1.1.0",
@@ -62,7 +62,7 @@
"source-map-support": "^0.5.16",
"stoppable": "^1.0.6",
"xdg-basedir": "^5.1.0",
"xen-api": "^5.1.0",
"xen-api": "^6.0.0",
"xo-common": "^0.11.0"
},
"devDependencies": {

View File

@@ -2,7 +2,7 @@
"name": "@xen-orchestra/qa-test",
"private": true,
"type": "module",
"version": "1.4.0",
"version": "1.5.0",
"description": "XenOrchestra QA Test Suite",
"author": {
"name": "Vates SAS",
@@ -22,10 +22,10 @@
"dependencies": {
"@vates/async-each": "^1.0.3",
"@vates/read-chunk": "^1.2.1",
"@xen-orchestra/backups": "^0.78.0",
"@xen-orchestra/fs": "^4.10.0",
"@xen-orchestra/log": "^0.7.2",
"@xen-orchestra/vmware-explorer": "^1.2.0",
"@xen-orchestra/backups": "^1.0.0",
"@xen-orchestra/fs": "^4.11.0",
"@xen-orchestra/log": "^1.0.0",
"@xen-orchestra/vmware-explorer": "^1.3.0",
"nodemailer": "^7.0.13",
"xo-lib": "^0.11.2"
},

View File

@@ -3,6 +3,10 @@ import assert from 'node:assert'
import { after, before, describe, it } from 'node:test'
import { createLogger } from '@xen-orchestra/log'
import { DispatchClient } from '../client/dispatchClient.js'
import { RestApiClient } from '../client/restApiClient.js'
import { createTestUser, deleteTestUser } from '../utils/aclUtils.js'
import { getRequiredEnv } from '../utils/index.js'
import { setup, teardown } from './setup.js'
const log = createLogger('qa:sdn-controller')
@@ -517,3 +521,142 @@ describe('SDN Controller REST API', { skip: !process.env.SDN_CONTROLLER_VM_ID },
})
})
})
// ---------------------------------------------------------------------------
// The networks go on the pools the suite already tests on: the pool of SDN_CONTROLLER_VM_ID and, when it is another
// one, the pool of REFERENCE_VM_ID. Never any other pool XO is connected to: a private network sets the SDN controller
// of its pools. The tunnels go through the network of the management PIF of each pool's master
describe('SDN Controller private networks', { skip: !process.env.SDN_CONTROLLER_VM_ID }, () => {
let dispatchClient
let pools
const networkIds = []
// RestApiClient answers only the body, and the route's statuses are checked too
const createPrivateNetwork = async (body, client = dispatchClient.restApiClient) => {
const response = await fetch(`${client.baseUrl}${BASE}/pools/actions/create_private_network?sync=true`, {
method: 'POST',
headers: client.headers,
body: JSON.stringify(body),
})
const result = await response.json()
networkIds.push(...(result.networkIds ?? []))
return { status: response.status, result }
}
const bodyFor = (pools, params) => ({
poolIds: pools.map(pool => pool.id),
pifIds: pools.map(pool => pool.pifId),
name: `qa-sdn-private-network-${Date.now()}`,
description: 'created by the qa-test suite',
encapsulation: 'gre',
...params,
})
const networksNamed = async name =>
(await dispatchClient.restApiClient.getObjects('/rest/v0/networks')).filter(network => network.name_label === name)
before(async () => {
dispatchClient = new DispatchClient()
await dispatchClient.initialize()
const { restApiClient } = dispatchClient
const vmPoolIds = await Promise.all(
[process.env.SDN_CONTROLLER_VM_ID, getRequiredEnv('REFERENCE_VM_ID')].map(
async id => (await restApiClient.get(`/rest/v0/vms/${id}`)).$pool
)
)
const [allPools, hosts, pifs] = await Promise.all(
['pools', 'hosts', 'pifs'].map(collection => restApiClient.getObjects(`/rest/v0/${collection}`))
)
pools = [...new Set(vmPoolIds)].map(id => {
const { master } = allPools.find(pool => pool.id === id)
return {
id,
masterId: master,
pifId: pifs.find(pif => pif.$host === master && pif.management)?.id,
hostCount: hosts.filter(host => host.$pool === id).length,
}
})
log.debug('Private network pools', { pools })
})
after(async () => {
for (const id of networkIds) {
try {
await dispatchClient.restApiClient.delete(`/rest/v0/networks/${id}`)
} catch (error) {
log.warn('Failed to delete a private network', { error, networkId: id })
}
}
await dispatchClient?.close()
})
// the preferred center is a host of the last pool, so that its network is not the first one asked for
it('should create one network per pool, each with a tunnel on every host, in a single private network', async t => {
if (pools.length === 1) {
t.diagnostic('XO is connected to a single pool: the private network spans it alone')
}
const preferredCenterId = pools.at(-1).masterId
const body = bodyFor(pools, { mtu: 1400, preferredCenterId })
const { status, result } = await createPrivateNetwork(body)
assert.strictEqual(status, 201, JSON.stringify(result))
assert.strictEqual(result.networkIds.length, pools.length)
const networks = await Promise.all(
result.networkIds.map(id => dispatchClient.restApiClient.get(`/rest/v0/networks/${id}?fields=*`))
)
const { 'xo:sdn-controller:private-network-uuid': privateNetworkUuid, 'xo:sdn-controller:vni': vni } =
networks[0].other_config
assert.match(privateNetworkUuid, /^[0-9a-f-]{36}$/)
assert.match(vni, /^\d+$/)
assert.deepStrictEqual(networks.map(network => network.$pool).sort(), pools.map(pool => pool.id).sort())
for (const network of networks) {
const pool = pools.find(pool => pool.id === network.$pool)
assert.strictEqual(network.name_label, body.name)
assert.strictEqual(network.MTU, 1400)
assert.strictEqual(network.PIFs.length, pool.hostCount, 'one tunnel access PIF per host')
assert.deepStrictEqual(
{
encapsulation: network.other_config['xo:sdn-controller:encapsulation'],
preferredCenter: network.other_config['xo:sdn-controller:preferred-center'],
privateNetworkUuid: network.other_config['xo:sdn-controller:private-network-uuid'],
vni: network.other_config['xo:sdn-controller:vni'],
},
{ encapsulation: 'gre', preferredCenter: preferredCenterId, privateNetworkUuid, vni }
)
}
})
it('should refuse an unknown pool, a pool without a PIF or an unknown encapsulation, creating no network', async () => {
const body = bodyFor(pools.slice(0, 1))
for (const [params, expectedStatus] of [
[{ poolIds: ['00000000-0000-0000-0000-000000000000'] }, 404],
[{ pifIds: [] }, 422],
[{ encapsulation: 'ipip' }, 422],
]) {
const { status, result } = await createPrivateNetwork({ ...body, ...params })
assert.strictEqual(status, expectedStatus, `${JSON.stringify(params)}: ${JSON.stringify(result)}`)
}
assert.deepStrictEqual(await networksNamed(body.name), [])
})
it('should refuse a user who is not an admin', async () => {
const user = await createTestUser(dispatchClient.xoClient)
try {
const client = new RestApiClient({
xoUrl: getRequiredEnv('HOSTNAME'),
username: user.email,
password: user.password,
})
await client.connect()
const body = bodyFor(pools.slice(0, 1))
const { status, result } = await createPrivateNetwork(body, client)
assert.strictEqual(status, 403, JSON.stringify(result))
assert.deepStrictEqual(await networksNamed(body.name), [])
} finally {
await deleteTestUser(dispatchClient.xoClient, user.id)
}
})
})

View File

@@ -6,7 +6,7 @@
"main": "./dist/index.mjs",
"name": "@xen-orchestra/rest-api",
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/@xen-orchestra/rest-api",
"version": "0.41.1",
"version": "0.42.0",
"description": "REST API to manage your XOA",
"license": "AGPL-3.0-or-later",
"private": false,
@@ -36,16 +36,16 @@
},
"dependencies": {
"@vates/async-each": "^1.0.3",
"@vates/obfuscate": "^0.1.0",
"@vates/obfuscate": "^0.2.0",
"@vates/task": "^0.7.0",
"@vates/types": "^2.5.0",
"@xen-orchestra/acl": "^1.8.0",
"@xen-orchestra/backups": "^0.78.0",
"@vates/types": "^3.0.0",
"@xen-orchestra/acl": "^1.9.0",
"@xen-orchestra/backups": "^1.0.0",
"@xen-orchestra/cron": "^1.0.7",
"@xen-orchestra/log": "^0.7.2",
"@xen-orchestra/log": "^1.0.0",
"@xen-orchestra/qcow2": "^1.4.1",
"@xen-orchestra/vmdk": "^1.0.0",
"@xen-orchestra/xapi": "^9.1.0",
"@xen-orchestra/xapi": "^10.0.0",
"complex-matcher": "^1.1.1",
"fast-xml-parser": "^5.10.1",
"golike-defer": "^0.5.1",
@@ -57,7 +57,7 @@
"swagger-ui-express": "^5.0.1",
"tsoa": "^6.6.0",
"value-matcher": "^0.2.0",
"vhd-lib": "^4.17.0",
"vhd-lib": "^4.17.1",
"xo-common": "^0.11.0",
"xo-remote-parser": "^2.0.0",
"zod": "^4.3.6",

View File

@@ -15,6 +15,8 @@ import type {
import type { RestApi } from '../rest-api/rest-api.mjs'
import { assertValidCron, vmContainsNoBakTag } from '../helpers/utils.helper.mjs'
import type { CreateBackupJobBody, CreateBackupJobSchedule, UpdateBackupJobBody } from './backup-job.type.mjs'
import { compileExpression, isExpression } from '@xen-orchestra/backups/_expressionPredicate.mjs'
import { buildRunContext, buildVmContext } from '@xen-orchestra/backups/_buildContext.mjs'
export class BackupJobService {
#backupJobTypes = ['backup', 'metadataBackup', 'mirrorBackup']
@@ -69,12 +71,24 @@ export class BackupJobService {
*/
assertJobHasValidExpressions(type: AnyXoBackupJob['type'], job: UpdateBackupJobBody): void {
if (type === 'backup') {
const { srs, remotes, settings } = job as Extract<UpdateBackupJobBody, { srs?: unknown }>
const { srs, remotes, vms, settings } = job as Extract<UpdateBackupJobBody, { srs?: unknown }>
assertValidExpression('srs', srs)
assertValidExpression('remotes', remotes)
assertValidExpression('vms', vms)
assertValidSettingsExpression(settings, ['healthCheckVmsWithTags', 'fullInterval'])
} else if (type === 'mirrorBackup') {
assertValidSettingsExpression(job.settings, ['healthCheckVmsWithTags', 'vmFilter'])
const { filter, remotes, settings } = job as Extract<UpdateBackupJobBody, { sourceRemote?: unknown }>
assertValidSettingsExpression(settings, ['healthCheckVmsWithTags', 'vmFilter'])
assertValidExpression('remotes', remotes)
if (filter != null && filter.vm.uuid.__or.length === 0) {
throw invalidParameters('filter must contain at least one VM', [
{ instancePath: '/filter/vm/uuid/__or', message: 'must NOT have fewer than 1 items' },
])
}
} else if (type === 'metadataBackup') {
const { remotes, pools } = job as Extract<UpdateBackupJobBody, { pools?: unknown }>
assertValidExpression('remotes', remotes)
assertValidExpression('pools', pools)
}
}
@@ -90,16 +104,47 @@ export class BackupJobService {
return false
}
const isVmInJob = await this.getBackupJobVmMatcher(backupJob)
return isVmInJob(vm)
}
/**
* Returns a function telling whether a VM is selected by the `vms` of the job,
* whether it is a list of IDs, an object pattern or an expression
*/
async getBackupJobVmMatcher(backupJob: XoVmBackupJob): Promise<(vm: XoVm) => boolean> {
try {
const vmIds: XoVm['id'][] = extractIdsFromSimplePattern(backupJob.vms)
return vmIds.some(id => id === vm.id)
const vmIds = new Set<XoVm['id']>(extractIdsFromSimplePattern(backupJob.vms))
return vm => vmIds.has(vm.id)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (_) {
const predicate = createPredicate(backupJob.vms)
return predicate(vm)
if (!isExpression(backupJob.vms)) {
return createPredicate(backupJob.vms)
}
// `run:` clauses depend on the timezone, which is resolved per schedule like the executor does,
// so the VM is in the job if it matches for at least one of its schedules
const predicate = compileExpression(backupJob.vms)
const now = new Date()
const runContexts = (await this.#getScheduleTimezones(backupJob)).map(timezone => buildRunContext(now, timezone))
return vm => runContexts.some(runContext => predicate(buildVmContext(vm, runContext)))
}
}
async #getScheduleTimezones(backupJob: XoVmBackupJob): Promise<(string | undefined)[]> {
const schedules = (await this.#restApi.xoApp.getAllSchedules()).filter(schedule => schedule.jobId === backupJob.id)
if (schedules.length === 0) {
return [backupJob.settings['']?.timezone]
}
return schedules.map(schedule => {
const scheduleTimezone = backupJob.settings[schedule.id]?.timezone
return typeof scheduleTimezone === 'string'
? scheduleTimezone
: (backupJob.settings['']?.timezone ?? schedule.timezone)
})
}
async backupJobHasAtLeastOneScheduleEnabled(id: XoVmBackupJob['id']): Promise<boolean> {
const backupJob = await this.#restApi.xoApp.getJob<XoVmBackupJob>(id)

View File

@@ -6,15 +6,19 @@ import type {
XoMetadataBackupJobGeneralSettings,
XoMetadataBackupJobScheduleSettings,
XoMirrorBackupGeneralSettings,
XoVm,
} from '@vates/types'
import { Unbrand } from '../open-api/common/response.common.mjs'
import type * as CMType from '@vates/types/lib/complex-matcher'
// Manual copy because with Unbrand<>, tsoa emits an empty schema. If XoVmBackupJobScheduleSettings changes
// in @vates/types, you have to update this copy too.
type UnbrandedXoVmBackupJobScheduleSettings = {
/**
* Copy of XoVmBackupJobScheduleSettings without the brand:
* tsoa empties any mapped type (Unbrand, Pick, Omit…) nested under Unbrand<UnbrandedXoVmBackupJob>,
* which dropped every schedule setting from the request bodies
*/
type VmBackupJobScheduleSettings = {
exportRetention?: number
healthCheckVmsWithTags?: string[] | string
healthCheckVmsWithTags?: XoVm['tags'] | string
fullInterval?: number | string
copyRetention?: number
snapshotRetention?: number
@@ -25,17 +29,17 @@ type UnbrandedXoVmBackupJobScheduleSettings = {
type UnbrandedXoVmBackupJob = Omit<XoVmBackupJob, 'settings' | 'remotes' | 'vms' | 'srs'> & {
remotes?: CMType.IdOr<string> | string
vms: CMType.IdOr<string> | Record<string, unknown>
vms: CMType.IdOr<string> | Record<string, unknown> | string
srs?: CMType.IdOr<string> | string
settings: {
'': XoVmBackupJobGeneralSettings
[scheduleId: string]: UnbrandedXoVmBackupJobScheduleSettings | undefined
[scheduleId: string]: VmBackupJobScheduleSettings | undefined
}
}
export type UnbrandXoVmBackupJob = Unbrand<UnbrandedXoVmBackupJob>
type UnbrandedXoMetadataBackupJob = Omit<XoMetadataBackupJob, 'settings' | 'pools' | 'remotes'> & {
pools?: CMType.IdOr<string>
pools?: CMType.IdOr<string> | string
remotes: CMType.IdOr<string>
settings: {
''?: XoMetadataBackupJobGeneralSettings
@@ -44,21 +48,23 @@ type UnbrandedXoMetadataBackupJob = Omit<XoMetadataBackupJob, 'settings' | 'pool
}
export type UnbrandXoMetadataBackupJob = Unbrand<UnbrandedXoMetadataBackupJob>
// Manual copy because with Unbrand<>, tsoa emits an empty schema. If XoMirrorBackupScheduleSettings changes
// in @vates/types, you have to update this copy too.
type UnbrandedXoMirrorBackupScheduleSettings = {
/**
* Same as VmBackupJobScheduleSettings
*/
type MirrorBackupJobScheduleSettings = {
exportRetention?: number
healthCheckVmsWithTags?: string[] | string
healthCheckVmsWithTags?: XoVm['tags'] | string
vmFilter?: string
healthCheckSr?: string
[key: string]: unknown
}
type UnbrandedXoMirrorBackupJob = Omit<XoMirrorBackupJob, 'settings' | 'remotes'> & {
type UnbrandedXoMirrorBackupJob = Omit<XoMirrorBackupJob, 'settings' | 'remotes' | 'filter'> & {
remotes: CMType.IdOr<string>
filter?: { vm: { uuid: { __or: string[] } } } | null
settings: {
'': XoMirrorBackupGeneralSettings
[scheduleId: string]: UnbrandedXoMirrorBackupScheduleSettings | undefined
[scheduleId: string]: MirrorBackupJobScheduleSettings | undefined
}
}
export type UnbrandXoMirrorBackupJob = Unbrand<UnbrandedXoMirrorBackupJob>

View File

@@ -195,3 +195,12 @@ export const parseXml = (function () {
export function ensureArray<T>(value: T | T[] | undefined): T[] {
return value === undefined ? [] : Array.isArray(value) ? value : [value]
}
export function getFileNameFromUrl(url: URL): string {
const fileName = url.pathname.slice(url.pathname.lastIndexOf('/') + 1)
try {
return decodeURIComponent(fileName)
} catch {
return fileName
}
}

View File

@@ -57,6 +57,11 @@ export const notImplementedResp = {
description: 'Not implemented',
} as const
export const proxyUnreachableResp = {
status: 502,
description: 'Proxy unreachable',
} as const
export const resourceAlreadyExists = {
status: 409,
description: 'Resource already exists',

View File

@@ -533,10 +533,12 @@ export const poolRollingUpdateRecovery = {
interruptedAt: '2026-08-31T14:18:47.000Z',
taskId: '0mf2gtitq',
variant: 'xcp',
attempt: 2,
resumable: true,
hostOrder: ['b61a5c92-700e-4966-a13b-00633f03eea8', '46522969-d891-4c48-a839-316b767b7b7b'],
hosts: {
'b61a5c92-700e-4966-a13b-00633f03eea8': {
status: 'running',
status: 'interrupted',
steps: {
evacuate: {
status: 'observed-succeeded',
@@ -559,7 +561,7 @@ export const poolRollingUpdateRecovery = {
lastError: null,
},
'46522969-d891-4c48-a839-316b767b7b7b': {
status: 'running',
status: 'interrupted',
steps: {
evacuate: { status: 'running', startedAt: '2026-08-31T14:12:50.000Z' },
update: { status: 'pending' },
@@ -574,4 +576,17 @@ export const poolRollingUpdateRecovery = {
haltedPinnedVms: {
'883b6265-6d54-c48b-6a24-4b0e6d88801f': 'b61a5c92-700e-4966-a13b-00633f03eea8',
},
vmConflicts: [
{
vmId: '613f541c-4bed-fc77-7ca8-2db6b68f079c',
vmName: 'Debian 12',
hostId: '46522969-d891-4c48-a839-316b767b7b7b',
reason: 'stopped',
},
],
operatorChanges: [],
planChange: {
attempt: 2,
addedHostIds: ['b61a5c92-700e-4966-a13b-00633f03eea8'],
},
}

View File

@@ -22,6 +22,8 @@ export const proxy = {
name: 'Proxy 2025-08-29T08:23:33.394Z',
vmUuid: '7330139d-288f-2248-5986-d508ea71f12c',
id: 'e625ea0c-a876-405a-b838-109d762efe88',
url: 'https://uxxa-NIAY9W29VlGMrRcKuxx2dsYMTldJo-7l2YnMNQ@10.1.7.238/',
url: 'proxy.url is no longer exposed by Xen Orchestra because it contained the proxy authentication token, see the Xen Orchestra changelog',
version: '0.29.29',
}
export const proxyHealth = { success: true }

View File

@@ -84,6 +84,7 @@ import type {
CreateVmParams,
FinalizeRollingUpdateBody,
PoolDashboard,
ResumeRollingUpdateBody,
RollingPoolActionBody,
RollingPoolUpdateBody,
} from './pool.type.mjs'
@@ -794,7 +795,13 @@ export class PoolController extends XapiXoController<XoPool> {
/**
* Recovery status of an incomplete rolling pool update: run and per-host
* step statuses, last error, pinned VMs still halted. 404 when the last
* step statuses, last error, pinned VMs still halted, VMs the update could
* not migrate back to their original host (`vmConflicts`), hosts a resume
* added to the plan because of patches released since the run started or
* because they joined the pool since (`planChange`), what an operator
* changed since: settings the update left changed, hosts, VMs or backup
* schedules of the update removed, which block its resume until accepted
* (`operatorChanges`). 404 when the last
* rolling pool update completed successfully (no recovery needed), or when
* the pool's master does not run XCP-ng or XenServer 8.4+ (no recovery
* record is kept for those pools).
@@ -820,12 +827,20 @@ export class PoolController extends XapiXoController<XoPool> {
}
/**
* Close the record of an incomplete rolling pool update, once the pool has been reviewed.
* Close the record of an incomplete rolling pool update.
*
* Refused with an `incorrect state` error listing what the update changed and did not restore (HA, auto power-on,
* WLB, load balancer, backup schedules, disabled hosts, displaced or halted VMs) while any item remains, or when
* the record cannot be read. Displaced VMs alone do not refuse it, they are only listed in the task. Set `force` to `true` to close it anyway: the items are abandoned and listed in the
* task, nothing is restored nor changed in the pool. 404 when the pool has no record.
* What the update changed and did not restore is restored first, best effort: disabled hosts are enabled, halted
* pinned VMs are started, displaced VMs are migrated back to their host, and HA, auto power-on, WLB, the load
* balancer and the backup schedules are enabled again. The record is closed once nothing is left but VMs which could
* not be migrated back: they do not keep the call refused.
*
* A host which was updated and not rebooted is left disabled, without its VMs: it keeps the call refused, resuming
* the update is what finishes it.
*
* Refused with an `incorrect state` error listing what could not be restored while any other item remains, or when
* the record cannot be read: the record is kept. Refused with a `forbidden operation` error while a backup runs or
* may run on the pool and VMs are left to migrate back. Set `force` to `true` to close it anyway: the items are
* abandoned and listed in the task, nothing is restored nor changed in the pool. 404 when the pool has no record.
*
* Required privilege:
* - resource: pool, action: rolling-update
@@ -865,6 +880,64 @@ export class PoolController extends XapiXoController<XoPool> {
})
}
/**
* Resume a failed or interrupted rolling pool update: the same run continues, the hosts with remaining work are
* evacuated, updated and rebooted, and a host a previous attempt finished is updated and rebooted again if patches
* were released since. Then the VMs are migrated back to the host they were on before the first attempt. The settings the previous attempts left disabled (HA, auto power on, backup schedules, WLB, load
* balancer) stay disabled until the end of the run, then are restored.
*
* The backup check is not taken from the previous attempts: set `bypassBackupCheck` again if needed.
*
* 404 when the pool has no record. Refused with an `incorrect state` error when the update is neither failed,
* interrupted nor awaiting acceptance.
*
* When an operator changed a setting the update left changed (HA, auto power on, WLB or a backup schedule enabled
* again, a heartbeat SR of HA deleted) or removed a host, a VM or a backup schedule of the update, the update goes
* to `awaiting-acceptance` and the resume is refused with an `incorrect state` error on `operatorChanges` listing
* them. Set
* `acceptOperatorChanges` to keep them: the update starts from the current state, as a new one would. A setting
* enabled again is disabled while the update runs and enabled again at its end, HA whose heartbeat SR was deleted
* stays disabled, and the removed hosts and VMs are left out.
*
* Required privilege:
* - resource: pool, action: rolling-update
*
* @example id "355ee47d-ff4c-4924-3db2-fd86ae629676"
* @example body { "bypassBackupCheck": false }
*/
@Example(taskLocation)
@Extension('x-mcp-exposure', 'confirm')
@Post('{id}/actions/resume_rolling_update')
@Middlewares([json(), acl({ resource: 'pool', action: 'rolling-update', objectId: 'params.id' })])
@SuccessResponse(asynchronousActionResp.status, asynchronousActionResp.description)
@Response(noContentResp.status, noContentResp.description)
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
@Response(featureUnauthorized.status, featureUnauthorized.description)
@Response(notFoundResp.status, notFoundResp.description)
@Response(incorrectStateResp.status, incorrectStateResp.description)
resumeRollingUpdate(
@Path() id: string,
@Body() body?: ResumeRollingUpdateBody,
@Query() sync?: boolean
): CreateActionReturnType<void> {
const poolId = id as XoPool['id']
const action = async (task: VatesTask) => {
const pool = this.getObject(poolId)
await this.restApi.xoApp.resumeRollingPoolUpdate(pool, { ...body, parentTask: task })
}
return this.createAction<void>(action, {
sync,
statusCode: noContentResp.status,
taskProperties: {
name: 'resume rolling pool update',
objectId: poolId,
params: body,
progress: 0,
},
})
}
/**
* Returns all messages that match the following privilege:
* - resource: message, action: read

View File

@@ -22,6 +22,7 @@ function createController({ v2vService = {} }: { v2vService?: object } = {}) {
tasks: { create: (properties: unknown) => ({ id: 'task-1', properties, run: (fn: () => unknown) => fn() }) },
xoApp: {
finalizeRollingUpdate: record('finalizeRollingUpdate'),
resumeRollingPoolUpdate: record('resumeRollingPoolUpdate'),
rollingPoolReboot: record('rollingPoolReboot'),
rollingPoolUpdate: record('rollingPoolUpdate'),
},
@@ -58,6 +59,22 @@ for (const [method, orchestrator] of [
})
}
describe('PoolController.resumeRollingUpdate', () => {
it('forwards bypassBackupCheck and acceptOperatorChanges from the body to the orchestrator', async () => {
const { calls, controller } = createController()
await controller.resumeRollingUpdate('pool-1', undefined, true)
await controller.resumeRollingUpdate('pool-1', { bypassBackupCheck: true }, true)
await controller.resumeRollingUpdate('pool-1', { acceptOperatorChanges: true }, true)
assert.deepEqual(calls, [
{ orchestrator: 'resumeRollingPoolUpdate', parentTask: 'task-1' },
{ orchestrator: 'resumeRollingPoolUpdate', parentTask: 'task-1', bypassBackupCheck: true },
{ orchestrator: 'resumeRollingPoolUpdate', parentTask: 'task-1', acceptOperatorChanges: true },
])
})
})
describe('PoolController.finalizeRollingUpdate', () => {
it('forwards force from the body to the orchestrator', async () => {
const { calls, controller } = createController()

View File

@@ -151,12 +151,22 @@ export type RollingPoolActionBody = {
export type FinalizeRollingUpdateBody = {
/**
* Close the record even though the update left items unrestored, or its record cannot be read: they are abandoned
* and listed in the task, nothing is restored nor changed in the pool. Defaults to false.
* Close the record without restoring what the update left unrestored, or when its record cannot be read: the items
* are abandoned and listed in the task, nothing is restored nor changed in the pool. Defaults to false.
*/
force?: boolean
}
export type ResumeRollingUpdateBody = {
/**
* Keep what an operator changed since the update: the update starts from the current state, as a new one would.
* Without it, such changes block the update. Defaults to false.
*/
acceptOperatorChanges?: boolean
/** Skip the backup safety check before rebooting the hosts, asked again on each resume. Defaults to false. */
bypassBackupCheck?: boolean
}
export type RollingPoolUpdateBody = RollingPoolActionBody & {
/**
* Start the update even though the master is already up to date while another host is not, ie from a pool left

View File

@@ -1,22 +1,53 @@
import { Example, Extension, Get, Middlewares, Path, Query, Request, Response, Route, Security, Tags } from 'tsoa'
import {
Example,
Extension,
Get,
Middlewares,
Path,
Query,
Request,
Response,
Route,
Security,
SuccessResponse,
Tags,
} from 'tsoa'
import { inject } from 'inversify'
import { provide } from 'inversify-binding-decorators'
import type { Request as ExRequest } from 'express'
import type { XoProxy } from '@vates/types'
import { acl } from '../middlewares/acl.middleware.mjs'
import { ApiError } from '../helpers/error.helper.mjs'
import {
badRequestResp,
forbiddenOperationResp,
internalServerErrorResp,
notFoundResp,
proxyUnreachableResp,
unauthorizedResp,
type Unbrand,
} from '../open-api/common/response.common.mjs'
import { partialProxies, proxy, proxyIds } from '../open-api/oa-examples/proxy.oa-example.mjs'
import { partialProxies, proxy, proxyHealth, proxyIds } from '../open-api/oa-examples/proxy.oa-example.mjs'
import type { SendObjects } from '../helpers/helper.type.mjs'
import { XoController } from '../abstract-classes/xo-controller.mjs'
import { RestApi } from '../rest-api/rest-api.mjs'
function isProxyUnreachable(error: unknown): boolean {
return error instanceof Error && 'code' in error && error.code === 'PROXY_UNREACHABLE'
}
async function callProxy<T>(call: Promise<T>): Promise<T> {
try {
return await call
} catch (error) {
if (isProxyUnreachable(error)) {
throw new ApiError(proxyUnreachableResp.description, proxyUnreachableResp.status)
}
throw error
}
}
@Route('proxies')
@Security('*')
@Response(badRequestResp.status, badRequestResp.description)
@@ -85,4 +116,34 @@ export class ProxyController extends XoController<XoProxy> {
getProxy(@Path() id: string): Promise<Unbrand<XoProxy>> {
return this.getObject(id as XoProxy['id'])
}
/**
* Checks that the proxy can be reached
*
* Required privilege:
* - resource: proxy, action: read
*
* @example id "e625ea0c-a876-405a-b838-109d762efe88"
*/
@Example(proxyHealth)
@Extension('x-mcp-exposure', 'allow')
@Get('{id}/health')
@Middlewares(
acl({
resource: 'proxy',
action: 'read',
objectId: 'params.id',
getObject: ({ restApi }) => restApi.xoApp.getProxy,
})
)
@SuccessResponse(200, 'OK')
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
@Response(notFoundResp.status, notFoundResp.description)
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
@Response(proxyUnreachableResp.status, proxyUnreachableResp.description)
async getProxyHealth(@Path() id: string): Promise<{ success: true }> {
await callProxy(this.restApi.xoApp.checkProxyHealth(id as XoProxy['id']))
return { success: true }
}
}

View File

@@ -0,0 +1,51 @@
import assert from 'node:assert/strict'
import { describe, it } from 'node:test'
import { ApiError } from '../helpers/error.helper.mjs'
import { ProxyController } from './proxy.controller.mjs'
import type { RestApi } from '../rest-api/rest-api.mjs'
function createController(checkProxyHealth: (id: string) => Promise<void>) {
const calls: unknown[] = []
const restApi = {
xoApp: {
checkProxyHealth: async (id: string) => {
calls.push(['checkProxyHealth', id])
return checkProxyHealth(id)
},
},
} as unknown as RestApi
const controller = new ProxyController(restApi)
return { calls, controller }
}
const proxyId = 'e625ea0c-a876-405a-b838-109d762efe88'
describe('ProxyController.getProxyHealth', () => {
it('forwards the id and returns success when the proxy is reachable', async () => {
const { calls, controller } = createController(async () => {})
assert.deepEqual(await controller.getProxyHealth(proxyId), { success: true })
assert.deepEqual(calls, [['checkProxyHealth', proxyId]])
})
it('throws a 502 ApiError when the proxy is unreachable', async () => {
const { controller } = createController(async () => {
throw Object.assign(new TypeError('fetch failed'), { code: 'PROXY_UNREACHABLE' })
})
await assert.rejects(
controller.getProxyHealth(proxyId),
error => error instanceof ApiError && error.status === 502 && error.message === 'Proxy unreachable'
)
})
it('rethrows unrelated errors unchanged', async () => {
const unrelatedError = new Error('500 Internal Server Error')
const { controller } = createController(async () => {
throw unrelatedError
})
await assert.rejects(controller.getProxyHealth(proxyId), error => error === unrelatedError)
})
})

View File

@@ -23,7 +23,7 @@ import type { XenApiVdi, XoMessage, XoTask, XoVdi, XoAlarm, XoSr } from '@vates/
import { SUPPORTED_VDI_FORMAT } from '@vates/types'
import { acl } from '../middlewares/acl.middleware.mjs'
import { AlarmService } from '../alarms/alarm.service.mjs'
import { BASE_URL, escapeUnsafeComplexMatcher } from '../helpers/utils.helper.mjs'
import { BASE_URL, escapeUnsafeComplexMatcher, getFileNameFromUrl } from '../helpers/utils.helper.mjs'
import { genericAlarmsExample } from '../open-api/oa-examples/alarm.oa-example.mjs'
import {
asynchronousActionResp,
@@ -46,7 +46,7 @@ import { XapiXoController } from '../abstract-classes/xapi-xo-controller.mjs'
import { messageIds, partialMessages } from '../open-api/oa-examples/message.oa-example.mjs'
import { taskIds, partialTasks, taskLocation } from '../open-api/oa-examples/task.oa-example.mjs'
import type { CreateActionReturnType } from '../abstract-classes/base-controller.mjs'
import { SrService, type CreateSrBody } from './sr.service.mjs'
import { SrService, type CreateSrBody, type ImportVdiFromUrlBody } from './sr.service.mjs'
@Route('srs')
@Security('*')
@@ -182,7 +182,7 @@ export class SrController extends XapiXoController<XoSr> {
* Import an exported VDI
*
* Required privilege:
* - resource: sr, action: import:vdi
* - resource: sr, action: import:vdi:upload
*
* @example id "c4284e12-37c9-7967-b9e8-83ef229c3e03"
* @example name_label "VDI_foo_import"
@@ -192,7 +192,7 @@ export class SrController extends XapiXoController<XoSr> {
@Example(vdiId)
@Extension('x-mcp-exposure', 'confirm')
@Post('{id}/vdis')
@Middlewares(acl({ resource: 'sr', action: 'import:vdi', objectId: 'params.id' }))
@Middlewares(acl({ resource: 'sr', action: 'import:vdi:upload', objectId: 'params.id' }))
@Tags('vdis')
@SuccessResponse(createdResp.status, 'VDI imported')
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
@@ -440,4 +440,69 @@ export class SrController extends XapiXoController<XoSr> {
async deleteSr(@Path() id: string): Promise<void> {
await this.#srService.delete(id as XoSr['id'])
}
/**
* Import a VDI from a URL
*
* The XO server fetches the URL and streams its content straight to the SR, without storing it on the XO server.
*
* Requirements:
* - The URL must be reachable by the XO server.
* - The URL must use `http` or `https`.
* - The URL must not contain a username/password (`https://user:password@...`).
* - The remote server must send a `Content-Length` header.
*
* Only ISO SRs are supported for now.
*
* Warning: The XO server sends a GET request to the given URL, whatever its address. It can reach internal
* services, and the response can then be read by exporting the imported VDI.
*
* Required privilege:
* - resource: sr, action: import:vdi:url
*
* @example id "c4284e12-37c9-7967-b9e8-83ef229c3e03"
* @example body { "url": "https://example.com/debian-13.iso", "name_label": "debian-13.iso", "name_description": "Debian 13 installer" }
*/
@Example(vdiId)
@Extension('x-mcp-exposure', 'confirm')
@Post('{id}/actions/import_vdi_from_url')
@Middlewares([json(), acl({ resource: 'sr', action: 'import:vdi:url', objectId: 'params.id' })])
@Tags('vdis')
@SuccessResponse(asynchronousActionResp.status, asynchronousActionResp.description)
@Response(createdResp.status, 'VDI imported')
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
@Response(notFoundResp.status, notFoundResp.description)
@Response(invalidParametersResp.status, invalidParametersResp.description)
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
@Response(502, 'The remote server is unreachable or failed to provide the file')
async srImportVdiFromUrl(
@Path() id: string,
@Body() body: ImportVdiFromUrlBody,
@Query() sync?: boolean
): CreateActionReturnType<{ id: Unbrand<XoVdi>['id'] }> {
const srId = id as XoSr['id']
// checked before creating the task, so that invalid parameters are rejected with a 422 even when not `sync`
const url = this.#srService.validateImportVdiFromUrl(srId, body.url)
const action = async () => {
const vdiId = await this.#srService.importVdiFromUrl(srId, url, body)
if (sync) {
this.setHeader('Location', `${BASE_URL}/vdis/${vdiId}`)
}
return { id: vdiId }
}
return this.createAction<{ id: XoVdi['id'] }>(action, {
sync,
statusCode: createdResp.status,
taskProperties: {
name: 'import VDI from URL',
objectId: srId,
// the full URL can contain secrets (e.g. `?token=…`) and tasks are readable with `task: read`,
// only keep its origin and the name of the downloaded file
params: { ...body, url: url.origin, fileName: getFileNameFromUrl(url) },
},
})
}
}

View File

@@ -1,7 +1,11 @@
import type { Xapi, XenApiSr, XoHost, XoSr } from '@vates/types'
import type { RestApi } from '../rest-api/rest-api.mjs'
import { Readable } from 'node:stream'
import { SUPPORTED_VDI_FORMAT } from '@vates/types'
import type { Xapi, XenApiVdi, XenApiSr, XoHost, XoSr, XoVdi } from '@vates/types'
import { ApiError } from '../helpers/error.helper.mjs'
import type { RestApi } from '../rest-api/rest-api.mjs'
import { LicenseService } from '../licenses/license.service.mjs'
import { invalidParameters } from 'xo-common/api-errors.js'
import { getFileNameFromUrl } from '../helpers/utils.helper.mjs'
// Derived from `xapi.SR_create` params, renamed to stay consistent with the XO SR
// representation returned by `GET /srs/:id`: `hostId` (XO id, not XAPI ref),
@@ -13,6 +17,13 @@ export type CreateSrBody = Omit<Parameters<Xapi['SR_create']>[0], 'host' | 'type
size?: number
}
export type ImportVdiFromUrlBody = {
url: string
/** Defaults to the file name in the URL */
name_label?: string
name_description?: string
}
// SR types backed by network/SAN storage, every other type is local to the host
const SHARED_SR_TYPES: ReadonlySet<XoSr['SR_type']> = new Set([
'cephfs',
@@ -78,4 +89,92 @@ export class SrService {
await xapi.destroySr(id)
}
}
/**
* Check the parameters of `importVdiFromUrl`, without any download, so that they can be rejected before
* creating a task
*/
validateImportVdiFromUrl(id: XoSr['id'], urlString: string): URL {
let url: URL
try {
url = new URL(urlString)
} catch {
throw invalidParameters('invalid URL')
}
if (url.protocol !== 'http:' && url.protocol !== 'https:') {
throw invalidParameters(`unsupported protocol ${url.protocol}, expected http: or https:`)
}
// rejected by `fetch` anyway
if (url.username !== '' || url.password !== '') {
throw invalidParameters('credentials in the URL are not supported')
}
const xapiSr = this.#restApi.getXapiObject<XoSr>(id, 'SR')
// XO ISO libraries (local, NFS, SMB) are all created with type and content_type `iso`,
// this excludes the XCP-ng tools SR and the DVD drives SR (type `udev`)
if (xapiSr.content_type !== 'iso' || xapiSr.type !== 'iso' || xapiSr.is_tools_sr) {
throw invalidParameters(`SR ${id} is not an ISO SR`)
}
return url
}
/**
* `url` must have been checked with `validateImportVdiFromUrl`
*/
async importVdiFromUrl(
id: XoSr['id'],
url: URL,
{ name_label, name_description }: Omit<ImportVdiFromUrlBody, 'url'>
): Promise<XoVdi['id']> {
// never put the full URL in errors, it can contain secrets
const { origin } = url
const xapiSr = this.#restApi.getXapiObject<XoSr>(id, 'SR')
const xapi = xapiSr.$xapi
let response: Response
try {
// `fetch` transparently decompresses gzip, but `Content-Length` would still be the compressed size
response = await fetch(url, { headers: { 'accept-encoding': 'identity' } })
} catch (error) {
// the remote server is unreachable (DNS, connection refused, TLS…)
throw new ApiError(`failed to download ${origin}`, 502)
}
// the failures below come from the remote server, not from XO nor from the caller: 502 Bad Gateway
if (!response.ok) {
await response.body?.cancel() // free the socket
throw new ApiError(`failed to download ${origin}: ${response.status} ${response.statusText}`, 502)
}
if (response.body === null) {
throw new ApiError(`failed to download ${origin}: empty response body`, 502)
}
// raw imports need the size of the VDI before reading the stream
const contentLength = response.headers.get('content-length')
if (contentLength === null) {
await response.body.cancel()
throw new ApiError(`the remote server did not provide a Content-Length for ${origin}`, 502)
}
const stream: Readable & { length?: number } = Readable.fromWeb(response.body)
stream.length = +contentLength
let vdiRef: XenApiVdi['$ref']
try {
vdiRef = await xapi.SR_importVdi(xapiSr.$ref, stream, {
format: SUPPORTED_VDI_FORMAT.raw,
name_label: name_label ?? getFileNameFromUrl(url),
name_description,
})
} catch (error) {
// the import can fail before reading the stream (e.g. `VDI.create` fails), close the download
stream.destroy()
throw error
}
const vdiId = await xapi.getField<XenApiVdi, 'uuid'>('VDI', vdiRef, 'uuid')
return vdiId as XoVdi['id']
}
}

View File

@@ -1,5 +1,8 @@
import assert from 'node:assert/strict'
import { describe, it } from 'node:test'
import type { Readable } from 'node:stream'
import { SUPPORTED_VDI_FORMAT, type XoSr } from '@vates/types'
import { invalidParameters } from 'xo-common/api-errors.js'
import { SrService, type CreateSrBody } from './sr.service.mjs'
import { ApiError } from '../helpers/error.helper.mjs'
@@ -119,3 +122,240 @@ describe('SrService.create', () => {
})
})
})
describe('SrService.validateImportVdiFromUrl and SrService.importVdiFromUrl', () => {
const SR_ID = 'sr-uuid' as XoSr['id']
const ISO_SR = { content_type: 'iso', type: 'iso', is_tools_sr: false }
// returns the service and the calls made to XAPI
function setup(srRecord: Record<string, unknown> = ISO_SR, { importError }: { importError?: Error } = {}) {
const calls = {
getXapiObject: [] as unknown[][],
SR_importVdi: [] as unknown[][],
getField: [] as unknown[][],
}
const fakeXapi = {
SR_importVdi: async (...args: unknown[]) => {
calls.SR_importVdi.push(args)
if (importError !== undefined) {
throw importError
}
return 'OpaqueRef:new-vdi'
},
getField: async (...args: unknown[]) => {
calls.getField.push(args)
return 'vdi-uuid-123'
},
}
const restApi = {
getXapiObject: (...args: unknown[]) => {
calls.getXapiObject.push(args)
return { ...srRecord, $ref: 'OpaqueRef:sr-1', $xapi: fakeXapi }
},
} as unknown as RestApi
return { calls, service: new SrService(restApi) }
}
// a response whose body records whether it has been cancelled
function createResponse({ status = 200, headers = {} }: { status?: number; headers?: Record<string, string> } = {}) {
const body = { cancelled: false }
const response = new Response(
new ReadableStream({
start(controller) {
controller.enqueue(new TextEncoder().encode('iso'))
controller.close()
},
cancel() {
body.cancelled = true
},
}),
{ status, headers }
)
return { body, response }
}
const isInvalidParameters = (error: unknown) => invalidParameters.is(error)
const isBadGateway = (error: unknown): error is ApiError => error instanceof ApiError && error.status === 502
it('imports the URL content as a raw VDI in the ISO SR and returns the VDI uuid', async t => {
const { response } = createResponse({ headers: { 'content-length': '3' } })
const fetchMock = t.mock.method(globalThis, 'fetch', async () => response)
const { calls, service } = setup()
const id = await service.importVdiFromUrl(SR_ID, new URL('https://example.net/isos/debian-13.iso'), {
name_label: 'Debian',
name_description: 'installer',
})
assert.deepEqual(calls.getXapiObject, [[SR_ID, 'SR']])
assert.equal(fetchMock.mock.callCount(), 1)
const [fetchUrl, fetchInit] = fetchMock.mock.calls[0].arguments as [URL, RequestInit]
assert.equal(String(fetchUrl), 'https://example.net/isos/debian-13.iso')
// no transparent decompression, so that Content-Length matches the received data
assert.deepEqual(fetchInit.headers, { 'accept-encoding': 'identity' })
assert.equal(calls.SR_importVdi.length, 1)
const [srRef, stream, opts] = calls.SR_importVdi[0] as [string, Readable & { length?: number }, unknown]
assert.equal(srRef, 'OpaqueRef:sr-1')
// the size of a raw VDI comes from the Content-Length header
assert.equal(stream.length, 3)
assert.deepEqual(opts, {
format: SUPPORTED_VDI_FORMAT.raw,
name_label: 'Debian',
name_description: 'installer',
})
assert.deepEqual(calls.getField, [['VDI', 'OpaqueRef:new-vdi', 'uuid']])
assert.equal(id, 'vdi-uuid-123')
})
it('defaults name_label to the decoded file name of the URL', async t => {
const { response } = createResponse({ headers: { 'content-length': '3' } })
t.mock.method(globalThis, 'fetch', async () => response)
const { calls, service } = setup()
await service.importVdiFromUrl(SR_ID, new URL('https://example.net/isos/my%20distro.iso?token=abc'), {})
const opts = calls.SR_importVdi[0][2] as { name_label: string }
assert.equal(opts.name_label, 'my distro.iso')
})
for (const [description, url] of [
['an invalid URL', 'not a url'],
['a non HTTP(S) URL', 'ftp://example.net/debian.iso'],
['a file URL', 'file:///etc/passwd'],
['a URL with credentials', 'https://alice:s3cret@example.net/debian.iso'],
['a URL with a username only', 'https://alice@example.net/debian.iso'],
]) {
it(`rejects ${description} with invalid parameters, before looking up the SR`, () => {
const { calls, service } = setup()
assert.throws(() => service.validateImportVdiFromUrl(SR_ID, url), isInvalidParameters)
assert.equal(calls.getXapiObject.length, 0)
})
}
for (const [description, srRecord] of [
['a VM SR', { content_type: 'user', type: 'nfs', is_tools_sr: false }],
['the XCP-ng tools SR', { content_type: 'iso', type: 'iso', is_tools_sr: true }],
['the DVD drives SR', { content_type: 'iso', type: 'udev', is_tools_sr: false }],
] as const) {
it(`rejects ${description} with invalid parameters`, () => {
const { service } = setup(srRecord)
assert.throws(
() => service.validateImportVdiFromUrl(SR_ID, 'https://example.net/debian.iso'),
isInvalidParameters
)
})
}
it('returns the parsed URL for an HTTP(S) URL and an ISO SR, without any download', t => {
const fetchMock = t.mock.method(globalThis, 'fetch', async () => createResponse().response)
const { calls, service } = setup()
const url = service.validateImportVdiFromUrl(SR_ID, 'https://example.net/isos/debian-13.iso?token=abc')
assert.ok(url instanceof URL)
assert.equal(url.href, 'https://example.net/isos/debian-13.iso?token=abc')
assert.deepEqual(calls.getXapiObject, [[SR_ID, 'SR']])
assert.equal(fetchMock.mock.callCount(), 0)
})
it('rejects with 502 when the remote server returns an error, and frees the response body', async t => {
const { body, response } = createResponse({ status: 404 })
t.mock.method(globalThis, 'fetch', async () => response)
const { calls, service } = setup()
await assert.rejects(service.importVdiFromUrl(SR_ID, new URL('https://example.net/missing.iso'), {}), error => {
assert.ok(isBadGateway(error))
assert.match((error as Error).message, /404/)
return true
})
assert.equal(body.cancelled, true)
assert.equal(calls.SR_importVdi.length, 0)
})
it('rejects with 502 when the download cannot start, keeping the URL origin', async t => {
const networkError = new TypeError('fetch failed', { cause: new Error('getaddrinfo ENOTFOUND example.net') })
t.mock.method(globalThis, 'fetch', async () => {
throw networkError
})
const { calls, service } = setup()
await assert.rejects(service.importVdiFromUrl(SR_ID, new URL('https://example.net/debian.iso'), {}), error => {
assert.ok(isBadGateway(error))
assert.match(error.message, /https:\/\/example\.net/)
return true
})
assert.equal(calls.SR_importVdi.length, 0)
})
it('closes the download when the import fails', async t => {
const { response } = createResponse({ headers: { 'content-length': '3' } })
t.mock.method(globalThis, 'fetch', async () => response)
const importError = new Error('VDI.create failed')
const { calls, service } = setup(ISO_SR, { importError })
await assert.rejects(service.importVdiFromUrl(SR_ID, new URL('https://example.net/debian.iso'), {}), importError)
const stream = calls.SR_importVdi[0][1] as Readable
assert.equal(stream.destroyed, true)
})
it('rejects with 502 when there is no Content-Length, and frees the response body', async t => {
const { body, response } = createResponse()
t.mock.method(globalThis, 'fetch', async () => response)
const { calls, service } = setup()
await assert.rejects(service.importVdiFromUrl(SR_ID, new URL('https://example.net/debian.iso'), {}), isBadGateway)
assert.equal(body.cancelled, true)
assert.equal(calls.SR_importVdi.length, 0)
})
it('rejects with 502 when the response has no body', async t => {
t.mock.method(globalThis, 'fetch', async () => new Response(null, { status: 200 }))
const { calls, service } = setup()
await assert.rejects(service.importVdiFromUrl(SR_ID, new URL('https://example.net/debian.iso'), {}), isBadGateway)
assert.equal(calls.SR_importVdi.length, 0)
})
describe('never leaks the full URL, which can contain a secret, in errors', () => {
const SECRET_URL = 'https://example.net/isos/debian.iso?token=s3cret'
const assertNoSecret = (error: unknown) => {
const { message } = error as Error
assert.doesNotMatch(message, /s3cret|debian\.iso/)
return true
}
it('when the remote server returns an error', async t => {
t.mock.method(globalThis, 'fetch', async () => createResponse({ status: 403 }).response)
const { service } = setup()
await assert.rejects(service.importVdiFromUrl(SR_ID, new URL(SECRET_URL), {}), assertNoSecret)
})
it('when the download cannot start', async t => {
t.mock.method(globalThis, 'fetch', async () => {
throw new TypeError('fetch failed')
})
const { service } = setup()
await assert.rejects(service.importVdiFromUrl(SR_ID, new URL(SECRET_URL), {}), assertNoSecret)
})
it('when there is no Content-Length', async t => {
t.mock.method(globalThis, 'fetch', async () => createResponse().response)
const { service } = setup()
await assert.rejects(service.importVdiFromUrl(SR_ID, new URL(SECRET_URL), {}), assertNoSecret)
})
it('when the URL is invalid', () => {
const { service } = setup()
assert.throws(() => service.validateImportVdiFromUrl(SR_ID, 'not a url?token=s3cret'), assertNoSecret)
})
})
})

View File

@@ -293,7 +293,6 @@ export class VdiController extends XapiXoController<XoVdi> {
* Create an empty VDI.
*
* Required privileges:
* - resource: sr, action: import:vdi (on the target SR)
* - resource: vdi, action: create
*
* @example body { "srId": "c4284e12-37c9-7967-b9e8-83ef229c3e03", "virtual_size": 10737418240, "name_label": "test VDI" }
@@ -301,13 +300,7 @@ export class VdiController extends XapiXoController<XoVdi> {
@Example(vdiId)
@Extension('x-mcp-exposure', 'confirm')
@Post('')
@Middlewares([
json(),
acl([
{ resource: 'sr', action: 'import:vdi', objectId: 'body.srId' },
{ resource: 'vdi', action: 'create', object: ({ req }) => req.body },
]),
])
@Middlewares([json(), acl([{ resource: 'vdi', action: 'create', object: ({ req }) => req.body }])])
@SuccessResponse(createdResp.status, createdResp.description)
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
@Response(notFoundResp.status, notFoundResp.description)

View File

@@ -14,7 +14,6 @@ import {
XoBackupLog,
} from '@vates/types'
import { createLogger } from '@xen-orchestra/log'
import { createPredicate } from 'value-matcher'
import { extractIdsFromSimplePattern } from '@xen-orchestra/backups/extractIdsFromSimplePattern.mjs'
import { noSuchObject } from 'xo-common/api-errors.js'
import { parse } from 'xo-remote-parser'
@@ -361,23 +360,22 @@ export class XoaService {
const nonReplicaVms = Object.values(this.#restApi.getObjectsByType<XoVm>('VM', { filter: vm => !isReplicaVm(vm) }))
const restApi = this.#restApi
const xoApp = restApi.xoApp
function _extractVmIdsFromBackupJob(job: XoVmBackupJob) {
let vmIds: XoVm['id'][]
const backupJobService = this.#backupJobService
async function _extractVmIdsFromBackupJob(job: XoVmBackupJob): Promise<XoVm['id'][]> {
try {
vmIds = extractIdsFromSimplePattern(job.vms)
return extractIdsFromSimplePattern(job.vms)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (_) {
const predicate = createPredicate(job.vms)
vmIds = nonReplicaVms.filter(predicate).map(vm => vm.id)
const isVmInJob = await backupJobService.getBackupJobVmMatcher(job)
return nonReplicaVms.filter(isVmInJob).map(vm => vm.id)
}
return vmIds
}
function _processVmsProtection(job: XoVmBackupJob, isProtected: boolean) {
async function _processVmsProtection(job: XoVmBackupJob, isProtected: boolean) {
if (job.type !== BACKUP_TYPE.backup) {
return
}
_extractVmIdsFromBackupJob(job).forEach(vmId => {
;(await _extractVmIdsFromBackupJob(job)).forEach(vmId => {
_updateVmProtection(vmId, isProtected)
})
}
@@ -434,7 +432,7 @@ export class XoaService {
for (const job of jobs) {
if (!(await this.#backupJobService.backupJobHasAtLeastOneScheduleEnabled(job.id))) {
_processVmsProtection(job, false)
await _processVmsProtection(job, false)
disabledJobs++
continue
}
@@ -486,7 +484,7 @@ export class XoaService {
}
if (last3BackupLogs.length === 0) {
_processVmsProtection(job, false)
await _processVmsProtection(job, false)
continue
}
@@ -500,11 +498,11 @@ export class XoaService {
backupLogStatusesByVm[id].push(isSuccess)
}
last3BackupLogs.forEach(jobLob => {
const { tasks, status } = jobLob
let jobVmIds: XoVm['id'][] | undefined
for (const { tasks, status } of last3BackupLogs) {
if (tasks === undefined) {
const vmIds = _extractVmIdsFromBackupJob(job)
vmIds.forEach(vmId => updateVmBackupLogStatuses(vmId, status === 'success'))
jobVmIds ??= await _extractVmIdsFromBackupJob(job)
jobVmIds.forEach(vmId => updateVmBackupLogStatuses(vmId, status === 'success'))
} else {
tasks.forEach(task => {
if (task.data === undefined) {
@@ -513,7 +511,7 @@ export class XoaService {
updateVmBackupLogStatuses(task.data.id as XoVm['id'], task.status === 'success')
})
}
})
}
for (const [vmId, statuses] of Object.entries(backupLogStatusesByVm)) {
_updateVmProtection(

View File

@@ -1,13 +1,13 @@
{
"license": "ISC",
"private": false,
"version": "1.2.0",
"version": "1.3.0",
"name": "@xen-orchestra/vmware-explorer",
"description": "Reads the VMs and the disks of an ESXi host or a vCenter",
"dependencies": {
"@vates/async-each": "^1.0.3",
"@vates/node-vsphere-soap": "^2.2.0",
"@xen-orchestra/log": "^0.7.2",
"@vates/node-vsphere-soap": "^2.2.1",
"@xen-orchestra/log": "^1.0.0",
"promise-toolbox": "^0.21.0",
"undici": "^7.8.0"
},

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