Compare commits

..

47 Commits

Author SHA1 Message Date
Thierry Goettelmann
5589203da7 feat(web-core/menu): add the restricted prop to action buttons and menu items
A restricted menu item is disabled and shows the "permission required"
reason in place of its hint. `VtsActionButton` and the actions of
`VtsActionsMenu` forward the flag, so a restricted action looks and behaves
the same as a button or a menu item.

See XO-3007
2026-12-04 10:00:41 +01:00
Thierry Goettelmann
36919c7a1c feat(web-core/button): add the restricted prop to UiButton and UiButtonIcon
A restricted button looks disabled but stays focusable, ignores clicks and
shows a "Permission required" tooltip, through the `vRestricted` directive.
It lets the app show the actions the user has no permission to run instead
of hiding them.

See XO-3007
2026-12-04 10:00:41 +01:00
Thierry Goettelmann
5a82f5ab2e feat(web-core/restricted): add the vRestricted directive
A restricted element keeps the keyboard focus but is announced as disabled
(`aria-disabled`), ignores clicks and shows a "Permission required" tooltip
on hover and on focus, in place of its own tooltip. Components can apply it
to the actions the user has no permission to run.

See XO-3007
2026-12-04 10:00:41 +01:00
Thierry Goettelmann
acee2c206a feat(web-core/tooltip): allow several tooltips per element
A tooltip is now registered under its own key instead of its target, so
an element can hold several tooltips. A registration can listen to
several event pairs, and a prioritized tooltip hides the other tooltips
of its element while it is shown. This prepares the "Permission
required" tooltip of restricted buttons.

A focus tooltip now only shows on a focus the browser makes visible
(`:focus-visible`), not on a focus that follows a click.

See XO-3007
2026-12-04 10:00:41 +01:00
Thierry Goettelmann
664947c3d4 fix(xo6/user,role): adapt to the form inputs, VM columns and test mocks changes
Since the rebase on master, the form inputs no longer accept the `brand`
accent (#10861, #10862), the VM columns include a last backup date column
(#10758), and the test files replace exports through the global module
mocks instead of `vi.mock` (#10841).

The user and role form inputs use the `neutral` accent, the VMs scope
table excludes the column it does not render, and the current user
privileges test stubs its collections with `mockedExport`.

The release emptied the packages to release: `@xen-orchestra/web` and
`@xen-orchestra/web-core` are listed again for the RBAC features.
2026-12-04 10:00:26 +01:00
Thierry Goettelmann
a7c1306e09 fix(xo6/role): hide the scope step errors after a resource change
Changing the resource of a privilege resets its scope selector and its
selected objects. The scope step then showed validation errors for
values the user never edited. The step is now marked untouched after
the reset.

The selector is kept in sync with the typed search through `syncRefs`
instead of a manual `watch`.
2026-12-04 10:00:26 +01:00
Thierry Goettelmann
12c99e7de5 fix(xo6/group,role): pass the side panel through the panel slot
Since the rebase on master, `VtsContentSidePanel` expects the side panel
in its `panel` slot (#10807). The groups, roles and role templates pages
still passed it in the default slot, so it rendered below the table.
2026-12-04 10:00:26 +01:00
Thierry Goettelmann
855e030b0a fix(xo6/role): replace the privilege scope selection workaround with selectedIds
`usePrivilegeScopeSelection` replayed the initial selection once the objects
were loaded. The `selectedIds` option of `useTableSelection` now covers it.

The "required" error no longer shows before any interaction on tables whose
objects load after the drawer opens. IDs that match no loaded object are now
kept in the privilege instead of being dropped.

See XO-3443
2026-12-04 10:00:25 +01:00
Thierry Goettelmann
ef12c23744 fix(xo6/user,group,role): adapt to the query builder and host columns changes
Since the rebase on master, the query builder filters while typing and no
longer emits the search query (#10797), and the host columns include an
actions column (#10821).

The RBAC tables bind the query builder through `searchBindings`, the
privilege selector preview follows the typed query the same way, and the
hosts scope table excludes the actions column it does not render.
2026-12-04 10:00:25 +01:00
Thierry Goettelmann
f0d681062c feat(xo6/user,role): select the new user or role after its creation
As for groups, the created user opens in the side panel instead of
keeping the previously selected one, and the role creation page goes
back to the roles list with the new role selected. The new item shows up
even when it lands on another page or outside the active filter.
2026-12-04 10:00:25 +01:00
Thierry Goettelmann
aff8179271 feat(xo6/role): add role creation from a template (#10788)
Role templates cannot be assigned to users or groups directly. A new page
lists them with their privileges, and selecting one opens the role
creation form prefilled with its name, description and privileges, which
can all be adjusted before the role is created.

See XO-3273
2026-12-04 10:00:24 +01:00
Thierry Goettelmann
16fa0228de feat(xo6/user): add current user privileges composable (#10771)
* feat(web/user): add current user privileges composable

Fetch the current user's ACL privileges and expose a `can` helper built on
`hasPrivilegeOn`, so the UI can later hide or disable actions a non-admin
user isn't allowed to perform. Admins skip the fetch and are always allowed.

See XO-3004

* feat(xo6/user): keep the current user up to date for privilege checks

`useCurrentUserPrivileges` now reads the user from `useXoCurrentUser`
instead of a second resource on the same `/users/me` endpoint.

That resource had its polling disabled because its only consumer needed
the user id. Privilege checks depend on `permission`, which can change,
so it is polled again like the privileges themselves. SSE is not an
option here: `user` events are only sent to users holding `user:read`.

Add unit tests for the composable.

See XO-3004
2026-12-04 10:00:23 +01:00
Thierry Goettelmann
01d67163c9 fix(xo6/role): offer the wildcard and sub-actions in the privilege form (#10776)
The action select only listed the top-level actions of a resource, so a
privilege on `*` or on a sub-action such as `create:vm` could not be
created from the form, although the API accepts them and the role
templates rely on them.

An action already covered by a broader selected one is now unselected
and disabled: all the selected actions share the same effect and scope,
so it would only create a redundant privilege.

See XO-2354
2026-12-04 10:00:23 +01:00
Thierry Goettelmann
9a497ac8b7 fix(xo6/role): use existing locale keys for the backup archive mode
The `backup:full` and `backup:incremental` keys were removed by the
backup refactoring (#10636), which made the lint fail on the backup
archive selector schema. Use `full` and `incremental` instead, as the
backup job mode label already does.
2026-12-04 10:00:23 +01:00
Thierry Goettelmann
f01f0c2f34 feat(xo6/group): add group deletion from the groups list and side panel (#10765)
A group can be deleted from a row of the groups table, whose selection
column is replaced by an action column, or from its side panel. Its members
stay as individual users and lose the roles they inherited from the group,
as the confirmation modal warns.

A synchronized group cannot be deleted: its provider would recreate
it at the next synchronization, without its roles.

Groups can be selected with checkboxes in the groups table and deleted together from
the bulk actions bar

See XO-2352
2026-12-04 10:00:22 +01:00
Thierry Goettelmann
ec06b0555e chore(xo6): drop XO6/ prefix from changelog entries 2026-12-04 10:00:20 +01:00
Thierry Goettelmann
88276f6884 feat(xo6/group): list the applied roles in the group side panel (#10659)
* feat(xo6/group): list the applied roles in the group side panel

The group side panel only showed the group's details and its users, while
the users side panel already lists the roles applied to a user. The new
card mirrors it, listing the roles assigned to the group with a link to
each of them in the roles list.

See XO-2659

* docs(changelog): add PR link
2026-12-04 10:00:15 +01:00
Thierry Goettelmann
48eed12ee5 feat(xo6/user): add user creation from the users list (#10658)
* feat(xo6/user): add user creation from the users list

A "New" button in the users list opens a multi-step drawer: user details,
groups, roles, then a review where each step can be edited again. Roles
inherited from the selected groups are shown but not assigned directly:
only the additional roles become direct roles of the user.

The user is created first, then added to its groups and assigned its
roles. A username or email address that is already taken shows a
dedicated error, and the drawer stays open so the form can be fixed.

See XO-2358

* fix(xo6/user): add the new user to its groups one at a time to keep every membership

* refactor(xo6/user): reuse the user details locale key in the user creation

* refactor(xo6/user): share the groups and roles selection tables between the drawers

The roles header checkbox is now disabled on a page of inherited roles only.
2026-12-04 10:00:15 +01:00
Thierry Goettelmann
c46954c5d5 feat(xo6/user): show the username, first name and last name of users (#10657)
The users are now shown by their username, which replaces the deprecated
name property, or by their email address when they have none. The users
list and the user side panel also show their first and last names.
2026-12-04 10:00:15 +01:00
Thierry Goettelmann
e3fe42d059 fix(xo6/user): list the applied roles in the user side panel (#10656)
* fix(xo6/user): list the applied roles in the user side panel

The "Roles applied" card of the user side panel was a placeholder that
always showed "No role applied". It now lists the roles of the user as in
the mockup: one section per group the roles are inherited from, then the
direct roles.

* refactor(xo6/user): reuse the user groups computed with the user roles in the roles card
2026-12-04 10:00:14 +01:00
Thierry Goettelmann
df9cd27a38 feat(xo6/privilege): add scope sub-page to the privilege detail page (#10655)
* feat(xo6/privilege): add scope sub-page to the privilege detail page

The Scope sub-page shows which objects a privilege applies to: its scope
type, the query of a dynamic selection, and the table of the objects it
currently applies to, whether selected manually, matched by the query or
covering all the objects of its resource.

See XO-2948

* fix(xo6/role): read the privilege scope type from its resource in the privilege scope page

* fix(xo6/role): show the error state of the objects a privilege currently applies to

* feat(xo6/privilege): show the full objects table in the privilege scope page

As in the mockups, the objects a privilege currently applies to are listed
in the same table as in its creation drawer (columns of the resource, search
engine), read-only, instead of a list of names.
2026-12-04 10:00:11 +01:00
Thierry Goettelmann
42b6296dbf feat(xo6/privilege): add privilege detail page with its general information (#10654)
* feat(xo6/privilege): add privilege detail page with its general information

The number of a privilege in the privileges table of a role, and the title
of its side panel, now open the privilege's detail page. It opens on
General, which lists the privilege's resource, action and effect, in the
same layout as the other detail pages. The breadcrumb leads back to the
role the privilege belongs to.

See XO-2947

* fix(xo6/role): show the not found page when the privilege cannot be fetched

* refactor(xo6/role): remove the unused panel slot of the privilege detail layout
2026-12-04 10:00:10 +01:00
Thierry Goettelmann
e204a4b5ac feat(xo6/role): add privileges sub-page to the role detail page (#10653)
* feat(xo6/role): add privileges sub-page to the role detail page

The Privileges sub-page lists the privileges granted by a role. Selecting one
opens a side panel with its details and its scope: the scope type, the query
of a dynamic selection, and the objects it currently applies to.

The privilege rows of the role side panel are extracted to be shared with
the privilege side panel.

See XO-2946

* fix(xo6/role): read the privilege scope type from its resource in the role privileges

* fix(xo6/role): show the loading and error states of the objects a privilege applies to

* feat(xo6/role): add a search engine to the role privileges table

As in the mockups, the privileges of a role can be filtered by resource,
scope, action and effect.
2026-12-04 10:00:09 +01:00
Thierry Goettelmann
0c2ab0810d feat(xo6/role): add groups sub-page to the role detail page (#10652)
* feat(xo6/role): add groups sub-page to the role detail page

The Groups sub-page lists the groups a role is assigned to, whose members
inherit it. The role can be assigned to groups from a drawer, synchronized
ones included, and detached from them one by one or by selection.

See XO-2945

* fix(xo6/role): unselect the groups detached from the role groups table

* fix(xo6/role): unselect the groups added back to the role groups table

A group detached from the side panel kept its selection flag, so adding it
back made it reappear selected, ready to be detached by a bulk action.
2026-12-04 10:00:09 +01:00
Thierry Goettelmann
00a0b1f8bd feat(xo6/role): add users sub-page to the role detail page (#10651)
* feat(xo6/role): add users sub-page to the role detail page

The Users sub-page lists the users a role is assigned to, directly or
through their groups. The role can be assigned to users from a drawer, and
detached from its direct users one by one or by selection.

See XO-2944

* fix(xo6/role): disable the users header checkbox on a page of inherited users only

* fix(xo6/role): show the no attached user message in an empty role users table

* fix(xo6/role): unselect the users detached from the role users table

* fix(xo6/role): unselect the users added back to the role users table

A user detached from the side panel kept its selection flag, so adding it
back made it reappear selected, ready to be detached by a bulk action.

* fix(xo6/role): hide the checkbox of the inherited users in the role users table

A user who holds the role through a group cannot be detached from the role,
and the disabled checkbox looked like an active one. As in the mockups, only
the direct users have a checkbox.
2026-12-04 10:00:09 +01:00
Thierry Goettelmann
8d385745d8 feat(xo6/role): add role detail page with its general information (#10650)
* feat(xo6/role): add role detail page with its general information

The role names in the roles tables and the title of the role side panel now
open the role's detail page. It opens on General, which lists the role's own
information, in the same layout as the user and group detail pages.

See XO-2943

* refactor(xo6/role): reuse the role details locale key in the role details card

* fix(xo6/role): show the role names as plain text in the roles selection drawer
2026-12-04 10:00:09 +01:00
Thierry Goettelmann
c569350f43 feat(xo6/group): add users sub-page to the group detail page (#10649)
* feat(xo6/group): add users sub-page to the group detail page

The Users sub-page lists the members of a group. Users can be added to the
group from a drawer, and removed from it one by one or by selection. The
members of a synchronized group are managed by its provider, so they cannot
be changed from XO.

See XO-2942

* refactor(xo6/user): share the formatting of the user providers

* fix(xo6/group): show the no attached user message in an empty group users table

* fix(xo6/group): unselect the users detached from the group users table

* fix(xo6/group): unselect the users added back to the group users table

A user detached from the side panel kept its selection flag, so adding it
back made it reappear selected, ready to be detached by a bulk action.
2026-12-04 10:00:09 +01:00
Thierry Goettelmann
4d5003c113 feat(xo6/group): add roles sub-page to the group detail page (#10648)
* feat(xo6/group): add roles sub-page to the group detail page

The Roles sub-page lists the roles assigned to a group, which all its members
inherit. Roles can be assigned to the group from a drawer, and detached from
it one by one or by selection.

See XO-2941

* fix(xo6/group): unselect the roles detached from the group roles table

* fix(xo6/group): unselect the roles added back to the group roles table

A role detached from the side panel kept its selection flag, so adding it
back made it reappear selected, ready to be detached by a bulk action.
2026-12-04 10:00:08 +01:00
Thierry Goettelmann
242a9404a4 feat(xo6/group): add group detail page with its general information (#10647)
* feat(xo6/group): add group detail page with its general information

The group names in the groups tables and the title of the group side panel
now open the group's detail page. It opens on General, which lists the
group's own information, in the same layout as the user detail page.

See XO-2940

* fix(xo6/group): show the group names as plain text in the groups selection drawer

* feat(xo6/user): link the group a role is inherited from in the user roles table

As in the mockups, the group column links to the group page. A role inherited
from several groups shows the first one and the number of the others.
2026-12-04 10:00:08 +01:00
Thierry Goettelmann
a368227836 feat(xo6/user): add roles sub-page to the user detail page (#10646)
* feat(xo6/user): add roles sub-page to the user detail page

The Roles sub-page lists the roles of a user: the ones assigned directly and
the ones inherited from its groups, with the groups they come from. Roles
can be assigned to the user from a drawer, including roles it already
inherits. Only direct roles can be detached: an inherited role is revoked
from the group.

See XO-2939

* fix(xo6/user): disable the roles header checkbox on a page of inherited roles only

* fix(xo6/user): unselect the roles detached from the user roles table

* refactor(xo6/user): stop exporting getUserRoles

* fix(xo6/user): unselect the roles added back to the user roles table

A role detached from the side panel kept its selection flag, so adding it
back made it reappear selected, ready to be detached by a bulk action.

* fix(xo6/user): hide the checkbox of the inherited roles in the user roles table

An inherited role cannot be detached from the user, and its disabled
checkbox looked like an active one. As in the mockups, only the direct
roles have a checkbox.
2026-12-04 10:00:08 +01:00
Thierry Goettelmann
b31f34cc5b feat(xo6/user): add groups sub-page to the user detail page (#10645)
* feat(xo6/user): add groups sub-page to the user detail page

The Groups sub-page lists the groups a user belongs to. The user can be
added to several groups at once from a drawer, and detached from one group
or from the selected ones. Synchronized groups are left out of the drawer
and cannot be detached, since the API rejects any change of their users.

The add and remove jobs take groups and users, so the group detail page
can reuse them to manage its members.

See XO-2938

* fix(xo6/group): add or remove group users one at a time to keep every membership

* fix(xo6/user): unselect the groups detached from the user groups table

* fix(xo6/user): unselect the groups added back to the user groups table

A group detached from the side panel kept its selection flag, so adding it
back made it reappear selected, ready to be detached by a bulk action.
2026-12-04 10:00:07 +01:00
Thierry Goettelmann
7f23fd5e73 feat(xo6/user): add user detail page with its general information (#10644)
* feat(xo6/user): add user detail page with its general information

The username in the users list and in the user side panel now opens the
user's detail page in XO 6, instead of the XO 5 users settings. The page
opens on General, which lists the user's own information, with a side menu
meant to host its other sub-pages.

The side menu layout is shared, so the group, role and privilege detail
pages can reuse it.

See XO-2937

* refactor(xo6): style the detail pages menu without UiMenuList
2026-12-04 10:00:07 +01:00
Thierry Goettelmann
51a9033c41 feat(xo6/role): add role creation with privileges from the roles list (#10605)
* feat(xo6/role): add role creation with privileges from the roles list

Administrators can create a role from the user management page and define
its privileges in the same form, instead of going through XO 5. Each
privilege targets one action on a resource type, scoped to all objects, a
manual selection or a query, with a preview of the matching objects.

See XO-2354

* docs(changelog): add PR link

* fix(xo6/role): move role creation page under /admin

* fix(xo6/role): read an id selector as a manual selection only when the resource allows it

* fix(xo6/role): use a non-breaking space in the role name hint

* refactor(xo6/role): use inline handlers in the new role form

* refactor(xo6/role): use named routes in the privilege scope tables

* refactor(xo6/role): remove the unused info prop of the role textarea

* refactor(xo6/role): remove explanatory comments from the role creation
2026-12-04 10:00:06 +01:00
Thierry Goettelmann
5f3bcf70da feat(xo6/user): add user deletion from the users list and side panel (#10356)
* feat(user): add user deletion from the users list and side panel

Delete one or more users from the users list row actions, or the
current user from the side panel. A user cannot delete itself.

See XO-2359

* docs(changelog): add PR link

* fix(xo6/user): clear the selected user only once its deletion succeeded

* fix(xo6/user): show the user delete action as a danger action

* refactor(xo6/user): remove a comment from the current user resource

* feat(xo6/user): delete several users at once from the users list

As in the mockups, the users list has a checkbox per row and a Delete table
action that deletes the selected users after confirmation.
2026-12-04 10:00:06 +01:00
Thierry Goettelmann
d5c0fde125 feat(xo6/role): add role deletion from the roles list and side panel (#10353)
* feat(xo6/role): add role deletion from the side panel

A role that is assigned to users or groups is refused: the delete button
stays disabled and its tooltip states why, so the constraint is visible
before the confirmation modal rather than as a server error afterwards.

Deleting the currently selected role clears the selection, since its
side panel would otherwise stay open on an object that no longer exists.

See XO-2356

* docs(changelog): add PR link

* feat(xo6/role): add role deletion from the roles list

Add a delete action to each row in the roles table, replacing the
selection column with an action column, so a role can be deleted
without opening the side panel first.

See XO-2356

* docs(changelog): merge role deletion changelog entries

* fix(xo6/role): clear the selected role only once its deletion succeeded

* fix(xo6/role): show the role delete action as a danger action

* feat(xo6/role): delete several roles at once from the roles list

As in the mockups, the roles list has a checkbox per row and a Delete table
action that deletes the selected roles after confirmation.
2026-12-04 10:00:05 +01:00
Thierry Goettelmann
ea39e0b9d5 feat(xo6/role): add side panel to the roles list (#10330)
* feat(xo6/role): add side panel to the roles list

Selecting a role in the list opens a side panel showing its description,
its privileges, and the users and groups it is assigned to. Users are
split between those holding the role directly and those inheriting it
from a group.

* docs(changelog): add PR link

* refactor(xo6/role): use logicAnd and logicOr in the role users card
2026-12-04 10:00:04 +01:00
Thierry Goettelmann
605aae89ae feat(xo6/role): add roles list in user management page (#10301)
* feat(xo6/role): add roles list in user management page

* docs(changelog): add PR link

* fix(xo6/role): count users inherited from groups in the users column

The column read `role.userIds`, which the server fills from the direct
user-role assignments only. A role assigned to one user and to a group
of eight was listed as having a single user, and the side panel, which
counts the effective users, contradicted it on the same screen.

The count now unions the direct users with the members of the role's
groups, deduplicated since a user can hold the role both ways. The page
waits for the groups collection so the column does not first show the
direct count then jump to the effective one.

* fix(xo6/role): wait for groups in the roles table and test user counting

The users column now depends on the groups collection, but only the page
waited for it. The table now handles the groups loading and error states
itself, like HostsTable does for PIFs, so any consumer gets a correct
count and the page no longer subscribes to groups only for this.

Add unit tests for getRoleUserIds, which deduplicates users holding a
role both directly and through groups, and drop a comment that only
restated the code.

* fix(xo6/role): refresh the roles table through SSE

The roles list was only refreshed by the default 30 s polling, while the
users and groups it counts from are already streamed. Subscribe to the
`acl-role` events so that role, user and group changes show up at once.

Template roles are rewritten each time xo-server starts and the SSE does
not apply the `!isTemplate?` filter, so they are dropped client-side with
a predicate.

Also use a non-breaking space before the question mark of the French
"What is a role?" title.
2026-12-04 10:00:04 +01:00
Thierry Goettelmann
9505bc0eb7 feat(xo6/group): add side panel to the groups list (#10291)
* feat(xo6/group): add side panel to the groups list

Selecting a group in the list opens a panel showing its identifier, its
provider and the users it contains, following the layout the users page
already uses.

Now that the panel reads the selected group from the `id` query
parameter, the groups listed in a user's panel can finally point at it.
They linked to the XO 5 settings page until now, for lack of an XO 6
destination. Both cards end up mirroring each other: group to users, and
user to groups.

* docs(changelog): add PR link
2026-12-04 10:00:04 +01:00
Thierry Goettelmann
08c79484e2 feat(xo6/group): add groups list in user management page (#10272) 2026-12-04 10:00:02 +01:00
spacotte-vates
6a222f2bb0 fix(xo-server): keep server statuses in sync with the live connections (#10834)
* fix(xo-server): keep server statuses in sync with the live connections

* fix review Ayoub

* fix rebase

* fix review mpiton

* Add missing bugfix in changelog

---------

Co-authored-by: Mathieu Piton <mathieu.piton@vates.tech>
2026-12-04 08:15:21 +01:00
spacotte-vates
5b854557e9 feat(backups): add sizeOnDisk for backup archives (#10685)
* feat(backups): add size on disk info for backup archives

* finish work

* update changelog

* first round of fixes

* add isDifferencing

* fix review Ayoub & Florent

* fix comment Florent

* fix review Ayoub & Florent

* fix rebase

* fix review Florent & Ayoub
2026-12-03 17:48:48 +01:00
Florent BEAUCHAMP
90cd1de6a2 feat(xo6): show backup and v2v speed in tasks (#10798)
* feat(backups,xo6): show the reading speed of tasks

Each source (disk, XVA) is read once whatever the number of writers, in its
own `read` subtask reporting its current speed, in bytes per second, in the
`speed` property.

xo6 shows the current reading speed of a running task: its own one, or the
sum of the ones of its running subtasks.
2026-12-03 17:20:22 +01:00
Joris K
62dcf1c0ca feat(xo6/tasks): filter the task lists with the query builder (#10972) 2026-12-03 16:54:12 +01:00
Olivier Lambert
0e5353a4c8 feat(rest-api): add vms/:id/actions/convert_to_template route (#10661) 2026-12-03 15:21:31 +01:00
Joris K
157be98c91 fix(web-core): show the query builder filter menus above its modal (#10975) 2026-12-03 12:11:05 +01:00
Joris K
9f568d0893 feat(lite): add SSH enable and disable actions for XCP-ng 9 hosts (#10974) 2026-12-03 11:37:16 +01:00
Alina D
b890851a31 feat(lite): add VIF page and link to it from Network tab (#10686)
Co-authored-by: Joris-K <joris.kosacki@vates.tech>
Co-authored-by: Joris K <43381087+J0ris-K@users.noreply.github.com>
2026-12-03 09:36:13 +01:00
406 changed files with 16027 additions and 1500 deletions

View File

@@ -101,21 +101,6 @@ export interface EditVifProps {
txChecksumming?: boolean
}
/**
* Properties accepted by {@link Xapi.editNetwork}: the fields of `XoNetwork` it can change.
*
* `nbd` and `insecureNbd` cannot both be true: `editNetwork` throws `invalidParameters` when they are.
*/
export interface EditNetworkProps {
automatic?: boolean
defaultIsLocked?: boolean
insecureNbd?: boolean
MTU?: number
name_description?: string
name_label?: string
nbd?: boolean
}
export type XcpPatches = {
changelog?: {
author: string
@@ -350,7 +335,6 @@ export interface Xapi {
checkLimits?: (limits: Record<string, number>, vm: XenApiVmWrapped) => Promise<void>
): Promise<void>
editVif(id: XoVif['id'], props: EditVifProps): Promise<void>
editNetwork(id: XoNetwork['id'], props: EditNetworkProps): Promise<void>
startVm(
id: XoVm['id'],
opts?: {
@@ -497,6 +481,8 @@ export interface Xapi {
MAC?: string
}
): Promise<XenApiVif['$ref']>
/** ejects all removable media (e.g. CDs) then flags the VM as a template */
VM_convertToTemplate(vmRef: XenApiVm['$ref']): Promise<void>
VM_createCloudInitConfig(
vmRef: XenApiVm['$ref'],
cloudConfig: string,

View File

@@ -193,12 +193,21 @@ export type XoVmBackupArchive = {
id: Branded<'vm-backup-archive'>
type: 'xo-vm-backup'
backupRepository: XoBackupRepository['id']
disks: { id: string; name: string; uuid: XoVdiSnapshot['uuid'] }[]
disks: {
id: string
name: string
uuid: XoVdiSnapshot['uuid']
sizeOnDisk?: number
isDifferencing?: boolean
}[]
isImmutable?: boolean
jobId: XoVmBackupJob['id']
mode: XoVmBackupJob['mode']
scheduleId: XoSchedule['id']
/** Transferred size */
size: number
/** Space used on the backup repository, if known */
sizeOnDisk?: number
timestamp: number
vm: {
uuid: XoVm['uuid']
@@ -209,6 +218,7 @@ export type XoVmBackupArchive = {
differencingVhds?: number
dynamicVhds?: number
withMemory: boolean
tags: string[]
}
type XoMetadataBackupArchive = {

View File

@@ -5,12 +5,5 @@ export default {
update: {
tags: true,
other_config: true,
automatic: true,
defaultIsLocked: true,
insecureNbd: true,
MTU: true,
name_description: true,
name_label: true,
nbd: true,
},
}

View File

@@ -1,5 +1,6 @@
export default {
clone: true,
'convert-to-template': true,
delete: true,
export: true,
'migrate-send': true,

View File

@@ -13,6 +13,7 @@ import {
CleanResult,
DEFAULT_MERGE_CONCURRENCY,
DEFAULT_REMOVE_CONCURRENCY,
MergedDisk,
ResolvedBackupCleanOptions,
} from './VmBackup.types.mjs'
import { asyncEach } from '@vates/async-each'
@@ -425,16 +426,19 @@ export class RemoteDiskLineage {
this.#opts.logInfo('Disk chain needs merging', { count: toMerge.length })
}
// mergeTargetPath: final size of the disk everything was merged into
const mergedSizes = new Map<string, number>()
// mergeTargetPath: the disk everything was merged into
const mergedDisks = new Map<string, MergedDisk>()
if (merge) {
const limitedMergeChain = defaultMergeLimiter(this.#mergeChain.bind(this))
const doMerge = async () => {
await asyncEach(
toMerge,
async ({ chain, isResuming }) => {
const { finalDiskSize, mergeTargetPath } = await limitedMergeChain([...chain], isResuming)
mergedSizes.set(mergeTargetPath, (mergedSizes.get(mergeTargetPath) ?? 0) + finalDiskSize)
const { finalSizeOnDisk, mergeTargetPath, streamSize, isDifferencing } = await limitedMergeChain(
[...chain],
isResuming
)
mergedDisks.set(mergeTargetPath, { sizeOnDisk: finalSizeOnDisk, streamSize, isDifferencing })
// parentPath alias deleted by parentDisk.rename(mergeTargetPath)
// intermediates deleted by childDisk.unlink() when removeUnused=true
// Unregister so #cleanOrphanDataFiles does not read already-deleted aliases
@@ -453,19 +457,31 @@ export class RemoteDiskLineage {
await this.#cleanOrphanDataFiles(remove)
const sizeOnDisks = [...mergedDisks.values()].map(({ sizeOnDisk }) => sizeOnDisk)
return {
removedFiles: Array.from(toDelete),
merge: toMerge.length > 0,
size: [...mergedSizes.values()].reduce((total, subSize) => total + subSize, 0),
mergedSizes,
size: sizeOnDisks.reduce<number | undefined>(
(total, subSize) => (total !== undefined && subSize !== undefined ? total + subSize : undefined),
0
),
mergedDisks,
}
}
/**
* Merges ancestors into the active child at the end of the chain.
* Returns the final size of the merge target and its path.
* Returns the final size of the merge target and its path, undefined if unknown.
*/
async #mergeChain(chain: string[], isResuming: boolean): Promise<{ finalDiskSize: number; mergeTargetPath: string }> {
async #mergeChain(
chain: string[],
isResuming: boolean
): Promise<{
finalSizeOnDisk: number | undefined
mergeTargetPath: string
streamSize: number
isDifferencing: boolean
}> {
assert.ok(chain.length >= 2, `look to merge a chain shorter than 2 ${JSON.stringify(chain)}`)
const parentPath = chain[0]
this.#opts.logInfo('merging disk chain', { chain: [...chain] }) // need a copy here to log full chain
@@ -489,8 +505,8 @@ export class RemoteDiskLineage {
force: isResuming,
})
const { finalDiskSize } = (await merger.merge(parentDisk, childDisk!))!
return { finalDiskSize, mergeTargetPath }
const { finalSizeOnDisk, streamSize, isDifferencing } = (await merger.merge(parentDisk, childDisk!))!
return { finalSizeOnDisk, mergeTargetPath, streamSize, isDifferencing }
} finally {
await parentDisk?.close().catch(error => {
this.#opts.logWarn('Error closing parent Disk', error)

View File

@@ -6,7 +6,12 @@ export interface PartialBackupMetadata {
vhds?: Record<string, string>
vdis?: Record<string, unknown>
isVhdDifferencing?: Record<string, boolean>
// Transferred size. A merge only rewrites it, with the merged disks' stream size, when their size on disk is unknown.
size?: number
// Space used by each disk, keyed by vdiRef, updated by merges
vhdsSizeOnDisk?: Record<string, number>
// Space used by the XVA of a full backup, .checksum included
sizeOnDisk?: number
jobId: string
scheduleId: string
timestamp: number
@@ -38,7 +43,7 @@ export type ResolvedBackupCleanOptions = BackupCleanOptions & {
export interface ArchiveCleanOptions {
remove?: boolean
merge?: boolean
mergedSizes?: Map<string, number>
mergedDisks?: Map<string, MergedDisk>
}
export interface CheckResult {
@@ -55,11 +60,11 @@ export interface CheckResult {
export type CleanResult = {
removedFiles: string[]
// Files rewritten in place (e.g. metadata whose size was updated after a merge)
// Files rewritten in place (e.g. metadata recording the size on disk of the disks a merge rewrote)
changedFiles?: string[]
merge?: boolean
size?: number
mergedSizes?: Map<string, number>
mergedDisks?: Map<string, MergedDisk>
}
export interface VmBackupInterface {
@@ -74,3 +79,9 @@ export interface VmBackupInterface {
clean(opts?: ArchiveCleanOptions): Promise<CleanResult>
getAssociatedFiles(opts: object): Array<string>
}
export type MergedDisk = {
sizeOnDisk: number | undefined
streamSize: number
isDifferencing: boolean
}

View File

@@ -13,6 +13,7 @@ import {
PartialBackupMetadata,
ResolvedBackupCleanOptions,
DEFAULT_MERGE_CONCURRENCY,
MergedDisk,
} from './VmBackup.types.mjs'
import { cleanOrphanDiskDirs } from '@xen-orchestra/backup-archive/disks'
import { asyncEach } from '@vates/async-each'
@@ -138,19 +139,19 @@ export class VmBackupDirectory implements VmBackupInterface {
let someLineageMergedOrShouldBe = false
// Merge/delete orphan disks in VDI directories covered by archives; collect merged sizes per disk path
const allMergedSizes = new Map<string, number>()
const allMergedDisks = new Map<string, MergedDisk>()
await asyncEach(
Array.from(this.#uniqueLineages!.entries()),
async ([_vdiDir, lineage]) => {
const { mergedSizes, removedFiles, merge: hasPendingMerge } = await lineage.clean({ remove, merge })
const { mergedDisks, removedFiles, merge: hasPendingMerge } = await lineage.clean({ remove, merge })
if (removedFiles.length > 0) {
cacheNeedsRegen = true
}
if (hasPendingMerge) {
someLineageMergedOrShouldBe = true
}
for (const [diskPath, size] of mergedSizes || []) {
allMergedSizes.set(diskPath, (allMergedSizes.get(diskPath) ?? 0) + size)
for (const [diskPath, mergedDisk] of mergedDisks || []) {
allMergedDisks.set(diskPath, mergedDisk)
}
},
{ concurrency: DEFAULT_MERGE_CONCURRENCY }
@@ -174,7 +175,7 @@ export class VmBackupDirectory implements VmBackupInterface {
async ([metadataPath, archive]: [string, VmBackupInterface]) => {
const { removedFiles, changedFiles: archiveChangedFiles } = await archive.clean({
remove,
mergedSizes: allMergedSizes,
mergedDisks: allMergedDisks,
})
if (removedFiles.length > 0) {
cacheNeedsRegen = true
@@ -194,7 +195,7 @@ export class VmBackupDirectory implements VmBackupInterface {
this.backupArchives.delete(metadataPath)
}
if (this.#cacheExisted && (allMergedSizes.size > 0 || cacheNeedsRegen || this.#cacheOutOfSync)) {
if (this.#cacheExisted && (allMergedDisks.size > 0 || cacheNeedsRegen || this.#cacheOutOfSync)) {
await this.#regenerateCache()
}
@@ -216,7 +217,12 @@ export class VmBackupDirectory implements VmBackupInterface {
{ concurrency: 2 }
)
}
const size = [...allMergedSizes.values()].reduce((total, merged) => total + merged, 0)
const sizeOnDisks = [...allMergedDisks.values()].map(({ sizeOnDisk }) => sizeOnDisk)
const size = sizeOnDisks.reduce<number | undefined>(
(total, merged) => (total !== undefined && merged !== undefined ? total + merged : undefined),
0
)
// `removedFiles` lists the files this run removed, or would have removed if `remove` were set:
// root-level orphans plus the files each archive deemed removable (e.g. the metadata of an
// incomplete backup). Callers acting on it must therefore check `remove` themselves.

View File

@@ -14,11 +14,13 @@ import { RemoteVhdDisk } from '../dist/disks/RemoteVhdDisk.mjs'
import { MergeRemoteDisk } from '../dist/disks/MergeRemoteDisk.mjs'
/* eslint-enable n/no-missing-import */
import { VHDFOOTER, VHDHEADER } from './tests.fixtures.mjs'
import { VhdFile, Constants, VhdDirectory, VhdAbstract } from 'vhd-lib'
import { VhdFile, Constants, VhdDirectory, VhdAbstract, openVhd } from 'vhd-lib'
import Disposable from 'promise-toolbox/Disposable'
import { dirname, basename } from 'node:path'
import { promisify } from 'node:util'
import zlib from 'node:zlib'
import { rimraf } from 'rimraf'
import { isVhdAlias, resolveVhdAlias } from 'vhd-lib/aliases.js'
const { beforeEach, afterEach, describe } = test
@@ -51,6 +53,42 @@ afterEach(async () => {
const uniqueId = () => uuid.v1()
const uniqueIdBuffer = () => uuid.v1({}, Buffer.alloc(16))
// sum of the stored size of every file under `entry`, the reference `VhdDirectory#sizeOnDisk` is checked against
async function getFullSize(entry) {
let files
try {
files = await handler.list(entry, { prependDir: true })
} catch (error) {
if (error.code === 'ENOTDIR') {
return await handler.getSizeOnDisk(entry)
} else {
throw error
}
}
let size = 0
for (const file of files) {
size += await getFullSize(file)
}
return size
}
async function getDiskSizeOnDisk(diskPath) {
if (isVhdAlias(diskPath)) {
return (await getFullSize(await resolveVhdAlias(handler, diskPath))) + (await handler.getSizeOnDisk(diskPath))
}
return getFullSize(diskPath)
}
async function getDiskStreamSize(diskPath) {
return Disposable.use(openVhd(handler, diskPath), async vhd => {
await vhd.readBlockAllocationTable()
return vhd.streamSize()
})
}
async function generateVhd(path, opts = {}) {
let vhd
@@ -336,7 +374,7 @@ test('it merges delta of non destroyed chain', async () => {
`${rootPath}/metadata.json`,
JSON.stringify({
mode: 'delta',
size: 12000, // a size too small
size: 12000,
vhds: [
`${relativePath}/grandchild.vhd`, // grand child should not be merged
`${relativePath}/child.vhd`,
@@ -381,7 +419,152 @@ test('it merges delta of non destroyed chain', async () => {
assert.equal(remainingVhds.includes('grandchild.vhd'), true)
const metadata = JSON.parse(await handler.readFile(`${rootPath}/metadata.json`))
assert.equal(metadata.size, 4299776, 'metadata.size should be updated after merge')
assert.equal(metadata.size, 12000, 'metadata.size should not change')
assert.equal(
metadata.vhdsSizeOnDisk['1'],
await getDiskSizeOnDisk(`${basePath}/child.vhd`),
'vhdsSizeOnDisk should contain the size of the child'
)
assert.equal(
metadata.vhdsSizeOnDisk['0'],
undefined,
'vhdsSizeOnDisk should not contain the size of the grandchild as it was not measured'
)
})
// a backup of two disks: `a` has an orphan parent to merge, `b` has nothing to merge
//
// with `mode: 'directory'`, the disks of `a` are aliased VHD directories written without size.json:
// their size on disk is unknown
async function writeBackupWithOneDiskToMerge(metadata, { mode } = {}) {
const useAlias = mode === 'directory'
const suffix = useAlias ? '.alias.vhd' : ''
const orphan = await generateVhd(`${basePath}/orphan.vhd`, { mode, useAlias })
await generateVhd(`${basePath}/child.vhd`, {
mode,
useAlias,
header: {
parentUnicodeName: `orphan.vhd${suffix}`,
parentUuid: orphan.footer.uuid,
},
blocks: [0, 1],
})
await generateVhd(`${basePath2}/disk.vhd`)
await handler.writeFile(
`${rootPath}/metadata.json`,
JSON.stringify({
mode: 'delta',
size: 12000,
vhds: { a: `${relativePath}/child.vhd${suffix}`, b: `${relativePath2}/disk.vhd` },
...metadata,
})
)
await VmBackupDirectory.cleanVm(handler, rootPath, {
remove: true,
merge: true,
logInfo: () => {},
logWarn: () => {},
})
return JSON.parse(await handler.readFile(`${rootPath}/metadata.json`))
}
test('it only updates the size on disk of the merged disks', async () => {
// fake values, which cannot be mistaken for a real size
const metadata = await writeBackupWithOneDiskToMerge({ vhdsSizeOnDisk: { a: 1, b: 2 } })
assert.equal(metadata.size, 12000, 'metadata.size should not change')
assert.equal(metadata.vhdsSizeOnDisk.a, await getDiskSizeOnDisk(`${basePath}/child.vhd`))
assert.equal(metadata.vhdsSizeOnDisk.b, 2, 'the size on disk of a disk which has not been merged should not change')
})
test('it only marks the merged disks as not differencing', async () => {
const metadata = await writeBackupWithOneDiskToMerge({
isVhdDifferencing: { a: true, b: true },
vdis: { a: {}, b: {} },
})
assert.equal(metadata.isVhdDifferencing.a, false)
assert.equal(
metadata.isVhdDifferencing.b,
true,
'the isVhdDifferencing of a disk which has not been merged should not change'
)
})
test('it records the size on disk of the merged disks of a backup without any', async () => {
// a backup written before the size on disk was recorded
const metadata = await writeBackupWithOneDiskToMerge({})
assert.equal(metadata.size, 12000, 'metadata.size should not change')
assert.deepEqual(metadata.vhdsSizeOnDisk, { a: await getDiskSizeOnDisk(`${basePath}/child.vhd`) })
})
test('it forgets the size on disk of a merged disk whose size is unknown', async () => {
// fake values: the one of `a` would be stale after the merge, which adds the blocks of its parent
const metadata = await writeBackupWithOneDiskToMerge({ vhdsSizeOnDisk: { a: 1, b: 2 } }, { mode: 'directory' })
assert.deepEqual(
metadata.vhdsSizeOnDisk,
{ b: 2 },
'the size on disk of a merged disk should be removed when unknown, the others should not change'
)
})
test('it records the stream size of the merged disks in size when a size on disk is unknown', async () => {
// a chain started before the size on disk was recorded: the backup usage falls back to `size`
const metadata = await writeBackupWithOneDiskToMerge({}, { mode: 'directory' })
assert.equal(
metadata.size,
await getDiskStreamSize(`${basePath}/child.vhd.alias.vhd`),
'metadata.size should be the stream size of the merged disk, which now contains the blocks of its parent'
)
})
test('it keeps differencing a disk merged in the middle of a chain', async () => {
// ancestor -> orphan -> child: the ancestor is still used by an older backup, only the orphan is merged
const ancestor = await generateVhd(`${basePath}/ancestor.vhd`, { blocks: [0] })
const orphan = await generateVhd(`${basePath}/orphan.vhd`, {
header: { parentUnicodeName: 'ancestor.vhd', parentUuid: ancestor.footer.uuid },
blocks: [1],
})
await generateVhd(`${basePath}/child.vhd`, {
header: { parentUnicodeName: 'orphan.vhd', parentUuid: orphan.footer.uuid },
blocks: [2],
})
await handler.writeFile(
`${rootPath}/older.json`,
JSON.stringify({ mode: 'delta', size: 12000, vhds: { a: `${relativePath}/ancestor.vhd` } })
)
await handler.writeFile(
`${rootPath}/metadata.json`,
JSON.stringify({
mode: 'delta',
size: 12000,
vhds: { a: `${relativePath}/child.vhd` },
vdis: { a: {} },
isVhdDifferencing: { a: true },
})
)
await VmBackupDirectory.cleanVm(handler, rootPath, {
remove: true,
merge: true,
logInfo: () => {},
logWarn: () => {},
})
const remainingVhds = await handler.list(basePath)
assert.equal(remainingVhds.includes('orphan.vhd'), false, 'the orphan should have been merged')
assert.equal(remainingVhds.includes('ancestor.vhd'), true, 'the ancestor is still used and should not be merged')
const metadata = JSON.parse(await handler.readFile(`${rootPath}/metadata.json`))
assert.equal(metadata.isVhdDifferencing.a, true, 'the merged disk still has the ancestor as parent')
})
test('it merges a chain of multiple consecutive orphan ancestors in one pass', async () => {
@@ -727,8 +910,28 @@ describe('tests multiple combination ', { concurrency: 1 }, () => {
await VmBackupDirectory.cleanVm(handler, rootPath, { remove: true, merge: true, logWarn: () => {} })
const metadata = JSON.parse(await handler.readFile(`${rootPath}/metadata.json`))
// size should be the size of children + grand children + clean after the merge
assert.deepEqual(metadata.size, 6501888)
// merges record the size on disk of the disks they merged into, child and clean.
// Directory disks without `size.json` stay unknown, so size falls back to their stream size
assert.equal(
metadata.size,
vhdMode === 'directory'
? (await getDiskStreamSize(`${basePath}/child.vhd.alias.vhd`)) +
(await getDiskStreamSize(`${basePath}/clean.vhd.alias.vhd`))
: undefined
)
assert.equal(
metadata.vhdsSizeOnDisk['1'],
vhdMode === 'directory'
? undefined
: await getDiskSizeOnDisk(`${basePath}/child.vhd${useAlias ? '.alias.vhd' : ''}`)
)
assert.equal(
metadata.vhdsSizeOnDisk['2'],
vhdMode === 'directory'
? undefined
: await getDiskSizeOnDisk(`${basePath}/clean.vhd${useAlias ? '.alias.vhd' : ''}`)
)
assert.equal(metadata.vhdsSizeOnDisk['0'], undefined)
// no cache.json.gz existed before this run, so a merge must not create one
assert.ok(
!(await handler.list(rootPath)).includes('cache.json.gz'),
@@ -864,7 +1067,7 @@ test('it regenerates a pre-existing cache after a merge', async () => {
`${rootPath}/metadata.json`,
JSON.stringify({
mode: 'delta',
size: 12000, // a size too small, the merge will fix it
size: 12000,
vhds: [`${relativePath}/grandchild.vhd`, `${relativePath}/child.vhd`],
})
)
@@ -900,13 +1103,26 @@ test('it regenerates a pre-existing cache after a merge', async () => {
})
const metadata = JSON.parse(await handler.readFile(`${rootPath}/metadata.json`))
// size of child + grandchild after orphan has been merged into child
assert.equal(metadata.size, 4299776, 'metadata.size should be updated after merge')
assert.equal(metadata.size, 12000, 'metadata.size should not change')
assert.equal(
metadata.vhdsSizeOnDisk['1'],
await getDiskSizeOnDisk(`${basePath}/child.vhd`),
'vhdsSizeOnDisk should contain the size of the child'
)
assert.equal(
metadata.vhdsSizeOnDisk['0'],
undefined,
'vhdsSizeOnDisk should not contain the size of the grandchild as it was not measured'
)
assert.deepEqual(result.changedFiles, [`/${rootPath}metadata.json`], 'the rewritten metadata should be reported')
const cache = JSON.parse((await gunzip(await handler.readFile(`${rootPath}/cache.json.gz`))).toString())
assert.equal(Object.keys(cache).length, 1)
assert.equal(Object.values(cache)[0].size, metadata.size, 'cache entry should carry the post-merge size')
assert.deepEqual(
Object.values(cache)[0].vhdsSizeOnDisk,
metadata.vhdsSizeOnDisk,
'cache entry should carry the post-merge size on disk'
)
})
test('it regenerates a pre-existing cache when its entry count is out of sync, even with nothing to merge/remove', async () => {

View File

@@ -6,9 +6,10 @@ import {
VmBackupInterface,
PartialBackupMetadata,
DEFAULT_REMOVE_CONCURRENCY,
MergedDisk,
} from './VmBackup.types.mjs'
import { RemoteHandlerAbstract } from '@xen-orchestra/fs'
import { basename, dirname, normalize } from '@xen-orchestra/fs/path'
import { basename, dirname, normalize, resolveFromFile } from '@xen-orchestra/fs/path'
import { RemoteDiskLineage } from './RemoteDiskLineage.mjs'
import { asyncEach } from '@vates/async-each'
@@ -126,10 +127,13 @@ export class VmIncrementalBackupArchive implements VmBackupInterface {
/**
* Removes the metadata file if the backup is incomplete (missing disks).
* If mergedSizes is provided, updates metadata with the total merged size for this archive's disks.
* If mergedDisks is provided, records the size on disk of this archive's merged disks
* in vhdsSizeOnDisk (removed when unknown) and records whether they are still differencing.
* When the size on disk of a merged disk is unknown (chains started before it was recorded),
* size is set to the stream size of the merged disks, which the backup usage falls back to.
* Actual disk merge/deletion is handled by RemoteDiskLineage.
*/
async clean({ remove = this.opts.remove ?? false, mergedSizes }: ArchiveCleanOptions = {}): Promise<CleanResult> {
async clean({ remove = this.opts.remove ?? false, mergedDisks }: ArchiveCleanOptions = {}): Promise<CleanResult> {
if (!this.#isChecked) {
await this.check()
}
@@ -150,13 +154,18 @@ export class VmIncrementalBackupArchive implements VmBackupInterface {
}
const changedFiles: string[] = []
let mergedSize = 0
if (mergedSizes !== undefined) {
for (const diskPath of this.diskPaths) {
mergedSize += mergedSizes.get(diskPath) ?? 0
const updates: Record<string, MergedDisk> = {}
if (mergedDisks !== undefined) {
for (const [vdiRef, relPath] of Object.entries(this.metadata.vhds ?? {})) {
const vhdPath = normalize(resolveFromFile(this.metadataPath, relPath))
const mergedDisk = mergedDisks.get(vhdPath)
if (mergedDisk !== undefined) {
updates[vdiRef] = mergedDisk
}
}
if (mergedSize > 0) {
await this.updateMetadata(mergedSize)
if (Object.keys(updates).length > 0) {
await this.updateMetadata(updates)
changedFiles.push(this.metadataPath)
}
}
@@ -165,17 +174,30 @@ export class VmIncrementalBackupArchive implements VmBackupInterface {
}
/**
* Updates metadata.size after a merge and writes the updated metadata file to disk.
* Also resets isVhdDifferencing so all VDIs are marked as full (non-differencing).
* Updates the size on disk and the differencing status of the merged disks, then writes the metadata file.
* If the size on disk of a merged disk is unknown, size is set to the stream size of the merged disks.
*/
async updateMetadata(mergedSize: number): Promise<void> {
this.metadata.size = mergedSize
if (this.metadata.vdis !== undefined) {
this.metadata.isVhdDifferencing = {}
for (const id of Object.keys(this.metadata.vdis)) {
this.metadata.isVhdDifferencing[id] = false
async updateMetadata(updates: Record<string, MergedDisk>): Promise<void> {
const vhdsSizeOnDisk = { ...this.metadata.vhdsSizeOnDisk }
const totalStreamSize = Object.values(updates).reduce((total, { streamSize }) => {
return total + streamSize
}, 0)
for (const [vdiRef, { sizeOnDisk }] of Object.entries(updates)) {
if (sizeOnDisk === undefined) {
// Chains started before sizeOnDisk existed have no size on disk: size keeps the merged disks' stream size,
// which the backup usage falls back to
this.metadata.size = totalStreamSize
delete vhdsSizeOnDisk[vdiRef]
} else {
vhdsSizeOnDisk[vdiRef] = sizeOnDisk
}
}
this.metadata.vhdsSizeOnDisk = vhdsSizeOnDisk
this.metadata.isVhdDifferencing = this.metadata.isVhdDifferencing ?? {}
for (const [vdiRef, { isDifferencing }] of Object.entries(updates)) {
this.metadata.isVhdDifferencing[vdiRef] = isDifferencing
}
await this.handler.writeFile(this.metadataPath, JSON.stringify(this.metadata), { flags: 'w' })
}

View File

@@ -11,6 +11,7 @@ import { createLogger } from '@xen-orchestra/log'
import { basename, dirname } from 'path'
import { asyncEach } from '@vates/async-each'
import { relativeFromFile, normalize, resolveFromFile } from '@xen-orchestra/fs/path'
import { isVhdAlias } from 'vhd-lib/aliases.js'
// @ts-ignore
const { warn } = createLogger('remote-disk:merge')
@@ -23,7 +24,9 @@ const { warn } = createLogger('remote-disk:merge')
* @property {number} currentBlock
* @property {number} mergedDataSize
* @property {'mergeBlocks' | 'cleanup'} step
* @property {number} diskSize
* @property {number} [sizeOnDisk]
* @property {number} [streamSize]
* @property {boolean} [isDifferencing]
* @typedef {(message: string, data?: Record<string, unknown>) => void} Logger
*/
@@ -38,7 +41,6 @@ export class MergeRemoteDisk {
currentBlock: 0,
mergedDataSize: 0,
step: 'mergeBlocks',
diskSize: 0,
}
/**
@@ -220,10 +222,28 @@ export class MergeRemoteDisk {
await this.#writeState()
}
// Loads the stored size before the blocks are modified
if (!this.#isResuming) {
try {
await parentDisk.readSizeOnDisk()
} catch (err) {
warn(`Unable to read sizeOnDisk on ${parentDisk.getPath()}`, { error: err })
}
}
await this.#mergeBlocks(parentDisk, childDisk)
await parentDisk.flushMetadata(childDisk)
await parentDisk.mergeMetadata(childDisk)
this.#state.diskSize = parentDisk.getSizeOnDisk()
// A resumed merge has lost the size changes of the blocks moved before the interruption,
// its size is unknown.
if (!this.#isResuming) {
try {
await parentDisk.saveSizeOnDisk()
} catch (err) {
warn(`Unable to save sizeOnDisk on ${parentDisk.getPath()}`, { error: err })
}
}
}
/**
@@ -301,6 +321,36 @@ export class MergeRemoteDisk {
throw error
}
}
this.#state.sizeOnDisk = await this.#getFinalSizeOnDisk(parentDisk, mergeTargetPath)
this.#state.streamSize = parentDisk.getStreamSize()
// The merged disk keeps the ancestors of the parent: it is differencing if the parent was.
this.#state.isDifferencing = parentDisk.isDifferencing()
}
/**
* @param {RemoteDisk} parentDisk
* @param {string} mergeTargetPath
* @returns {Promise<number | undefined>}
*/
async #getFinalSizeOnDisk(parentDisk, mergeTargetPath) {
try {
let sizeOnDisk = await parentDisk.readSizeOnDisk()
if (sizeOnDisk === undefined) {
return undefined
}
if (isVhdAlias(mergeTargetPath)) {
sizeOnDisk += await this.#handler.getSizeOnDisk(mergeTargetPath)
}
return sizeOnDisk
} catch (err) {
warn(`Unable to get finalSizeOnDisk on ${parentDisk.getPath()}`, { error: err })
}
return undefined
}
/**
@@ -308,11 +358,13 @@ export class MergeRemoteDisk {
* @param {RemoteDisk} childDisk
* @param {boolean} cleanStateFile
*
* @returns {Promise<{mergedDataSize: number, finalDiskSize: number}>} result
* @returns {Promise<{mergedDataSize: number, finalSizeOnDisk: number | undefined, streamSize: number, isDifferencing: boolean}>} result
*/
async #cleanup(parentDisk, childDisk, cleanStateFile) {
const finalDiskSize = this.#state?.diskSize ?? 0
const finalSizeOnDisk = this.#state?.sizeOnDisk
const streamSize = this.#state?.streamSize ?? 0
const mergedDataSize = this.#state?.mergedDataSize ?? 0
const isDifferencing = this.#state?.isDifferencing ?? false
await parentDisk.close().catch(warn)
await childDisk.close().catch(warn)
@@ -320,7 +372,7 @@ export class MergeRemoteDisk {
await this.#handler.unlink(this.#statePath).catch(warn)
}
return { mergedDataSize, finalDiskSize }
return { mergedDataSize, finalSizeOnDisk, streamSize, isDifferencing }
}
/**

View File

@@ -36,8 +36,8 @@ export class RemoteDisk extends RandomAccessDisk {
* Abstract
* @returns {number} size
*/
getSizeOnDisk() {
throw new Error(`getSizeOnDisk must be implemented`)
getStreamSize() {
throw new Error(`getStreamSize must be implemented`)
}
/**
@@ -294,4 +294,22 @@ export class RemoteDisk extends RandomAccessDisk {
}
return parent
}
/**
* Write the disk size to its size.json metadata file, if it is known.
*
* @returns {Promise<void>}
*/
async saveSizeOnDisk() {
throw new Error(`saveSizeOnDisk must be implemented`)
}
/**
* Returns the space used by the data and undefined if unknown
*
* @returns {Promise<number|undefined>}
*/
async readSizeOnDisk() {
throw new Error(`readSizeOnDisk must be implemented`)
}
}

View File

@@ -13,12 +13,35 @@ import { RemoteVhdDiskChain } from './RemoteVhdDiskChain.mjs'
import { dirname, basename } from 'node:path'
import { rimraf } from 'rimraf'
import { MergeRemoteDisk } from './MergeRemoteDisk.mjs'
import { resolveVhdAlias } from 'vhd-lib/aliases.js'
import { normalize } from '@xen-orchestra/fs/path'
const { beforeEach, afterEach, describe } = test
let tempDir, handler, jobId, vdiId, basePath, relativePath
const rootPath = 'xo-vm-backups/VMUUID'
// sum of the stored size of every file under `entry`, the reference `VhdDirectory#sizeOnDisk` is checked against
async function getFullSize(handler, entry) {
let files
try {
files = await handler.list(entry, { prependDir: true })
} catch (error) {
if (error.code === 'ENOTDIR') {
return await handler.getSizeOnDisk(entry)
} else {
throw error
}
}
let size = 0
for (const file of files) {
size += await getFullSize(handler, file)
}
return size
}
beforeEach(async () => {
tempDir = await pFromCallback(cb => tmp.dir(cb))
handler = getHandler({ url: `file://${tempDir}` })
@@ -75,6 +98,9 @@ async function generateVhd(path, opts = {}) {
await vhd.writeBlockAllocationTable()
await vhd.writeHeader()
await vhd.writeFooter()
if (opts.mode === 'directory' && opts.writeSize !== false) {
await vhd.saveSize()
}
return vhd
}
@@ -350,9 +376,12 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
const result = await mergeRemoteDisk.merge(parent, child)
assert.ok(result.finalDiskSize > 0, 'merged disks should have non-zero size')
assert.equal(result.finalSizeOnDisk, await handler.getSizeOnDisk(`${basePath}/child.vhd`))
assert.ok(result.finalSizeOnDisk > 0, 'merged disks should have non-zero size')
assert.ok(result.mergedDataSize > 0, 'merged data size should be > 0')
assert.ok(progressCalls > 0, 'onProgress should have been called')
assert.equal(result.isDifferencing, false, 'the merged disk should not be differencing, like its parent')
// Check that ancestor was renamed to child
const remainingDisks = await handler.list(basePath)
@@ -362,6 +391,27 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
assert.deepEqual(parentIndexes, expectedIndexes, 'all child blocks should be merged into parent')
})
test('MergeRemoteDisk merges into a differencing parent a disk which stays differencing', async () => {
// the parent has its own parent: merging its child into it does not make it a full disk
await generateVhd(`${basePath}/ancestor.vhd`, {
header: { parentUnicodeName: 'grandAncestor.vhd', parentUuid: uniqueIdBuffer() },
blocks: [0, 1],
})
await generateVhd(`${basePath}/child.vhd`, { blocks: [2, 3] })
const parent = new RemoteVhdDisk({ handler, path: `${basePath}/ancestor.vhd` })
const child = new RemoteVhdDisk({ handler, path: `${basePath}/child.vhd` })
const mergeRemoteDisk = new MergeRemoteDisk(handler, { removeUnused: true })
await parent.init()
await child.init()
const result = await mergeRemoteDisk.merge(parent, child)
assert.equal(result.isDifferencing, true)
})
test('MergeRemoteDisk merges a simple ancestor VHD + child VHD chain', async () => {
let progressCalls = 0
const onProgress = () => {
@@ -412,7 +462,7 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
const result = await mergeRemoteDisk.merge(parent, childDiskChain)
assert.ok(result.finalDiskSize > 0, 'merged disks should have non-zero size')
assert.ok(result.finalSizeOnDisk > 0, 'merged disks should have non-zero size')
assert.ok(result.mergedDataSize > 0, 'merged data size should be > 0')
assert.ok(progressCalls > 0, 'onProgress should have been called')
@@ -450,7 +500,7 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
const result = await mergeRemoteDisk.merge(parent, child)
assert.ok(result.finalDiskSize > 0, 'merged disks should have non-zero size')
assert.ok(result.finalSizeOnDisk > 0, 'merged disks should have non-zero size')
assert.ok(result.mergedDataSize > 0, 'merged data size should be > 0')
assert.ok(progressCalls > 0, 'onProgress should have been called')
@@ -505,7 +555,7 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
const result = await mergeRemoteDisk.merge(parent, childDiskChain)
assert.ok(result.finalDiskSize > 0, 'merged disks should have non-zero size')
assert.ok(result.finalSizeOnDisk > 0, 'merged disks should have non-zero size')
assert.ok(result.mergedDataSize > 0, 'merged data size should be > 0')
assert.ok(progressCalls > 0, 'onProgress should have been called')
@@ -546,7 +596,7 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
const result = await mergeRemoteDisk.merge(parent, child)
assert.ok(result.finalDiskSize > 0, 'merged disks should have non-zero size')
assert.ok(result.finalSizeOnDisk > 0, 'merged disks should have non-zero size')
assert.ok(result.mergedDataSize > 0, 'merged data size should be > 0')
assert.ok(progressCalls > 0, 'onProgress should have been called')
@@ -587,7 +637,7 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
const result = await mergeRemoteDisk.merge(parent, child)
assert.ok(result.finalDiskSize > 0, 'merged disks should have non-zero size')
assert.ok(result.finalSizeOnDisk > 0, 'merged disks should have non-zero size')
assert.ok(result.mergedDataSize > 0, 'merged data size should be > 0')
assert.ok(progressCalls > 0, 'onProgress should have been called')
@@ -595,11 +645,33 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
const remainingDisks = await handler.list(basePath)
assert.deepEqual(remainingDisks, ['child.vhd.alias.vhd', 'data'])
// the ancestor is a plain file: it has been moved under `data` to be the target of the alias
const remainingDatas = await handler.list(basePath + '/data')
assert.deepEqual(remainingDatas, [])
assert.deepEqual(remainingDatas, ['ancestor.vhd'])
const aliasPath = `${basePath}/child.vhd.alias.vhd`
const dataPath = `${basePath}/data/ancestor.vhd`
assert.equal(normalize(await resolveVhdAlias(handler, aliasPath)), normalize(dataPath))
assert.equal(
result.finalSizeOnDisk,
(await handler.getSizeOnDisk(dataPath)) + (await handler.getSizeOnDisk(aliasPath))
)
const parentIndexes = parent.getBlockIndexes()
assert.deepEqual(parentIndexes, expectedIndexes, 'all child blocks should be merged into parent')
// the merged data are readable through the alias
const merged = new RemoteVhdDisk({ handler, path: aliasPath })
await merged.init()
try {
const { data } = await merged.readBlock(2)
assert.ok(
data.every(byte => byte === 2),
'block 2 should come from the child'
)
} finally {
await merged.close()
}
})
test('MergeRemoteDisk merges a alias ancestor VHD directory + alias child VHD directory', async () => {
@@ -628,7 +700,7 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
const result = await mergeRemoteDisk.merge(parent, child)
assert.ok(result.finalDiskSize > 0, 'merged disks should have non-zero size')
assert.ok(result.finalSizeOnDisk > 0, 'merged disks should have non-zero size')
assert.ok(result.mergedDataSize > 0, 'merged data size should be > 0')
assert.ok(progressCalls > 0, 'onProgress should have been called')
@@ -767,7 +839,7 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
const result = await mergeRemoteDisk.merge(parent2, child2)
// Verify merge completed
assert.ok(result.finalDiskSize > 0, 'final disk size should be > 0')
assert.ok(result.finalSizeOnDisk > 0, 'final disk size should be > 0')
assert.ok(result.mergedDataSize > 0, 'merged data size should be > 0')
// Verify state file removed after successful resume
@@ -863,7 +935,7 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
const result = await mergeRemoteDisk.merge(parent2, child2)
// Verify merge completed
assert.ok(result.finalDiskSize > 0, 'final disk size should be > 0')
assert.strictEqual(result.finalSizeOnDisk, undefined, 'the size of a resumed merge is unknown')
assert.ok(result.mergedDataSize > 0, 'merged data size should be > 0')
// Verify state file removed after successful resume
@@ -957,7 +1029,7 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
const result = await mergeRemoteDisk.merge(parent2, childDiskChain2)
assert.ok(result.finalDiskSize > 0, 'final disk size should be > 0')
assert.ok(result.finalSizeOnDisk > 0, 'final disk size should be > 0')
assert.equal(
(await handler.list(basePath)).includes(stateFileName),
@@ -1047,6 +1119,281 @@ describe('tests MergeRemoteDisk', { concurrency: 1 }, () => {
const parentIndexes = parent.getBlockIndexes()
assert.deepEqual(parentIndexes, expectedIndexes, 'all child blocks should be merged into parent')
})
test('mergeRemoteDisk merge on a parent with a size computes the correct size', async () => {
// Create ancestor and child VHDs
await generateVhd(`${basePath}/ancestor.vhd`, { blocks: [0, 1], mode: 'directory', useAlias: true })
await generateVhd(`${basePath}/child.vhd`, { blocks: [2, 3], mode: 'directory', useAlias: true })
const parent = new RemoteVhdDisk({ handler, path: `${basePath}/ancestor.vhd.alias.vhd` })
const child = new RemoteVhdDisk({ handler, path: `${basePath}/child.vhd.alias.vhd` })
const mergeRemoteDisk = new MergeRemoteDisk(handler, { removeUnused: true })
const isResumingMerge = await mergeRemoteDisk.isResuming(parent)
await parent.init({ force: isResumingMerge })
await child.init({ force: isResumingMerge })
assert.strictEqual(typeof (await parent.readSizeOnDisk()), 'number')
const result = await mergeRemoteDisk.merge(parent, child)
assert.equal(
result.finalSizeOnDisk,
(await getFullSize(handler, `${basePath}/data/ancestor.vhd`)) +
(await handler.getSizeOnDisk(`${basePath}/child.vhd.alias.vhd`))
)
const resultingDisk = new RemoteVhdDisk({ handler, path: `${basePath}/child.vhd.alias.vhd` })
await resultingDisk.init()
assert.strictEqual(
await resultingDisk.readSizeOnDisk(),
await getFullSize(handler, `${basePath}/data/ancestor.vhd`)
)
})
test('mergeRemoteDisk merge on a parent without a size has undefined size', async () => {
// Create ancestor and child VHDs
await generateVhd(`${basePath}/ancestor.vhd`, {
blocks: [0, 1],
mode: 'directory',
useAlias: true,
writeSize: false,
})
await generateVhd(`${basePath}/child.vhd`, { blocks: [2, 3], mode: 'directory', useAlias: true, writeSize: false })
const parent = new RemoteVhdDisk({ handler, path: `${basePath}/ancestor.vhd.alias.vhd` })
const child = new RemoteVhdDisk({ handler, path: `${basePath}/child.vhd.alias.vhd` })
const mergeRemoteDisk = new MergeRemoteDisk(handler, { removeUnused: true })
const isResumingMerge = await mergeRemoteDisk.isResuming(parent)
await parent.init({ force: isResumingMerge })
await child.init({ force: isResumingMerge })
assert.strictEqual(await parent.readSizeOnDisk(), undefined)
const result = await mergeRemoteDisk.merge(parent, child)
assert.equal(result.finalSizeOnDisk, undefined)
const resultingDisk = new RemoteVhdDisk({ handler, path: `${basePath}/child.vhd.alias.vhd` })
await resultingDisk.init()
assert.strictEqual(await resultingDisk.readSizeOnDisk(), undefined)
})
test('mergeRemoteDisk merge on a parent with a size does not recompute it', async t => {
await generateVhd(`${basePath}/ancestor.vhd`, { blocks: [0, 1], mode: 'directory', useAlias: true })
await generateVhd(`${basePath}/child.vhd`, { blocks: [1, 2], mode: 'directory', useAlias: true })
const parent = new RemoteVhdDisk({ handler, path: `${basePath}/ancestor.vhd.alias.vhd` })
const child = new RemoteVhdDisk({ handler, path: `${basePath}/child.vhd.alias.vhd` })
const mergeRemoteDisk = new MergeRemoteDisk(handler, { removeUnused: true })
const isResumingMerge = await mergeRemoteDisk.isResuming(parent)
await parent.init({ force: isResumingMerge })
await child.init({ force: isResumingMerge })
// listing and stating every block is what the stored size avoids
const list = t.mock.method(handler, 'list')
const result = await mergeRemoteDisk.merge(parent, child)
assert.equal(list.mock.callCount(), 0, 'the size should be updated, not recomputed')
assert.equal(
result.finalSizeOnDisk,
(await getFullSize(handler, `${basePath}/data/ancestor.vhd`)) +
(await handler.getSizeOnDisk(`${basePath}/child.vhd.alias.vhd`))
)
})
// the size on disk is only informative: failing to measure it must not fail the merge
for (const [failure, mockFailure] of [
[
'reading the size',
(t, parent) =>
t.mock.method(parent, 'readSizeOnDisk', async () => {
throw new Error('read failure')
}),
],
[
'saving the size',
(t, parent) =>
t.mock.method(parent, 'saveSizeOnDisk', async () => {
throw new Error('save failure')
}),
],
[
'measuring the alias',
t => {
const getSizeOnDisk = handler.getSizeOnDisk.bind(handler)
t.mock.method(handler, 'getSizeOnDisk', async path => {
if (path.endsWith('child.vhd.alias.vhd')) {
throw new Error('stat failure')
}
return getSizeOnDisk(path)
})
},
],
]) {
test(`mergeRemoteDisk merges and has undefined size when ${failure} fails`, async t => {
await generateVhd(`${basePath}/ancestor.vhd`, { blocks: [0, 1], mode: 'directory', useAlias: true })
await generateVhd(`${basePath}/child.vhd`, { blocks: [2, 3], mode: 'directory', useAlias: true })
const parent = new RemoteVhdDisk({ handler, path: `${basePath}/ancestor.vhd.alias.vhd` })
const child = new RemoteVhdDisk({ handler, path: `${basePath}/child.vhd.alias.vhd` })
const mergeRemoteDisk = new MergeRemoteDisk(handler, { removeUnused: true })
await parent.init()
await child.init()
mockFailure(t, parent)
const result = await mergeRemoteDisk.merge(parent, child)
if (failure === 'saving the size') {
// the size known in memory is still returned, but it is not stored
assert.equal(typeof result.finalSizeOnDisk, 'number')
} else {
assert.equal(result.finalSizeOnDisk, undefined)
}
t.mock.restoreAll()
const resultingDisk = new RemoteVhdDisk({ handler, path: `${basePath}/child.vhd.alias.vhd` })
await resultingDisk.init()
try {
for (const blockId of [0, 1, 2, 3]) {
assert.ok(resultingDisk.hasBlock(blockId), `block ${blockId} should be merged`)
}
if (failure !== 'measuring the alias') {
assert.equal(await resultingDisk.readSizeOnDisk(), undefined, 'no valid size.json should be stored')
}
} finally {
await resultingDisk.close()
}
})
}
test('mergeRemoteDisk merge on a parent with a stale size has undefined size', async () => {
await generateVhd(`${basePath}/ancestor.vhd`, { blocks: [0, 1], mode: 'directory', useAlias: true })
await generateVhd(`${basePath}/child.vhd`, { blocks: [2, 3], mode: 'directory', useAlias: true })
// like a merge done by a version which does not know size.json: a block is added and the footer takes the UUID
// of the merged child, but size.json is not updated
const { value: ancestor, dispose } = await VhdDirectory.open(handler, `${basePath}/data/ancestor.vhd`, {
flags: 'r+',
})
try {
await ancestor.readBlockAllocationTable()
await ancestor.writeEntireBlock({ id: 4, buffer: Buffer.alloc(2 * 1024 * 1024 + 512, 4) })
await ancestor.writeBlockAllocationTable()
ancestor.footer.uuid = uniqueIdBuffer()
await ancestor.writeFooter()
} finally {
await dispose()
}
const parent = new RemoteVhdDisk({ handler, path: `${basePath}/ancestor.vhd.alias.vhd` })
const child = new RemoteVhdDisk({ handler, path: `${basePath}/child.vhd.alias.vhd` })
const mergeRemoteDisk = new MergeRemoteDisk(handler, { removeUnused: true })
const isResumingMerge = await mergeRemoteDisk.isResuming(parent)
await parent.init({ force: isResumingMerge })
await child.init({ force: isResumingMerge })
assert.strictEqual(await parent.readSizeOnDisk(), undefined, 'a stale size must not be trusted')
const result = await mergeRemoteDisk.merge(parent, child)
assert.equal(result.finalSizeOnDisk, undefined)
const resultingDisk = new RemoteVhdDisk({ handler, path: `${basePath}/child.vhd.alias.vhd` })
await resultingDisk.init()
assert.strictEqual(await resultingDisk.readSizeOnDisk(), undefined)
})
test('mergeRemoteDisk resumes after interruption has undefined size', async () => {
// Create parent and child VHDs
await generateVhd(`${basePath}/ancestor.vhd`, { blocks: [0, 1], mode: 'directory', useAlias: true })
await generateVhd(`${basePath}/child.vhd`, {
blocks: [2, 3, 4, 5, 6, 7, 8, 9, 10],
mode: 'directory',
useAlias: true,
})
const parent = new RemoteVhdDisk({ handler, path: `${basePath}/ancestor.vhd.alias.vhd` })
const child = new RemoteVhdDisk({ handler, path: `${basePath}/child.vhd.alias.vhd` })
const mergeRemoteDisk = new MergeRemoteDisk(handler, { removeUnused: true, writeStateDelay: 0 })
let isResuming = await mergeRemoteDisk.isResuming(parent)
assert.ok(!isResuming, 'merge is not resuming')
await parent.init({ force: isResuming })
await child.init({ force: isResuming })
// Track merge progress
let blocksMerged = 0
const originalMergeBlock = parent.mergeBlock.bind(parent)
// Make mergeBlock fail on the second block
parent.mergeBlock = async (childDisk, index, isResumingMerge) => {
if (blocksMerged === 5) {
throw new Error('simulated interruption')
}
blocksMerged++
return originalMergeBlock(childDisk, index, isResumingMerge)
}
// First merge attempt should throw
let threw = false
try {
await mergeRemoteDisk.merge(parent, child)
} catch (err) {
threw = true
assert.equal(err.message, 'simulated interruption')
}
assert.equal(threw, true, 'merge should throw on simulated interruption')
// Verify that state file exists
assert.ok(
(await handler.list(dirname(parent.getPath()))).includes(`.${basename(parent.getPath())}.merge.json`),
'merge state file should exist after failure'
)
// Recreate new remoteDisks to simulate a new operation
const parent2 = new RemoteVhdDisk({ handler, path: `${basePath}/ancestor.vhd.alias.vhd` })
const child2 = new RemoteVhdDisk({ handler, path: `${basePath}/child.vhd.alias.vhd` })
isResuming = await mergeRemoteDisk.isResuming(parent)
assert.ok(isResuming, 'merge is resuming')
await parent2.init({ force: isResuming })
await child2.init({ force: isResuming })
// Resume merge
const result = await mergeRemoteDisk.merge(parent2, child2)
assert.equal(result.finalSizeOnDisk, undefined)
const resultingDisk = new RemoteVhdDisk({ handler, path: `${basePath}/child.vhd.alias.vhd` })
await resultingDisk.init()
assert.strictEqual(await resultingDisk.readSizeOnDisk(), undefined)
})
})
/**

View File

@@ -16,7 +16,7 @@ import { RemoteDisk } from './RemoteDisk.mjs'
import { DISK_TYPES } from 'vhd-lib/_constants.js'
import { isVhdAlias, resolveVhdAlias } from 'vhd-lib/aliases.js'
import { stringify } from 'uuid'
import { dirname, join } from 'node:path'
import { dirname, join, basename } from 'node:path'
import { RemoteVhdDiskChain } from './RemoteVhdDiskChain.mjs'
import { normalize } from '@xen-orchestra/fs/path'
@@ -138,9 +138,9 @@ export class RemoteVhdDisk extends RemoteDisk {
/**
* @returns {number} size
*/
getSizeOnDisk() {
getStreamSize() {
if (this.#vhd === undefined) {
throw new Error(`can't call getVirtualSize of a RemoteVhdDisk before init`)
throw new Error(`can't call getStreamSize of a RemoteVhdDisk before init`)
}
return this.#vhd.streamSize()
@@ -322,9 +322,7 @@ export class RemoteVhdDisk extends RemoteDisk {
(await childDisk.isDirectory())
) {
try {
await this.#handler.rename(childDisk.getBlockPath(index), this.getBlockPath(index))
this.setAllocatedBlocks([index])
await /** @type {VhdDirectory} */ (this.#vhd).moveBlockFrom(index, childDisk.getBlockPath(index))
} catch (error) {
// @ts-ignore
if (error.code === 'ENOENT' && isResumingMerge === true) {
@@ -333,9 +331,6 @@ export class RemoteVhdDisk extends RemoteDisk {
// it will throw an error if block is missing in parent
// won't detect if the block was already in parent and is broken/missing in child
// since we can't know the initial size, this will create a discrepancy
// on the size
const { data } = await this.readBlock(index)
if (data.length !== this.getBlockSize()) {
throw error
@@ -395,6 +390,39 @@ export class RemoteVhdDisk extends RemoteDisk {
await this.#vhd.ensureBatSize(blockCount)
}
/**
* Write the disk size to its size.json metadata file, if it is known.
* Does nothing to a VHD file
*
* @returns {Promise<void>}
*/
async saveSizeOnDisk() {
if (this.#vhd === undefined) {
throw new Error(`can't call saveSizeOnDisk of a RemoteVhdDisk before init`)
}
if (this.#vhd instanceof VhdDirectory) {
await this.#vhd.saveSize()
}
}
/**
* Returns the space used by the data and undefined if unknown
*
* @returns {Promise<number|undefined>}
*/
async readSizeOnDisk() {
if (this.#vhd === undefined) {
throw new Error(`can't call readSizeOnDisk of a RemoteVhdDisk before init`)
}
if (this.#vhd instanceof VhdDirectory) {
return this.#vhd.readSizeOnDisk()
} else {
return this.#handler.getSizeOnDisk(await resolveVhdAlias(this.#handler, this.#path))
}
}
/**
* Writes Block Allocation Table
* @param {RemoteDisk} childDisk
@@ -487,15 +515,29 @@ export class RemoteVhdDisk extends RemoteDisk {
/**
* Rename alias/disk
*
* A plain VHD file renamed to an alias is moved to the `data` directory next to the alias, which then points to it.
* @param {string} newPath
*/
async rename(newPath) {
if (isVhdAlias(newPath)) {
const dataPath = await resolveVhdAlias(this.#handler, this.#path)
if (isVhdAlias(this.#path)) {
const dataPath = await resolveVhdAlias(this.#handler, this.#path)
await this.#handler.unlink(newPath)
await VhdAbstract.createAlias(this.#handler, newPath, dataPath)
await this.#handler.unlink(this.#path)
await this.#handler.unlink(newPath)
await VhdAbstract.createAlias(this.#handler, newPath, dataPath)
await this.#handler.unlink(this.#path)
} else {
// the file is the data itself: keep it, under `data` to be claimed by the alias
//
// if interrupted before the alias is created, the data stays in `data` without any alias, like when
// interrupted after `newPath` has been removed in the other case
const dataPath = join(dirname(newPath), 'data', basename(this.#path))
await this.#handler.rename(this.#path, dataPath)
await this.#handler.unlink(newPath)
await VhdAbstract.createAlias(this.#handler, newPath, dataPath)
}
this.#path = newPath
} else {

View File

@@ -93,7 +93,7 @@ export class RemoteVhdDiskChain extends RemoteDisk {
/**
* @returns {number} size
*/
getSizeOnDisk() {
getStreamSize() {
const batEntrySize = 4
const sectorSize = 512
const batSize = Math.ceil((this.getMaxBlockCount() * batEntrySize) / sectorSize) * sectorSize
@@ -253,6 +253,24 @@ export class RemoteVhdDiskChain extends RemoteDisk {
throw new Error(`Can't flush metadata on a disk chain`)
}
/**
* Write the disk size to its size.json metadata file, if it is known.
*
* @returns {Promise<void>}
*/
async saveSizeOnDisk() {
throw new Error(`Can't save size on disk on a disk chain`)
}
/**
* Returns the space used by the data and undefined if unknown
*
* @returns {Promise<number|undefined>}
*/
async readSizeOnDisk() {
throw new Error(`Can't get size on disk on a disk chain`)
}
/**
* @param {RemoteDisk} childDisk
* @returns {Promise<void>}

View File

@@ -5,6 +5,7 @@ import { importIncrementalVm } from './_incrementalVm.mjs'
import { liveMountXapiLabels } from './liveMountXapiLabels.mjs'
import { destroyOnAbort } from './_destroyOnAbort.mjs'
import { watchStreamSize } from './_watchStreamSize.mjs'
import { meterDisk, SourceReadTask } from './_SourceReadTask.mjs'
import { decorateClass } from '@vates/decorate-with'
import { Task } from '@vates/task'
import { createLogger } from '@xen-orchestra/log'
@@ -425,6 +426,7 @@ export class ImportVmBackup {
throw new Error('live mounting a disk is only supported when restoring an incremental backup')
}
backup = await adapter.readFullVmBackup(metadata)
sizeContainer.readTask = new SourceReadTask('read')
watchStreamSize(backup, sizeContainer)
// the restore stops once aborted (e.g. the health check of an aborted backup): a full backup is a stream that
@@ -440,6 +442,9 @@ export class ImportVmBackup {
// releases them, a successful one hands their ids back to the caller
$defer.onFailure(() => this.#releaseLiveMounts())
backup = await this._decorateIncrementalVmMetadata()
for (const key in backup.disks) {
backup.disks[key] = meterDisk(backup.disks[key], backup.vdis[key])
}
}
return Task.run(

View File

@@ -16,6 +16,7 @@ import { openVhd, VhdFile, VhdAbstract, Constants, VhdDirectory } from 'vhd-lib'
import computeGeometryForSize from 'vhd-lib/_computeGeometryForSize.js'
import { dirname, basename } from 'node:path'
import { rimraf } from 'rimraf'
import { resolveVhdAlias } from 'vhd-lib/aliases.js'
const { beforeEach, afterEach, describe } = test
@@ -23,6 +24,27 @@ let tempDir, handler, jobId, vdiId, basePath, relativePath
const vmUuid = 'a1b2c3d4-0000-0000-0000-000000000000'
const rootPath = `xo-vm-backups/${vmUuid}`
// sum of the stored size of every file under `entry`, the reference `VhdDirectory#sizeOnDisk` is checked against
async function getFullSize(handler, entry) {
let files
try {
files = await handler.list(entry, { prependDir: true })
} catch (error) {
if (error.code === 'ENOTDIR') {
return await handler.getSizeOnDisk(entry)
} else {
throw error
}
}
let size = 0
for (const file of files) {
size += await getFullSize(handler, file)
}
return size
}
beforeEach(async () => {
tempDir = await pFromCallback(cb => tmp.dir(cb))
jobId = uniqueId()
@@ -256,11 +278,20 @@ describe('RemoteAdapter#writeVhd validated by checkDisk', { concurrency: 1 }, ()
const adapter = await getAdapter({ useVhdDirectory })
const path = `${basePath}/${adapter.getVhdFileName('base')}`
const size = await adapter.writeVhd(path, new MockDisk(2, [0, 1], 0x42), {
const { size, sizeOnDisk } = await adapter.writeVhd(path, new MockDisk(2, [0, 1], 0x42), {
validator: tmpPath => checkDisk(handler, tmpPath),
uuid: uniqueIdBuffer(),
})
if (mode === 'directory') {
assert.equal(
sizeOnDisk,
(await getFullSize(handler, await resolveVhdAlias(handler, path))) + (await handler.getSizeOnDisk(path))
)
} else {
assert.equal(sizeOnDisk, await handler.getSizeOnDisk(path))
}
assert.ok(size > 0, 'reported size should be greater than 0')
assert.equal(basename(path).endsWith('.alias.vhd'), useVhdDirectory)
await Disposable.use(openVhd(handler, path), async vhd => {

View File

@@ -38,6 +38,7 @@ import { watchStreamSize } from './_watchStreamSize.mjs'
import { RemoteVhdDisk, openDiskChain, openDisposableDisk } from '@xen-orchestra/backup-archive/disks'
import { toVhdStream, writeToVhdDirectory } from 'vhd-lib/disk-consumer/index.mjs'
import { ReadAhead } from '@xen-orchestra/disk-transform'
import { getVmBackupSizeOnDisk } from './formatVmBackups.mjs'
export const DIR_XO_CONFIG_BACKUPS = 'xo-config-backups'
@@ -687,7 +688,11 @@ export class RemoteAdapter {
return path
}
// `signal` stops the write once aborted: the partial disk is then removed
/**
* `signal` stops the write once aborted: the partial disk is then removed
*
* @returns {Promise<{size: number, sizeOnDisk: number}>}
*/
async writeVhd(path, disk, { signal, validator = noop, writeBlockConcurrency, uuid, parentUuid, parentPath } = {}) {
const handler = this._handler
@@ -719,7 +724,8 @@ export class RemoteAdapter {
checksum: false,
})
await validator(path)
return size
const sizeOnDisk = await this._handler.getSizeOnDisk(path)
return { size, sizeOnDisk }
}
}
@@ -889,9 +895,11 @@ export class RemoteAdapter {
return reduce(
backups,
(prev, backup) => {
const _backup = Array.isArray(backup) ? this.#computeTotalBackupSizeRecursively(backup) : backup
const size = Array.isArray(backup)
? this.#computeTotalBackupSizeRecursively(backup).onDisk
: (getVmBackupSizeOnDisk(backup) ?? backup.size)
return {
onDisk: prev.onDisk + (_backup.onDisk ?? _backup.size),
onDisk: prev.onDisk + size,
}
},
{ onDisk: 0 }

View File

@@ -0,0 +1,125 @@
import { Task } from '@vates/task'
import { MeteredDisk } from '@xen-orchestra/disk-transform'
const SPEED_INTERVAL = 5e3
/**
* Reports the reading of a source (a disk, a XVA) in its own task, child of the current task
*
* A source is read once, even when it is consumed by multiple writers, but from the async context of the writer
* pulling the next block: the task is held here instead of relying on the current task
*
* Its lifecycle follows the source: started on the first read, ended when the source is exhausted, fails or is closed
* early. A source never read (a step failing before the transfer, a disk without blocks) leaves no task
*
* The current reading speed, in bytes per second, is reported in the `speed` property every 5 seconds: it is 0 when
* the source is stalled. The total number of bytes read is reported in the `bytesRead` property at the end, to compute
* the average speed
*
* When the number of bytes to read is known, the `progress` property (a percentage) is reported with the speed
*
* Implements `ReadMeter` from `@xen-orchestra/disk-transform`
*/
export class SourceReadTask {
#bytesRead = 0
#bytesReadSinceLastSpeed = 0
#bytesToRead
#lastProgress
#lastSpeed
#speedInterval
#task
/**
* @param {string} name of the task
*/
constructor(name) {
// created here to be a child of the current task, only started on the first read
this.#task = new Task({ properties: { name } })
}
/**
* @param {number} length number of bytes the source will produce
*/
setBytesToRead(length) {
this.#bytesToRead = length
}
/**
* @param {number} length number of bytes read
*/
onRead(length) {
if (this.#speedInterval === undefined) {
this.#task.start()
this.#reportProgress()
// on a timer instead of on read: a stalled source must report a speed of 0, not its last one
this.#speedInterval = setInterval(() => this.#reportSpeed(), SPEED_INTERVAL)
// must not keep the process alive if the source is never ended
this.#speedInterval.unref()
}
// late reads, after the end, are never reported
this.#bytesRead += length
this.#bytesReadSinceLastSpeed += length
}
#reportSpeed() {
const speed = Math.round((this.#bytesReadSinceLastSpeed * 1e3) / SPEED_INTERVAL)
this.#bytesReadSinceLastSpeed = 0
// a source stalled for a long time must not emit an event every interval
if (speed !== this.#lastSpeed) {
this.#lastSpeed = speed
this.#task.set('speed', speed)
}
this.#reportProgress()
}
/**
* @param {number} [progress] defaults to the progress of the bytes read, never 100 before the end
*/
#reportProgress(progress) {
const bytesToRead = this.#bytesToRead
if (!(bytesToRead > 0)) {
return
}
progress ??= Math.min(99, Math.floor((this.#bytesRead * 100) / bytesToRead))
if (progress !== this.#lastProgress) {
this.#lastProgress = progress
this.#task.set('progress', progress)
}
}
/**
* A source closed early is not a failure: its consumers stopped, they report their own errors
*
* @param {unknown} [error]
*/
onEnd(error) {
const task = this.#task
// never started or already ended
if (this.#speedInterval === undefined || task.status !== 'pending') {
return
}
clearInterval(this.#speedInterval)
task.set('bytesRead', this.#bytesRead)
if (error === undefined) {
// the UI shows the progress of an ended task: a success is complete, even a source producing less than expected
this.#reportProgress(100)
task.success()
} else {
task.failure(error)
}
}
}
/**
* Reports the reading of a disk of an incremental export in its own task, child of the current task
*
* The returned `MeteredDisk` only exposes the generic `Disk` interface: source specific methods (`useNbd()` for
* example) must be called before
*
* @param {import('@xen-orchestra/disk-transform').Disk} disk
* @param {{ name_label: string }} vdi
*/
export function meterDisk(disk, vdi) {
return new MeteredDisk(disk, new SourceReadTask(`read disk ${vdi.name_label}`))
}

View File

@@ -0,0 +1,300 @@
import assert from 'node:assert/strict'
import { Readable, Writable } from 'node:stream'
import { pipeline } from 'node:stream/promises'
import { describe, it, mock } from 'node:test'
import { setTimeout as delay } from 'node:timers/promises'
import { Task } from '@vates/task'
import { MeteredDisk, RandomAccessDisk, SynchronizedDisk } from '@xen-orchestra/disk-transform'
import { forkStreamUnpipe } from './_runners/_forkStreamUnpipe.mjs'
import { meterDisk, SourceReadTask } from './_SourceReadTask.mjs'
import { watchStreamSize } from './_watchStreamSize.mjs'
const BLOCK_SIZE = 1024
const NB_BLOCKS = 20
class MemoryDisk extends RandomAccessDisk {
getVirtualSize() {
return NB_BLOCKS * BLOCK_SIZE
}
getBlockSize() {
return BLOCK_SIZE
}
async init() {}
async close() {}
isDifferencing() {
return false
}
getBlockIndexes() {
return Array.from({ length: NB_BLOCKS }, (_, index) => index)
}
hasBlock() {
return true
}
async readBlock(index) {
return { index, data: Buffer.alloc(BLOCK_SIZE) }
}
}
/**
* Runs `fn` in a root task, and returns the tasks created inside, by name
*/
async function collectTasks(fn) {
const tasksById = new Map()
const root = new Task({
properties: { name: 'root' },
onProgress(event) {
if (event.type === 'start') {
const { name, ...properties } = event.properties
tasksById.set(event.id, { id: event.id, name, parentId: event.parentId, properties, progresses: [], speeds: [] })
return
}
const task = tasksById.get(event.id)
if (task === undefined) {
return
}
if (event.type === 'property') {
task.properties[event.name] = event.value
if (event.name === 'speed') {
task.speeds.push(event.value)
} else if (event.name === 'progress') {
task.progresses.push(event.value)
}
} else if (event.type === 'end') {
task.status = event.status
task.result = event.result
}
},
})
await root.run(fn).catch(() => {})
const tasksByName = {}
for (const task of tasksById.values()) {
task.isRootChild = task.parentId === root.id
tasksByName[task.name] = task
}
return tasksByName
}
// each writer consumes its fork at its own pace, in its own task
function runWriters(consumers) {
return Promise.all(Object.entries(consumers).map(([name, consume]) => Task.run({ properties: { name } }, consume)))
}
function createMeteredDisk() {
return new MeteredDisk(new MemoryDisk(), new SourceReadTask('read disk'))
}
describe('SourceReadTask', () => {
it('reports the current speed every 5 seconds', async () => {
mock.timers.enable({ apis: ['setInterval'] })
try {
const tasks = await collectTasks(async () => {
const readTask = new SourceReadTask('read')
readTask.onRead(1e3)
mock.timers.tick(2e3)
readTask.onRead(4e3)
mock.timers.tick(3e3)
readTask.onRead(10e3)
mock.timers.tick(5e3)
readTask.onEnd()
})
assert.deepEqual(tasks.read.speeds, [1e3, 2e3])
assert.equal(tasks.read.properties.bytesRead, 15e3)
assert.equal(tasks.read.status, 'success')
// the number of bytes to read is unknown (a XVA exported by XAPI)
assert.deepEqual(tasks.read.progresses, [])
} finally {
mock.timers.reset()
}
})
it('reports a speed of 0 once, when the source is stalled', async () => {
mock.timers.enable({ apis: ['setInterval'] })
try {
const tasks = await collectTasks(async () => {
const readTask = new SourceReadTask('read')
readTask.onRead(5e3)
mock.timers.tick(5e3)
// nothing read during 3 intervals
mock.timers.tick(15e3)
readTask.onRead(5e3)
mock.timers.tick(5e3)
readTask.onEnd()
})
assert.deepEqual(tasks.read.speeds, [1e3, 0, 1e3])
} finally {
mock.timers.reset()
}
})
it('stops reporting the speed once ended', async () => {
mock.timers.enable({ apis: ['setInterval'] })
try {
const tasks = await collectTasks(async () => {
const readTask = new SourceReadTask('read')
readTask.onRead(5e3)
readTask.onEnd()
mock.timers.tick(10e3)
})
assert.deepEqual(tasks.read.speeds, [])
} finally {
mock.timers.reset()
}
})
it('reports the progress with the speed, and 100 only at the end', async () => {
mock.timers.enable({ apis: ['setInterval'] })
try {
const tasks = await collectTasks(async () => {
const readTask = new SourceReadTask('read')
readTask.setBytesToRead(20e3)
readTask.onRead(5e3)
mock.timers.tick(5e3)
readTask.onRead(15e3)
mock.timers.tick(5e3)
// nothing more read: the progress does not change
mock.timers.tick(5e3)
readTask.onEnd()
})
assert.deepEqual(tasks.read.progresses, [0, 25, 99, 100])
assert.equal(tasks.read.status, 'success')
} finally {
mock.timers.reset()
}
})
it('keeps the last progress when the source fails', async () => {
mock.timers.enable({ apis: ['setInterval'] })
try {
const tasks = await collectTasks(async () => {
const readTask = new SourceReadTask('read')
readTask.setBytesToRead(10e3)
readTask.onRead(5e3)
mock.timers.tick(5e3)
readTask.onEnd(new Error('read failed'))
})
assert.deepEqual(tasks.read.progresses, [0, 50])
assert.equal(tasks.read.status, 'failure')
} finally {
mock.timers.reset()
}
})
it('reports a disk read by multiple writers only in its own task', async () => {
const tasks = await collectTasks(async () => {
const synchronizedDisk = new SynchronizedDisk(createMeteredDisk())
const forks = { backup: synchronizedDisk.fork('backup'), replication: synchronizedDisk.fork('replication') }
await runWriters({
async backup() {
for await (const block of forks.backup.diskBlocks()) {
assert.equal(block.data.length, BLOCK_SIZE)
await delay(1)
}
},
async replication() {
for await (const block of forks.replication.diskBlocks()) {
assert.equal(block.data.length, BLOCK_SIZE)
await delay(Math.random() * 3)
}
},
})
})
const readTask = tasks['read disk']
assert.equal(readTask.isRootChild, true)
assert.equal(readTask.status, 'success')
assert.equal(readTask.properties.progress, 100)
assert.deepEqual(tasks.backup.properties, {})
assert.deepEqual(tasks.replication.properties, {})
})
it('reports a forked stream only in its own task', async () => {
const chunks = Array.from({ length: NB_BLOCKS }, () => Buffer.alloc(BLOCK_SIZE))
const tasks = await collectTasks(async () => {
const stream = Readable.from(chunks)
// set by the remote handler on the stream of a backup file
stream.length = NB_BLOCKS * BLOCK_SIZE
watchStreamSize(stream, { size: 0, readTask: new SourceReadTask('read') })
const forks = [forkStreamUnpipe(stream), forkStreamUnpipe(stream)]
const sink = () =>
new Writable({
write(_chunk, _encoding, callback) {
setTimeout(callback, 1)
},
})
await runWriters({
remote: () => pipeline(forks[0], sink()),
sr: () => pipeline(forks[1], sink()),
})
})
assert.equal(tasks.read.isRootChild, true)
assert.equal(tasks.read.status, 'success')
assert.equal(tasks.read.properties.progress, 100)
assert.deepEqual(tasks.remote.properties, {})
assert.deepEqual(tasks.sr.properties, {})
})
it('leaves no task when the source is never read', async () => {
const tasks = await collectTasks(async () => {
createMeteredDisk()
})
assert.deepEqual(Object.keys(tasks), ['root'])
})
it('succeeds when its consumers stop early', async () => {
const tasks = await collectTasks(async () => {
let nbRead = 0
for await (const block of createMeteredDisk().diskBlocks()) {
assert.equal(block.data.length, BLOCK_SIZE)
if (++nbRead === 5) {
break
}
}
})
assert.equal(tasks['read disk'].status, 'success')
})
it('fails when the source fails', async () => {
const tasks = await collectTasks(async () => {
const disk = new MemoryDisk()
disk.readBlock = async index => {
if (index === 2) {
throw new Error('NBD connection lost')
}
return { index, data: Buffer.alloc(BLOCK_SIZE) }
}
const meteredDisk = new MeteredDisk(disk, new SourceReadTask('read disk'))
await assert.rejects(async () => {
for await (const block of meteredDisk.diskBlocks()) {
assert.equal(block.data.length, BLOCK_SIZE)
}
})
})
assert.equal(tasks['read disk'].status, 'failure')
assert.equal(tasks['read disk'].properties.bytesRead, 2 * BLOCK_SIZE)
assert.equal(tasks['read disk'].result.message, 'NBD connection lost')
})
it('names the task of a disk after its VDI', async () => {
const tasks = await collectTasks(async () => {
const disk = meterDisk(new MemoryDisk(), { name_label: 'system' })
for await (const block of disk.diskBlocks()) {
assert.equal(block.data.length, BLOCK_SIZE)
}
})
assert.equal(tasks['read disk system'].isRootChild, true)
assert.equal(tasks['read disk system'].status, 'success')
})
})

View File

@@ -38,7 +38,7 @@ const BACKUP_JOURNAL_EVENTS = /** @type {const} */ (['add', 'change', 'del'])
* - `retention`: it was rotated out by a retention setting
* - `user`: a user explicitly deleted it
* - `clean-vm`: `cleanVm()` removed it, e.g. the metadata of an incomplete backup
* - `merge`: `cleanVm()` rewrote its size after merging its disks
* - `merge`: `cleanVm()` rewrote it after merging its disks, to record their new size on disk
*
* @typedef {'backup'|'retention'|'user'|'clean-vm'|'merge'} BackupJournalReason
*/

View File

@@ -8,7 +8,8 @@ import { getHandler } from '@xen-orchestra/fs'
import { pFromCallback } from 'promise-toolbox'
import { RemoteAdapter } from './RemoteAdapter.mjs'
import { VHDFOOTER, VHDHEADER } from './tests.fixtures.mjs'
import { VhdFile, Constants, VhdDirectory, VhdAbstract } from 'vhd-lib'
import { VhdFile, Constants, VhdDirectory, VhdAbstract, openVhd } from 'vhd-lib'
import Disposable from 'promise-toolbox/Disposable'
import { dirname, basename } from 'node:path'
import { rimraf } from 'rimraf'
@@ -34,6 +35,14 @@ afterEach(async () => {
await handler.forget()
})
// stream size of a disk, its block allocation table included
async function getDiskStreamSize(diskPath) {
return Disposable.use(openVhd(handler, diskPath), async vhd => {
await vhd.readBlockAllocationTable()
return vhd.streamSize()
})
}
const uniqueId = () => uuid.v1()
const uniqueIdBuffer = () => uuid.v1({}, Buffer.alloc(16))
@@ -198,7 +207,7 @@ test('it merges delta of non destroyed chain', async () => {
`${rootPath}/metadata.json`,
JSON.stringify({
mode: 'delta',
size: 12000, // a size too small
size: 12000,
vhds: [
`${relativePath}/grandchild.vhd`, // grand child should not be merged
`${relativePath}/child.vhd`,
@@ -239,7 +248,7 @@ test('it merges delta of non destroyed chain', async () => {
const metadata = JSON.parse(await handler.readFile(`${rootPath}/metadata.json`))
// size should be the size of children + grand children after the merge
assert.equal(metadata.size, 4299776)
assert.equal(metadata.size, 12000)
// merging is already tested in vhd-lib, don't retest it here (and theses vhd are as empty as my stomach at 12h12)
// only check deletion
@@ -453,8 +462,15 @@ describe('tests multiple combination ', { concurrency: 1 }, () => {
await adapter.cleanVm(rootPath, { remove: true, merge: true, logWarn: () => {}, lock: false })
const metadata = JSON.parse(await handler.readFile(`${rootPath}/metadata.json`))
// size is the sum of the merged chains' final on-disk sizes:
assert.deepEqual(metadata.size, 6501888)
// merges record the size on disk of the disks they merged into, child and clean.
// Directory disks without `size.json` stay unknown, so size falls back to their stream size
assert.equal(
metadata.size,
vhdMode === 'directory'
? (await getDiskStreamSize(`${basePath}/child.vhd.alias.vhd`)) +
(await getDiskStreamSize(`${basePath}/clean.vhd.alias.vhd`))
: undefined
)
// broken vhd, non referenced, abandoned should be deleted ( alias and data)
// ancestor and child should be merged

View File

@@ -5,6 +5,7 @@ import { FullRemoteWriter } from '../_writers/FullRemoteWriter.mjs'
import { forkStreamUnpipe } from '../_forkStreamUnpipe.mjs'
import { destroyOnAbort } from '../../_destroyOnAbort.mjs'
import { watchStreamSize } from '../../_watchStreamSize.mjs'
import { SourceReadTask } from '../../_SourceReadTask.mjs'
import { AggregatedFullRemoteWriter } from '../_writers/AggregatedFullRemoteWriter.mjs'
import { Task } from '@vates/task'
@@ -26,7 +27,8 @@ export const FullRemote = class FullRemoteVmBackupRunner extends AbstractRemote
for (const metadata of transferList) {
Task.abortSignal?.throwIfAborted()
const stream = this._throttleStream(await this._sourceRemoteAdapter.readFullVmBackup(metadata))
const sizeContainer = watchStreamSize(stream)
// the backup is read once, whatever the number of writers
const sizeContainer = watchStreamSize(stream, { size: 0, readTask: new SourceReadTask('read') })
let checksum
try {
// the unencrypted destinations store the same data as the source: no need to compute their checksum again

View File

@@ -5,6 +5,7 @@ import { forkStreamUnpipe } from '../_forkStreamUnpipe.mjs'
import { FullRemoteWriter } from '../_writers/FullRemoteWriter.mjs'
import { FullXapiWriter } from '../_writers/FullXapiWriter.mjs'
import { watchStreamSize } from '../../_watchStreamSize.mjs'
import { SourceReadTask } from '../../_SourceReadTask.mjs'
import { AbstractXapi } from './_AbstractXapi.mjs'
import { AggregatedFullRemoteWriter } from '../_writers/AggregatedFullRemoteWriter.mjs'
import { AggregatedFullXapiWriter } from '../_writers/AggregatedFullXapiWriter.mjs'
@@ -81,7 +82,8 @@ export const FullXapi = class FullXapiVmBackupRunner extends AbstractXapi {
maxStreamLength += XVA_BLOCK_SIZE * nbBlocks + headersSize
}
const sizeContainer = watchStreamSize(stream)
// the export is read once, whatever the number of writers
const sizeContainer = watchStreamSize(stream, { size: 0, readTask: new SourceReadTask('read') })
const transferStart = Date.now()
await this._callWriters(

View File

@@ -13,6 +13,7 @@ import { SynchronizedDisk, ThrottledDisk } from '@xen-orchestra/disk-transform'
import { AggregatedIncrementalRemoteWriter } from '../_writers/AggregatedIncrementalRemoteWriter.mjs'
import { Task } from '@vates/task'
import { TaskProgressHandler } from './_TaskProgressHandler.mjs'
import { meterDisk } from '../../_SourceReadTask.mjs'
const { warn } = createLogger('xo:backups:Incrementalremote')
class IncrementalRemoteVmBackupRunner extends AbstractRemote {
@@ -101,6 +102,8 @@ class IncrementalRemoteVmBackupRunner extends AbstractRemote {
let disk = incrementalExport.disks[key]
isVhdDifferencing[key] = disk.isDifferencing()
disk.addProgressHandler(new TaskProgressHandler())
// each disk is read once, whatever the number of writers
disk = meterDisk(disk, incrementalExport.vdis[key])
disk = new ThrottledDisk(disk, this._throttleGenerator)
incrementalExport.disks[key] = new SynchronizedDisk(disk)
}

View File

@@ -20,6 +20,7 @@ import { AggregatedIncrementalXapiWriter } from '../_writers/AggregatedIncrement
import { TaskProgressHandler } from './_TaskProgressHandler.mjs'
import { compileExpression, isExpression } from '../../_expressionPredicate.mjs'
import { buildVmContext } from '../../_buildContext.mjs'
import { meterDisk } from '../../_SourceReadTask.mjs'
const { debug } = createLogger('xo:backups:IncrementalXapiVmBackup')
@@ -69,6 +70,8 @@ export const IncrementalXapi = class IncrementalXapiVmBackupRunner extends Abstr
Task.warning('Backup fell back to a full')
}
useNbd = useNbd || disk.useNbd()
// each disk is read once, whatever the number of writers
disk = meterDisk(disk, deltaExport.vdis[key])
disk = new ThrottledDisk(disk, this._throttleGenerator)
deltaExport.disks[key] = new SynchronizedDisk(disk)
}

View File

@@ -69,6 +69,7 @@ export class FullRemoteWriter extends MixinRemoteWriter(AbstractFullWriter) {
await deleteOldBackups()
}
let sizeOnDisk = 0
await Task.run({ properties: { name: 'transfer' } }, async () => {
await adapter.outputStream(dataFilename, stream, {
checksum,
@@ -76,9 +77,20 @@ export class FullRemoteWriter extends MixinRemoteWriter(AbstractFullWriter) {
streamLength,
validator: tmpPath => adapter.isValidXva(tmpPath),
})
sizeOnDisk = await adapter.handler.getSizeOnDisk(dataFilename)
try {
const size = await adapter.handler.getSizeOnDisk(`${dataFilename}.checksum`)
sizeOnDisk += size
} catch (error) {
if (error.code !== 'ENOENT') {
throw error
}
}
return { size: sizeContainer.size }
})
metadata.size = sizeContainer.size
metadata.sizeOnDisk = sizeOnDisk
metadata.tags = await this.getLongTermRetentionTags(metadata)
this._metadataFileName = await adapter.writeVmBackupMetadata(vm.uuid, metadata)

View File

@@ -280,6 +280,7 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
vtpms: deltaExport.vtpms,
}
let size = 0
const vhdsSizeOnDisk = {}
await Task.run({ properties: { name: 'transfer' } }, async () => {
// stops the writes once the backup is aborted
const signal = Task.abortSignal
@@ -299,7 +300,7 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
parentPath = relativeFromFile(path, parentDestPath)
}
const transferred = await adapter.writeVhd(path, disk, {
const { size: transferred, sizeOnDisk } = await adapter.writeVhd(path, disk, {
// no checksum for VHDs, because they will be invalidated by
// merges and chains
checksum: false,
@@ -311,6 +312,7 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
parentPath,
})
size += transferred
vhdsSizeOnDisk[diskRef] = sizeOnDisk
},
{
concurrency: settings.diskPerVmConcurrency,
@@ -326,6 +328,7 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
metadataContent.tags = await this.getLongTermRetentionTags(metadataContent)
metadataContent.size = size // @todo return exactly the size written by this writer
metadataContent.vhdsSizeOnDisk = vhdsSizeOnDisk
this._metadataFileName = await adapter.writeVmBackupMetadata(vm.uuid, metadataContent)
// TODO: run cleanup?

View File

@@ -1,17 +1,34 @@
import { TaskProgressHandler } from './_runners/_vmRunners/_TaskProgressHandler.mjs'
/**
* @param {import('node:stream').Readable} stream
* @param {{ size: number, progressHandler?: TaskProgressHandler, readTask?: import('./_SourceReadTask.mjs').SourceReadTask }} [container]
* `readTask`: reports the reading of the stream in its own task
*/
export function watchStreamSize(stream, container = { size: 0 }) {
const progressHandler = container.progressHandler ?? new TaskProgressHandler()
const { progressHandler = new TaskProgressHandler(), readTask } = container
stream.on('data', data => {
container.size += data.length
if (stream.length) {
// empty for xva exported by xapi
progressHandler.setProgress(container.size / stream.length)
}
readTask?.onRead(data.length)
})
stream.on('finish', () => {
progressHandler.setProgress(1)
})
if (readTask !== undefined) {
// unknown for a XVA exported by XAPI or read from an encrypted remote: no progress then
if (stream.length > 0) {
readTask.setBytesToRead(stream.length)
}
// no-op once the read task has ended
stream.on('error', error => readTask.onEnd(error))
stream.on('close', () => readTask.onEnd())
}
stream.pause()
return container
}

View File

@@ -29,7 +29,17 @@ import { normalize } from '@xen-orchestra/fs/path'
*/
/**
* @returns {import('@vates/types').XoVmBackupArchive & { tags: string[] }}
* The fields of the metadata of a backup which tell the space it uses on the repository
*
* @typedef {object} BackupSizeMetadata
* @property {'full' | 'delta'} mode
* @property {number} [sizeOnDisk] full backup: size of the XVA, `.checksum` included
* @property {Record<string, string>} [vhds] delta backup: path of each disk, by VDI ref
* @property {Record<string, number>} [vhdsSizeOnDisk] delta backup: size of each disk, by VDI ref
*/
/**
* @returns {import('@vates/types').XoVmBackupArchive}
*/
export function formatVmBackup(backup) {
const { isVhdDifferencing, vmSnapshot } = backup
@@ -59,6 +69,8 @@ export function formatVmBackup(backup) {
id: `${dirname(backup._filename)}/${backup.vhds[vdiId]}`,
name: vdi.name_label,
uuid: vdi.uuid,
sizeOnDisk: backup.vhdsSizeOnDisk?.[vdiId],
isDifferencing: backup.isVhdDifferencing?.[vdiId],
}
}),
@@ -68,6 +80,7 @@ export function formatVmBackup(backup) {
mode: backup.mode,
scheduleId: backup.scheduleId,
size: backup.size,
sizeOnDisk: getVmBackupSizeOnDisk(backup),
timestamp: backup.timestamp,
vm: {
uuid: backup.vm.uuid,
@@ -131,3 +144,30 @@ export function formatJournalEvents(events, backupRepositoryId) {
return { event, vmUuid, filename, backup: formatVmBackupAt(metadata, filename, backupRepositoryId) }
})
}
/**
* Returns the space used on the repository or undefined if unknown or if a single disk is unknown
*
* @param {BackupSizeMetadata} metadata
* @returns {number | undefined}
*/
export function getVmBackupSizeOnDisk(metadata) {
if (metadata.mode === 'full') {
return metadata.sizeOnDisk
} else if (metadata.mode === 'delta' && metadata.vhds !== undefined) {
const vhdSizes = Object.keys(metadata.vhds).map(vdiRef => metadata.vhdsSizeOnDisk?.[vdiRef])
let sizeOnDisk = 0
for (const vhdSize of vhdSizes) {
if (vhdSize === undefined) {
return undefined
}
sizeOnDisk += vhdSize
}
return sizeOnDisk
}
return undefined
}

View File

@@ -54,7 +54,13 @@ describe('formatVmBackupAt()', () => {
for (const filename of [FILENAME, FILENAME.slice(1)]) {
assert.deepEqual(formatVmBackupAt(metadata, filename, REPOSITORY).disks, [
{ id: `/xo-vm-backups/${VM}/vdi.vhd`, name: 'a disk', uuid: 'a-vdi-uuid' },
{
id: `/xo-vm-backups/${VM}/vdi.vhd`,
isDifferencing: undefined,
name: 'a disk',
uuid: 'a-vdi-uuid',
sizeOnDisk: undefined,
},
])
}
})
@@ -99,6 +105,87 @@ describe('formatVmBackups()', () => {
})
})
describe('size on disk', () => {
const sizeOnDiskOf = metadata => {
const { disks, sizeOnDisk } = formatVmBackupAt(metadata, FILENAME, REPOSITORY)
return {
// keyed by uuid: the order of the disks follows the one of `vhds`
disks: Object.fromEntries(disks.map(disk => [disk.uuid, disk.sizeOnDisk])),
sizeOnDisk,
}
}
it('is the sum of the disks of a delta backup', () => {
const { disks, sizeOnDisk } = sizeOnDiskOf({
...metadata,
vhdsSizeOnDisk: { 'OpaqueRef:2f7a': 10, 'OpaqueRef:9c1b': 20 },
})
assert.deepEqual(disks, { 'snapshot-vdi-uuid-1': 10, 'snapshot-vdi-uuid-2': 20 })
assert.equal(sizeOnDisk, 30)
})
// a partial sum would look exact while missing disks
it('is unknown for a delta backup if the size of one of its disks is unknown', () => {
const { disks, sizeOnDisk } = sizeOnDiskOf({ ...metadata, vhdsSizeOnDisk: { 'OpaqueRef:2f7a': 10 } })
assert.deepEqual(disks, { 'snapshot-vdi-uuid-1': 10, 'snapshot-vdi-uuid-2': undefined })
assert.equal(sizeOnDisk, undefined)
})
it('is unknown for a delta backup written before it was recorded', () => {
const { disks, sizeOnDisk } = sizeOnDiskOf(metadata)
assert.deepEqual(disks, { 'snapshot-vdi-uuid-1': undefined, 'snapshot-vdi-uuid-2': undefined })
assert.equal(sizeOnDisk, undefined)
})
// a broken backup: its size is not known, and certainly not 0
it('is unknown for a delta backup without disks', () => {
assert.equal(sizeOnDiskOf({ ...metadata, vhds: undefined, vhdsSizeOnDisk: {} }).sizeOnDisk, undefined)
})
it('is the size of the XVA of a full backup', () => {
const { disks, sizeOnDisk } = sizeOnDiskOf(metadataOf({ sizeOnDisk: 42 }))
assert.deepEqual(disks, {})
assert.equal(sizeOnDisk, 42)
})
it('is unknown for a full backup written before it was recorded', () => {
assert.equal(sizeOnDiskOf(metadataOf()).sizeOnDisk, undefined)
})
it('is not the transferred size', () => {
const formatted = formatVmBackupAt(metadataOf({ size: 100, sizeOnDisk: 42 }), FILENAME, REPOSITORY)
assert.equal(formatted.size, 100)
assert.equal(formatted.sizeOnDisk, 42)
})
})
describe('is differencing', () => {
const isVhdDifferencingOf = metadata => {
const { disks } = formatVmBackupAt(metadata, FILENAME, REPOSITORY)
return Object.fromEntries(disks.map(disk => [disk.uuid, disk.isDifferencing]))
}
it('forwards isVhdDifferencing', () => {
const disks = isVhdDifferencingOf({
...metadata,
isVhdDifferencing: { 'OpaqueRef:2f7a': true, 'OpaqueRef:9c1b': false },
})
assert.deepEqual(disks, { 'snapshot-vdi-uuid-1': true, 'snapshot-vdi-uuid-2': false })
})
it('handles missing isVhdDifferencing', () => {
const disks = isVhdDifferencingOf(metadata)
assert.deepEqual(disks, { 'snapshot-vdi-uuid-1': undefined, 'snapshot-vdi-uuid-2': undefined })
})
})
describe('formatJournalEvents()', () => {
it('resolves the backup of the events which carry a metadata', () => {
const metadata = metadataOf()

View File

@@ -3,8 +3,8 @@ $ xo-disk-cli --help
Usage: xo-disk-cli <command> <handler-url> <path> [options]
Commands:
info Show disk info (virtual size, uid, parent uid, block size); --chain shows the full parent chain, --size adds the size on disk
list List all disks at a path and display their properties in a table; --size adds the size on disk
info Show disk info (virtual size, uid, parent uid, block size); --chain shows the full parent chain, --size adds the stream size
list List all disks at a path and display their properties in a table; --size adds the stream size
transform Convert a disk to another format and write to stdout (raw | vhd | qcow2)
```
@@ -30,8 +30,8 @@ Disk info: /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/snapshot.vhd
```
By default the disk is opened without reading its block allocation table, which
is cheap but does not allow computing the size on disk. Pass `--size` to read
the block allocation table and print the size on disk as an extra line:
is cheap but does not allow computing the stream size. Pass `--size` to read
the block allocation table and print the stream size as an extra line:
```
$ xo-disk-cli info file:///mnt/backups /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/snapshot.vhd --size
@@ -40,7 +40,7 @@ Disk info: /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/snapshot.vhd
Parent UID: <parent-uuid>
Virtual size: 8.00 GiB (8589934592 bytes)
Block size: 2.00 MiB (2097152 bytes)
Size on disk: 128.00 MiB (134217728 bytes)
Stream size: 128.00 MiB (134217728 bytes)
```
With `--chain`, the disk's full parent chain is opened and each disk is printed
@@ -73,7 +73,7 @@ xo-disk-cli list <handler-url> <dir-path> [--size]
```
By default disks are opened without reading their block allocation table (cheap),
so the "Size on disk" column is omitted:
so the "Stream size" column is omitted:
```
$ xo-disk-cli list file:///mnt/backups /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/
@@ -85,12 +85,12 @@ $ xo-disk-cli list file:///mnt/backups /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/
└──────────────┴──────────────────────────────────────┴──────────────┴─────────────┴──────────────────────────────────────┘
```
Pass `--size` to read each disk's block allocation table and add the "Size on disk" column:
Pass `--size` to read each disk's block allocation table and add the "Stream size" column:
```
$ xo-disk-cli list file:///mnt/backups /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/ --size
┌──────────────┬──────────────────────────────────────┬─────────────┬──────────────┬─────────────┬──────────────────────────────────────┐
│ File │ UID │ Size on disk│ Virtual size │ Differencing │ Parent UID │
│ File │ UID │ Stream size │ Virtual size │ Differencing │ Parent UID │
├──────────────┼──────────────────────────────────────┼─────────────┼──────────────┼─────────────┼──────────────────────────────────────┤
│ base.vhd │ xxxxxxxx-... │ 1.20 GiB │ 8.00 GiB │ no │ (none) │
│ snapshot.vhd │ yyyyyyyy-... │ 128.00 MiB │ 8.00 GiB │ yes │ ↑ │

View File

@@ -21,8 +21,8 @@ $ xo-disk-cli --help
Usage: xo-disk-cli <command> <handler-url> <path> [options]
Commands:
info Show disk info (virtual size, uid, parent uid, block size); --chain shows the full parent chain, --size adds the size on disk
list List all disks at a path and display their properties in a table; --size adds the size on disk
info Show disk info (virtual size, uid, parent uid, block size); --chain shows the full parent chain, --size adds the stream size
list List all disks at a path and display their properties in a table; --size adds the stream size
transform Convert a disk to another format and write to stdout (raw | vhd | qcow2)
```
@@ -48,8 +48,8 @@ Disk info: /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/snapshot.vhd
```
By default the disk is opened without reading its block allocation table, which
is cheap but does not allow computing the size on disk. Pass `--size` to read
the block allocation table and print the size on disk as an extra line:
is cheap but does not allow computing the stream size. Pass `--size` to read
the block allocation table and print the stream size as an extra line:
```
$ xo-disk-cli info file:///mnt/backups /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/snapshot.vhd --size
@@ -58,7 +58,7 @@ Disk info: /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/snapshot.vhd
Parent UID: <parent-uuid>
Virtual size: 8.00 GiB (8589934592 bytes)
Block size: 2.00 MiB (2097152 bytes)
Size on disk: 128.00 MiB (134217728 bytes)
Stream size: 128.00 MiB (134217728 bytes)
```
With `--chain`, the disk's full parent chain is opened and each disk is printed
@@ -91,7 +91,7 @@ xo-disk-cli list <handler-url> <dir-path> [--size]
```
By default disks are opened without reading their block allocation table (cheap),
so the "Size on disk" column is omitted:
so the "Stream size" column is omitted:
```
$ xo-disk-cli list file:///mnt/backups /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/
@@ -103,12 +103,12 @@ $ xo-disk-cli list file:///mnt/backups /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/
└──────────────┴──────────────────────────────────────┴──────────────┴─────────────┴──────────────────────────────────────┘
```
Pass `--size` to read each disk's block allocation table and add the "Size on disk" column:
Pass `--size` to read each disk's block allocation table and add the "Stream size" column:
```
$ xo-disk-cli list file:///mnt/backups /xo-vm-backups/<vm-uuid>/vdis/<vdi-uuid>/ --size
┌──────────────┬──────────────────────────────────────┬─────────────┬──────────────┬─────────────┬──────────────────────────────────────┐
│ File │ UID │ Size on disk│ Virtual size │ Differencing │ Parent UID │
│ File │ UID │ Stream size │ Virtual size │ Differencing │ Parent UID │
├──────────────┼──────────────────────────────────────┼─────────────┼──────────────┼─────────────┼──────────────────────────────────────┤
│ base.vhd │ xxxxxxxx-... │ 1.20 GiB │ 8.00 GiB │ no │ (none) │
│ snapshot.vhd │ yyyyyyyy-... │ 128.00 MiB │ 8.00 GiB │ yes │ ↑ │

View File

@@ -10,7 +10,7 @@ type DiskInfoLine = {
virtualSize: number
blockSize: number
// Only computed with --size; requires reading the block allocation table.
sizeOnDisk?: number
streamSize?: number
}
function readDiskInfo(disk: RemoteDisk, path: string, showSize: boolean): DiskInfoLine {
@@ -21,7 +21,7 @@ function readDiskInfo(disk: RemoteDisk, path: string, showSize: boolean): DiskIn
parentUid: isDifferencing ? disk.getParentUuid() : null,
virtualSize: disk.getVirtualSize(),
blockSize: disk.getBlockSize(),
sizeOnDisk: showSize ? disk.getSizeOnDisk() : undefined,
streamSize: showSize ? disk.getStreamSize() : undefined,
}
}
@@ -31,8 +31,8 @@ function printDiskInfo(info: DiskInfoLine): void {
console.log(` Parent UID: ${info.parentUid ?? '(none)'}`)
console.log(` Virtual size: ${formatBytes(info.virtualSize)} (${info.virtualSize} bytes)`)
console.log(` Block size: ${formatBytes(info.blockSize)} (${info.blockSize} bytes)`)
if (info.sizeOnDisk !== undefined) {
console.log(` Size on disk: ${formatBytes(info.sizeOnDisk)} (${info.sizeOnDisk} bytes)`)
if (info.streamSize !== undefined) {
console.log(` Stream size: ${formatBytes(info.streamSize)} (${info.streamSize} bytes)`)
}
}

View File

@@ -4,17 +4,17 @@ import { isDisk, openDisposableDisk, RemoteDisk } from '@xen-orchestra/backup-ar
import { formatBytes, renderTable } from '../utils.mjs'
import { asyncEach } from '@vates/async-each'
// The "Size on disk" column is only shown with --size: computing it requires
// The "Stream size" column is only shown with --size: computing it requires
// reading the block allocation table of every disk, which is costly.
function buildHeaders(showSize: boolean): string[] {
return ['File', 'UID', ...(showSize ? ['Size on disk'] : []), 'Virtual size', 'Differencing', 'Parent UID']
return ['File', 'UID', ...(showSize ? ['Stream size'] : []), 'Virtual size', 'Differencing', 'Parent UID']
}
export type OkDiskInfo = {
ok: true
filename: string
uid: string
sizeOnDisk?: string
streamSize?: string
virtualSize: string
differencing: boolean
parentUid: string | null
@@ -70,7 +70,7 @@ export function toTableRow(disk: DiskInfo, prevDisk: DiskInfo | undefined, showS
return [
disk.filename,
disk.uid,
...(showSize ? [disk.sizeOnDisk ?? '-'] : []),
...(showSize ? [disk.streamSize ?? '-'] : []),
disk.virtualSize,
disk.differencing ? 'yes' : 'no',
disk.differencing ? (parentIsAbove ? '↑' : (disk.parentUid ?? '')) : '(none)',
@@ -103,7 +103,7 @@ export async function listCommand(handlerUrl: string, dirPath: string, extraArgs
ok: true as const,
filename,
uid: disk.getUuid(),
sizeOnDisk: showSize ? formatBytes(disk.getSizeOnDisk()) : undefined,
streamSize: showSize ? formatBytes(disk.getStreamSize()) : undefined,
virtualSize: formatBytes(disk.getVirtualSize()),
differencing,
parentUid: differencing ? disk.getParentUuid() : null,

View File

@@ -51,7 +51,7 @@ declare module '@xen-orchestra/backup-archive/disks' {
import type { RandomAccessDisk } from '@xen-orchestra/disk-transform'
export interface RemoteDisk extends RandomAccessDisk {
getSizeOnDisk(): number
getStreamSize(): number
getPath(): string
getPaths(): string[]
getUuid(): string

View File

@@ -14,8 +14,8 @@ const COMMANDS: Record<string, CommandFn> = {
function showHelp(exitCode: number): never {
const commandDescriptions: Record<string, string> = {
info: 'Show disk info (virtual size, uid, parent uid, block size); --chain shows the full parent chain, --size adds the size on disk',
list: 'List all disks at a path and display their properties in a table; --size adds the size on disk',
info: 'Show disk info (virtual size, uid, parent uid, block size); --chain shows the full parent chain, --size adds the stream size',
list: 'List all disks at a path and display their properties in a table; --size adds the stream size',
transform: 'Convert a disk to another format and write to stdout (raw | vhd | qcow2)',
}

View File

@@ -5,7 +5,7 @@
* - Handler and disk are always disposed, even when disk methods throw.
* - Errors from broken disks are propagated (not swallowed).
* - By default disks are opened with ignoreBlockIndexes: true (cheap); --size
* opens with ignoreBlockIndexes: false and prints the size on disk.
* opens with ignoreBlockIndexes: false and prints the stream size.
* - --chain opens the whole lineage and prints each disk.
*
* Design: mock.module() is called once at the top level. The mocks read mutable
@@ -27,7 +27,7 @@ const baseDisk = {
isDifferencing: () => false,
getVirtualSize: () => 1024 * 1024 * 1024,
getBlockSize: () => 2 * 1024 * 1024,
getSizeOnDisk: () => 128 * 1024 * 1024,
getStreamSize: () => 128 * 1024 * 1024,
getUuid: () => 'aaaa-bbbb',
getParentUuid: () => 'pppp-qqqq',
}
@@ -128,17 +128,17 @@ describe('info command', () => {
await assert.rejects(() => infoCommand('file:///test', '/vdis/disk.vhd', []), /corrupt header/)
})
test('by default opens the disk with ignoreBlockIndexes: true and hides size on disk', async () => {
test('by default opens the disk with ignoreBlockIndexes: true and hides stream size', async () => {
const output = await captureLog(() => infoCommand('file:///test', '/vdis/disk.vhd', []))
assert.strictEqual(openDiskParams.length, 1)
assert.strictEqual(openDiskParams[0].ignoreBlockIndexes, true, 'block indexes must be skipped by default')
assert.ok(!output.includes('Size on disk'), 'size on disk must not be printed without --size')
assert.ok(!output.includes('Stream size'), 'stream size must not be printed without --size')
})
test('--size opens the disk with ignoreBlockIndexes: false and prints size on disk', async () => {
test('--size opens the disk with ignoreBlockIndexes: false and prints stream size', async () => {
const output = await captureLog(() => infoCommand('file:///test', '/vdis/disk.vhd', ['--size']))
assert.strictEqual(openDiskParams[0].ignoreBlockIndexes, false, 'block indexes must be read with --size')
assert.ok(output.includes('Size on disk'), 'size on disk must be printed with --size')
assert.ok(output.includes('Stream size'), 'stream size must be printed with --size')
})
test('without --chain, openDiskChain is never called', async () => {
@@ -164,15 +164,15 @@ describe('info command', () => {
)
})
test('--chain --size reads block indexes and prints size on disk for each disk', async () => {
test('--chain --size reads block indexes and prints stream size for each disk', async () => {
const output = await captureLog(() => infoCommand('file:///test', '/vdis/leaf.vhd', ['--chain', '--size']))
assert.strictEqual(openChainParams[0].ignoreBlockIndexes, false, 'chain walk must read block indexes with --size')
assert.ok(
openDiskParams.every(p => p.ignoreBlockIndexes === false),
'each chain disk must be opened with ignoreBlockIndexes: false'
)
const sizeLines = output.split('\n').filter(l => l.includes('Size on disk'))
assert.strictEqual(sizeLines.length, chainPaths.length, 'size on disk must be printed for each disk')
const sizeLines = output.split('\n').filter(l => l.includes('Stream size'))
assert.strictEqual(sizeLines.length, chainPaths.length, 'stream size must be printed for each disk')
})
test('--chain: chain is closed even when opening a disk in it throws', async () => {

View File

@@ -21,7 +21,7 @@ const diskDispose = mock.fn(() => Promise.resolve())
const baseDisk = {
isDifferencing: () => false,
getSizeOnDisk: () => 1024 * 1024 * 1024,
getStreamSize: () => 1024 * 1024 * 1024,
getVirtualSize: () => 8 * 1024 * 1024 * 1024,
getUuid: () => 'disk-uuid',
getParentUuid: () => null as unknown as string,
@@ -134,7 +134,7 @@ describe('list command', () => {
openDiskParams.every(p => p.ignoreBlockIndexes === true),
'disks must be opened with ignoreBlockIndexes: true by default'
)
assert.ok(!output.includes('Size on disk'), 'the size column must be hidden without --size')
assert.ok(!output.includes('Stream size'), 'the size column must be hidden without --size')
})
test('--size opens disks with ignoreBlockIndexes: false and shows the size column', async () => {
@@ -143,6 +143,6 @@ describe('list command', () => {
openDiskParams.every(p => p.ignoreBlockIndexes === false),
'disks must be opened with ignoreBlockIndexes: false with --size'
)
assert.ok(output.includes('Size on disk'), 'the size column must appear with --size')
assert.ok(output.includes('Stream size'), 'the size column must appear with --size')
})
})

View File

@@ -2,7 +2,7 @@ import { describe, test } from 'node:test'
import assert from 'node:assert/strict'
import { sortDisks, toTableRow, type DiskInfo } from '../commands/list.mjs'
// These tests assert on the full-width row (with the "Size on disk" column), so
// These tests assert on the full-width row (with the "Stream size" column), so
// they always exercise toTableRow with showSize = true.
const toTableRowWithSize = (disk: DiskInfo, prevDisk: DiskInfo | undefined) => toTableRow(disk, prevDisk, true)
@@ -15,7 +15,7 @@ function ok(uid: string, parentUid: string | null = null): DiskInfo & { ok: true
ok: true,
filename: `${uid}.vhd`,
uid,
sizeOnDisk: '1.00 GiB',
streamSize: '1.00 GiB',
virtualSize: '8.00 GiB',
differencing: parentUid !== null,
parentUid,

View File

@@ -0,0 +1,48 @@
import { Disk, DiskBlock } from './Disk.mjs'
import { DiskPassthrough } from './DiskPassthrough.mjs'
export type ReadMeter = {
/** called once, before the first read, with the number of bytes the source will produce */
setBytesToRead(length: number): void
/** called for each block read from the source */
onRead(length: number): void
/** called once, when the source is exhausted, closed early by its consumer or failed (`error`) */
onEnd(error?: unknown): void
}
/**
* Reports the bytes read from the source, and the end of its reading
*
* The meter is called from the async context of the consumer pulling the next block, which may be any of the
* forks of a SynchronizedDisk: it must not rely on this context
*/
export class MeteredDisk extends DiskPassthrough {
#meter: ReadMeter
constructor(source: Disk, meter: ReadMeter) {
super(source)
this.#meter = meter
}
async buildDiskBlockGenerator(): Promise<AsyncGenerator<DiskBlock>> {
const generator = await this.source.buildDiskBlockGenerator()
const meter = this.#meter
// known once the source is initialized, which building its generator requires: each block is full sized
meter.setBytesToRead(this.source.getBlockIndexesCount() * this.source.getBlockSize())
async function* meteredGenerator(): AsyncGenerator<DiskBlock> {
let error: unknown
try {
for await (const block of generator) {
meter.onRead(block.data.length)
yield block
}
} catch (err) {
error = err
throw err
} finally {
meter.onEnd(error)
}
}
return meteredGenerator()
}
}

View File

@@ -0,0 +1,123 @@
import { test } from 'node:test'
import assert from 'node:assert'
import { DebugDisk } from './utils/DebugDisk.mjs'
import { MeteredDisk, ReadMeter } from './MeteredDisk.mjs'
import { SynchronizedDisk } from './SynchronizedDisk.mjs'
import { DiskBlock } from './Disk.mjs'
const blockSize = 1024
const nbBlocks = 20
function createMeter() {
const meter = {
readSize: 0,
bytesToRead: [] as number[],
ends: [] as unknown[],
setBytesToRead(length: number) {
meter.bytesToRead.push(length)
},
onRead(length: number) {
meter.readSize += length
},
onEnd(error?: unknown) {
meter.ends.push(error)
},
} satisfies ReadMeter & Record<string, unknown>
return meter
}
async function createDisk() {
const disk = new DebugDisk({ nbBlocks, blockSize, fillRate: 100 })
await disk.init()
return disk
}
test('MeteredDisk', async t => {
await t.test('reports the bytes read and the end', async () => {
const disk = await createDisk()
const meter = createMeter()
const metered = new MeteredDisk(disk, meter)
for await (const block of metered.diskBlocks()) {
assert.strictEqual(block.data.length, blockSize)
}
assert.strictEqual(meter.readSize, nbBlocks * blockSize)
assert.deepStrictEqual(meter.bytesToRead, [nbBlocks * blockSize])
assert.deepStrictEqual(meter.ends, [undefined])
assert.strictEqual(disk.closeDone, true)
})
await t.test('reports an early stop of the consumer without error', async () => {
const meter = createMeter()
const metered = new MeteredDisk(await createDisk(), meter)
let nbRead = 0
for await (const block of metered.diskBlocks()) {
assert.strictEqual(block.data.length, blockSize)
if (++nbRead === 3) {
break
}
}
assert.strictEqual(meter.readSize, 3 * blockSize)
assert.deepStrictEqual(meter.ends, [undefined])
})
await t.test('reports the error of the source', async () => {
const disk = await createDisk()
const error = new Error('read failed')
disk.readBlock = async (index: number): Promise<DiskBlock> => {
if (index === 5) {
throw error
}
return { index, data: Buffer.alloc(blockSize) }
}
const meter = createMeter()
const metered = new MeteredDisk(disk, meter)
await assert.rejects(async () => {
for await (const block of metered.diskBlocks()) {
assert.strictEqual(block.data.length, blockSize)
}
}, error)
assert.strictEqual(meter.readSize, 5 * blockSize)
assert.deepStrictEqual(meter.ends, [error])
})
await t.test('counts a source read once by multiple forks', async () => {
const meter = createMeter()
const synchronized = new SynchronizedDisk(new MeteredDisk(await createDisk(), meter))
const forks = [synchronized.fork('first'), synchronized.fork('second')]
await Promise.all(
forks.map(async fork => {
for await (const block of fork.diskBlocks()) {
assert.strictEqual(block.data.length, blockSize)
await new Promise(resolve => setTimeout(resolve, Math.random() * 3))
}
})
)
assert.strictEqual(meter.readSize, nbBlocks * blockSize)
assert.deepStrictEqual(meter.bytesToRead, [nbBlocks * blockSize])
assert.deepStrictEqual(meter.ends, [undefined])
})
await t.test('reports the size of the blocks present in the source', async () => {
const disk = new DebugDisk({ nbBlocks, blockSize, fillRate: 50 })
await disk.init()
const meter = createMeter()
for await (const block of new MeteredDisk(disk, meter).diskBlocks()) {
assert.strictEqual(block.data.length, blockSize)
}
assert.strictEqual(meter.readSize, disk.getBlockIndexesCount() * blockSize)
// only the blocks present are to read, not the virtual size
assert.deepStrictEqual(meter.bytesToRead, [disk.getBlockIndexesCount() * blockSize])
})
await t.test('reads nothing from a source without blocks', async () => {
const disk = new DebugDisk({ nbBlocks, blockSize, fillRate: 0 })
await disk.init()
const meter = createMeter()
for await (const block of new MeteredDisk(disk, meter).diskBlocks()) {
assert.strictEqual(block.data.length, blockSize)
}
assert.strictEqual(meter.readSize, 0)
assert.deepStrictEqual(meter.bytesToRead, [0])
assert.deepStrictEqual(meter.ends, [undefined])
})
})

View File

@@ -9,5 +9,7 @@ export { RawDisk } from './RawDisk.mjs'
export { ReadAhead } from './ReadAhead.mjs'
export { SynchronizedDisk } from './SynchronizedDisk.mjs'
export { TimeoutDisk } from './Timeout.mjs'
export { MeteredDisk } from './MeteredDisk.mjs'
export type { ReadMeter } from './MeteredDisk.mjs'
export { ThrottledDisk } from './Throttled.mjs'
export { ProgressHandler } from './ProgressHandler.mjs'

View File

@@ -23,6 +23,14 @@ const computeRate = (hrtime, size) => {
return size / seconds
}
const getDataSize = data => {
if (Array.isArray(data)) {
return data.reduce((size, buffer) => size + Buffer.byteLength(buffer), 0)
}
return Buffer.byteLength(data)
}
const DEFAULT_TIMEOUT = 12e5 // 20 min
const DEFAULT_MAX_PARALLEL_OPERATIONS = 10
@@ -407,6 +415,7 @@ export default class RemoteHandlerAbstract {
encryptedData = Buffer.concat(encryptedData)
}
await this._outputFile(normalizePath(file), encryptedData, { dirMode, flags })
return getDataSize(encryptedData)
}
async read(file, buffer, position) {
@@ -596,6 +605,7 @@ export default class RemoteHandlerAbstract {
async __writeFile(file, data, { flags = 'wx' } = {}) {
const encryptedData = this.#encryptor.encryptData(data)
await this._writeFile(normalizePath(file), encryptedData, { flags })
return getDataSize(encryptedData)
}
// Methods that can be called by private methods to avoid parallel limit on public methods

View File

@@ -248,4 +248,21 @@ describe('encryption', () => {
code: 'MISSING_ENCRYPTION_KEY',
})
})
it('encrypted write returns the correct size', async () => {
const data = '0000000000'
await Disposable.use(
getSyncedHandler({ url: `file://${dir}?encryptionKey="73c1838d7d8a6088ca2317fb5f29cd91"` }),
async handler => {
const outputDataSize = await handler.outputFile('file', data)
const writeDataSize = await handler.writeFile('other', data)
assert.equal(outputDataSize, await handler.getSizeOnDisk(`file`))
assert(outputDataSize > Buffer.byteLength(data))
assert.equal(writeDataSize, await handler.getSizeOnDisk(`other`))
assert(writeDataSize > Buffer.byteLength(data))
}
)
})
})

View File

@@ -230,7 +230,7 @@ export default class AzureHandler extends RemoteHandlerAbstract {
*/
async _writeFile(file, data) {
const blobClient = this.#containerClient.getBlockBlobClient(this.#makeFullPath(file))
await blobClient.upload(data, data.length)
await blobClient.upload(data, Buffer.byteLength(data))
}
async _createReadStream(file) {

View File

@@ -190,6 +190,33 @@ handlers.forEach(url => {
await handler.sync()
await handler.outputFile(`xo-fs-tests-${Date.now()}/test`, '')
}, 40)
it('returns the correct file size', async () => {
const dataSize = await handler.outputFile('file', TEST_DATA)
assert.equal(dataSize, await handler.getSizeOnDisk('file'))
})
it('returns the correct file size with multi-byte character', async () => {
const dataSize = await handler.outputFile('file', 'é')
assert.equal(dataSize, await handler.getSizeOnDisk('file'))
})
it('returns the correct file size with buffer array', async () => {
const dataSize = await handler.outputFile('file', [TEST_DATA, TEST_DATA])
assert.equal(dataSize, await handler.getSizeOnDisk('file'))
})
})
describe('#writeFile()', () => {
it('returns the correct file size', async () => {
const dataSize = await handler.writeFile('file', TEST_DATA)
assert.equal(dataSize, await handler.getSizeOnDisk('file'))
})
it('returns the correct file size with multi-byte character', async () => {
const dataSize = await handler.writeFile('file', 'é')
assert.equal(dataSize, await handler.getSizeOnDisk('file'))
})
})
describe('#read()', () => {

View File

@@ -4,6 +4,9 @@
- [VM/Network] Add possibility to delete a VIF (PR [#10726](https://github.com/vatesfr/xen-orchestra/pull/10726))
- [Web-Core/VtsErrorModal] Add an optional details log viewer, unified icon (PR [#10536](https://github.com/vatesfr/xen-orchestra/pull/10536))
- [VM/Network] Add a link to the pool network in the VIF side panel and table (PR [#10686](https://github.com/vatesfr/xen-orchestra/pull/10686))
- [VIF] Add a VIF page with general and network information, linked from the VM network table and the VIF side panel (PR [#10686](https://github.com/vatesfr/xen-orchestra/pull/10686))
- [Host] Add possibility to enable SSH on XCP-ng 9 hosts, and to disable it with auto-enable if XAPI goes down. The SSH status is shown in the host dashboard and System tab (PR [#10974](https://github.com/vatesfr/xen-orchestra/pull/10974))
## **0.28.0** (2026/12/01)

View File

@@ -19,7 +19,7 @@ const props = defineProps<{
id?: I
}>()
const route = useRoute<'/pool/[uuid]' | '/host/[uuid]' | '/vm/[uuid]'>()
const route = useRoute<'/pool/[uuid]' | '/host/[uuid]' | '/vm/[uuid]' | '/vif/[uuid]'>()
const id = computed(() => props.id ?? (route.params.uuid as I))

View File

@@ -8,6 +8,11 @@
</template>
</VtsKeyValueRow>
<VtsKeyValueRow :label="t('ip-address')" :value="host.address" copy />
<VtsKeyValueRow v-if="isSshManageable" :label="t('ssh')">
<template #value>
<VtsStatus :status="host.ssh_enabled ?? false" />
</template>
</VtsKeyValueRow>
<VtsKeyValueRow :label="t('started')" :value="isRunning ? relativeStartTime : undefined" />
<VtsKeyValueRow :label="t('master')">
<template #value>
@@ -49,7 +54,7 @@
<script lang="ts" setup>
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import { useHostUtils } from '@/modules/host/composables/host-utils.composable.ts'
import { getHostCoreSocketInfo, getHostManufacturerInfo } from '@/modules/host/utils/host.util.ts'
import { getHostCoreSocketInfo, getHostManufacturerInfo, isHostSshManageable } from '@/modules/host/utils/host.util.ts'
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
import { useHostStore } from '@/stores/xen-api/host.store.ts'
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
@@ -57,6 +62,7 @@ import VtsIcon from '@core/components/icon/VtsIcon.vue'
import VtsKeyValueList from '@core/components/key-value-list/VtsKeyValueList.vue'
import VtsKeyValueRow from '@core/components/key-value-row/VtsKeyValueRow.vue'
import VtsQuickInfoCard from '@core/components/quick-info-card/VtsQuickInfoCard.vue'
import VtsStatus from '@core/components/status/VtsStatus.vue'
import VtsTag from '@core/components/tag/VtsTag.vue'
import UiLink from '@core/components/ui/link/UiLink.vue'
import UiTagsList from '@core/components/ui/tag/UiTagsList.vue'
@@ -84,6 +90,8 @@ const manufacturerInfo = computed(() => getHostManufacturerInfo(host))
const coreSocketInfo = computed(() => getHostCoreSocketInfo(host))
const isSshManageable = computed(() => isHostSshManageable(host))
const ram = computed(() => {
const memory = getHostMemory(host)

View File

@@ -5,6 +5,11 @@
</UiTitle>
<VtsTabularKeyValueList>
<VtsTabularKeyValueRow :label="t('ip-address')" :value="host.address" copy />
<VtsTabularKeyValueRow v-if="isSshManageable" :label="t('ssh')">
<template #value>
<VtsStatus :status="host.ssh_enabled ?? false" />
</template>
</VtsTabularKeyValueRow>
<VtsTabularKeyValueRow :label="t('remote-syslog')" :value="host.logging.syslog_destination" />
<VtsTabularKeyValueRow :label="t('iscsi-iqn')" :value="host.iscsi_iqn" copy />
<VtsTabularKeyValueRow :label="t('multi-pathing')">
@@ -18,16 +23,20 @@
<script setup lang="ts">
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import { isHostSshManageable } from '@/modules/host/utils/host.util.ts'
import VtsStatus from '@core/components/status/VtsStatus.vue'
import VtsTabularKeyValueList from '@core/components/tabular-key-value-list/VtsTabularKeyValueList.vue'
import VtsTabularKeyValueRow from '@core/components/tabular-key-value-row/VtsTabularKeyValueRow.vue'
import UiCard from '@core/components/ui/card/UiCard.vue'
import UiTitle from '@core/components/ui/title/UiTitle.vue'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
defineProps<{
const { host } = defineProps<{
host: XenApiHost
}>()
const { t } = useI18n()
const isSshManageable = computed(() => isHostSshManageable(host))
</script>

View File

@@ -85,6 +85,7 @@
<script setup lang="ts">
import PifRow from '@/components/pif/PifRow.vue'
import type { XenApiNetwork } from '@/libs/xen-api/xen-api.types.ts'
import { useNetworkUtils } from '@/modules/network/composables/network-utils.composable.ts'
import { useNetworkDelete } from '@/modules/network/composables/use-network-delete.composable.ts'
import { usePifStore } from '@/stores/xen-api/pif.store.ts'
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
@@ -108,6 +109,7 @@ const emit = defineEmits<{
}>()
const { getPifsByNetworkRef } = usePifStore().subscribe()
const { getNetworkVlan } = useNetworkUtils()
const { t } = useI18n()
@@ -115,13 +117,7 @@ const { deleteNetworks, isDeletingNetworks } = useNetworkDelete(() => (network !
const pifs = computed(() => (network !== undefined ? getPifsByNetworkRef(network.$ref) : []))
const networkVlan = computed(() => {
if (pifs.value.length === 0) {
return
}
return pifs.value[0].VLAN !== -1 ? pifs.value[0].VLAN.toString() : t('none')
})
const networkVlan = computed(() => (network !== undefined ? getNetworkVlan(network) : undefined))
const networkNbd = computed(() => (network?.purpose[0] ? t('on') : t('off')))

View File

@@ -20,6 +20,10 @@ export function createHostOperations(xenApi: XenApi) {
const restartAgent = (hostRef: HostRef) => xenApi.call('host.restart_agent', [hostRef])
const enableSsh = (hostRef: HostRef) => xenApi.call('host.enable_ssh', [hostRef])
const setSshAutoMode = (hostRef: HostRef, value: boolean) => xenApi.call('host.set_ssh_auto_mode', [hostRef, value])
const clearHost = async (hostRef: HostRef, force: boolean) => {
await disable(hostRef)
@@ -41,6 +45,8 @@ export function createHostOperations(xenApi: XenApi) {
powerOn,
destroy,
restartAgent,
enableSsh,
setSshAutoMode,
cleanReboot: async (hostRef: HostRef, forceReboot: boolean) => {
await clearHost(hostRef, forceReboot)

View File

@@ -164,6 +164,7 @@ export interface XenApiHost extends XenApiRecord<'host'> {
multipathing: boolean
enabled: boolean
PGPUs: XenApiPgpu['$ref'][]
ssh_enabled?: boolean
}
export interface XenApiSr extends XenApiRecord<'sr'> {

View File

@@ -13,6 +13,10 @@
<HostRestartToolstackButton :host />
<HostDisableButton v-if="displayDisableButton" :host />
<HostEnableButton v-else :host />
<template v-if="isSshManageable">
<HostDisableSshButton v-if="host.ssh_enabled" :host />
<HostEnableSshButton v-else :host />
</template>
<HostDetachButton :host />
<HostForgetButton :host />
<VtsDivider v-if="layout !== 'sections'" type="stretch" />
@@ -23,12 +27,15 @@
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import HostDetachButton from '@/modules/host/components/actions/detach/HostDetachButton.vue'
import HostDisableButton from '@/modules/host/components/actions/disable/HostDisableButton.vue'
import HostDisableSshButton from '@/modules/host/components/actions/disable-ssh/HostDisableSshButton.vue'
import HostDownloadButton from '@/modules/host/components/actions/download/HostDownloadButton.vue'
import HostEnableButton from '@/modules/host/components/actions/enable/HostEnableButton.vue'
import HostEnableSshButton from '@/modules/host/components/actions/enable-ssh/HostEnableSshButton.vue'
import HostForgetButton from '@/modules/host/components/actions/forget/HostForgetButton.vue'
import HostPowerStateActions from '@/modules/host/components/actions/HostPowerStateActions.vue'
import HostRestartToolstackButton from '@/modules/host/components/actions/restart-toolstack/HostRestartToolstackButton.vue'
import type { HostQuickAction } from '@/modules/host/composables/host-quick-actions.composable.ts'
import { isHostSshManageable } from '@/modules/host/utils/host.util.ts'
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
import VtsDivider from '@core/components/divider/VtsDivider.vue'
import VtsChangeStateMenuItem from '@core/components/menu/VtsChangeStateMenuItem.vue'
@@ -54,4 +61,6 @@ const { getHostPowerState } = useHostMetricsStore().subscribe()
const isHostHalted = computed(() => getHostPowerState(host) === HOST_POWER_STATE.HALTED)
const displayDisableButton = computed(() => host.enabled || isHostHalted.value)
const isSshManageable = computed(() => isHostSshManageable(host))
</script>

View File

@@ -0,0 +1,52 @@
<template>
<MenuItem
v-tooltip="!canDisableSsh && disableSshErrorMessage"
accent="neutral"
:busy="isDisablingSsh"
:disabled="!canDisableSsh"
icon="action:disable"
@click="disableSsh()"
>
{{ t('action:disable-ssh') }}
<i class="em-dash-prefix">{{ t('auto-enable-if-xapi-goes-down') }}</i>
</MenuItem>
</template>
<script lang="ts" setup>
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import { useHostDisableSshJob } from '@/modules/host/jobs/host-disable-ssh.job.ts'
import MenuItem from '@core/components/menu/MenuItem.vue'
import { useActionModal } from '@core/composables/modals/use-action-modal.ts'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import { useI18n } from 'vue-i18n'
const { host } = defineProps<{
host: XenApiHost
}>()
const { t } = useI18n()
const { open: openActionModal } = useActionModal()
const {
run,
canRun: canDisableSsh,
isRunning: isDisablingSsh,
errorMessage: disableSshErrorMessage,
} = useHostDisableSshJob(() => host)
function disableSsh() {
return openActionModal({
props: {
accent: 'info',
action: 'disable-ssh',
object: 'host',
hostName: host.name_label,
icon: 'status:info-picto',
},
events: {
onConfirm: () => run({ detached: true }),
},
})
}
</script>

View File

@@ -7,7 +7,7 @@
icon="action:disable"
@click="disableHost()"
>
{{ t('action:disable') }}
{{ t('action:disable-host') }}
</MenuItem>
</template>

View File

@@ -0,0 +1,51 @@
<template>
<MenuItem
v-tooltip="!canEnableSsh && enableSshErrorMessage"
accent="neutral"
:busy="isEnablingSsh"
:disabled="!canEnableSsh"
icon="status:success-circle"
@click="enableSsh()"
>
{{ t('action:enable-ssh') }}
</MenuItem>
</template>
<script lang="ts" setup>
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import { useHostEnableSshJob } from '@/modules/host/jobs/host-enable-ssh.job.ts'
import MenuItem from '@core/components/menu/MenuItem.vue'
import { useActionModal } from '@core/composables/modals/use-action-modal.ts'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import { useI18n } from 'vue-i18n'
const { host } = defineProps<{
host: XenApiHost
}>()
const { t } = useI18n()
const { open: openActionModal } = useActionModal()
const {
run,
canRun: canEnableSsh,
isRunning: isEnablingSsh,
errorMessage: enableSshErrorMessage,
} = useHostEnableSshJob(() => host)
function enableSsh() {
return openActionModal({
props: {
accent: 'info',
action: 'enable-ssh',
object: 'host',
hostName: host.name_label,
icon: 'status:info-picto',
},
events: {
onConfirm: () => run({ detached: true }),
},
})
}
</script>

View File

@@ -7,7 +7,7 @@
icon="status:success-circle"
@click="enableHost()"
>
{{ t('action:enable') }}
{{ t('action:enable-host') }}
</MenuItem>
</template>

View File

@@ -0,0 +1,34 @@
import { hostArg } from '@/modules/host/jobs/host-args.ts'
import { isHostSshManageable } from '@/modules/host/utils/host.util.ts'
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
import { useXenApiStore } from '@/stores/xen-api.store.ts'
import { defineJob, JobError, JobRunningError } from '@core/packages/job'
import { useI18n } from 'vue-i18n'
export const useHostDisableSshJob = defineJob('host.disable-ssh', [hostArg], () => {
const xapi = useXenApiStore().getXapi()
const { t } = useI18n()
const { isHostRunning } = useHostMetricsStore().subscribe()
return {
run: host => xapi.host.setSshAutoMode(host.$ref, true),
validate: (isRunning, host) => {
if (host === undefined) {
throw new JobError(t('job:host-disable-ssh:missing-host'))
}
if (isRunning) {
throw new JobRunningError(t('job:host-disable-ssh:in-progress'))
}
if (!isHostSshManageable(host)) {
throw new JobError(t('job:host-disable-ssh:unsupported-version'))
}
if (!isHostRunning(host)) {
throw new JobError(t('job:host-disable-ssh:bad-power-state'))
}
},
}
})

View File

@@ -0,0 +1,34 @@
import { hostArg } from '@/modules/host/jobs/host-args.ts'
import { isHostSshManageable } from '@/modules/host/utils/host.util.ts'
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
import { useXenApiStore } from '@/stores/xen-api.store.ts'
import { defineJob, JobError, JobRunningError } from '@core/packages/job'
import { useI18n } from 'vue-i18n'
export const useHostEnableSshJob = defineJob('host.enable-ssh', [hostArg], () => {
const xapi = useXenApiStore().getXapi()
const { t } = useI18n()
const { isHostRunning } = useHostMetricsStore().subscribe()
return {
run: host => xapi.host.enableSsh(host.$ref),
validate: (isRunning, host) => {
if (host === undefined) {
throw new JobError(t('job:host-enable-ssh:missing-host'))
}
if (isRunning) {
throw new JobRunningError(t('job:host-enable-ssh:in-progress'))
}
if (!isHostSshManageable(host)) {
throw new JobError(t('job:host-enable-ssh:unsupported-version'))
}
if (!isHostRunning(host)) {
throw new JobError(t('job:host-enable-ssh:bad-power-state'))
}
},
}
})

View File

@@ -3,6 +3,7 @@ import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import { objectIcon } from '@core/icons'
import { HOST_POWER_STATE } from '@vates/types'
import { castArray } from 'lodash-es'
import { coerce, satisfies } from 'semver'
export type HostState = Lowercase<HOST_POWER_STATE> | 'disabled'
@@ -45,6 +46,9 @@ export const getHostState = (host: XenApiHost | undefined, powerState: HOST_POWE
return host.enabled ? 'running' : 'disabled'
}
export const isHostSshManageable = (host: XenApiHost) =>
satisfies(coerce(host.software_version.product_version) ?? '', '>=8.99')
export const getHostIcon = (host: XenApiHost | undefined, powerState: HOST_POWER_STATE) =>
objectIcon('host', getHostState(host, powerState))

View File

@@ -2,9 +2,12 @@ import type { XenApiNetwork } from '@/libs/xen-api/xen-api.types.ts'
import { usePifMetricsStore } from '@/stores/xen-api/pif-metrics.store.ts'
import { usePifStore } from '@/stores/xen-api/pif.store.ts'
import { getConnectionStatus } from '@core/utils/connection.util.ts'
import { useI18n } from 'vue-i18n'
export function useNetworkUtils() {
const { records: pifs } = usePifStore().subscribe()
const { t } = useI18n()
const { records: pifs, getPifsByNetworkRef } = usePifStore().subscribe()
const { getPifCarrier } = usePifMetricsStore().subscribe()
function getNetworkStatus(network: XenApiNetwork) {
@@ -13,5 +16,15 @@ export function useNetworkUtils() {
return getConnectionStatus(networkPifs.map(pif => pif.currently_attached && getPifCarrier(pif)))
}
return { getNetworkStatus }
function getNetworkVlan(network: XenApiNetwork) {
const networkPifs = getPifsByNetworkRef(network.$ref)
if (networkPifs.length === 0) {
return
}
return networkPifs[0].VLAN !== -1 ? networkPifs[0].VLAN.toString() : t('none')
}
return { getNetworkStatus, getNetworkVlan }
}

View File

@@ -0,0 +1,72 @@
<template>
<div class="breadcrumb-container">
<UiBreadcrumb :size>
<UiLink v-if="vm" :size :to="{ name: '/vm/[uuid]/dashboard', params: { uuid: vm.uuid } }">
<VtsObjectIcon type="vm" :state="vmPowerState" size="current" />
{{ vm.name_label }}
</UiLink>
<UiLink v-if="vm && network" :size :to="{ name: '/vm/[uuid]/network', params: { uuid: vm.uuid } }">
{{ t('network') }}
</UiLink>
<span>
<VtsIcon name="object:vif" size="current" />
{{ t('vif-device', { device: vif.device }) }}
</span>
</UiBreadcrumb>
</div>
<UiHeadBar icon="object:vif">
{{ t('vif-device', { device: vif.device }) }}
</UiHeadBar>
<TabList :label="t('vif-device', { device: vif.device })">
<RouterTab :to="{ name: '/vif/[uuid]/general', params: { uuid: vif.uuid } }">
{{ t('general') }}
</RouterTab>
</TabList>
</template>
<script setup lang="ts">
import RouterTab from '@/components/RouterTab.vue'
import type { XenApiVif } from '@/libs/xen-api/xen-api.types.ts'
import { useNetworkStore } from '@/stores/xen-api/network.store.ts'
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
import VtsIcon from '@core/components/icon/VtsIcon.vue'
import VtsObjectIcon from '@core/components/object-icon/VtsObjectIcon.vue'
import TabList from '@core/components/tab-list/TabList.vue'
import UiBreadcrumb from '@core/components/ui/breadcrumb/UiBreadcrumb.vue'
import UiHeadBar from '@core/components/ui/head-bar/UiHeadBar.vue'
import UiLink from '@core/components/ui/link/UiLink.vue'
import { useUiStore } from '@core/stores/ui.store.ts'
import { toLower } from 'lodash-es'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { vif } = defineProps<{ vif: XenApiVif }>()
const { t } = useI18n()
const uiStore = useUiStore()
const size = computed(() => (uiStore.isSmall ? 'small' : 'medium'))
const { getByOpaqueRef: getVmByOpaqueRef } = useVmStore().subscribe()
const { getByOpaqueRef: getNetworkByOpaqueRef } = useNetworkStore().subscribe()
const vm = computed(() => getVmByOpaqueRef(vif.VM))
const network = computed(() => getNetworkByOpaqueRef(vif.network))
const vmPowerState = computed(() => toLower(vm.value?.power_state))
</script>
<style lang="postcss" scoped>
.breadcrumb-container {
min-height: 5.6rem;
padding: 1.2rem 1.6rem;
display: flex;
gap: 1.6rem;
align-items: center;
border-bottom: 0.1rem solid var(--color-neutral-border);
background-color: var(--color-neutral-background-primary);
justify-content: space-between;
overflow-y: auto;
}
</style>

View File

@@ -22,12 +22,16 @@
</div>
</template>
<script lang="ts" setup>
import type { XenApiNetwork, XenApiVif, XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
<script setup lang="ts">
import type { XenApiVif, XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import { getPoolNetworkRoute } from '@/modules/network/utils/network.util.ts'
import { useVifConnection } from '@/modules/vif/composables/use-vif-connection.composable.ts'
import { useVifDelete } from '@/modules/vif/composables/use-vif-delete.composable.ts'
import { useVifEdit } from '@/modules/vif/composables/use-vif-edit.composable.ts'
import { useVifUtils } from '@/modules/vif/composables/vif-utils.composable.ts'
import { getVifRoute } from '@/modules/vif/utils/vif.util.ts'
import { useNetworkStore } from '@/stores/xen-api/network.store.ts'
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
import { useVifStore } from '@/stores/xen-api/vif.store.ts'
import { useVmGuestMetricsStore } from '@/stores/xen-api/vm-guest-metrics.store.ts'
import VtsRow from '@core/components/table/VtsRow.vue'
@@ -38,16 +42,18 @@ import { usePagination } from '@core/composables/pagination.composable.ts'
import { useRouteQuery } from '@core/composables/route-query.composable.ts'
import { useSearchFilter } from '@core/composables/search-filter.composable.ts'
import { useTableState } from '@core/composables/table-state.composable.ts'
import { icon } from '@core/icons'
import { useMapper } from '@core/packages/mapper'
import { type ActionItem } from '@core/tables/column-definitions/action-column.ts'
import { useVifColumns } from '@core/tables/column-sets/vif-columns.ts'
import { CONNECTION_ACTION } from '@core/types/connection.ts'
import { useVifNetworkColumns } from '@core/tables/column-sets/vif-network-columns.ts'
import { renderBodyCell } from '@core/tables/helpers/render-body-cell.ts'
import { CONNECTION_ACTION, CONNECTION_STATUS } from '@core/types/connection.ts'
import { getUniqueIpAddressesForDevice } from '@core/utils/ip-address.utils.ts'
import { logicNot } from '@vueuse/math'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { vifs, vm } = defineProps<{
const { vifs: rawVifs, vm } = defineProps<{
vifs: XenApiVif[]
vm: XenApiVm
}>()
@@ -56,17 +62,29 @@ defineSlots<{
'title-actions'(): any
}>()
const { isReady, hasError } = useVifStore().subscribe()
const { getByOpaqueRef: getNetworkByOpaqueRef } = useNetworkStore().subscribe()
const { getByOpaqueRef: getGuestMetricsByOpaqueRef } = useVmGuestMetricsStore().subscribe()
const { isReady, hasError } = useVifStore().subscribe()
const { pool } = usePoolStore().subscribe()
const { t } = useI18n()
const { goToVifEdit } = useVifEdit()
const selectedVifId = useRouteQuery('id')
const getNetworkName = (networkRef: XenApiNetwork['$ref']) => getNetworkByOpaqueRef(networkRef)?.name_label ?? ''
const getNetworkName = (vif: XenApiVif) => getNetworkByOpaqueRef(vif.network)?.name_label ?? ''
const { items: filteredVifs, searchBindings } = useSearchFilter(
() => rawVifs,
vif => [...Object.values(vif), getNetworkName(vif)]
)
const state = useTableState({
busy: logicNot(isReady),
error: hasError,
empty: () =>
rawVifs.length === 0 ? t('no-vif-detected') : filteredVifs.value.length === 0 ? { type: 'no-result' } : false,
})
const getIpAddresses = (vif: XenApiVif) => {
const networks = getGuestMetricsByOpaqueRef(vm.guest_metrics)?.networks
@@ -74,25 +92,20 @@ const getIpAddresses = (vif: XenApiVif) => {
return getUniqueIpAddressesForDevice(networks, vif.device)
}
const { items: filteredVifs, searchBindings } = useSearchFilter(
() => vifs,
vif => [...Object.values(vif), getNetworkName(vif.network)]
)
const state = useTableState({
busy: logicNot(isReady),
error: hasError,
empty: () =>
vifs.length === 0 ? t('no-vif-detected') : filteredVifs.value.length === 0 ? { type: 'no-result' } : false,
})
const { pageRecords: paginatedVifs, paginationBindings } = usePagination('vifs', filteredVifs)
const { HeadCells, BodyCells } = useVifColumns({
const { HeadCells, BodyCells } = useVifNetworkColumns({
body: (vif: XenApiVif) => {
const name = computed(() => getNetworkName(vif.network))
const ipAddresses = computed(() => getIpAddresses(vif))
const network = computed(() => getNetworkByOpaqueRef(vif.network))
const poolNetworkRoute = computed(() =>
pool.value && network.value ? getPoolNetworkRoute(pool.value.uuid, network.value.uuid) : undefined
)
const { lockingModeLabel } = useVifUtils(() => vif)
const {
connectVifs,
disconnectVifs,
@@ -133,13 +146,26 @@ const { HeadCells, BodyCells } = useVifColumns({
)
return {
network: r => r({ label: name.value }),
vif: r =>
r({
label: t('vif'),
to: getVifRoute(vif.uuid),
icon: icon('object:vif'),
}),
network: r =>
network.value
? r({
label: network.value.name_label,
to: poolNetworkRoute.value,
icon: icon('object:network'),
})
: renderBodyCell(),
device: r => r(t('vif-device', { device: vif.device })),
status: r => r(vif.currently_attached ? 'connected' : 'disconnected'),
status: r => r(vif.currently_attached ? CONNECTION_STATUS.CONNECTED : CONNECTION_STATUS.DISCONNECTED),
ipsAddresses: r => r(ipAddresses.value),
macAddresses: r => r(vif.MAC),
mtu: r => r(vif.MTU),
lockingMode: r => r(vif.locking_mode),
lockingMode: r => r(lockingModeLabel.value),
actions: r =>
r({
onClick: () => (selectedVifId.value = vif.uuid),

View File

@@ -0,0 +1,88 @@
<template>
<UiCard>
<UiTitle>
{{ t('general-information') }}
</UiTitle>
<VtsTabularKeyValueList>
<VtsTabularKeyValueRow :label="t('name')" :value="vifDevice" />
<VtsTabularKeyValueRow :label="t('uuid')">
<template #value>
<VtsCodeSnippet :content="vif.uuid" />
</template>
</VtsTabularKeyValueRow>
<VtsTabularKeyValueRow :label="t('network')">
<template v-if="network" #value>
<UiLink size="medium" :to="networkTo" icon="object:network">
{{ network.name_label }}
</UiLink>
</template>
</VtsTabularKeyValueRow>
<VtsTabularKeyValueRow :label="t('device')" :value="vifDevice" />
<VtsTabularKeyValueRow :label="t('vif-status')">
<template #value>
<VtsStatus :status="vifStatus" />
</template>
</VtsTabularKeyValueRow>
<VtsTabularKeyValueRow :label="t('vlan')" :value="networkVlan" />
<VtsTabularKeyValueRow :label="t('mtu')" :value="String(vif.MTU)" />
<VtsTabularKeyValueRow :label="t('rate-limit')" :value="rateLimit" />
<VtsTabularKeyValueRow :label="t('locking-mode')" :value="lockingModeLabel">
<template v-if="vif.locking_mode === VIF_LOCKING_MODE.DISABLED" #value>
<VtsStatus status="disabled" />
</template>
</VtsTabularKeyValueRow>
<VtsTabularKeyValueRow :label="t('check-summing')">
<template #value>
<VtsStatus :status="txChecksumming" />
</template>
</VtsTabularKeyValueRow>
</VtsTabularKeyValueList>
</UiCard>
</template>
<script setup lang="ts">
import type { XenApiVif } from '@/libs/xen-api/xen-api.types.ts'
import { useNetworkUtils } from '@/modules/network/composables/network-utils.composable.ts'
import { getPoolNetworkRoute } from '@/modules/network/utils/network.util.ts'
import { useVifUtils } from '@/modules/vif/composables/vif-utils.composable.ts'
import { useNetworkStore } from '@/stores/xen-api/network.store.ts'
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
import VtsCodeSnippet from '@core/components/code-snippet/VtsCodeSnippet.vue'
import VtsStatus from '@core/components/status/VtsStatus.vue'
import VtsTabularKeyValueList from '@core/components/tabular-key-value-list/VtsTabularKeyValueList.vue'
import VtsTabularKeyValueRow from '@core/components/tabular-key-value-row/VtsTabularKeyValueRow.vue'
import UiCard from '@core/components/ui/card/UiCard.vue'
import UiLink from '@core/components/ui/link/UiLink.vue'
import UiTitle from '@core/components/ui/title/UiTitle.vue'
import { CONNECTION_STATUS } from '@core/types/connection.ts'
import { VIF_LOCKING_MODE } from '@vates/types'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { vif } = defineProps<{ vif: XenApiVif }>()
const { t } = useI18n()
const { getByOpaqueRef: getNetworkByOpaqueRef } = useNetworkStore().subscribe()
const { pool } = usePoolStore().subscribe()
const { lockingModeLabel, rateLimit: rawRateLimit, txChecksumming } = useVifUtils(() => vif)
const { getNetworkVlan } = useNetworkUtils()
const network = computed(() => getNetworkByOpaqueRef(vif.network))
const networkTo = computed(() =>
pool.value && network.value ? getPoolNetworkRoute(pool.value.uuid, network.value.uuid) : undefined
)
const networkVlan = computed(() => (network.value !== undefined ? getNetworkVlan(network.value) : undefined))
const vifStatus = computed(() =>
vif.currently_attached ? CONNECTION_STATUS.CONNECTED : CONNECTION_STATUS.DISCONNECTED
)
const vifDevice = computed(() => t('vif-device', { device: vif.device }))
const rateLimit = computed(() =>
rawRateLimit.value !== undefined ? `${rawRateLimit.value} ${t('bytes:kbs')}` : undefined
)
</script>

View File

@@ -0,0 +1,55 @@
<template>
<UiCard>
<UiTitle>
{{ t('vif-network-info') }}
</UiTitle>
<VtsTabularKeyValueList>
<VtsTabularKeyValueRow :label="t('ip-addresses')">
<template v-if="ipAddresses.length" #value>
<div class="ip-list">
<span v-for="ip in ipAddresses" :key="ip">{{ ip }}</span>
</div>
</template>
</VtsTabularKeyValueRow>
<VtsTabularKeyValueRow :label="t('mac-address')" :value="vif.MAC" />
</VtsTabularKeyValueList>
</UiCard>
</template>
<script setup lang="ts">
import type { XenApiVif } from '@/libs/xen-api/xen-api.types.ts'
import { useVmGuestMetricsStore } from '@/stores/xen-api/vm-guest-metrics.store.ts'
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
import VtsTabularKeyValueList from '@core/components/tabular-key-value-list/VtsTabularKeyValueList.vue'
import VtsTabularKeyValueRow from '@core/components/tabular-key-value-row/VtsTabularKeyValueRow.vue'
import UiCard from '@core/components/ui/card/UiCard.vue'
import UiTitle from '@core/components/ui/title/UiTitle.vue'
import { getUniqueIpAddressesForDevice } from '@core/utils/ip-address.utils.ts'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { vif } = defineProps<{ vif: XenApiVif }>()
const { t } = useI18n()
const { getByOpaqueRef: getVmByOpaqueRef } = useVmStore().subscribe()
const { getByOpaqueRef: getGuestMetricsByOpaqueRef } = useVmGuestMetricsStore().subscribe()
const ipAddresses = computed(() => {
const vm = getVmByOpaqueRef(vif.VM)
if (vm === undefined) {
return []
}
return getUniqueIpAddressesForDevice(getGuestMetricsByOpaqueRef(vm.guest_metrics)?.networks, vif.device)
})
</script>
<style scoped lang="postcss">
.ip-list {
display: flex;
flex-direction: column;
gap: 0.4rem;
}
</style>

View File

@@ -1,5 +1,5 @@
<template>
<VtsSidePanel :has-selection="!!vif" class="vm-vifs-side-panel" @close="emit('close')">
<VtsSidePanel :has-selection="!!vif" class="vif-side-panel" @close="emit('close')">
<template v-if="vif" #actions>
<VifEditButton :vif />
<VifConnectionToggleButton v-if="vm" :vif :vm />
@@ -8,15 +8,19 @@
<template v-if="vif" #default>
<!-- VIF -->
<UiPanelCard>
<UiPanelCardTitle :id="vif.uuid" size="medium" :label="t('vif')" />
<UiPanelCardTitle :id="vif.uuid" size="medium" :to="vifTo" :label="t('vif')" icon="object:vif" />
<VtsCardRowList>
<!-- NETWORK -->
<VtsCardRowKeyValue>
<template #key>
{{ t('network') }}
</template>
<template #value>{{ network?.name_label }}</template>
<template v-if="network?.name_label" #addons>
<template #value>
<UiLink v-if="network" size="small" :to="networkTo" icon="object:network">
{{ network.name_label }}
</UiLink>
</template>
<template v-if="network" #addons>
<VtsCopyButton :value="network.name_label" />
</template>
</VtsCardRowKeyValue>
@@ -68,7 +72,7 @@
{{ t('locking-mode') }}
</template>
<template #value>
{{ vif.locking_mode }}
{{ lockingModeLabel }}
</template>
</VtsCardRowKeyValue>
<!-- TX CHECK SUMMING -->
@@ -77,12 +81,12 @@
{{ t('check-summing') }}
</template>
<template #value>
{{ isTxChecksummingEnabled(vif) }}
{{ txChecksumming }}
</template>
</VtsCardRowKeyValue>
</VtsCardRowList>
</UiPanelCard>
<!-- VIF NETWORK INFORMATION -->
<!-- NETWORK INFORMATION -->
<UiPanelCard>
<UiPanelCardTitle size="medium" :label="t('network-information')" />
<VtsCardRowList>
@@ -110,11 +114,14 @@
<script setup lang="ts">
import type { XenApiVif } from '@/libs/xen-api/xen-api.types.ts'
import { getPoolNetworkRoute } from '@/modules/network/utils/network.util.ts'
import VifConnectionToggleButton from '@/modules/vif/components/actions/connection/VifConnectionToggleButton.vue'
import VifDeleteButton from '@/modules/vif/components/actions/delete/VifDeleteButton.vue'
import VifEditButton from '@/modules/vif/components/actions/edit/VifEditButton.vue'
import { isTxChecksummingEnabled } from '@/modules/vif/utils/vif-tx-checksumming.util.ts'
import { useVifUtils } from '@/modules/vif/composables/vif-utils.composable.ts'
import { getVifRoute } from '@/modules/vif/utils/vif.util.ts'
import { useNetworkStore } from '@/stores/xen-api/network.store.ts'
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
import { useVmGuestMetricsStore } from '@/stores/xen-api/vm-guest-metrics.store.ts'
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
@@ -122,8 +129,10 @@ import VtsCardRowList from '@core/components/card/VtsCardRowList.vue'
import VtsCopyButton from '@core/components/copy-button/VtsCopyButton.vue'
import VtsSidePanel from '@core/components/panel/VtsSidePanel.vue'
import VtsStatus from '@core/components/status/VtsStatus.vue'
import UiLink from '@core/components/ui/link/UiLink.vue'
import UiPanelCard from '@core/components/ui/panel-card/UiPanelCard.vue'
import UiPanelCardTitle from '@core/components/ui/panel-card-title/UiPanelCardTitle.vue'
import { CONNECTION_STATUS } from '@core/types/connection.ts'
import { getUniqueIpAddressesForDevice } from '@core/utils/ip-address.utils.ts'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
@@ -141,8 +150,13 @@ const { t } = useI18n()
const { getByOpaqueRef: getNetworkByOpaqueRef } = useNetworkStore().subscribe()
const { getByOpaqueRef: getGuestMetricsByOpaqueRef } = useVmGuestMetricsStore().subscribe()
const { getByOpaqueRef: getVmByOpaqueRef } = useVmStore().subscribe()
const { pool } = usePoolStore().subscribe()
const { lockingModeLabel, rateLimit, txChecksumming } = useVifUtils(() => vif)
const vm = computed(() => (vif !== undefined ? getVmByOpaqueRef(vif.VM) : undefined))
const vifTo = computed(() => (vif !== undefined ? getVifRoute(vif.uuid) : undefined))
const ipAddresses = computed(() => {
if (vif === undefined) {
return []
@@ -159,19 +173,15 @@ const ipAddresses = computed(() => {
const network = computed(() => (vif !== undefined ? getNetworkByOpaqueRef(vif.network) : undefined))
const status = computed(() => (vif?.currently_attached ? 'connected' : 'disconnected'))
const networkTo = computed(() =>
pool.value && network.value ? getPoolNetworkRoute(pool.value.uuid, network.value.uuid) : undefined
)
const rateLimit = computed(() => {
if (vif?.qos_algorithm_type !== 'ratelimit') {
return undefined
}
return vif.qos_algorithm_params.kbps
})
const status = computed(() => (vif?.currently_attached ? CONNECTION_STATUS.CONNECTED : CONNECTION_STATUS.DISCONNECTED))
</script>
<style scoped lang="postcss">
.vm-vifs-side-panel {
.vif-side-panel {
.value:empty::before {
content: '-';
}

View File

@@ -5,7 +5,7 @@ export function useVifEdit() {
const router = useRouter()
function goToVifEdit(vif: XenApiVif) {
return router.push({ name: '/vif/[uuid]/edit', params: { uuid: vif.uuid } })
return router.push({ name: '/vif/edit', query: { vifUuid: vif.uuid } })
}
return { goToVifEdit }

View File

@@ -0,0 +1,22 @@
import type { XenApiVif } from '@/libs/xen-api/xen-api.types.ts'
import { isTxChecksummingEnabled } from '@/modules/vif/utils/vif-tx-checksumming.util.ts'
import { getVifRateLimit } from '@/modules/vif/utils/vif.util.ts'
import { useVifLockingModeLabel } from '@core/composables/vif-locking-mode-label.composable.ts'
import { toComputed } from '@core/utils/to-computed.util.ts'
import { computed, type MaybeRefOrGetter } from 'vue'
export function useVifUtils(rawVif: MaybeRefOrGetter<XenApiVif | undefined>) {
const vif = toComputed(rawVif)
const lockingModeLabel = useVifLockingModeLabel(() => vif.value?.locking_mode)
const rateLimit = computed(() => (vif.value !== undefined ? getVifRateLimit(vif.value) : undefined))
const txChecksumming = computed(() => vif.value !== undefined && isTxChecksummingEnabled(vif.value))
return {
lockingModeLabel,
rateLimit,
txChecksumming,
}
}

View File

@@ -1,18 +1,19 @@
import type { XenApiVif } from '@/libs/xen-api/xen-api.types.ts'
import { useVifForm } from '@/modules/vif/form/use-vif-form-base.ts'
import { isTxChecksummingEnabled } from '@/modules/vif/utils/vif-tx-checksumming.util.ts'
import { getVifRateLimit } from '@/modules/vif/utils/vif.util.ts'
import { useI18n } from 'vue-i18n'
export function useEditVifForm(vif: XenApiVif) {
const { t } = useI18n()
const { kbps } = vif.qos_algorithm_params
const kbps = getVifRateLimit(vif)
return useVifForm(
{
network: vif.network,
mac: vif.MAC,
rateLimit: vif.qos_algorithm_type === 'ratelimit' && kbps !== undefined ? Number(kbps) : undefined,
rateLimit: kbps !== undefined ? Number(kbps) : undefined,
allowedIps: [...vif.ipv4_allowed, ...vif.ipv6_allowed].join('; '),
txChecksumming: isTxChecksummingEnabled(vif),
},

View File

@@ -3,6 +3,7 @@ import { vifArg } from '@/modules/vif/jobs/vif-args.ts'
import type { VifPayload } from '@/modules/vif/jobs/vif-create.job.ts'
import { editVifPayloadArg } from '@/modules/vif/jobs/vif-edit-args.ts'
import { isTxChecksummingEnabled } from '@/modules/vif/utils/vif-tx-checksumming.util.ts'
import { getVifRateLimit } from '@/modules/vif/utils/vif.util.ts'
import { useXenApiStore } from '@/stores/xen-api.store.ts'
import { defineJob, JobError, JobRunningError } from '@core/packages/job'
import { VIF_LOCKING_MODE } from '@vates/types'
@@ -91,7 +92,7 @@ export const useVifEditJob = defineJob('vif.edit', [vifArg, editVifPayloadArg],
}
const kbps = payload.qos_algorithm_params?.kbps
const currentKbps = vif.qos_algorithm_type === 'ratelimit' ? vif.qos_algorithm_params.kbps : undefined
const currentKbps = getVifRateLimit(vif)
if (kbps !== currentKbps) {
await xapi.vif.setRateLimit(vif.$ref, kbps === undefined ? null : Number(kbps))

View File

@@ -0,0 +1,13 @@
import type { XenApiVif } from '@/libs/xen-api/xen-api.types.ts'
import type { RouteLocationAsRelative } from 'vue-router'
export function getVifRoute(vifId: XenApiVif['uuid']): RouteLocationAsRelative {
return {
name: '/vif/[uuid]/general',
params: { uuid: vifId },
}
}
export function getVifRateLimit(vif: XenApiVif) {
return vif.qos_algorithm_type === 'ratelimit' ? vif.qos_algorithm_params.kbps : undefined
}

View File

@@ -0,0 +1,29 @@
<template>
<ObjectNotFoundWrapper :is-ready :uuid-checker="hasUuid">
<template v-if="vif">
<VifHeader v-if="uiStore.hasUi" :vif />
<RouterView v-slot="{ Component }">
<component :is="Component" :vif />
</RouterView>
</template>
</ObjectNotFoundWrapper>
</template>
<script lang="ts" setup>
import ObjectNotFoundWrapper from '@/components/ObjectNotFoundWrapper.vue'
import type { XenApiVif } from '@/libs/xen-api/xen-api.types.ts'
import VifHeader from '@/modules/vif/components/VifHeader.vue'
import { useVifStore } from '@/stores/xen-api/vif.store.ts'
import { useDefaultTab } from '@core/composables/default-tab.composable.ts'
import { useUiStore } from '@core/stores/ui.store.ts'
import { computed } from 'vue'
import { useRoute } from 'vue-router'
useDefaultTab('/vif/[uuid]', 'general')
const route = useRoute<'/vif/[uuid]'>()
const uiStore = useUiStore()
const { getByUuid, hasUuid, isReady } = useVifStore().subscribe()
const vif = computed(() => getByUuid(route.params.uuid as XenApiVif['uuid']))
</script>

View File

@@ -0,0 +1,30 @@
<template>
<div class="scroll-container">
<VtsColumns extra-space-around>
<VtsColumn>
<VifGeneralInfoCard :vif />
</VtsColumn>
<VtsColumn>
<VifNetworkInfoCard :vif />
</VtsColumn>
</VtsColumns>
</div>
</template>
<script setup lang="ts">
import type { XenApiVif } from '@/libs/xen-api/xen-api.types.ts'
import VifGeneralInfoCard from '@/modules/vif/components/cards/VifGeneralInfoCard.vue'
import VifNetworkInfoCard from '@/modules/vif/components/cards/VifNetworkInfoCard.vue'
import VtsColumn from '@core/components/column/VtsColumn.vue'
import VtsColumns from '@core/components/columns/VtsColumns.vue'
defineProps<{ vif: XenApiVif }>()
</script>
<style lang="postcss" scoped>
.scroll-container {
flex: 1;
min-height: 0;
overflow-y: auto;
}
</style>

View File

@@ -52,14 +52,14 @@ import { type RouteLocationRaw, useRoute, useRouter } from 'vue-router'
const { t } = useI18n()
const router = useRouter()
const route = useRoute<'/vif/[uuid]/edit'>()
const route = useRoute()
const { isReady: areVifsReady, getByUuid: getVifByUuid } = useVifStore().subscribe()
const { getByOpaqueRef: getVmByOpaqueRef } = useVmStore().subscribe()
const vifUuid = computed(() => route.params.uuid as XenApiVif['uuid'])
const vifUuid = computed(() => route.query.vifUuid as XenApiVif['uuid'] | undefined)
const vif = computed(() => getVifByUuid(vifUuid.value))
const vif = computed(() => (vifUuid.value === undefined ? undefined : getVifByUuid(vifUuid.value)))
const vm = computed(() => (vif.value === undefined ? undefined : getVmByOpaqueRef(vif.value.VM)))

View File

@@ -1227,11 +1227,25 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/vif/[uuid]/edit': RouteRecordInfo<
'/vif/[uuid]/edit',
'/vif/:uuid/edit',
'/vif/[uuid]': RouteRecordInfo<
'/vif/[uuid]',
'/vif/:uuid',
{ uuid: ParamValue<true> },
{ uuid: ParamValue<false> },
| '/vif/[uuid]/general'
>,
'/vif/[uuid]/general': RouteRecordInfo<
'/vif/[uuid]/general',
'/vif/:uuid/general',
{ uuid: ParamValue<true> },
{ uuid: ParamValue<false> },
| never
>,
'/vif/edit': RouteRecordInfo<
'/vif/edit',
'/vif/edit',
Record<never, never>,
Record<never, never>,
| never
>,
'/vif/new': RouteRecordInfo<
@@ -2368,9 +2382,22 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/pages/vif/[uuid]/edit.vue': {
'src/pages/vif/[uuid].vue': {
routes:
| '/vif/[uuid]/edit'
| '/vif/[uuid]'
| '/vif/[uuid]/general'
views:
| 'default'
}
'src/pages/vif/[uuid]/general.vue': {
routes:
| '/vif/[uuid]/general'
views:
| never
}
'src/pages/vif/edit.vue': {
routes:
| '/vif/edit'
views:
| never
}

View File

@@ -11,6 +11,7 @@
prop('accent').type('ButtonAccent').enum('brand', 'warning', 'danger').preset('brand').required().widget(),
iconProp().preset('action:connect'),
prop('disabled').bool().widget(),
prop('restricted').bool().widget(),
prop('busy').bool().widget().help('In a VtsHeadBarActions, the button is disabled without showing a loader'),
prop('hint').str().preset('Already connected').widget().help('Shown when disabled'),
event('click'),

View File

@@ -25,6 +25,7 @@ const actions: ActionItem[] = [
{ label: 'Edit', icon: 'action:edit', onClick },
{ label: 'Copy', icon: 'action:copy', hint: 'Clipboard', onClick },
{ label: 'Disabled', icon: 'action:duplicate', disabled: true, onClick },
{ label: 'Restricted', icon: 'action:connect', restricted: true, onClick },
{ label: 'Busy', icon: 'action:download', busy: true, onClick },
{ label: 'Delete', icon: 'action:delete', accent: 'danger', separator: true, onClick },
]

View File

@@ -6,6 +6,7 @@
prop('accent').required().enum('brand', 'info', 'warning', 'danger').preset('brand').widget(),
prop('size').required().enum('small', 'medium', 'large').preset('medium').widget(),
prop('disabled').bool().widget(),
prop('restricted').bool().widget(),
prop('selected').bool().widget(),
prop('counter')
.type('CounterValue | { value: CounterValue; accent: CounterAccent }')

View File

@@ -12,6 +12,7 @@
prop('size').type('ButtonSize').enum('small', 'medium').preset('medium').required().widget(),
prop('busy').bool().widget(),
prop('disabled').bool().widget().ctx(),
prop('restricted').bool().widget(),
prop('lockIcon').bool().widget(),
iconProp('leftIcon'),
iconProp('rightIcon'),

View File

@@ -49,7 +49,6 @@
"qa:export:restore": "node --env-file-if-exists=.env --test tests/export.vhd.test.js --test-name-pattern='Restoration'",
"qa:backup:metadata": "node --env-file-if-exists=.env --test tests/metadata-backup.test.js",
"qa:sdn-controller": "node --env-file-if-exists=.env --test tests/sdn-controller.test.js",
"qa:network": "node --env-file-if-exists=.env --test tests/network.test.js",
"demo": "node --env-file-if-exists=.env index.js",
"report": "node --env-file-if-exists=.env scripts/run-and-report.mjs",
"report:smtp-test": "node --env-file-if-exists=.env scripts/run-and-report.mjs --smtp-test",

View File

@@ -14,7 +14,7 @@ import {
assertHealthCheckSuccess,
getRequiredEnv,
} from '../utils/index.js'
import { assertBackupSuccess } from '../utils/backupUtils.js'
import { assertBackupSuccess, assertArchivesSizeOnDisk } from '../utils/backupUtils.js'
import { setup, teardown } from './setup.js'
const log = createLogger('qa:backup:base')
@@ -164,6 +164,7 @@ describe('Backup basic tests', () => {
assertHealthCheckSuccess(result)
const healthCheckData = extractHealthCheckData(result)
log.debug('Health check validated', { status: healthCheckData.status, duration: healthCheckData.duration })
await assertArchivesSizeOnDisk(dispatchClient, backupRepository, vm.uuid)
}
})
it('should run the backup job in full mode with health checks', async () => {
@@ -181,6 +182,7 @@ describe('Backup basic tests', () => {
assertHealthCheckSuccess(result)
const healthCheckData = extractHealthCheckData(result)
log.debug('Health check validated', { status: healthCheckData.status, duration: healthCheckData.duration })
await assertArchivesSizeOnDisk(dispatchClient, backupRepository, vm.uuid)
})
it('should run backup without health check when SR not configured', async () => {
const name = generateBackupJobName()

View File

@@ -1,215 +0,0 @@
import '../logSetup.js'
import assert from 'node:assert/strict'
import { after, before, describe, it } from 'node:test'
import { isDeepStrictEqual } from 'node:util'
import { createLogger } from '@xen-orchestra/log'
import { RestApiClient } from '../client/restApiClient.js'
import { xoConnection } from '../client/xoLibClient.js'
import { createTestUser, deleteTestUser } from '../utils/aclUtils.js'
import { delay, getRequiredEnv } from '../utils/index.js'
const log = createLogger('xo:qa-test:network')
const BASE = '/rest/v0'
// every network this suite creates carries this prefix, so a run that died before its after() hook
// can be cleaned up by the next one
const NETWORK_PREFIX = 'qa-network-patch-'
const newRestClient = async ({ username, password }) => {
const client = new RestApiClient({ xoUrl: getRequiredEnv('HOSTNAME'), username, password })
await client.connect()
return client
}
const rejectsWithStatus = (promise, status) =>
assert.rejects(promise, error => {
assert.equal(error.status, status, `expected HTTP ${status}, got ${error.message} ${error.body ?? ''}`)
return true
})
describe('REST API — PATCH /networks/{id}', () => {
let admin
/** JSON-RPC admin connection, for the throwaway user */
let xo
let poolId
let networkId
let networkPath
const getNetwork = () => admin.get(`${networkPath}?fields=*`)
// a PATCH answers once XAPI has applied it, but GET reads XO's object cache, which only follows the XAPI
// event a moment later: read until the network shows the expected fields
const waitForNetwork = async expected => {
const deadline = Date.now() + 10_000
for (;;) {
const network = await getNetwork()
const current = Object.fromEntries(Object.keys(expected).map(key => [key, network[key]]))
if (isDeepStrictEqual(current, expected) || Date.now() > deadline) {
assert.deepEqual(current, expected)
return network
}
await delay(250)
}
}
before(async () => {
const credentials = { username: getRequiredEnv('USERNAME'), password: getRequiredEnv('PASSWORD') }
admin = await newRestClient(credentials)
xo = await xoConnection({ xoUrl: getRequiredEnv('HOSTNAME'), ...credentials })
const referenceVmId = getRequiredEnv('REFERENCE_VM_ID')
poolId = (await admin.get(`${BASE}/vms/${referenceVmId}?fields=$pool`)).$pool
assert.notEqual(poolId, undefined, `REFERENCE_VM_ID ${referenceVmId} has no pool`)
// an after() hook does not run when its before() threw: networks left by such a run are deleted here
const leftovers = (await admin.get(`${BASE}/networks?fields=id,name_label`)).filter(({ name_label }) =>
name_label.startsWith(NETWORK_PREFIX)
)
for (const { id } of leftovers) {
log.warn('deleting a network left by a previous run', { id })
await admin.delete(`${BASE}/networks/${id}`)
}
// an internal network: no PIF, so an MTU change replugs nothing on the pool's hosts
;({ id: networkId } = await admin.post(`${BASE}/pools/${poolId}/actions/create_internal_network?sync=true`, {
name_label: `${NETWORK_PREFIX}${Date.now()}`,
name_description: 'created by the qa-test network suite',
MTU: 1500,
}))
networkPath = `${BASE}/networks/${networkId}`
log.debug('created test network', { networkId, poolId })
})
after(async () => {
if (networkId !== undefined) {
try {
await admin.delete(networkPath)
} catch (error) {
log.warn('failed to delete the test network', { error, networkId })
}
}
await xo?.close()
})
it('creates a network from the field names PATCH uses', async () => {
const network = await getNetwork()
assert.ok(network.name_label.startsWith(NETWORK_PREFIX))
assert.equal(network.name_description, 'created by the qa-test network suite')
assert.equal(network.MTU, 1500)
})
it('refuses a create body giving both spellings of the name', async () => {
const name = `${NETWORK_PREFIX}both-${Date.now()}`
await rejectsWithStatus(
admin.post(`${BASE}/pools/${poolId}/actions/create_internal_network?sync=true`, { name, name_label: name }),
422
)
})
it('updates the name and the description', async () => {
const name_label = `${NETWORK_PREFIX}renamed-${Date.now()}`
await admin.patch(networkPath, { name_label, name_description: 'renamed by PATCH' })
await waitForNetwork({ name_label, name_description: 'renamed by PATCH' })
})
it('updates automatic and defaultIsLocked, both ways', async () => {
await admin.patch(networkPath, { automatic: true, defaultIsLocked: true })
await waitForNetwork({ automatic: true, defaultIsLocked: true })
await admin.patch(networkPath, { automatic: false, defaultIsLocked: false })
await waitForNetwork({ automatic: false, defaultIsLocked: false })
})
it('updates the MTU', async () => {
await admin.patch(networkPath, { MTU: 9000 })
await waitForNetwork({ MTU: 9000 })
})
it('refuses an MTU below 68 or not an integer, and keeps the current one', async () => {
await rejectsWithStatus(admin.patch(networkPath, { MTU: 67 }), 422)
await rejectsWithStatus(admin.patch(networkPath, { MTU: 1450.5 }), 422)
assert.equal((await getNetwork()).MTU, 9000)
})
it('swaps the NBD purposes: enabling one removes the other', async () => {
await admin.patch(networkPath, { nbd: true })
await waitForNetwork({ nbd: true, insecureNbd: false })
await admin.patch(networkPath, { insecureNbd: true })
await waitForNetwork({ nbd: false, insecureNbd: true })
})
it('refuses nbd and insecureNbd together, and changes nothing', async () => {
await rejectsWithStatus(admin.patch(networkPath, { nbd: true, insecureNbd: true }), 422)
const network = await getNetwork()
assert.equal(network.nbd, false)
assert.equal(network.insecureNbd, true)
})
it('refuses a body with none of the fields', async () => {
await rejectsWithStatus(admin.patch(networkPath, {}), 422)
})
it('answers 404 for an unknown network', async () => {
await rejectsWithStatus(
admin.patch(`${BASE}/networks/00000000-0000-0000-0000-000000000000`, { name_label: 'nope' }),
404
)
})
describe('as a user whose role grants update:name_label and update:nbd on this network', () => {
let testUser
let roleId
let user
before(async () => {
testUser = await createTestUser(xo)
const selector = `id:${networkId}`
;({ id: roleId } = await admin.post(`${BASE}/acl-roles`, {
name: `${NETWORK_PREFIX}role-${Date.now()}`,
privileges: [
{ resource: 'network', action: 'update:name_label', effect: 'allow', selector },
{ resource: 'network', action: 'update:nbd', effect: 'allow', selector },
],
}))
await admin.put(`${BASE}/acl-roles/${roleId}/users/${testUser.id}`)
user = await newRestClient({ username: testUser.email, password: testUser.password })
})
after(async () => {
if (roleId !== undefined) {
try {
await admin.delete(`${BASE}/acl-roles/${roleId}`)
} catch (error) {
log.warn('failed to delete the test role', { error, roleId })
}
}
if (testUser !== undefined) {
await deleteTestUser(xo, testUser.id)
}
})
it('can rename the network', async () => {
const name_label = `${NETWORK_PREFIX}by-user-${Date.now()}`
await user.patch(networkPath, { name_label })
await waitForNetwork({ name_label })
})
it('cannot change the MTU', async () => {
await rejectsWithStatus(user.patch(networkPath, { MTU: 1500 }), 403)
assert.equal((await getNetwork()).MTU, 9000)
})
// nbd: true also removes the insecure_nbd purpose, which update:nbd alone does not cover
it('cannot enable nbd without update:insecureNbd', async () => {
await rejectsWithStatus(user.patch(networkPath, { nbd: true }), 403)
const network = await getNetwork()
assert.equal(network.nbd, false)
assert.equal(network.insecureNbd, true)
})
})
})

View File

@@ -213,3 +213,41 @@ export const assertSynchronizedSnapshot = (result, vmCount) => {
const latestSnapshotEnd = Math.max(...snapshots.map(t => t.end))
assert(latestSnapshotEnd <= earliestStart, `Synchronized backup snapshots should be complete before transfer starts`)
}
/**
* Asserts that every backup of the VM on the repository records the space it uses, consistently between the archive and its disks
*
* @param {import('../client/dispatchClient.js').DispatchClient} dispatchClient
* @param {{ id: string, name: string }} backupRepository
* @param {string} vmUuid
* @returns {Promise<void>}
*/
export const assertArchivesSizeOnDisk = async (dispatchClient, backupRepository, vmUuid) => {
const backups = await dispatchClient.backup.listVmBackups([backupRepository.id])
const archives = backups[backupRepository.id]?.[vmUuid] ?? []
assert.ok(archives.length > 0, `no backup of VM ${vmUuid} on repository ${backupRepository.name}`)
for (const archive of archives) {
assert.strictEqual(typeof archive.sizeOnDisk, 'number', `${archive.id}: sizeOnDisk must be a number`)
assert.ok(archive.sizeOnDisk > 0, `${archive.id}: sizeOnDisk must be higher than 0`)
if (archive.mode === 'delta') {
let totalDiskSizeOnDisk = 0
for (const disk of archive.disks) {
assert.strictEqual(typeof disk.sizeOnDisk, 'number', `${archive.id} ${disk.id}: sizeOnDisk must be a number`)
assert.ok(disk.sizeOnDisk > 0, `${archive.id} ${disk.id}: sizeOnDisk must be higher than 0`)
totalDiskSizeOnDisk += disk.sizeOnDisk
}
assert.strictEqual(
archive.sizeOnDisk,
totalDiskSizeOnDisk,
`${archive.id}: disks sizeOnDisk sum should match archive sizeOnDisk`
)
} else {
assert.deepStrictEqual(archive.disks, [], `${archive.id}: disks should be empty`)
}
}
}

View File

@@ -1,11 +1,9 @@
import {
Body,
Delete,
Example,
Extension,
Get,
Middlewares,
Patch,
Path,
Put,
Query,
@@ -18,9 +16,8 @@ import {
} from 'tsoa'
import { inject } from 'inversify'
import { provide } from 'inversify-binding-decorators'
import { invalidParameters } from 'xo-common/api-errors.js'
import { json, NextFunction, Request as ExRequest, Response as ExResponse } from 'express'
import type { EditNetworkProps, XoAlarm, XoMessage, XoNetwork, XoTask } from '@vates/types'
import { Request as ExRequest } from 'express'
import type { XoAlarm, XoMessage, XoNetwork, XoTask } from '@vates/types'
import { AlarmService } from '../alarms/alarm.service.mjs'
import { escapeUnsafeComplexMatcher } from '../helpers/utils.helper.mjs'
@@ -29,8 +26,6 @@ import { network, networkIds, partialNetworks } from '../open-api/oa-examples/ne
import {
badRequestResp,
forbiddenOperationResp,
internalServerErrorResp,
invalidParameters as invalidParametersResp,
noContentResp,
notFoundResp,
unauthorizedResp,
@@ -41,60 +36,7 @@ import type { SendObjects } from '../helpers/helper.type.mjs'
import { XapiXoController } from '../abstract-classes/xapi-xo-controller.mjs'
import { messageIds, partialMessages } from '../open-api/oa-examples/message.oa-example.mjs'
import { partialTasks, taskIds } from '../open-api/oa-examples/task.oa-example.mjs'
import { acl, actionsFromBody } from '../middlewares/acl.middleware.mjs'
import type { AuthenticatedRequest } from '../helpers/helper.type.mjs'
// the fields come from EditNetworkProps, so a field added there reaches the body too; MTU and insecureNbd
// are redeclared only to carry their tsoa JSDoc (validation and description in the OpenAPI spec)
type UpdateNetworkRequestBody = Omit<EditNetworkProps, 'MTU' | 'insecureNbd'> & {
/**
* @isInt
* @minimum 68 the MTU must be at least 68 (RFC 791)
*/
MTU?: number
/**
* NBD in clear, only on a network dedicated to backups. Mutually exclusive with `nbd`
*/
insecureNbd?: boolean
}
// the privileges a PATCH checks: update:<field> for each field in the body, and the other NBD
// purpose when one is set, since the XAPI side removes it (setNbdPurposes in
// xo-server/src/xapi/mixins/networking.mjs): nbd: true removes insecure_nbd, insecureNbd: true removes nbd
export function updateNetworkActions({ req }: { req: AuthenticatedRequest }) {
const actions = actionsFromBody<'network'>([
'update:automatic',
'update:defaultIsLocked',
'update:insecureNbd',
'update:MTU',
'update:name_description',
'update:name_label',
'update:nbd',
])({ req })
const body: UpdateNetworkRequestBody = req.body
if (body.insecureNbd === true) {
actions.push('update:nbd')
}
if (body.nbd === true) {
actions.push('update:insecureNbd')
}
return actions
}
// runs before acl(): a body with no gated field gets no privilege checked, so it is refused here, for a missing
// network too. Refusing it in the handler, after the ACL has resolved the network, would answer 404 for a missing
// network and 422 for an existing one, which tells them apart
export function refuseEmptyUpdate(req: AuthenticatedRequest, _res: ExResponse, next: NextFunction) {
if (updateNetworkActions({ req }).length > 0) {
return next()
}
// the api-errors factories throw, so the error is caught to reach next()
try {
invalidParameters('the body must contain at least one field to update')
} catch (error) {
return next(error)
}
}
import { acl } from '../middlewares/acl.middleware.mjs'
@Route('networks')
@Security('*')
@@ -152,56 +94,6 @@ export class NetworkController extends XapiXoController<XoNetwork> {
return this.getObject(id as XoNetwork['id'])
}
/**
* Partial update of a network: only the fields present in the body are modified.
*
* Changing `MTU` unplugs and replugs the network's PIFs and the VIFs of its running VMs: their
* traffic is briefly interrupted.
* `nbd` and `insecureNbd` are mutually exclusive; setting one to `false` only removes that purpose.
* `automatic` adds the network to new VMs automatically; `defaultIsLocked` blocks the traffic of
* VIFs with no allowed IP.
* A body with none of the fields below is refused with a 422, whether or not the network exists.
*
* Required privilege per field provided in the body:
* - resource: network, action: update:&lt;field&gt;
* - and with `nbd: true`, also resource: network, action: update:insecureNbd (it removes the
* insecure NBD purpose); with `insecureNbd: true`, also action: update:nbd (it removes the NBD purpose)
*
* @example id "9fe12ca3-d75d-cfb0-492e-cfd2bc6c568f"
* @example body { "name_label": "backups", "MTU": 9000, "insecureNbd": true }
*/
@Extension('x-mcp-exposure', 'confirm')
@Patch('{id}')
@Middlewares([
json(),
refuseEmptyUpdate,
acl({
resource: 'network',
actions: updateNetworkActions,
objectId: 'params.id',
}),
])
@SuccessResponse(noContentResp.status, noContentResp.description)
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
@Response(notFoundResp.status, notFoundResp.description)
@Response(invalidParametersResp.status, invalidParametersResp.description)
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
async updateNetwork(@Path() id: string, @Body() body: UpdateNetworkRequestBody): Promise<void> {
const networkId = id as XoNetwork['id']
const { automatic, defaultIsLocked, insecureNbd, MTU, name_description, name_label, nbd } = body
// forward only the declared fields: the ACL above checked their privileges and the NBD purpose each one removes
await this.getXapi(networkId).editNetwork(networkId, {
automatic,
defaultIsLocked,
insecureNbd,
MTU,
name_description,
name_label,
nbd,
})
}
/**
* Required privilege:
* - resource: network, action: delete

View File

@@ -1,90 +0,0 @@
import assert from 'node:assert/strict'
import { describe, it, mock } from 'node:test'
import { getMissingPrivileges, type AnyPrivilege, type AnyPrivilegeOnParam } from '@xen-orchestra/acl'
import type { XoUser } from '@vates/types'
import type { NextFunction, Response } from 'express'
import { invalidParameters } from 'xo-common/api-errors.js'
import { NetworkController, refuseEmptyUpdate, updateNetworkActions } from './network.controller.mjs'
import type { AuthenticatedRequest } from '../helpers/helper.type.mjs'
import type { RestApi } from '../rest-api/rest-api.mjs'
const user = { id: 'user-1', permission: 'none' } as XoUser
const network = { id: 'network-1' }
const NETWORK_ID = '9fe12ca3-d75d-cfb0-492e-cfd2bc6c568f'
function missingPrivileges(body: object, userPrivileges: AnyPrivilege[]) {
const req = { body } as AuthenticatedRequest
const params = updateNetworkActions({ req }).map(
action => ({ user, resource: 'network', action, objects: [network] }) as AnyPrivilegeOnParam
)
return getMissingPrivileges(params, userPrivileges)
}
describe('updateNetworkActions', () => {
it('refuses insecureNbd: true to a user with only update:insecureNbd, as it removes the nbd purpose', () => {
const privileges = [
{ id: 'privilege-1', resource: 'network', action: 'update:insecureNbd', effect: 'allow', roleId: 'role-1' },
] as unknown as AnyPrivilege[]
const missing = missingPrivileges({ insecureNbd: true }, privileges)
assert.equal(missing.length, 1)
assert.equal(missing[0].action, 'update:nbd')
})
})
describe('refuseEmptyUpdate', () => {
it('refuses an empty body with a 422 before the ACL resolves the network', () => {
const next = mock.fn()
refuseEmptyUpdate({ body: {} } as AuthenticatedRequest, {} as Response, next as NextFunction)
assert.equal(next.mock.callCount(), 1)
assert.ok(invalidParameters.is(next.mock.calls[0].arguments[0]))
})
})
describe('NetworkController.updateNetwork', () => {
it('forwards only the seven declared fields to editNetwork, with the id the route got', async () => {
const editCalls: unknown[][] = []
const restApi = {
xoApp: {
getXapi: () => ({
editNetwork: async (...args: unknown[]) => {
editCalls.push(args)
},
}),
},
} as unknown as RestApi
const controller = new NetworkController(restApi, {} as never)
// not an object literal passed inline: an extra key is only allowed on a value, not on a fresh literal
const body = {
automatic: true,
defaultIsLocked: false,
insecureNbd: false,
MTU: 9000,
name_description: 'description',
name_label: 'label',
nbd: true,
notAField: 'dropped',
}
await controller.updateNetwork(NETWORK_ID, body)
assert.deepEqual(editCalls, [
[
NETWORK_ID,
{
automatic: true,
defaultIsLocked: false,
insecureNbd: false,
MTU: 9000,
name_description: 'description',
name_label: 'label',
nbd: true,
},
],
])
})
})

View File

@@ -1,62 +1,10 @@
import { invalidParameters } from 'xo-common/api-errors.js'
import type { CreateBondedNetworkBody, CreateInternalNetworkBody, CreateNetworkBody } from '../pools/pool.type.mjs'
import type { AuthenticatedRequest, ReplaceKey } from '../helpers/helper.type.mjs'
import type { NextFunction, Response as ExResponse } from 'express'
import type { ReplaceKey } from '../helpers/helper.type.mjs'
import type { RestApi } from '../rest-api/rest-api.mjs'
import type { Xapi, XenApiNetworkWrapped, XoNetwork, XoPool } from '@vates/types'
type NetworkCreateNames = Pick<
CreateNetworkBody,
'name' | 'name_label' | 'description' | 'name_description' | 'mtu' | 'MTU'
>
// maps the names the create routes accept to the ones xapi.createNetwork reads (name, description, mtu), and
// refuses a body giving both spellings of one field or no name. The create routes call it before their task
// starts, so the refusal is a 422 and not a failed task
export function normalizeNetworkCreateBody<T extends NetworkCreateNames>(body: T) {
const { name, name_label, description, name_description, mtu, MTU, ...rest } = body
if (name !== undefined && name_label !== undefined) {
throw invalidParameters('give either name or name_label, not both')
}
if (description !== undefined && name_description !== undefined) {
throw invalidParameters('give either description or name_description, not both')
}
if (mtu !== undefined && MTU !== undefined) {
throw invalidParameters('give either mtu or MTU, not both')
}
const networkName = name_label ?? name
if (networkName === undefined) {
throw invalidParameters('name_label is required')
}
return {
...rest,
name: networkName,
description: name_description ?? description,
mtu: MTU ?? mtu,
}
}
// runs before acl(): acl() awaits its object callback outside any try, and Express 4 does not catch that rejection,
// so a refusal thrown there would hang the request. Checked here, the callback below can't throw
export function refuseInvalidNetworkCreateBody(req: AuthenticatedRequest, _res: ExResponse, next: NextFunction) {
try {
normalizeNetworkCreateBody(req.body)
} catch (error) {
return next(error)
}
next()
}
// the ACL checks the privileges against the names xapi reads, so the selectors written on name, description and
// mtu match whatever spelling the client used
export function networkCreateAclObject({ req }: { req: AuthenticatedRequest }) {
return normalizeNetworkCreateBody(req.body)
}
export class NetworkService {
#restApi: RestApi
@@ -64,12 +12,9 @@ export class NetworkService {
this.#restApi = restApi
}
// body must come from normalizeNetworkCreateBody
async create(
poolId: XoPool['id'],
body: (ReplaceKey<CreateNetworkBody, 'pif', 'pifId'> | CreateBondedNetworkBody | CreateInternalNetworkBody) & {
name: string
}
body: ReplaceKey<CreateNetworkBody, 'pif', 'pifId'> | CreateBondedNetworkBody | CreateInternalNetworkBody
): Promise<XoNetwork['id']> {
const { nbd, insecureNbd, ...rest } = body
if (nbd && insecureNbd) {

View File

@@ -1,43 +0,0 @@
import assert from 'node:assert/strict'
import { describe, it } from 'node:test'
import { invalidParameters } from 'xo-common/api-errors.js'
import { networkCreateAclObject, normalizeNetworkCreateBody } from './network.service.mjs'
describe('normalizeNetworkCreateBody', () => {
it('maps name_label, name_description and MTU to the names xapi.createNetwork reads', () => {
const body = normalizeNetworkCreateBody({
name_label: 'label',
name_description: 'description',
MTU: 9000,
vlan: 0,
})
assert.deepEqual(body, { name: 'label', description: 'description', mtu: 9000, vlan: 0 })
})
it('still accepts the deprecated name, description and mtu', () => {
const body = normalizeNetworkCreateBody({ name: 'label', description: 'description', mtu: 1450 })
assert.deepEqual(body, { name: 'label', description: 'description', mtu: 1450 })
})
it('refuses a body giving both spellings of one field', () => {
assert.throws(() => normalizeNetworkCreateBody({ name: 'a', name_label: 'b' }), invalidParameters.is)
assert.throws(
() => normalizeNetworkCreateBody({ name_label: 'a', description: 'b', name_description: 'c' }),
invalidParameters.is
)
assert.throws(() => normalizeNetworkCreateBody({ name_label: 'a', mtu: 1450, MTU: 9000 }), invalidParameters.is)
})
it('refuses a body with no name', () => {
assert.throws(() => normalizeNetworkCreateBody({ name_description: 'description' }), invalidParameters.is)
})
it('gives the ACL the old keys for a body sent with the new names', () => {
const req = { body: { name_label: 'label', name_description: 'description', MTU: 9000 } }
assert.deepEqual(networkCreateAclObject({ req } as never), { name: 'label', description: 'description', mtu: 9000 })
})
})

View File

@@ -12,14 +12,19 @@ export const partialBackupArchives = [
id: '/xo-vm-backups/6ef7c09e-677b-1e6f-0546-7ab30413c61c/vdis/8b650248-ddd6-4188-ad8b-c0502865ac6c/f1f3c902-dcaa-4ec6-943e-6162c9d85fb2/20250801T080832Z.vhd',
name: 'debian 12 hub disk',
uuid: 'cbe1e3ba-8e5c-4c79-9e4d-708144518d50',
sizeOnDisk: 52428800,
isDifferencing: true,
},
{
id: '/xo-vm-backups/6ef7c09e-677b-1e6f-0546-7ab30413c61c/vdis/8b650248-ddd6-4188-ad8b-c0502865ac6c/870e6142-d4e4-4622-bd19-6b101c8da3cc/20250801T080832Z.vhd',
name: 'XO CloudConfigDrive',
uuid: 'bea8193d-80ba-4a72-94e4-901f03ffc225',
sizeOnDisk: 1048576,
isDifferencing: true,
},
],
href: '/rest/v0/backup-archives/231264c3-af43-4ec0-a3be-394c5b1fdbfc/xo-vm-backups/6ef7c09e-677b-1e6f-0546-7ab30413c61c/20250801T080832Z.json',
sizeOnDisk: 53477376,
},
{
id: '1af95910-01b4-4e87-9c2f-d895cafe0776/xo-vm-backups/7cf6150f-a978-09e6-6b41-0d1d41967bdc/20250918T132942Z.json',
@@ -29,9 +34,12 @@ export const partialBackupArchives = [
id: '/xo-vm-backups/803c2676-c309-721e-7123-e6c3de854c32/vdis/ce91bf34-099c-4241-a608-3373f101c02b/7384cf5a-3202-4a21-bfd0-8da467449fa6/20250916T144850Z.vhd',
name: 'AlmaLinux 9_ivopu',
uuid: '73ed06ed-fdc8-43ef-a1c4-253e9005fbe0',
sizeOnDisk: 100000,
isDifferencing: false,
},
],
href: '/rest/v0/backup-archives/1af95910-01b4-4e87-9c2f-d895cafe0776/xo-vm-backups/7cf6150f-a978-09e6-6b41-0d1d41967bdc/20250918T132942Z.json',
sizeOnDisk: 100000,
},
]
@@ -52,13 +60,16 @@ export const backupArchive = {
id: '/xo-vm-backups/7cf6150f-a978-09e6-6b41-0d1d41967bdc/vdis/f2599aa4-7bb4-434b-bf71-cf0ebe1e06a4/007e4f3e-6315-4779-aab5-461b519836f3/20250918T132942Z.alias.vhd',
name: 'min-alpine-mra_alegi',
uuid: 'c922ef3c-9d76-4482-87f8-a4da5849ee45',
sizeOnDisk: 1048576,
isDifferencing: true,
},
],
id: '1af95910-01b4-4e87-9c2f-d895cafe0776/xo-vm-backups/7cf6150f-a978-09e6-6b41-0d1d41967bdc/20250918T132942Z.json',
jobId: 'f2599aa4-7bb4-434b-bf71-cf0ebe1e06a4',
mode: 'delta',
scheduleId: '8db1c2da-2635-436f-8f78-62079fea3aa6',
size: 0,
size: 2058370,
sizeOnDisk: 1048576,
timestamp: 1758202182963,
vm: {
uuid: '7cf6150f-a978-09e6-6b41-0d1d41967bdc',

View File

@@ -320,19 +320,22 @@ export const vmDashboard = {
id: '1af95910-01b4-4e87-9c2f-d895cafe0776//xo-vm-backups/613f541c-4bed-fc77-7ca8-2db6b68f079c/20251102T230026Z.json',
timestamp: 1762124426346,
backupRepository: '1af95910-01b4-4e87-9c2f-d895cafe0776',
size: 0,
size: 1058370,
sizeOnDisk: 48576,
},
{
id: '1af95910-01b4-4e87-9c2f-d895cafe0776//xo-vm-backups/613f541c-4bed-fc77-7ca8-2db6b68f079c/20251101T230026Z.json',
timestamp: 1762038026319,
backupRepository: '1af95910-01b4-4e87-9c2f-d895cafe0776',
size: 0,
size: 2058370,
sizeOnDisk: 1048576,
},
{
id: '1af95910-01b4-4e87-9c2f-d895cafe0776//xo-vm-backups/613f541c-4bed-fc77-7ca8-2db6b68f079c/20251031T230025Z.json',
timestamp: 1761951625256,
backupRepository: '1af95910-01b4-4e87-9c2f-d895cafe0776',
size: 0,
size: 3058370,
sizeOnDisk: 2048576,
},
],
},

View File

@@ -95,12 +95,7 @@ import { PoolService } from './pool.service.mjs'
import { BASE_URL, escapeUnsafeComplexMatcher, NDJSON_CONTENT_TYPE } from '../helpers/utils.helper.mjs'
import { messageIds, partialMessages } from '../open-api/oa-examples/message.oa-example.mjs'
import type { CreateActionReturnType } from '../abstract-classes/base-controller.mjs'
import {
NetworkService,
networkCreateAclObject,
normalizeNetworkCreateBody,
refuseInvalidNetworkCreateBody,
} from '../networks/network.service.mjs'
import { NetworkService } from '../networks/network.service.mjs'
import { v2vStartResult } from '../open-api/oa-examples/v2v.oa-example.mjs'
import { V2V_TASK_PROPERTY } from '@vates/types'
import { V2vService, V2V_TASK_NAME } from '../v2v/v2v.service.mjs'
@@ -185,8 +180,8 @@ export class PoolController extends XapiXoController<XoPool> {
*
* @example id "355ee47d-ff4c-4924-3db2-fd86ae629676"
* @example body {
* "name_label": "awes0me_network",
* "name_description": "random description",
* "name": "awes0me_network",
* "description": "random description",
* "pif": "ad15b2c8-3d9a-194e-c43a-e3dcda74b256",
* "vlan": 0
* }
@@ -197,11 +192,10 @@ export class PoolController extends XapiXoController<XoPool> {
@Post('{id}/actions/create_network')
@Middlewares([
json(),
refuseInvalidNetworkCreateBody,
acl([
// these two rights are a bit redundant, but for now this is the only way to restrict network creation on a given pool
{ resource: 'pool', action: 'create:network', objectId: 'params.id' },
{ resource: 'network', action: 'create', object: networkCreateAclObject },
{ resource: 'network', action: 'create', object: ({ req }) => req.body },
]),
])
@Tags('networks')
@@ -217,8 +211,8 @@ export class PoolController extends XapiXoController<XoPool> {
@Query() sync?: boolean
): CreateActionReturnType<{ id: Unbrand<XoNetwork>['id'] }> {
const poolId = id as XoPool['id']
const { pif, ...rest } = normalizeNetworkCreateBody(body)
const action = async () => {
const { pif, ...rest } = body
const networkId = await this.#networkService.create(poolId, { pifId: pif as XoPif['id'], ...rest })
return { id: networkId }
@@ -242,8 +236,8 @@ export class PoolController extends XapiXoController<XoPool> {
*
* @example id "355ee47d-ff4c-4924-3db2-fd86ae629676"
* @example body {
* "name_label": "awes0me_bonded_network",
* "name_description": "random description",
* "name": "awes0me_bonded_network",
* "description": "random description",
* "pifIds": ["ad15b2c8-3d9a-194e-c43a-e3dcda74b256", "7b6bed50-26b2-bd27-8f3a-1b5a81989a92"],
* "bondMode": "lacp"
* }
@@ -254,10 +248,9 @@ export class PoolController extends XapiXoController<XoPool> {
@Post('{id}/actions/create_bonded_network')
@Middlewares([
json(),
refuseInvalidNetworkCreateBody,
acl([
{ resource: 'pool', action: 'create:network', objectId: 'params.id' },
{ resource: 'network', action: 'create', object: networkCreateAclObject },
{ resource: 'network', action: 'create', object: ({ req }) => req.body },
]),
])
@Tags('networks')
@@ -273,8 +266,8 @@ export class PoolController extends XapiXoController<XoPool> {
@Query() sync?: boolean
): CreateActionReturnType<{ id: Unbrand<XoNetwork>['id'] }> {
const poolId = id as XoPool['id']
const { pifIds, ...rest } = normalizeNetworkCreateBody(body)
const action = async () => {
const { pifIds, ...rest } = body
const networkId = await this.#networkService.create(poolId, { pifIds: pifIds as XoPif['id'][], ...rest })
return { id: networkId }
@@ -298,8 +291,8 @@ export class PoolController extends XapiXoController<XoPool> {
*
* @example id "355ee47d-ff4c-4924-3db2-fd86ae629676"
* @example body {
* "name_label": "awes0me_internal_network",
* "name_description": "random description"
* "name": "awes0me_internal_network",
* "description": "random description"
* }
*/
@Example(taskLocation)
@@ -308,10 +301,9 @@ export class PoolController extends XapiXoController<XoPool> {
@Post('{id}/actions/create_internal_network')
@Middlewares([
json(),
refuseInvalidNetworkCreateBody,
acl([
{ resource: 'pool', action: 'create:network', objectId: 'params.id' },
{ resource: 'network', action: 'create', object: networkCreateAclObject },
{ resource: 'network', action: 'create', object: ({ req }) => req.body },
]),
])
@Tags('networks')
@@ -327,9 +319,8 @@ export class PoolController extends XapiXoController<XoPool> {
@Query() sync?: boolean
): CreateActionReturnType<{ id: Unbrand<XoNetwork>['id'] }> {
const poolId = id as XoPool['id']
const networkBody = normalizeNetworkCreateBody(body)
const action = async () => {
const networkId = await this.#networkService.create(poolId, networkBody)
const networkId = await this.#networkService.create(poolId, body)
return { id: networkId }
}

View File

@@ -12,28 +12,13 @@ import type {
} from '@vates/types'
import { Unbrand } from '../open-api/common/response.common.mjs'
// the names are the ones PATCH /networks/{id} takes (name_label, name_description, MTU); name, description and mtu
// are the names these routes took before and still work. tsoa cannot express "exactly one of", so name and
// name_label are both optional here and normalizeNetworkCreateBody (network.service.mts) refuses a body with neither
type BaseCreateNetworkBody = {
/**
* @deprecated use `name_label`
*/
name?: string
name_label?: string
/**
* @deprecated use `name_description`
*/
name: string
description?: string
name_description?: string
/**
* @deprecated use `MTU`
*/
mtu?: number
/**
* @default 1500
*/
MTU?: number
mtu?: number
nbd?: boolean
/**
* NBD in clear, only on a network dedicated to backups. Mutually exclusive with `nbd`

View File

@@ -33,6 +33,7 @@ import type {
XoVdi,
XoVm,
XoVmSnapshot,
XoVmTemplate,
XoMessage,
XoNetwork,
XoVif,
@@ -638,6 +639,51 @@ export class VmController extends XapiXoController<XoVm> {
})
}
/**
* The VM must be halted. Removable media (e.g. CDs) are ejected before the conversion.
*
* The template keeps the same ID as the VM and is then available under `/vm-templates/{id}`.
*
* Required privilege:
* - resource: vm, action: convert-to-template
*
* @example id "f07ab729-c0e8-721c-45ec-f11276377030"
*/
@Example(taskLocation)
@Extension('x-mcp-exposure', 'confirm')
@Post('{id}/actions/convert_to_template')
@Middlewares(acl({ resource: 'vm', action: 'convert-to-template', objectId: 'params.id' }))
@SuccessResponse(asynchronousActionResp.status, asynchronousActionResp.description)
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
@Response(createdResp.status, 'Template created')
@Response(notFoundResp.status, notFoundResp.description)
@Response(incorrectStateResp.status, incorrectStateResp.description)
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
async convertVmToTemplate(
@Path() id: string,
@Query() sync?: boolean
): CreateActionReturnType<{ id: Unbrand<XoVmTemplate>['id'] }> {
const vmId = id as XoVm['id']
const action = async () => {
await this.#vmService.convertToTemplate(vmId)
if (sync) {
this.setHeader('Location', `${BASE_URL}/vm-templates/${vmId}`)
}
return { id: vmId }
}
return this.createAction<{ id: Unbrand<XoVmTemplate>['id'] }>(action, {
sync,
statusCode: createdResp.status,
taskProperties: {
name: 'convert VM to template',
objectId: vmId,
},
})
}
/**
* Required privilege:
* - resource: vm, action: revert-snapshot

View File

@@ -22,6 +22,7 @@ import {
type XoVmTemplate,
} from '@vates/types'
import { Response as ExResponse } from 'express'
import { incorrectState } from 'xo-common/api-errors.js'
import { Readable, Writable } from 'node:stream'
import type { CreateVmAfterCreateParams, CreateVmParams } from '../pools/pool.type.mjs'
@@ -242,6 +243,22 @@ export class VmService {
await xoApp.getXapi(id).editVm(id, editProps)
}
async convertToTemplate(id: XoVm['id']): Promise<void> {
const vm = this.#restApi.getObject<XoVm>(id, 'VM')
// Checked before ejecting the media, so a VM that cannot be converted is left untouched
if (vm.power_state !== VM_POWER_STATE.HALTED) {
throw incorrectState({
actual: vm.power_state,
expected: VM_POWER_STATE.HALTED,
object: vm.id,
property: 'power_state',
})
}
const xapiVm = this.#restApi.getXapiObject<XoVm>(id, 'VM')
await xapiVm.$xapi.VM_convertToTemplate(xapiVm.$ref)
}
#getDashboardQuickInfo(id: XoVm['id']): VmDashboard['quickInfo'] {
const {
power_state,
@@ -429,7 +446,13 @@ export class VmService {
.flatMap(backupArchiveByVm => backupArchiveByVm[vm.id] ?? [])
.sort((a, b) => b.timestamp - a.timestamp)
.splice(0, 3)
.map(ba => ({ id: ba.id, timestamp: ba.timestamp, backupRepository: ba.backupRepository, size: ba.size }))
.map(ba => ({
id: ba.id,
timestamp: ba.timestamp,
backupRepository: ba.backupRepository,
size: ba.size,
sizeOnDisk: ba.sizeOnDisk,
}))
}
async getVmDashboard(id: XoVm['id'], { stream }: { stream?: Writable } = {}): Promise<VmDashboard> {

View File

@@ -23,6 +23,7 @@ type VmDashboardBackupArchive = {
timestamp: XoVmBackupArchive['timestamp']
backupRepository: XoVmBackupArchive['backupRepository']
size: XoVmBackupArchive['size']
sizeOnDisk?: XoVmBackupArchive['sizeOnDisk']
}
export type VmDashboard = {

View File

@@ -172,6 +172,18 @@ These classes MUST be used to ensure the typography is consistent across all com
>
> `<div class="typo-body-regular` />
## Component MUST use the z-index variables
A z-index only means something compared to the others: a menu, a select dropdown and a modal can all show at the same time. To keep them in the right order, each layer is a variable of the [z-index file](../../lib/assets/css/_z-indexes.pcss), from bottom to top:
- `--z-index-panel`: the sidebar, the side panels and the mobile menu laid over the page, and the backdrop under them
- `--z-index-popup`: the popups opened from the page (menus), which stay under an overlay opened from one of their items
- `--z-index-overlay-backdrop` and `--z-index-overlay`: the overlays (modals, drawers) and their backdrop
- `--z-index-overlay-popup`: the popups above the overlays: the menus opened from the current overlay, and the select dropdowns, which close as soon as something else is clicked
- `--z-index-tooltip`: the tooltips, above everything
Use the variable of the layer the element belongs to rather than a number. If none fits, add a layer to the file.
## New CSS features support
We try to keep up to date with new CSS features and use them when they address a problem or specific integration use case.

View File

@@ -18,6 +18,7 @@
# Directives
- [vRestricted](../lib/directives/restricted.directive.md)
- [vTooltip](../lib/directives/tooltip.directive.md)
# Utils

View File

@@ -65,6 +65,10 @@ Testing uses **Vitest 5** with a single `unit` project (see `vitest.config.ts`):
| `test/mount-with-select.ts` | `renderSelect(id, { accent?, ref? }, slots?)`: renders the `VtsSelect` of a select id, `neutral` accent by default; `mountSelect`: a `VtsSelect` of string sources, its config, accent, wrapper message, option slot and a callback receiving the mounted select |
| `test/find-title.ts` | `findTitle`: the `.title` of a `VtsSuccessStateHero` or a list item, `undefined` without one (also used by XO 6) |
| `test/create-task-item.ts` | `createTaskItem`: a `Task` as the task lists display it, with the given overrides (also used by XO 6) |
| `test/overlay.ts` | `registerOverlay(key?)`: an open overlay in the store of the last mounted wrapper, on top of those already open; `provideOverlayKey(key)`: what that overlay provides to its content, nothing without a key |
| `test/query-builder.ts` | `getLabels`: the label of each property of a query builder schema, or of each value of an operator, by its key (also used by XO 6); `useSchemaWithOptionalTag`: a schema of a name and a tag offered once `hasTag` is set, called in a setup; `getFirstFilter` (also used by XO 6), `findPropertyLabels`: the first filter of a group and the label of each property it offers |
| `test/find-tooltip-contents.ts` | `findTooltipContents`: the content of every tooltip currently shown, in order |
| `test/hover.ts` | `hover`: moves the mouse over an element |
| `tsconfig.vitest.json` | Type-checks test files with the Vitest globals and the `@core-test` alias |
| `tsconfig.app.json` | Type-checks the library, test files excluded |

View File

@@ -0,0 +1,8 @@
:root {
--z-index-panel: 1010;
--z-index-popup: 1011;
--z-index-overlay-backdrop: 1015;
--z-index-overlay: 1016;
--z-index-overlay-popup: 1020;
--z-index-tooltip: 999999;
}

View File

@@ -3,6 +3,7 @@
@import '_fonts.pcss';
@import '_context.pcss';
@import '_shadows.pcss';
@import '_z-indexes.pcss';
@import '_typography.pcss';
:root {

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