Compare commits

..

80 Commits

Author SHA1 Message Date
Thierry Goettelmann
26bd093efb 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-02 10:38:28 +01:00
Thierry Goettelmann
3278c5a257 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-02 10:38:28 +01:00
Thierry Goettelmann
d41de74e01 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-02 10:38:28 +01:00
Thierry Goettelmann
43617968e7 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-02 10:38:27 +01:00
Thierry Goettelmann
1194f91fa4 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-02 10:38:25 +01:00
Thierry Goettelmann
dfdb8c7703 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-02 10:38:25 +01:00
Thierry Goettelmann
65157be841 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-02 10:38:25 +01:00
Thierry Goettelmann
000016c00c 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-02 10:38:25 +01:00
Thierry Goettelmann
3a4bc5cb3e 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-02 10:38:24 +01:00
Thierry Goettelmann
26a9d4d105 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-02 10:38:24 +01:00
Thierry Goettelmann
aeb1222037 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-02 10:38:24 +01:00
Thierry Goettelmann
a7c0c017a6 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-02 10:38:24 +01:00
Thierry Goettelmann
2b98689656 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-02 10:38:24 +01:00
Thierry Goettelmann
d86917f0c0 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-02 10:38:24 +01:00
Thierry Goettelmann
8279f3153d chore(xo6): drop XO6/ prefix from changelog entries 2026-12-02 10:38:23 +01:00
Thierry Goettelmann
39dfc5ee46 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-02 10:38:22 +01:00
Thierry Goettelmann
4608251950 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-02 10:38:21 +01:00
Thierry Goettelmann
b44333596c 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-02 10:38:21 +01:00
Thierry Goettelmann
a0f3436613 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-02 10:38:21 +01:00
Thierry Goettelmann
88fbfd1a7e 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-02 10:38:17 +01:00
Thierry Goettelmann
2ad7d19662 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-02 10:38:17 +01:00
Thierry Goettelmann
e41c89d25b 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-02 10:38:17 +01:00
Thierry Goettelmann
3e2b11bb2d 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-02 10:38:17 +01:00
Thierry Goettelmann
0ae2e903b9 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-02 10:38:17 +01:00
Thierry Goettelmann
bb887c46f6 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-02 10:38:17 +01:00
Thierry Goettelmann
758f07c7b5 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-02 10:38:17 +01:00
Thierry Goettelmann
480d34bac2 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-02 10:38:16 +01:00
Thierry Goettelmann
e9aca6b844 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-02 10:38:16 +01:00
Thierry Goettelmann
8d7a072156 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-02 10:38:16 +01:00
Thierry Goettelmann
3aefa5ee86 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-02 10:38:16 +01:00
Thierry Goettelmann
b3a39c45da 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-02 10:38:16 +01:00
Thierry Goettelmann
bb144ba2df 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-02 10:38:16 +01:00
Thierry Goettelmann
83abb31558 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-02 10:38:16 +01:00
Thierry Goettelmann
4e6bde5d99 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-02 10:38:16 +01:00
Thierry Goettelmann
f0937427ad 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-02 10:38:15 +01:00
Thierry Goettelmann
886637cf11 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-02 10:38:15 +01:00
Thierry Goettelmann
bc402c6c2d 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-02 10:38:15 +01:00
Thierry Goettelmann
388e48b3d1 feat(xo6/group): add groups list in user management page (#10272) 2026-12-02 10:38:14 +01:00
Marie Garde
c0e7843274 feat(xo6): fix style backup job form (#10940)
* wip

* fix style on form

* fix checkbox and radio button in DS

* fix pipeline

* fix tests

* remove version DS

* edit style

* fix tests

* fix build

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

* rebase ok

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

🔗 XO-3352

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

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

* feat: scope urlencode middleware to signin routes

* feat: cookie sameSite default to lax

* changelog

---------

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

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

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

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

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

* feat(@vates/types): 3.1.0

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

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

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

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

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

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

* feat(xo-server): 5.214.1

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

* add changelog

* changing logs display and unblocking non-locked tasks

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

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

    stream has ended without data, was looking for 8 bytes

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

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

Introduced by #10381

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

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

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

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

* docs(v2v): flag the guide as new and the XO 5 section as legacy
2026-11-25 09:52:27 +01:00
spacotte-vates
2a4491aeda fix(backup-jobs): fix issues on backup job creation from the REST API (#10779)
* fix(rest-api): backup-job schedule settings lost on creation
* fix(backup-jobs): fix mirror and metadata job failing due to targeting backup repo with expression
* feat(backup-jobs): add expression support for vms and pools
* fix(rest-api): add filter support to backup-jobs
2026-11-25 09:44:12 +01:00
676 changed files with 20565 additions and 31041 deletions

View File

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

View File

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

View File

@@ -13,7 +13,7 @@
"url": "https://vates.fr"
},
"license": "ISC",
"version": "3.7.1",
"version": "3.7.2",
"engines": {
"node": ">=14.0"
},

View File

@@ -37,7 +37,7 @@ exports.merge = merge
const obfuscate = value => replace(value, OBFUSCATED_VALUE)
exports.obfuscate = obfuscate
const SENSITIVE_PARAMS = ['token', 'passphrase', /password/i, /private_?key/i, 'encryptionKey']
const SENSITIVE_PARAMS = ['token', 'passphrase', /password/i, 'encryptionKey']
const isSensitiveParam = name =>
SENSITIVE_PARAMS.some(pattern => (typeof pattern === 'string' ? pattern === name : pattern.test(name)))
@@ -83,7 +83,7 @@ const SMB_CREDENTIALS_RE = /^(smb:\/\/)[^\0]*@/i
// URL encoded and end at the first `@`, see https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.1
const URL_CREDENTIALS_RE = /([a-z][a-z\d+.-]*:\/\/)[^\s/?#@]*@/gi
// e.g. `?encryptionKey=` in a backup repository URL, same names as SENSITIVE_PARAMS (private keys aside: never in a URL)
// e.g. `?encryptionKey=` in a backup repository URL, same names as SENSITIVE_PARAMS
const SENSITIVE_QUERY_PARAM_RE = /([?&](?:encryptionKey|passphrase|token|[^=&#\s]*password[^=&#\s]*)=)[^&#\s]*/gi
// replaces the credentials and the sensitive query parameters of the URLs in a string

View File

@@ -3,7 +3,7 @@
const { describe, it } = require('node:test')
const assert = require('node:assert/strict')
const { merge, obfuscate, OBFUSCATED_VALUE, redact, redactUrls, replace } = require('./')
const { obfuscate, OBFUSCATED_VALUE, redact, redactUrls } = require('./')
describe('redact()', () => {
it('replaces sensitive entries at any depth, whatever their type, and keeps the keys', () => {
@@ -92,54 +92,3 @@ describe('redactUrls()', () => {
assert.equal(redactUrls('user:pass@host'), 'user:pass@host')
})
})
describe('replace()', () => {
it('replaces the sensitive string params, recursively', () => {
assert.deepEqual(
replace(
{
host: 'example.org',
password: 'secret',
adminPassword: 'secret',
passphrase: 'secret',
token: 'secret',
encryptionKey: 'secret',
privateKey: 'secret',
private_key: 'secret',
sshPrivateKey: 'secret',
nested: [{ privatekey: 'secret', username: 'root' }],
},
'X'
),
{
host: 'example.org',
password: 'X',
adminPassword: 'X',
passphrase: 'X',
token: 'X',
encryptionKey: 'X',
privateKey: 'X',
private_key: 'X',
sshPrivateKey: 'X',
nested: [{ privatekey: 'X', username: 'root' }],
}
)
})
it('keeps non string values', () => {
assert.deepEqual(replace({ password: null, privateKey: undefined, token: 42 }, 'X'), {
password: null,
privateKey: undefined,
token: 42,
})
})
})
describe('obfuscate() and merge()', () => {
it('merge() restores the obfuscated values', () => {
const value = { username: 'root', privateKey: 'secret' }
const obfuscated = obfuscate(value)
assert.deepEqual(obfuscated, { username: 'root', privateKey: OBFUSCATED_VALUE })
assert.deepEqual(merge({ ...obfuscated, username: 'admin' }, value), { username: 'admin', privateKey: 'secret' })
})
})

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -6,7 +6,6 @@ export * from './lib/xen-orchestra-xapi.mjs'
export * from './lib/xen-orchestra-acl.mjs'
export * from './lib/xen-orchestra-plugins.mjs'
export * from './lib/xen-orchestra-v2v.mjs'
export * from './lib/xen-orchestra-docker.mjs'
export * from './lib/complex-matcher.mjs'
export * from './lib/rest-api.mjs'
export * from './lib/xen-orchestra-vmware-explorer.mjs'

View File

@@ -1,175 +0,0 @@
// DTOs of the Docker engines reached through SSH (xo-server `xo-mixins/docker.mjs`)
//
// Dates are milliseconds since the epoch. Optional values which do not apply
// are omitted, except the stats values which are `null` when they cannot be
// computed.
import type { XoDockerEngine, XoVm } from '../xo.mjs'
export type XoDockerContainerState = 'created' | 'running' | 'paused' | 'restarting' | 'removing' | 'exited' | 'dead'
export type XoDockerContainerHealth = 'starting' | 'healthy' | 'unhealthy'
export type XoDockerContainerAction = 'start' | 'stop' | 'restart' | 'pause' | 'unpause'
export type XoDockerPort = {
/** only for a published port, absent when published on all interfaces of an old daemon */
ip?: string
privatePort: number
/** absent when the port is not published */
publicPort?: number
protocol: string
}
export type XoDockerCompose = {
project: string
service?: string
containerNumber?: number
oneOff?: boolean
workingDir?: string
configFiles?: string[]
}
export type XoDockerNetwork = {
name: string
ipAddress?: string
ipv6Address?: string
}
export type XoDockerMount = {
type: string
name?: string
source: string
destination: string
readOnly: boolean
}
export type XoDockerHealthCheck = {
failingStreak: number
lastCheckAt?: number
lastExitCode?: number
}
export type XoDockerRestartPolicy = {
/** `no` when the container has no restart policy */
name: string
maximumRetryCount: number
}
/**
* Stats of one container, like `docker stats`
*/
export type XoDockerContainerStats = {
sampledAt: number | null
/** 100 means one full CPU: can go up to `100 * onlineCpus` */
cpuPercent: number | null
onlineCpus?: number
/** bytes, without the reclaimable page cache */
memoryUsage: number | null
memoryLimit: number | null
memoryPercent: number | null
networkRx: number | null
networkTx: number | null
blockRead: number | null
blockWrite: number | null
pids: number | null
}
export type XoDockerComposeSummary = {
projects: { name: string; containers: number; running: number }[]
}
export type XoDockerError = {
/** DockerError code, e.g. `SSH_AUTH_FAILED` */
code: string
message: string
data?: Record<string, unknown>
}
/** Podman is told from Docker by its `GET /version` */
export type XoDockerEngineKind = 'docker' | 'podman'
export type XoDockerEngineInfoConnected = {
status: 'connected'
kind: XoDockerEngineKind
asOf: number
/** the daemon's ID, not the engine's */
daemonId?: string
name?: string
engineVersion?: string
/** the Docker API version negotiated by XO */
apiVersion?: string
/** the newest Docker API version of the daemon */
daemonApiVersion?: string
minApiVersion?: string
operatingSystem?: string
osType?: string
kernelVersion?: string
architecture?: string
cpus?: number
/** bytes */
memory?: number
storageDriver?: string
loggingDriver?: string
cgroupDriver?: string
cgroupVersion?: string
rootless: boolean
containers: { total?: number; running?: number; paused?: number; stopped?: number }
images?: number
warnings: string[]
compose: XoDockerComposeSummary
}
export type XoDockerEngineInfoDisconnected = {
status: 'unreachable' | 'auth-failed' | 'host-key-mismatch'
asOf: number
error: XoDockerError
}
/**
* Live information about an engine: `status` tells whether it could be reached
*/
export type XoDockerEngineInfo = XoDockerEngineInfoConnected | XoDockerEngineInfoDisconnected
export type XoDockerSocketDiagnostic = {
code: 'socket-missing' | 'not-a-socket' | 'permission-denied' | 'forwarding-disabled' | 'probe-failed'
message: string
}
export type XoDockerEngineTestResult = {
ok: boolean
apiVersion?: string
engineVersion?: string
/** observed SSH host key, `SHA256:…` */
fingerprint?: string
algorithm?: string
error?: XoDockerError
/** only when the Docker socket could not be opened */
diagnostic?: XoDockerSocketDiagnostic
}
export type XoDockerLogEntry = {
/** RFC 3339 date with nanoseconds, absent with `timestamps: false` */
timestamp?: string
stream: 'stdout' | 'stderr'
message: string
}
export type XoDockerLogs = {
entries: XoDockerLogEntry[]
/** the logs have been cut: at `docker.maxLogsSize`, or when reading them timed out */
truncated: boolean
/** reading stopped at `docker.logsTimeout` (overall) or `docker.logsIdleTimeout` (no data) */
timedOut: boolean
asOf: number
}
/**
* Failure of one engine in a container listing
*/
export type XoDockerContainerListError = {
$engine: XoDockerEngine['id']
$VM?: XoVm['id']
code: string
message: string
}

View File

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

View File

@@ -9,8 +9,6 @@ import type {
XoBackupRepository,
XoBrowserMediaSession,
XoConfigBackupArchive,
XoDockerContainer,
XoDockerEngine,
XoGroup,
XoHost,
XoMetadataBackupJob,
@@ -36,14 +34,6 @@ import { VatesTask } from './lib/vates-task.mjs'
import type { PluginRestRouteDefinition } from './lib/rest-api.mjs'
import type { VmwareInventory } from './lib/xen-orchestra-vmware-explorer.mjs'
import type { XoV2vStatus } from './lib/xen-orchestra-v2v.mjs'
import type {
XoDockerContainerAction,
XoDockerContainerListError,
XoDockerContainerStats,
XoDockerEngineInfo,
XoDockerEngineTestResult,
XoDockerLogs,
} from './lib/xen-orchestra-docker.mjs'
import type { RPU_RECOVERY_STEP_NAME } from './common.mjs'
import {
Xapi,
@@ -285,28 +275,6 @@ export type EsxiConnectionParams = {
sslVerify: boolean
}
/**
* Properties of a Docker engine, as accepted by `createDockerEngine` and
* `updateDockerEngine`
*
* On update, omitted properties are kept, `null` or `''` clears them (`port`
* and `socketPath` are reset to their defaults).
*/
export type XoDockerEngineProperties = {
$VM?: XoVm['id'] | null
label?: string | null
host?: string | null
port?: number | null
username?: string
password?: string | null
privateKey?: string | null
passphrase?: string | null
socketPath?: string | null
hostKeyFingerprint?: string | null
/** transient, never stored: pin the observed host key when there is no fingerprint */
acceptUnknownHostKey?: boolean
}
export type XoApp = EventEmitter & {
hooks: EventEmitter
_redis: {
@@ -385,20 +353,6 @@ export type XoApp = EventEmitter & {
opts?: { bypassOtp?: boolean; bypassTaskCreation?: boolean }
) => Promise<{ bypassOtp: boolean; expiration: number; user: XoUser }>
backupGuard(objectId: XapiXoRecord['id'], opts?: { bypassBackupCheck?: boolean; operation: string }): Promise<void>
/**
* raw Docker Engine API request (admin-only REST passthrough), bounded by `docker.maxRawRequestSize` and
* `docker.maxRawResponseSize`
*/
callDockerEngineRawApi(
id: XoDockerEngine['id'],
opts: {
method: string
path: string
headers?: Record<string, string>
body?: Readable
signal?: AbortSignal
}
): Promise<{ statusCode: number; headers: Record<string, string | string[] | undefined>; body: Readable }>
/* Throw if no authorization */
checkFeatureAuthorization(featureCode: FeatureCode): Promise<void>
/* whether this machine can run the tools of an import from VMware */
@@ -443,8 +397,6 @@ export type XoApp = EventEmitter & {
/** keyed by temporary IDs, which can be used as keys in `props.settings` */
schedules: Record<string, Pick<XoSchedule, 'cron' | 'enabled' | 'name' | 'timezone'>>
): Promise<XoMetadataBackupJob>
/** connects first (TOFU: DockerError HOST_KEY_UNKNOWN without fingerprint), saves nothing on failure */
createDockerEngine(properties: XoDockerEngineProperties): Promise<XoDockerEngine>
createAuthenticationToken(opts: {
client?: {
id?: string
@@ -483,8 +435,6 @@ export type XoApp = EventEmitter & {
): Promise<boolean>
deleteAclV2Privilege(privilegeId: XoAclBasePrivilege['id'], options?: { force?: boolean }): Promise<boolean>
deleteAclV2Role(roleId: XoAclRole['id'], options?: { force?: boolean }): Promise<boolean>
deleteDockerContainer(id: XoDockerContainer['id'], opts?: { force?: boolean; removeVolumes?: boolean }): Promise<void>
deleteDockerEngine(id: XoDockerEngine['id']): Promise<void>
deleteGroup(id: XoGroup['id']): Promise<void>
deleteSchedule(id: XoSchedule['id']): Promise<void>
deleteUser(id: XoUser['id']): Promise<void>
@@ -515,8 +465,6 @@ export type XoApp = EventEmitter & {
userId: XoUser['id'],
opts?: { bypassAuthorization?: boolean; fromGroup?: boolean; fromUser?: boolean }
): Promise<XoAclRole[]>
/** never connects */
getAllDockerEngines(): Promise<XoDockerEngine[]>
getAllGroups(): Promise<XoGroup[]>
getAllProxies(): Promise<XoProxy[]>
getAllJobs<T extends AnyXoJob['type']>(type: T): Promise<Extract<AnyXoJob, { type: T }>[]>
@@ -524,6 +472,7 @@ export type XoApp = EventEmitter & {
getPlugin(id: XoPlugin['id']): Promise<XoPlugin>
getPlugins(): Promise<XoPlugin[]>
getProxy(id: XoProxy['id']): Promise<XoProxy>
getProxyApplianceUpdaterState(id: XoProxy['id']): Promise<{ level: string; message: string; state: string }>
getRemote(id: XoBackupRepository['id']): Promise<XoBackupRepository>
getAllRemotes(): Promise<XoBackupRepository[]>
removeRemote(id: XoBackupRepository['id']): Promise<void>
@@ -555,7 +504,10 @@ export type XoApp = EventEmitter & {
* `assertBrowserMediaInsertable` reports the predictable failures synchronously, e.g. before
* starting a task.
*/
insertBrowserMedia(params: { id: XoBrowserMediaSession['id']; vmId: XoVm['id'] }): Promise<{ vdiId: XoVdi['id'] }>
insertBrowserMedia(params: {
id: XoBrowserMediaSession['id']
vmId: XoVm['id']
}): Promise<{ vdiId: XoVdi['id'] }>
assertBrowserMediaInsertable(params: { id: XoBrowserMediaSession['id']; vmId: XoVm['id'] }): void
/** Eject the ISO of a browser media session, release its storage, and disconnect the browser */
ejectBrowserMedia(id: XoBrowserMediaSession['id']): Promise<void>
@@ -581,38 +533,6 @@ export type XoApp = EventEmitter & {
filter: (log: AnyXoLog) => boolean
limit?: number
}): Promise<AnyXoLog[]>
getDockerContainer(id: XoDockerContainer['id']): Promise<XoDockerContainer>
/**
* never connects: the container and the objects it belongs to, from its engine (the container itself may not
* exist), e.g. for the ACLs
*/
getDockerContainerScope(
id: XoDockerContainer['id']
): Promise<Pick<XoDockerContainer, 'id' | '$engine' | '$VM' | '$pool'>>
getDockerContainerLogs(
id: XoDockerContainer['id'],
opts?: {
tail?: number
since?: number | string
until?: number | string
stdout?: boolean
stderr?: boolean
timestamps?: boolean
}
): Promise<XoDockerLogs>
/** the stats sampler's latest sample if ready, else one `stream=false` call (~1-2 s) */
getDockerContainerStats(id: XoDockerContainer['id']): Promise<XoDockerContainerStats>
/** an engine which fails does not fail the list, see `errors` */
getDockerContainers(opts: {
engines: XoDockerEngine['id'][]
all?: boolean
stats?: boolean
forceRefresh?: boolean
}): Promise<{ containers: XoDockerContainer[]; errors: XoDockerContainerListError[]; asOf: number }>
/** never connects */
getDockerEngine(id: XoDockerEngine['id']): Promise<XoDockerEngine>
/** connects, never throws for connection problems (see `status`) */
getDockerEngineInfo(id: XoDockerEngine['id']): Promise<XoDockerEngineInfo>
getGroup(id: XoGroup['id']): Promise<XoGroup>
getHVSupportedVersions: undefined | (() => Promise<{ [key: XoHost['productBrand']]: string }>)
getJob<T extends AnyXoJob>(id: T['id']): Promise<T>
@@ -761,11 +681,8 @@ export type XoApp = EventEmitter & {
setVmResourceSet(vmId: XoVm['id'], resourceSetId: string | null, force?: boolean): Promise<void>
shareVmResourceSet(vmId: XoVm['id']): Promise<void>
removeUserFromGroup(userId: XoUser['id'], id: XoGroup['id']): Promise<void>
runDockerContainerAction(id: XoDockerContainer['id'], action: XoDockerContainerAction): Promise<void>
runJob(job: AnyXoJob, schedule: XoSchedule): void
runWithApiContext: (user: XoUser | undefined, fn: () => void) => Promise<unknown>
/** new, non pooled, connection; never throws for connection problems */
testDockerEngine(id: XoDockerEngine['id']): Promise<XoDockerEngineTestResult>
testPlugin(id: XoPlugin['id'], data?: unknown): Promise<void>
testRemote(
id: XoBackupRepository['id']
@@ -827,7 +744,6 @@ export type XoApp = EventEmitter & {
force?: boolean
}
): Promise<XoAclRole>
updateDockerEngine(id: XoDockerEngine['id'], properties: XoDockerEngineProperties): Promise<XoDockerEngine>
updateGroup(
id: XoGroup['id'],
updates: {

View File

@@ -20,18 +20,6 @@ import type {
} from './common.mjs'
import type * as CMType from './lib/complex-matcher.mjs'
import { XoAclBasePrivilege, XoAclRole } from './lib/xen-orchestra-acl.mjs'
import type {
XoDockerCompose,
XoDockerContainerHealth,
XoDockerContainerState,
XoDockerContainerStats,
XoDockerEngineKind,
XoDockerHealthCheck,
XoDockerMount,
XoDockerNetwork,
XoDockerPort,
XoDockerRestartPolicy,
} from './lib/xen-orchestra-docker.mjs'
import type { XenApiHost, XenApiPool } from './xen-api.mjs'
import type {
XoAuditPlugin,
@@ -97,11 +85,6 @@ type BaseXoVm = BaseXapiXo & {
cpuWeight?: number
creation: Record<string, string>
current_operations: Record<string, VM_OPERATIONS>
/**
* @deprecated legacy xscontainer data scraped from `other_config`, use the
* `XoDockerEngine`/`XoDockerContainer` records (`/rest/v0/docker-engines`,
* `/rest/v0/docker-containers`) instead
*/
docker?: {
containers?: string[]
enabled: boolean
@@ -275,84 +258,6 @@ export type XoGpuGroup = BaseXapiXo & {
type: 'gpuGroup'
}
/**
* A Docker engine reached through SSH (`direct-streamlocal` to its socket)
*
* Secrets (password, private key, passphrase) are never included.
*/
export type XoDockerEngine = {
id: Branded<'docker-engine'>
/** VM running the engine, absent for an engine which is not a VM */
$VM?: XoVm['id']
/** pool of the VM, denormalized at read time */
$pool?: XoPool['id']
label?: string
/** absent: resolved from the addresses reported by the VM at connection time */
host?: string
resolvedHost?: string
port: number
username: string
socketPath: string
/** pinned SSH host key, `SHA256:…` as printed by `ssh-keygen -l` */
hostKeyFingerprint?: string
hostKeyAlgorithm?: string
hasPassword: boolean
hasPrivateKey: boolean
/** Docker or Podman: from the current connection, else the last one, absent until a connection negotiated */
kind?: XoDockerEngineKind
/** state of the pooled connection, reading it never connects */
connectionStatus: 'idle' | 'connected' | 'error'
/** last connection failure, if any */
error?: { code: string; message: string }
}
/**
* A container of a Docker engine, fetched live
*
* The fields after `mounts` come from an inspection: they are absent from the
* list entries of stopped containers (and above `docker.inspectThreshold`).
*/
export type XoDockerContainer = {
/** `<engine id>_<full Docker id>` */
id: Branded<'docker-container'>
$engine: XoDockerEngine['id']
$VM?: XoVm['id']
$pool?: XoPool['id']
dockerId: string
name?: string
image: string
imageId: string
command: string
createdAt?: number
state: XoDockerContainerState
/** human readable status, e.g. `Up 3 hours (healthy)` */
status?: string
exitCode?: number
health?: XoDockerContainerHealth
ports: XoDockerPort[]
labels: Record<string, string>
compose?: XoDockerCompose
networks: XoDockerNetwork[]
mounts: XoDockerMount[]
startedAt?: number
finishedAt?: number
oomKilled?: boolean
error?: string
healthCheck?: XoDockerHealthCheck
restartPolicy?: XoDockerRestartPolicy
restartCount?: number
tty?: boolean
hostname?: string
workingDir?: string
user?: string
/** only with `stats=true`, for running and paused containers: latest sample of the engine's stats sampler */
stats?: XoDockerContainerStats
/** only with `stats=true`: the first samples are not there yet (`stats` missing, or `cpuPercent: null`) */
statsPending?: boolean
}
export type XoGroup = {
id: Branded<'group'>
name: string
@@ -741,7 +646,7 @@ export type XoVmBackupJob = BaseXoJob & {
proxy?: XoProxy['id']
mode: 'full' | 'delta'
remotes?: CMType.IdOr<XoBackupRepository['id']> | string
vms: CMType.IdOr<XoVm['id']> | Record<string, unknown>
vms: CMType.IdOr<XoVm['id']> | Record<string, unknown> | string
srs?: CMType.IdOr<XoSr['id']> | string
type: 'backup'
settings: {
@@ -758,7 +663,7 @@ export type XoMetadataBackupJobScheduleSettings = {
}
export type XoMetadataBackupJob = BaseXoJob & {
type: 'metadataBackup'
pools?: CMType.IdOr<XoPool['id']>
pools?: CMType.IdOr<XoPool['id']> | string
remotes: CMType.IdOr<XoBackupRepository['id']>
settings: {
''?: XoMetadataBackupJobGeneralSettings
@@ -791,6 +696,7 @@ export type XoMirrorBackupJob = BaseXoJob & {
sourceRemote: XoBackupRepository['id']
remotes: CMType.IdOr<XoBackupRepository['id']>
proxy?: XoProxy['id']
filter?: { vm: { uuid: { __or: XoVm['id'][] } } } | null
settings: {
'': XoMirrorBackupGeneralSettings
[scheduleId: XoSchedule['id']]: XoMirrorBackupScheduleSettings | undefined
@@ -924,8 +830,6 @@ export type XoTask = {
| 'backup-log'
| 'backup-repository'
| 'browser-media'
| 'docker-container'
| 'docker-engine'
| 'group'
| 'plugin'
| 'proxy'
@@ -1148,8 +1052,6 @@ export type NonXapiXoRecord =
| XoProxy
| XoJob
| XoBackupRepository
| XoDockerContainer
| XoDockerEngine
| XoSchedule
| XoServer
| XoTask

View File

@@ -30,7 +30,7 @@
},
"devDependencies": {
"@eslint/js": "^9.19.0",
"@vates/types": "^3.0.0",
"@vates/types": "^3.2.0",
"rimraf": "^6.0.1",
"typescript": "~5.6",
"typescript-eslint": "^8.61.0"

View File

@@ -21,7 +21,7 @@
"tar-stream": "^3.1.8",
"@types/tar-stream": "^3.1.4",
"tmp": "^0.2.1",
"@vates/types": "^3.0.0"
"@vates/types": "^3.2.0"
},
"dependencies": {
"@xen-orchestra/log": "^1.0.0",

View File

@@ -8,7 +8,7 @@
"dependencies": {
"@vates/async-each": "^1.0.3",
"@xen-orchestra/async-map": "^0.1.5",
"@xen-orchestra/backups": "^1.0.0",
"@xen-orchestra/backups": "^1.0.1",
"@xen-orchestra/fs": "^4.11.0",
"filenamify": "^6.0.0",
"getopts": "^2.2.5",

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -8,7 +8,7 @@
"type": "git",
"url": "https://github.com/vatesfr/xen-orchestra.git"
},
"version": "1.0.0",
"version": "1.0.1",
"engines": {
"node": ">=22.19"
},
@@ -27,10 +27,10 @@
"@vates/disposable": "^0.1.7",
"@vates/fuse-vhd": "^2.1.4",
"@vates/generator-toolbox": "^1.1.3",
"@vates/nbd-client": "^3.7.1",
"@vates/nbd-client": "^3.7.2",
"@vates/parse-duration": "^0.1.1",
"@vates/task": "^0.7.0",
"@vates/types": "^3.0.0",
"@vates/types": "^3.2.0",
"@xen-orchestra/async-map": "^0.1.5",
"@xen-orchestra/disk-transform": "^1.3.4",
"@xen-orchestra/fs": "^4.11.0",
@@ -70,7 +70,7 @@
"typescript": "^5.9.3"
},
"peerDependencies": {
"@xen-orchestra/xapi": "^10.0.0"
"@xen-orchestra/xapi": "^10.1.0"
},
"license": "AGPL-3.0-or-later",
"author": {

View File

@@ -20,7 +20,7 @@
},
"dependencies": {
"@vates/async-each": "^1.0.3",
"@xen-orchestra/backups": "^1.0.0",
"@xen-orchestra/backups": "^1.0.1",
"@xen-orchestra/backup-archive": "^1.2.1",
"@xen-orchestra/disk-transform": "^1.3.4",
"@xen-orchestra/fs": "^4.11.0",

View File

@@ -1,42 +0,0 @@
Talks to the Docker Engine API of a remote host through SSH: the requests go over `direct-streamlocal@openssh.com` channels to the host's Docker socket, so nothing has to be installed on the host besides an OpenSSH server (≥ 6.7) and a user allowed to use the socket. It is the transport of the Docker integration of Xen Orchestra: its normalizers produce the `XoDocker*` types of `@vates/types`, but it knows nothing of XO records, permissions or configuration.
- host key pinning (`SHA256:…` fingerprint), or trust on first use with `acceptUnknownHostKey` and `observedHostKey`
- API version negotiation (between `MIN_API_VERSION` and `MAX_API_VERSION`)
- one SSH connection per host, HTTP keep-alive over its channels, a bounded number of concurrent requests
- typed errors (`DockerError` and its `code`: `SSH_AUTH_FAILED`, `HOST_KEY_MISMATCH`, `DOCKER_SOCKET_UNREACHABLE`…)
- helpers: a connection pool with idle GC and a negative cache (`DockerConnectionPool`), a stats sampler (`DockerStatsSampler`), the log stream demuxer (`createStdcopyDemuxer`) and normalizers of the Docker responses
```js
import { readFileSync } from 'node:fs'
import { DockerConnection, normalizeContainerListEntry, DockerError } from '@xen-orchestra/docker-ssh'
const env = process.env // host, user, key path…
const connection = new DockerConnection({
host: env.XO_DOCKER_TEST_SSH_HOST,
port: Number(env.XO_DOCKER_TEST_SSH_PORT),
username: env.XO_DOCKER_TEST_SSH_USER,
privateKey: readFileSync(env.XO_DOCKER_TEST_SSH_KEY),
socketPath: env.XO_DOCKER_TEST_SOCKET,
// pinned host key: a different key is refused with HOST_KEY_MISMATCH
hostKeyFingerprint: env.XO_DOCKER_TEST_SSH_FINGERPRINT,
})
try {
await connection.connect()
const { body: version } = await connection.request({ path: '/version' })
console.log('Docker %s, API %s negotiated', version.Version, connection.apiVersion)
const { body: containers } = await connection.request({
path: '/containers/json',
query: { all: 1, filters: JSON.stringify({ name: ['^/xo-', '^/demo-'] }) },
})
for (const container of containers.map(normalizeContainerListEntry)) {
console.log('%s\t%s\t%s', container.name, container.state, container.image)
}
} catch (error) {
if (error instanceof DockerError) console.error(error.code, error.message)
else throw error
} finally {
await connection.close()
}
```

View File

@@ -1 +0,0 @@
src/docker-api.gen.mts linguist-generated=true

View File

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

View File

@@ -1,75 +0,0 @@
<!-- DO NOT EDIT MANUALLY, THIS FILE HAS BEEN GENERATED -->
# @xen-orchestra/docker-ssh
[![Package Version](https://badgen.net/npm/v/@xen-orchestra/docker-ssh)](https://npmjs.org/package/@xen-orchestra/docker-ssh) ![License](https://badgen.net/npm/license/@xen-orchestra/docker-ssh) [![PackagePhobia](https://badgen.net/bundlephobia/minzip/@xen-orchestra/docker-ssh)](https://bundlephobia.com/result?p=@xen-orchestra/docker-ssh) [![Node compatibility](https://badgen.net/npm/node/@xen-orchestra/docker-ssh)](https://npmjs.org/package/@xen-orchestra/docker-ssh)
> Docker Engine API client reaching the Docker socket of a remote host through SSH
## Install
Installation of the [npm package](https://npmjs.org/package/@xen-orchestra/docker-ssh):
```sh
npm install --save @xen-orchestra/docker-ssh
```
## Usage
Talks to the Docker Engine API of a remote host through SSH: the requests go over `direct-streamlocal@openssh.com` channels to the host's Docker socket, so nothing has to be installed on the host besides an OpenSSH server (≥ 6.7) and a user allowed to use the socket. It is the transport of the Docker integration of Xen Orchestra: its normalizers produce the `XoDocker*` types of `@vates/types`, but it knows nothing of XO records, permissions or configuration.
- host key pinning (`SHA256:…` fingerprint), or trust on first use with `acceptUnknownHostKey` and `observedHostKey`
- API version negotiation (between `MIN_API_VERSION` and `MAX_API_VERSION`)
- one SSH connection per host, HTTP keep-alive over its channels, a bounded number of concurrent requests
- typed errors (`DockerError` and its `code`: `SSH_AUTH_FAILED`, `HOST_KEY_MISMATCH`, `DOCKER_SOCKET_UNREACHABLE`…)
- helpers: a connection pool with idle GC and a negative cache (`DockerConnectionPool`), a stats sampler (`DockerStatsSampler`), the log stream demuxer (`createStdcopyDemuxer`) and normalizers of the Docker responses
```js
import { readFileSync } from 'node:fs'
import { DockerConnection, normalizeContainerListEntry, DockerError } from '@xen-orchestra/docker-ssh'
const env = process.env // host, user, key path…
const connection = new DockerConnection({
host: env.XO_DOCKER_TEST_SSH_HOST,
port: Number(env.XO_DOCKER_TEST_SSH_PORT),
username: env.XO_DOCKER_TEST_SSH_USER,
privateKey: readFileSync(env.XO_DOCKER_TEST_SSH_KEY),
socketPath: env.XO_DOCKER_TEST_SOCKET,
// pinned host key: a different key is refused with HOST_KEY_MISMATCH
hostKeyFingerprint: env.XO_DOCKER_TEST_SSH_FINGERPRINT,
})
try {
await connection.connect()
const { body: version } = await connection.request({ path: '/version' })
console.log('Docker %s, API %s negotiated', version.Version, connection.apiVersion)
const { body: containers } = await connection.request({
path: '/containers/json',
query: { all: 1, filters: JSON.stringify({ name: ['^/xo-', '^/demo-'] }) },
})
for (const container of containers.map(normalizeContainerListEntry)) {
console.log('%s\t%s\t%s', container.name, container.state, container.image)
}
} catch (error) {
if (error instanceof DockerError) console.error(error.code, error.message)
else throw error
} finally {
await connection.close()
}
```
## Contributions
Contributions are _very_ welcomed, either on the documentation or on
the code.
You may:
- report any [issue](https://github.com/vatesfr/xen-orchestra/issues)
you've encountered;
- fork and create a pull request.
## License
[AGPL-3.0-or-later](https://spdx.org/licenses/AGPL-3.0-or-later) © [Vates SAS](https://vates.fr)

View File

@@ -1,6 +0,0 @@
// @ts-check
import eslint from '@eslint/js'
import tseslint from 'typescript-eslint'
export default tseslint.config(eslint.configs.recommended, tseslint.configs.recommended)

View File

@@ -1,55 +0,0 @@
{
"name": "@xen-orchestra/docker-ssh",
"version": "0.0.0",
"main": "./dist/index.mjs",
"types": "./dist/index.d.mts",
"license": "AGPL-3.0-or-later",
"private": false,
"type": "module",
"description": "Docker Engine API client reaching the Docker socket of a remote host through SSH",
"keywords": [
"docker",
"ssh",
"streamlocal",
"xen-orchestra"
],
"dependencies": {
"@vates/types": "^3.0.0",
"@xen-orchestra/log": "^1.0.0",
"ssh2": "^1.16.0"
},
"devDependencies": {
"@eslint/js": "^9.19.0",
"@types/node": "^22.3.0",
"@types/ssh2": "^1.15.5",
"rimraf": "^6.0.1",
"typescript": "~5.6",
"typescript-eslint": "^8.61.0",
"yaml": "^2.9.0"
},
"scripts": {
"build": "tsc",
"clean": "rimraf dist/",
"dev": "tsc --watch",
"generate-api-types": "node scripts/generate-api-types.mjs",
"postversion": "npm publish --access public",
"prebuild": "rimraf dist/",
"predev": "yarn run prebuild",
"test": "tsc && node --test \"dist/**/*.test.mjs\"",
"test-integration": "tsc && node --test \"dist/**/*.integ.mjs\""
},
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/@xen-orchestra/docker-ssh",
"bugs": "https://github.com/vatesfr/xen-orchestra/issues",
"repository": {
"directory": "@xen-orchestra/docker-ssh",
"type": "git",
"url": "https://github.com/vatesfr/xen-orchestra.git"
},
"author": {
"name": "Vates SAS",
"url": "https://vates.fr"
},
"engines": {
"node": ">=22"
}
}

View File

@@ -1,140 +0,0 @@
#!/usr/bin/env node
// Generates `src/docker-api.gen.mts`: the TypeScript types of the Docker Engine
// API definitions this package reads, from the official OpenAPI (Swagger 2.0)
// specifications published by Docker.
//
// - API 1.44 (`MAX_API_VERSION` in `src/connection.mts`) for everything
// - API 1.48 for the stats: before it, the spec documents the stats response as
// a plain `object` (the field names did not change, `ContainerStatsResponse`
// only documents them)
//
// Only the definitions reachable from `ROOTS` are kept. The inspect response is
// inline in the 1.44 spec: it is added as `ContainerInspectResponse`, the name
// later specs use.
//
// yarn generate-api-types # needs network access (specs + npx)
import { execFileSync } from 'node:child_process'
import { mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { parse } from 'yaml'
const SPEC_URL = version => `https://docs.docker.com/reference/api/engine/version/v${version}.yaml`
const API_VERSION = '1.44'
const STATS_API_VERSION = '1.48'
const OPENAPI_TYPESCRIPT = 'openapi-typescript@5.4.2' // last major reading Swagger 2.0
const ROOTS = [
'SystemVersion',
'SystemInfo',
'ContainerSummary',
'ContainerInspectResponse',
'ContainerConfig',
'ContainerState',
'Health',
'HealthcheckResult',
'Port',
'EndpointSettings',
'MountPoint',
'RestartPolicy',
]
const STATS_ROOTS = ['ContainerStatsResponse']
async function fetchSpec(version) {
const response = await fetch(SPEC_URL(version))
if (!response.ok) {
throw new Error(`${SPEC_URL(version)}: ${response.status}`)
}
return parse(await response.text())
}
function getResponseSchema(spec, path) {
const { responses } = spec.paths[path].get
return (responses[200] ?? responses['200']).schema
}
// definitions reachable from `roots`, following every `$ref`
function pickDefinitions(definitions, roots) {
const picked = {}
const visit = value => {
if (Array.isArray(value)) {
value.forEach(visit)
} else if (value !== null && typeof value === 'object') {
for (const [key, child] of Object.entries(value)) {
if (key === '$ref' && typeof child === 'string') {
add(child.slice('#/definitions/'.length))
} else {
visit(child)
}
}
}
}
const add = name => {
if (picked[name] === undefined) {
if (definitions[name] === undefined) {
throw new Error(`missing definition ${name}`)
}
picked[name] = definitions[name]
visit(definitions[name])
}
}
roots.forEach(add)
return picked
}
const spec = await fetchSpec(API_VERSION)
const statsSpec = await fetchSpec(STATS_API_VERSION)
const definitions = pickDefinitions(
{ ...spec.definitions, ContainerInspectResponse: getResponseSchema(spec, '/containers/{id}/json') },
ROOTS
)
const statsDefinitions = pickDefinitions(statsSpec.definitions, STATS_ROOTS)
for (const name of Object.keys(statsDefinitions)) {
if (definitions[name] !== undefined) {
throw new Error(`${name} is in both specs`)
}
}
const dir = mkdtempSync(join(tmpdir(), 'docker-api-types-'))
try {
const input = join(dir, 'spec.json')
const output = join(dir, 'types.ts')
writeFileSync(
input,
JSON.stringify({
swagger: '2.0',
info: { title: 'Docker Engine API (subset)', version: API_VERSION },
paths: {},
definitions: { ...definitions, ...statsDefinitions },
})
)
execFileSync('npx', ['--yes', OPENAPI_TYPESCRIPT, input, '--output', output], { stdio: 'inherit' })
const types = readFileSync(output, 'utf8')
// no paths, no operations: only `definitions` is useful
.replace(/^export interface paths \{\}\n\n/m, '')
.replace(/^export interface operations \{\}\n\n/m, '')
.replace(/^export interface external \{\}\n?/m, '')
const target = new URL('../src/docker-api.gen.mts', import.meta.url)
writeFileSync(
target,
`// Generated by scripts/generate-api-types.mjs, do not edit.
//
// Docker Engine API ${API_VERSION} definitions read by this package (and the stats
// definitions of API ${STATS_API_VERSION}), from the official specifications:
// ${SPEC_URL(API_VERSION)}
// ${SPEC_URL(STATS_API_VERSION)}
//
// These are what the daemon is documented to send, they are not checked at
// runtime: see \`wire.mts\` for how this package uses them.
${types.trim()}
`
)
execFileSync('npx', ['prettier', '--write', target.pathname], { stdio: 'inherit' })
console.log('definitions:', Object.keys(definitions).length + Object.keys(statsDefinitions).length)
} finally {
rmSync(dir, { recursive: true, force: true })
}

View File

@@ -1,314 +0,0 @@
// Integration tests against a real Docker daemon reached through a real SSH
// server.
//
// Skipped unless the following environment variables are set:
//
// - XO_DOCKER_TEST_SSH_HOST
// - XO_DOCKER_TEST_SSH_PORT (default: 22)
// - XO_DOCKER_TEST_SSH_USER
// - XO_DOCKER_TEST_SSH_KEY: path of an authorized private key
// - XO_DOCKER_TEST_SSH_BAD_KEY: path of a private key which is NOT authorized
// - XO_DOCKER_TEST_SSH_FINGERPRINT: host key fingerprint (`SHA256:…`, ED25519)
// - XO_DOCKER_TEST_SOCKET: path of the Docker socket on the SSH host
// - XO_DOCKER_TEST_SSH_NOFWD_PORT (optional): port of an SSH server on the same
// host with `AllowStreamLocalForwarding no` and the same authorized key
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { createServer, type AddressInfo } from 'node:net'
import test from 'node:test'
import { Client } from 'ssh2'
import {
DockerConnection,
MAX_API_VERSION,
type DockerConnectionInternals,
type DockerConnectionOptions,
type SshClient,
} from './connection.mjs'
import {
DOCKER_SOCKET_UNREACHABLE,
HOST_KEY_MISMATCH,
HOST_KEY_UNKNOWN,
CONNECTION_CLOSED,
SSH_AUTH_FAILED,
SSH_UNREACHABLE,
TIMEOUT,
type DockerError,
} from './errors.mjs'
import { type DockerConnectionFacade, DockerConnectionPool } from './pool.mjs'
import type { DockerInfo, DockerVersion } from './wire.mjs'
const { after, before, describe, it } = test
const {
XO_DOCKER_TEST_SSH_HOST: host,
XO_DOCKER_TEST_SSH_PORT: port = '22',
XO_DOCKER_TEST_SSH_USER: username,
XO_DOCKER_TEST_SSH_KEY: keyPath,
XO_DOCKER_TEST_SSH_BAD_KEY: badKeyPath,
XO_DOCKER_TEST_SSH_FINGERPRINT: fingerprint,
XO_DOCKER_TEST_SOCKET: socketPath,
XO_DOCKER_TEST_SSH_NOFWD_PORT: noForwardingPort,
} = process.env
const skip = host === undefined ? 'XO_DOCKER_TEST_SSH_HOST is not set' : false
// a local TCP port on which nothing listens
async function getClosedPort() {
const server = createServer()
await new Promise<void>(resolve => server.listen(0, '127.0.0.1', resolve))
// a TCP server: an `AddressInfo`
const { port } = server.address() as AddressInfo
await new Promise(resolve => server.close(resolve))
return port
}
describe('DockerConnection (real SSH + dockerd)', { skip }, () => {
let privateKey: Buffer, badPrivateKey: Buffer
const connections: DockerConnection[] = []
// `!`: the environment is set, the tests are skipped otherwise
before(() => {
privateKey = readFileSync(keyPath!)
badPrivateKey = readFileSync(badKeyPath!)
})
after(async () => {
await Promise.all(connections.map(connection => connection.close()))
})
const createConnection = (opts?: Partial<DockerConnectionOptions>, internals?: DockerConnectionInternals) => {
const connection = new DockerConnection(
{
host: host!,
port: Number(port),
username: username!,
privateKey,
socketPath,
hostKeyFingerprint: fingerprint,
connectTimeout: 5e3,
requestTimeout: 10e3,
...opts,
},
internals
)
connections.push(connection)
return connection
}
describe('with the right fingerprint', () => {
let connection: DockerConnection
before(async () => {
connection = createConnection()
await connection.connect()
})
it('negotiates the API version', () => {
assert.equal(connection.apiVersion, MAX_API_VERSION)
assert.match(connection.engineVersion!, /^\d+\.\d+/)
assert.equal(connection.observedHostKey!.fingerprint, fingerprint)
})
it('GET /version', async () => {
const { statusCode, body } = await connection.request({ path: '/version' })
assert.equal(statusCode, 200)
assert.equal((body as DockerVersion).Version, connection.engineVersion)
})
it('GET /containers/json?all=1', async () => {
const { body } = await connection.request({ path: '/containers/json', query: { all: 1 } })
assert.ok(Array.isArray(body))
for (const container of body) {
assert.equal(typeof container.Id, 'string')
}
})
it('GET /info', async () => {
const { body } = await connection.request({ path: '/info' })
assert.equal(typeof (body as DockerInfo).ID, 'string')
assert.equal(typeof (body as DockerInfo).Containers, 'number')
})
it('handles 10 concurrent requests', async () => {
const results = await Promise.all(
Array.from({ length: 10 }, (_, i) => connection.request({ path: i % 2 === 0 ? '/info' : '/containers/json' }))
)
for (const { statusCode } of results) {
assert.equal(statusCode, 200)
}
})
it('reports Docker errors', async () => {
await assert.rejects(connection.request({ path: '/containers/xo-does-not-exist/json' }), (error: DockerError) => {
assert.equal(error.code, 'DOCKER_API_ERROR')
assert.equal(error.data!.statusCode, 404)
assert.match(error.message, /No such container/)
return true
})
})
})
it('times out with TIMEOUT on a long-lived request and stays usable', async () => {
const connection = createConnection({ requestTimeout: 500 })
await connection.connect()
// `/events` never ends by itself
await assert.rejects(connection.request({ path: '/events' }), { code: TIMEOUT })
const controller = new AbortController()
const events = await connection.requestStream({ path: '/events', signal: controller.signal })
// the stream outlives requestTimeout
await new Promise(resolve => setTimeout(resolve, 700))
assert.equal(events.destroyed, false)
controller.abort()
const { statusCode } = await connection.request({ path: '/_ping' })
assert.equal(statusCode, 200)
})
it('SSH connection losses: the pool replaces the lost connection (no reuse of dead channels, no leaked slots)', async () => {
const clients: SshClient[] = []
const lost: DockerConnection[] = []
const pool = new DockerConnectionPool()
const use = <T,>(fn: (connection: DockerConnectionFacade) => Promise<T>) =>
pool.use(
{ id: 'engine' },
() => {
const connection = createConnection(
{ requestTimeout: 2e3 },
{
createClient: () => {
const client = new Client()
clients.push(client)
return client
},
}
)
lost.push(connection)
return connection
},
fn
)
try {
// more drops than the max number of free sockets and concurrent requests
for (let i = 0; i < 5; ++i) {
await use(connection =>
Promise.all([connection.request({ path: '/_ping' }), connection.request({ path: '/_ping' })])
)
// simulate a network failure
clients.at(-1)!._sock!.destroy()
await new Promise(resolve => setTimeout(resolve, 100))
// removed from the pool, closed for good, without leaked slots
assert.deepEqual(pool.getState('engine'), { status: 'idle' })
const dead = lost.at(-1)!
assert.equal(dead.closed, true)
assert.deepEqual(dead.activeRequests, { requests: 0, streams: 0 })
await assert.rejects(dead.request({ path: '/_ping' }), { code: CONNECTION_CLOSED })
const start = Date.now()
const results = await use(connection =>
Promise.all(
Array.from({ length: 3 }, () => connection.request({ path: '/_ping' }).then(({ statusCode }) => statusCode))
)
)
assert.deepEqual(results, [200, 200, 200])
assert.ok(Date.now() - start < 2e3)
}
// one SSH session per connection
assert.equal(clients.length, 6)
assert.equal(lost.length, 6)
} finally {
await pool.destroy()
}
})
it('close() rejects queued requests with CONNECTION_CLOSED and does not reconnect', async () => {
const clients: SshClient[] = []
const connection = createConnection(
{},
{
createClient: () => {
const client = new Client()
clients.push(client)
return client
},
}
)
await connection.connect()
const results = Array.from({ length: 20 }, () =>
connection.request({ path: '/containers/json', query: { all: 1 } }).then(
() => 'ok',
error => error.code
)
)
await connection.close()
for (const result of await Promise.all(results)) {
assert.equal(result, CONNECTION_CLOSED)
}
await new Promise(resolve => setTimeout(resolve, 200))
assert.equal(clients.length, 1)
assert.equal(clients[0]._sock!.destroyed, true)
})
it('fails with HOST_KEY_MISMATCH on a wrong fingerprint', async () => {
const connection = createConnection({ hostKeyFingerprint: 'SHA256:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' })
await assert.rejects(connection.connect(), (error: DockerError) => {
assert.equal(error.code, HOST_KEY_MISMATCH)
assert.equal(error.data!.expected, 'SHA256:AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA')
assert.equal(error.data!.actual, fingerprint)
return true
})
})
it('fails with HOST_KEY_UNKNOWN without fingerprint', async () => {
const connection = createConnection({ hostKeyFingerprint: undefined })
await assert.rejects(connection.connect(), (error: DockerError) => {
assert.equal(error.code, HOST_KEY_UNKNOWN)
assert.equal(error.data!.fingerprint, fingerprint)
assert.equal(error.data!.algorithm, 'ssh-ed25519')
return true
})
assert.equal(connection.observedHostKey!.fingerprint, fingerprint)
})
it('accepts an unknown host key when asked to', async () => {
const connection = createConnection({ hostKeyFingerprint: undefined, acceptUnknownHostKey: true })
await connection.connect()
assert.equal(connection.observedHostKey!.fingerprint, fingerprint)
})
it('fails with SSH_AUTH_FAILED with a bad key', async () => {
const connection = createConnection({ privateKey: badPrivateKey })
await assert.rejects(connection.connect(), (error: DockerError) => {
assert.equal(error.code, SSH_AUTH_FAILED)
assert.doesNotMatch(JSON.stringify(error.data) + JSON.stringify(error.cause), /PRIVATE KEY/)
return true
})
})
it('fails with DOCKER_SOCKET_UNREACHABLE with a wrong socket path', async () => {
const connection = createConnection({ socketPath: '/xo-does-not-exist/docker.sock' })
await assert.rejects(connection.connect(), { code: DOCKER_SOCKET_UNREACHABLE })
})
it('fails with SSH_UNREACHABLE on a closed port', async () => {
const connection = createConnection({ port: await getClosedPort() })
await assert.rejects(connection.connect(), { code: SSH_UNREACHABLE })
})
it(
'fails with DOCKER_SOCKET_UNREACHABLE when stream local forwarding is disabled (OpenSSH answers CONNECT_FAILED)',
{ skip: noForwardingPort === undefined ? 'XO_DOCKER_TEST_SSH_NOFWD_PORT is not set' : false },
async () => {
const connection = createConnection({
port: Number(noForwardingPort),
hostKeyFingerprint: undefined,
acceptUnknownHostKey: true,
})
await assert.rejects(connection.connect(), (error: DockerError) => {
assert.equal(error.code, DOCKER_SOCKET_UNREACHABLE)
assert.equal(error.data!.reason, 2)
assert.equal(error.data!.description, 'open failed')
return true
})
}
)
})

File diff suppressed because it is too large Load Diff

View File

@@ -1,967 +0,0 @@
import assert from 'node:assert/strict'
import { EventEmitter, once } from 'node:events'
import { mkdtemp, rm } from 'node:fs/promises'
import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'
import { connect as netConnect, type Socket } from 'node:net'
import { Duplex } from 'node:stream'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import test from 'node:test'
import {
compareApiVersions,
computeFingerprint,
DockerConnection,
getKeyAlgorithm,
MAX_API_VERSION,
negotiateApiVersion,
normalizeFingerprint,
parseFingerprint,
verifyHostKey,
type DockerConnectionOptions,
} from './connection.mjs'
import {
DOCKER_API_ERROR,
DOCKER_API_VERSION_UNSUPPORTED,
DOCKER_SOCKET_UNREACHABLE,
HOST_KEY_MISMATCH,
CONNECTION_CLOSED,
HOST_KEY_UNKNOWN,
SSH_AUTH_FAILED,
TIMEOUT,
type DockerError,
} from './errors.mjs'
import type { ClientCallback, ClientChannel, ConnectConfig } from 'ssh2'
const { after, before, beforeEach, describe, it } = test
// generated with `ssh-keygen -t ed25519`, fingerprints from `ssh-keygen -lf`
const ED25519_KEY = 'AAAAC3NzaC1lZDI1NTE5AAAAIDIKbtnnl0BlnKuKjKJoUJOsCWA910CX/XMkuMh4Ornr'
const ED25519_FINGERPRINT = 'SHA256:xo1L4JygV0hw5XQ+LHcn2iI3C9GvGsDRBNh+q7iQazs'
const RSA_KEY =
'AAAAB3NzaC1yc2EAAAADAQABAAAAgQDgLtqnXodwWvIQMujeXcGidrnppkGG5W+gk9bZHwi054aQfV3LNEZtq7wctk2EYeyVzZgFmcGOsfhu+L578Xe09zj92SovHsu9a+V1FxjAbRrnZMdG4bGSXyimSrGyM1XdzSs6dmh7gaX4DY2+peLkoAtObD6WwpvK0tfhYOFpkQ=='
const RSA_FINGERPRINT = 'SHA256:oADNJ8NlHsMYm0YHHYG3FN/qcWHowk7e/7L9V/Rm6yk'
describe('host key fingerprint', () => {
it('matches ssh-keygen -lf', () => {
assert.equal(computeFingerprint(Buffer.from(ED25519_KEY, 'base64')), ED25519_FINGERPRINT)
assert.equal(computeFingerprint(Buffer.from(RSA_KEY, 'base64')), RSA_FINGERPRINT)
})
it('extracts the key algorithm', () => {
assert.equal(getKeyAlgorithm(Buffer.from(ED25519_KEY, 'base64')), 'ssh-ed25519')
assert.equal(getKeyAlgorithm(Buffer.from(RSA_KEY, 'base64')), 'ssh-rsa')
assert.equal(getKeyAlgorithm(Buffer.from([0, 0, 0, 10, 1])), undefined)
})
it('normalizes user input', () => {
assert.equal(normalizeFingerprint(' xo1L4JygV0hw5XQ+LHcn2iI3C9GvGsDRBNh+q7iQazs= '), ED25519_FINGERPRINT)
assert.equal(normalizeFingerprint(ED25519_FINGERPRINT), ED25519_FINGERPRINT)
})
it('parses a whole ssh-keygen -l line, taking the algorithm from its type', () => {
const fp = ED25519_FINGERPRINT
assert.deepEqual(parseFingerprint(`256 ${fp} root@host (ED25519)`), { fingerprint: fp, algorithm: 'ssh-ed25519' })
assert.deepEqual(parseFingerprint(` 384 ${fp} a comment with spaces (ECDSA) `), {
fingerprint: fp,
algorithm: 'ecdsa-sha2-nistp384',
})
assert.deepEqual(parseFingerprint(`3072 ${fp} no comment (RSA)`), { fingerprint: fp, algorithm: 'ssh-rsa' })
assert.deepEqual(parseFingerprint(`256 ${fp} (ED25519)`), { fingerprint: fp, algorithm: 'ssh-ed25519' })
assert.deepEqual(parseFingerprint(`256 ${fp} (FOO)`), { fingerprint: fp, algorithm: undefined })
assert.deepEqual(parseFingerprint(fp.slice('SHA256:'.length) + '='), { fingerprint: fp, algorithm: undefined })
})
it('verifyHostKey() mentions the presented algorithm on HOST_KEY_MISMATCH', () => {
assert.throws(() => verifyHostKey(Buffer.from(RSA_KEY, 'base64'), { expectedFingerprint: ED25519_FINGERPRINT }), {
code: HOST_KEY_MISMATCH,
message: /\(ssh-rsa\)/,
})
})
it('verifyHostKey() accepts the expected key', () => {
assert.deepEqual(verifyHostKey(Buffer.from(ED25519_KEY, 'base64'), { expectedFingerprint: ED25519_FINGERPRINT }), {
fingerprint: ED25519_FINGERPRINT,
algorithm: 'ssh-ed25519',
})
})
it('verifyHostKey() rejects a missing fingerprint with HOST_KEY_UNKNOWN', () => {
assert.throws(
() => verifyHostKey(Buffer.from(ED25519_KEY, 'base64'), {}),
(error: DockerError) =>
error.code === HOST_KEY_UNKNOWN &&
error.data!.fingerprint === ED25519_FINGERPRINT &&
error.data!.algorithm === 'ssh-ed25519'
)
})
it('verifyHostKey() treats a null fingerprint as missing', () => {
assert.throws(() => verifyHostKey(Buffer.from(ED25519_KEY, 'base64'), { expectedFingerprint: null }), {
code: HOST_KEY_UNKNOWN,
})
})
it('verifyHostKey() accepts an unknown key when asked to', () => {
assert.equal(
verifyHostKey(Buffer.from(ED25519_KEY, 'base64'), { acceptUnknownHostKey: true }).fingerprint,
ED25519_FINGERPRINT
)
})
it('verifyHostKey() rejects another key with HOST_KEY_MISMATCH', () => {
assert.throws(
() => verifyHostKey(Buffer.from(ED25519_KEY, 'base64'), { expectedFingerprint: RSA_FINGERPRINT }),
(error: DockerError) =>
error.code === HOST_KEY_MISMATCH &&
error.data!.expected === RSA_FINGERPRINT &&
error.data!.actual === ED25519_FINGERPRINT
)
})
})
describe('DockerConnection (real ssh2 client, no network)', () => {
it('fails with SSH_AUTH_FAILED on an unparsable private key, without leaking it', async () => {
const connection = new DockerConnection({
host: '127.0.0.1',
username: 'user',
privateKey: 'not a key: TOP-SECRET',
passphrase: 'hunter2',
})
await assert.rejects(connection.connect(), (error: DockerError) => {
assert.equal(error.code, SSH_AUTH_FAILED)
assert.doesNotMatch(
JSON.stringify({ ...error, cause: error.cause, message: error.cause!.message }),
/TOP-SECRET|hunter2/
)
return true
})
// must not wait for a `close` which will never come
const start = Date.now()
await connection.close()
assert.ok(Date.now() - start < 1e3)
})
})
describe('negotiateApiVersion()', () => {
it('compares versions numerically', () => {
assert.ok(compareApiVersions('1.9', '1.10') < 0)
assert.ok(compareApiVersions('1.43', '1.43') === 0)
assert.ok(compareApiVersions('2.0', '1.99') > 0)
})
it('uses the lowest of the max versions', () => {
assert.equal(negotiateApiVersion({ ApiVersion: '1.47', MinAPIVersion: '1.24' }), MAX_API_VERSION)
assert.equal(negotiateApiVersion({ ApiVersion: '1.41', MinAPIVersion: '1.12' }), '1.41')
})
it('rejects a too old daemon', () => {
assert.throws(() => negotiateApiVersion({ ApiVersion: '1.23' }), { code: DOCKER_API_VERSION_UNSUPPORTED })
})
it("negotiates Podman's Docker-compatible API (ApiVersion 1.41, MinAPIVersion 1.24)", () => {
assert.equal(negotiateApiVersion({ ApiVersion: '1.41', MinAPIVersion: '1.24' }), '1.41')
})
it('negotiates 1.44 with Docker 29 (MinAPIVersion 1.44)', () => {
assert.equal(negotiateApiVersion({ ApiVersion: '1.52', MinAPIVersion: '1.44' }), '1.44')
})
it("uses the daemon's oldest version, with a warning, when it does not support our max version", () => {
const symbol = Symbol.for('@xen-orchestra/log')
const global = globalThis as unknown as Record<symbol, unknown>
const transport = global[symbol]
const logs: { level: number; message: string }[] = []
global[symbol] = (log: { level: number; message: string }) => logs.push(log)
try {
assert.equal(negotiateApiVersion({ ApiVersion: '1.52', MinAPIVersion: '1.45' }), '1.45')
} finally {
global[symbol] = transport
}
assert.equal(logs.length, 1)
assert.match(logs[0].message, /does not support the API version/)
})
it('ignores an inconsistent MinAPIVersion', () => {
assert.equal(negotiateApiVersion({ ApiVersion: '1.52', MinAPIVersion: '1.60' }), MAX_API_VERSION)
assert.equal(negotiateApiVersion({ ApiVersion: '1.52', MinAPIVersion: 'x' }), MAX_API_VERSION)
})
it('rejects an invalid answer', () => {
assert.throws(() => negotiateApiVersion({}), { code: DOCKER_API_VERSION_UNSUPPORTED })
})
})
/**
* Minimal stand-in for `ssh2.Client`: channels are plain connections to a
* local Unix socket.
*/
/**
* Mimic an ssh2 channel whose SSH connection is gone: writes are swallowed,
* nothing is ever received, and `destroy()` emits neither `close` nor `error`
* (like ssh2's Channel#destroy() once the connection is lost).
*/
function createDeadChannel() {
const channel = new Duplex({
read() {},
write(chunk, encoding, cb) {
cb()
},
})
channel.destroy = function (this: Duplex) {
return this
}
return channel
}
// what `DockerConnection` passes to ssh2: its `hostVerifier` is synchronous
type FakeConnectConfig = Omit<ConnectConfig, 'hostVerifier'> & { hostVerifier?: (keyBlob: Buffer) => boolean }
class FakeSshClient extends EventEmitter {
channels: Socket[] = []
channelsOpened = 0
connectConfig!: FakeConnectConfig
// host key presented to the host verifier (if any)
hostKey = Buffer.from(ED25519_KEY, 'base64')
deadChannels = false
// when false, end() does not emit close (unresponsive server)
endEmitsClose = true
openError: Error | undefined
_sock: { destroyed: boolean; destroy: () => boolean } = {
destroyed: false,
destroy: () => (this._sock.destroyed = true),
}
connect(config: FakeConnectConfig) {
this.connectConfig = config
process.nextTick(() => {
if (config.hostVerifier !== undefined && !config.hostVerifier(this.hostKey)) {
this.emit('error', Object.assign(new Error('Host denied (verification failed)'), { level: 'handshake' }))
this.emit('close')
return
}
this.emit('ready')
})
return this
}
openssh_forwardOutStreamLocal(socketPath: string, cb: (error: Error | undefined, channel: Duplex) => void) {
if (this.openError !== undefined) {
process.nextTick(cb, this.openError)
return this
}
++this.channelsOpened
if (this.deadChannels) {
process.nextTick(cb, undefined, createDeadChannel())
return this
}
const socket = netConnect(socketPath)
this.channels.push(socket)
socket.once('connect', () => cb(undefined, socket))
socket.once('error', cb)
return this
}
// what ssh2 does to its channels when the connection is lost: they emit
// `close` but stay writable
simulateDrop() {
for (const channel of this.channels) {
channel.removeAllListeners('data')
channel.pause()
channel.write = (chunk: unknown, encoding?: unknown, cb?: () => void) => {
if (typeof encoding === 'function') cb = encoding as () => void
cb?.()
return true
}
channel.destroy = function (this: Socket) {
return this
}
channel.emit('close')
}
this.channels = []
}
end() {
if (this.endEmitsClose) {
process.nextTick(() => this.emit('close'))
}
return this
}
// part of `SshClient`, replaced by the tests which use it
// eslint-disable-next-line @typescript-eslint/no-unused-vars
exec(command: string, cb: ClientCallback): this {
throw new Error('not implemented')
}
}
describe('DockerConnection (fake daemon)', () => {
let dir: string, socketPath: string, server: Server
let handler: (req: IncomingMessage, res: ServerResponse) => void, requests: string[]
before(async () => {
dir = await mkdtemp(join(tmpdir(), 'xo-docker-test-'))
socketPath = join(dir, 'docker.sock')
server = createServer((req, res) => {
requests.push(req.url!)
handler(req, res)
})
server.listen(socketPath)
await once(server, 'listening')
})
after(async () => {
server.closeAllConnections()
server.close()
await rm(dir, { recursive: true, force: true })
})
const json = (res: ServerResponse, statusCode: number, body: unknown) => {
res.writeHead(statusCode, { 'content-type': 'application/json' })
res.end(JSON.stringify(body))
}
const defaultHandler = (req: IncomingMessage, res: ServerResponse) => {
if (req.url === '/version') {
return json(res, 200, { Version: '27.3.1', ApiVersion: '1.47', MinAPIVersion: '1.24' })
}
if (req.url!.startsWith(`/v${MAX_API_VERSION}/containers/json`)) {
return json(res, 200, [{ Id: 'abc', Names: ['/foo'] }])
}
if (req.url === `/v${MAX_API_VERSION}/containers/missing/json`) {
return json(res, 404, { message: 'No such container: missing' })
}
if (req.url === `/v${MAX_API_VERSION}/echo`) {
const chunks: Buffer[] = []
req.on('data', chunk => chunks.push(chunk))
req.on('end', () => json(res, 201, { method: req.method, body: JSON.parse(Buffer.concat(chunks).toString()) }))
return
}
if (req.url === `/v${MAX_API_VERSION}/logs`) {
res.writeHead(200, { 'content-type': 'application/vnd.docker.raw-stream' })
res.end('line 1\nline 2\n')
return
}
if (req.url === `/v${MAX_API_VERSION}/stream`) {
// headers, then a body which never ends
res.writeHead(200, { 'content-type': 'application/json' })
res.write('{}\n')
return
}
if (req.url!.startsWith('/v1.40/raw') || req.url!.startsWith(`/v${MAX_API_VERSION}/raw`)) {
return json(res, 418, { url: req.url })
}
if (req.url === `/v${MAX_API_VERSION}/hang`) {
// never answers
return
}
res.writeHead(500)
res.end()
}
beforeEach(() => {
handler = defaultHandler
requests = []
})
const createConnection = (opts: Partial<DockerConnectionOptions> = {}) => {
const client = new FakeSshClient()
const connection = new DockerConnection(
{
host: 'fake',
username: 'user',
password: 'secret',
hostKeyFingerprint: ED25519_FINGERPRINT,
socketPath,
requestTimeout: 1e3,
...opts,
},
{ createClient: () => client }
)
return { client, connection }
}
it('exec() times out when the session channel is never opened, and drops a late one', async () => {
const { client, connection } = createConnection({ requestTimeout: 50 })
let callback: ClientCallback | undefined
client.exec = (command, cb) => {
callback = cb
return client
}
await assert.rejects(connection.exec('true'), { code: TIMEOUT })
let destroyed = false
const late = new Duplex({ read() {}, write: (chunk, encoding, cb) => cb() })
late.destroy = function (this: Duplex) {
destroyed = true
return this
}
callback!(undefined, late as unknown as ClientChannel)
assert.ok(destroyed)
await connection.close()
})
it('exec() ends stdin and collects the output', async () => {
const { client, connection } = createConnection()
let stdinEnded = false
client.exec = (command, cb) => {
const channel = Object.assign(
new Duplex({ read() {}, write: (chunk, encoding, cb) => cb(), final: cb => ((stdinEnded = true), cb()) }),
{ stderr: new EventEmitter() }
)
process.nextTick(cb, undefined, channel as unknown as ClientChannel)
setImmediate(() => {
channel.push('ok\n')
channel.emit('exit', 0)
channel.emit('close')
})
return client
}
assert.deepEqual(await connection.exec('true'), { code: 0, signal: undefined, stdout: 'ok\n', stderr: '' })
assert.ok(stdinEnded)
await connection.close()
})
it('reports a daemon closing the channel or answering garbage as DOCKER_API_ERROR', async () => {
const { connection } = createConnection()
await connection.connect()
handler = req => req.socket.destroy()
await assert.rejects(connection.request({ path: '/containers/json' }), { code: DOCKER_API_ERROR })
handler = req => req.socket.end('garbage\r\n\r\n')
await assert.rejects(connection.request({ path: '/containers/json' }), { code: DOCKER_API_ERROR })
await connection.close()
})
it('caps a buffered response at 8 MiB by default, maxSize allows more', async () => {
const { connection } = createConnection({ requestTimeout: 10e3 })
await connection.connect()
handler = (req, res) => {
res.writeHead(200, { 'content-type': 'application/octet-stream' })
res.end(Buffer.alloc(9 * 1024 * 1024))
}
await assert.rejects(connection.request({ path: '/big' }), { code: DOCKER_API_ERROR })
const { body } = await connection.request({ path: '/big', maxSize: 16 * 1024 * 1024 })
assert.equal((body as Buffer).length, 9 * 1024 * 1024)
await connection.close()
})
it('drops keep-alive channels closed by an SSH connection loss (still writable)', async () => {
const { client, connection } = createConnection()
await Promise.all([
connection.request({ path: '/containers/json' }),
connection.request({ path: '/containers/json' }),
])
const opened = client.channelsOpened
client.simulateDrop()
const results = await Promise.all([
connection.request({ path: '/containers/json' }),
connection.request({ path: '/containers/json' }),
])
for (const { statusCode } of results) {
assert.equal(statusCode, 200)
}
assert.ok(client.channelsOpened > opened)
await connection.close()
})
it('settles and releases the slot when a channel never emits close or error', async () => {
const { client, connection } = createConnection({ requestTimeout: 50 })
await connection.connect()
client.deadChannels = true
// the channel used by the negotiation is now dead too
client.simulateDrop()
// more than the max concurrency: leaked slots would make the last ones
// wait forever in the queue (they would still TIMEOUT, so check timing)
for (let i = 0; i < 10; ++i) {
const start = Date.now()
await assert.rejects(connection.request({ path: '/containers/json' }), { code: TIMEOUT })
assert.ok(Date.now() - start < 1e3)
}
client.deadChannels = false
connection.request({ path: '/containers/json' }).catch(() => {})
// a free slot is available immediately
const { statusCode } = await connection.request({ path: '/containers/json', signal: AbortSignal.timeout(1e3) })
assert.equal(statusCode, 200)
await connection.close()
})
it('close() destroys the SSH socket when the server does not close the connection', async () => {
const client = new FakeSshClient()
client.endEmitsClose = false
const connection = new DockerConnection(
{ host: 'fake', username: 'user', hostKeyFingerprint: ED25519_FINGERPRINT, socketPath },
{ createClient: () => client, closeTimeout: 50 }
)
await connection.connect()
await connection.close()
assert.equal(client._sock.destroyed, true)
})
it('close() rejects queued and in-flight requests with CONNECTION_CLOSED and does not reconnect', async () => {
handler = (req: IncomingMessage, res: ServerResponse) =>
req.url === '/version' ? defaultHandler(req, res) : setTimeout(() => json(res, 200, {}), 300).unref()
let clients = 0
const connection = new DockerConnection(
{ host: 'fake', username: 'user', hostKeyFingerprint: ED25519_FINGERPRINT, socketPath, requestTimeout: 5e3 },
{
createClient: () => {
++clients
return new FakeSshClient()
},
}
)
await connection.connect()
const results = Array.from({ length: 12 }, () =>
connection.request({ path: '/slow' }).then(
() => 'ok',
error => error.code
)
)
await new Promise(resolve => setTimeout(resolve, 50))
await connection.close()
assert.deepEqual(await Promise.all(results), Array(12).fill(CONNECTION_CLOSED))
assert.equal(clients, 1)
await connection.close()
})
it('accepts an unknown host key via acceptUnknownHostKey, without requesting an algorithm', async () => {
const client = new FakeSshClient()
const connection = new DockerConnection(
{ host: 'fake', username: 'user', socketPath, acceptUnknownHostKey: true, hostKeyFingerprint: null },
{ createClient: () => client }
)
await connection.connect()
assert.equal(client.connectConfig.algorithms, undefined)
assert.equal(connection.observedHostKey!.fingerprint, ED25519_FINGERPRINT)
await connection.close()
})
it('requests the configured host key algorithm', async () => {
const { client, connection } = createConnection({
hostKeyAlgorithm: 'ssh-rsa',
hostKeyFingerprint: RSA_FINGERPRINT,
})
client.hostKey = Buffer.from(RSA_KEY, 'base64')
await connection.connect()
assert.deepEqual(client.connectConfig.algorithms, { serverHostKey: ['rsa-sha2-512', 'rsa-sha2-256', 'ssh-rsa'] })
await connection.close()
})
it('maps a missing host key type to HOST_KEY_MISMATCH when the algorithm is pinned', async () => {
const { client, connection } = createConnection({
hostKeyAlgorithm: 'ssh-rsa',
hostKeyFingerprint: RSA_FINGERPRINT,
})
client.connect = function (this: FakeSshClient, config: FakeConnectConfig) {
this.connectConfig = config
process.nextTick(() => {
this.emit(
'error',
Object.assign(new Error('Handshake failed: no matching host key format'), { level: 'handshake' })
)
this.emit('close')
})
return this
}
await assert.rejects(connection.connect(), (error: DockerError) => {
assert.equal(error.code, HOST_KEY_MISMATCH)
assert.equal(error.data!.expectedAlgorithm, 'ssh-rsa')
return true
})
})
it('treats a null hostKeyFingerprint as missing (HOST_KEY_UNKNOWN)', async () => {
const { connection } = createConnection({ hostKeyFingerprint: null })
await assert.rejects(connection.connect(), (error: DockerError) => {
assert.equal(error.code, HOST_KEY_UNKNOWN)
assert.equal(error.data!.fingerprint, ED25519_FINGERPRINT)
return true
})
})
it('the caller signal interrupts a pending API version negotiation', async () => {
handler = () => {}
const { connection } = createConnection({ requestTimeout: 10e3 })
const start = Date.now()
await assert.rejects(connection.request({ path: '/info', signal: AbortSignal.timeout(100) }), { code: TIMEOUT })
assert.ok(Date.now() - start < 1e3)
await connection.close()
})
it('negotiates with Podman (API 1.41) and tells it from Docker', async () => {
handler = (req: IncomingMessage, res: ServerResponse) =>
req.url === '/version'
? json(res, 200, {
Version: '5.4.2',
ApiVersion: '1.41',
MinAPIVersion: '1.24',
Platform: { Name: 'linux/amd64/debian-13' },
Components: [{ Name: 'Podman Engine', Version: '5.4.2', Details: { MinAPIVersion: '4.0.0' } }],
})
: json(res, 200, req.url)
const { connection } = createConnection()
assert.equal(connection.engineKind, undefined)
const { body } = await connection.request({ path: '/info' })
assert.equal(body, '/v1.41/info')
assert.equal(connection.apiVersion, '1.41')
assert.equal(connection.engineKind, 'podman')
await connection.close()
})
it('reports TIMEOUT (not DOCKER_API_ERROR) when aborted while reading an error body', async () => {
handler = (req: IncomingMessage, res: ServerResponse) => {
if (req.url === '/version') {
return defaultHandler(req, res)
}
res.writeHead(500, { 'content-type': 'application/json' })
res.write('{"message":')
// never ends
}
const { connection } = createConnection({ requestTimeout: 200 })
await connection.connect()
await assert.rejects(connection.request({ path: '/info' }), { code: TIMEOUT })
await assert.rejects(connection.requestStream({ path: '/info' }), { code: TIMEOUT })
await connection.close()
})
it('configures ssh2 as expected', async () => {
const { client, connection } = createConnection()
await connection.connect()
const { connectConfig } = client
assert.equal(connectConfig.port, 22)
assert.equal(connectConfig.keepaliveInterval, 10e3)
assert.equal(connectConfig.keepaliveCountMax, 3)
assert.equal(connectConfig.hostHash, undefined)
assert.equal(typeof connectConfig.hostVerifier, 'function')
assert.equal(connectConfig.hostVerifier!(Buffer.from(ED25519_KEY, 'base64')), true)
assert.equal(connectConfig.hostVerifier!(Buffer.from(RSA_KEY, 'base64')), false)
assert.equal(connection.observedHostKey!.fingerprint, RSA_FINGERPRINT)
await connection.close()
})
it('negotiates the API version once and prefixes paths', async () => {
const { connection } = createConnection()
const results = await Promise.all([
connection.request({ path: '/containers/json', query: { all: 1, filters: { status: ['running'] } } }),
connection.request({ path: '/containers/json' }),
connection.request({ path: '/containers/json' }),
])
assert.equal(connection.apiVersion, MAX_API_VERSION)
assert.equal(connection.engineVersion, '27.3.1')
assert.equal(connection.engineKind, 'docker')
assert.equal(requests.filter(url => url === '/version').length, 1)
assert.equal(
requests.find(url => url.includes('filters')),
`/v${MAX_API_VERSION}/containers/json?all=1&filters=%7B%22status%22%3A%5B%22running%22%5D%7D`
)
for (const { statusCode, body } of results) {
assert.equal(statusCode, 200)
assert.deepEqual(body, [{ Id: 'abc', Names: ['/foo'] }])
}
await connection.close()
})
it('uses the daemon version when lower than ours', async () => {
handler = (req: IncomingMessage, res: ServerResponse) =>
req.url === '/version'
? json(res, 200, { Version: '20.10.0', ApiVersion: '1.41', MinAPIVersion: '1.12' })
: json(res, 200, { url: req.url })
const { connection } = createConnection()
const { body } = await connection.request({ path: '/info' })
assert.equal((body as { url: string }).url, '/v1.41/info')
await connection.close()
})
it('fails with DOCKER_API_VERSION_UNSUPPORTED and retries negotiation later', async () => {
handler = (req: IncomingMessage, res: ServerResponse) => json(res, 200, { Version: '1.11', ApiVersion: '1.23' })
const { connection } = createConnection()
await assert.rejects(connection.connect(), { code: DOCKER_API_VERSION_UNSUPPORTED })
await assert.rejects(connection.request({ path: '/info' }), { code: DOCKER_API_VERSION_UNSUPPORTED })
assert.equal(requests.filter(url => url === '/version').length, 2)
await connection.close()
})
it('reuses channels across sequential requests (keep-alive)', async () => {
const { client, connection } = createConnection()
for (let i = 0; i < 5; ++i) {
await connection.request({ path: '/containers/json' })
}
// 1 for /version + 5 requests, all on the same channel
assert.equal(requests.length, 6)
assert.equal(client.channelsOpened, 1)
await connection.close()
})
it('opens several channels for concurrent requests', async () => {
const { client, connection } = createConnection()
await connection.connect()
await Promise.all(Array.from({ length: 10 }, () => connection.request({ path: '/containers/json' })))
// bounded by maxSockets
assert.ok(client.channelsOpened > 1 && client.channelsOpened <= 8, `${client.channelsOpened} channels`)
await connection.close()
})
it('sends JSON bodies', async () => {
const { connection } = createConnection()
const { statusCode, body } = await connection.request({ method: 'POST', path: '/echo', body: { foo: 'bar' } })
assert.equal(statusCode, 201)
assert.deepEqual(body, { method: 'POST', body: { foo: 'bar' } })
await connection.close()
})
it('returns a Buffer for non-JSON responses', async () => {
const { connection } = createConnection()
const { body } = await connection.request({ path: '/logs' })
assert.ok(Buffer.isBuffer(body))
assert.equal(body.toString(), 'line 1\nline 2\n')
await connection.close()
})
it('streams responses', async () => {
const { connection } = createConnection()
const response = await connection.requestStream({ path: '/logs' })
const chunks = []
for await (const chunk of response) {
chunks.push(chunk)
}
assert.equal(Buffer.concat(chunks).toString(), 'line 1\nline 2\n')
await connection.close()
})
it('long-lived streams do not use the request slots', async () => {
const { client, connection } = createConnection()
await connection.connect()
const streams = await Promise.all(
Array.from({ length: 20 }, () => connection.requestStream({ path: '/stream', longLived: true }))
)
// closing the connection aborts them
streams.forEach(stream => stream.on('error', () => {}))
assert.deepEqual(connection.activeRequests, { requests: 0, streams: 20 })
// one channel per stream, on the same SSH connection
assert.ok(client.channelsOpened >= 21, `${client.channelsOpened} channels`)
// the regular requests are not starved
await Promise.all(Array.from({ length: 10 }, () => connection.request({ path: '/containers/json' })))
// a stream releases its slot when destroyed, and its channel is not reused
streams[0].destroy()
await once(streams[0], 'close')
assert.equal(connection.activeRequests.streams, 19)
await connection.close()
// not `once()`: it rejects on `error`
await Promise.all(
streams.slice(1).map(stream => (stream.closed ? undefined : new Promise(resolve => stream.on('close', resolve))))
)
assert.deepEqual(connection.activeRequests, { requests: 0, streams: 0 })
})
it('raw requests: verbatim path and query, version prefix unless present, errors returned', async () => {
const { connection } = createConnection()
const read = async (response: IncomingMessage) => {
const chunks: Buffer[] = []
for await (const chunk of response) {
chunks.push(chunk)
}
return JSON.parse(Buffer.concat(chunks).toString())
}
let response = await connection.requestStream({ path: '/raw?a=1&b=%2F', raw: true, longLived: true })
assert.equal(response.statusCode, 418)
assert.deepEqual(await read(response), { url: `/v${MAX_API_VERSION}/raw?a=1&b=%2F` })
response = await connection.requestStream({ path: '/v1.40/raw', raw: true })
assert.deepEqual(await read(response), { url: '/v1.40/raw' })
await connection.close()
})
it('fails with DOCKER_API_ERROR on non-2xx', async () => {
const { connection } = createConnection()
await assert.rejects(connection.request({ path: '/containers/missing/json' }), (error: DockerError) => {
assert.equal(error.code, DOCKER_API_ERROR)
assert.equal(error.data!.statusCode, 404)
assert.equal(error.message, 'No such container: missing')
return true
})
await assert.rejects(connection.requestStream({ path: '/containers/missing/json' }), {
code: DOCKER_API_ERROR,
data: {
host: 'fake',
port: 22,
socketPath,
path: '/containers/missing/json',
statusCode: 404,
message: 'No such container: missing',
},
})
await connection.close()
})
it('reads at most 4 KiB of an error body and truncates the message (hostile daemon)', async () => {
let written = 0
handler = (req: IncomingMessage, res: ServerResponse) => {
if (req.url === '/version') {
return defaultHandler(req, res)
}
if (req.url!.endsWith('/object')) {
return json(res, 500, { message: { toString: 'x' } })
}
if (req.url!.endsWith('/text')) {
res.writeHead(500, { 'content-type': 'text/plain' })
return res.end('y'.repeat(3000))
}
// a never-ending JSON error body
res.writeHead(500, { 'content-type': 'application/json' })
res.write('{"message":"')
const chunk = 'x'.repeat(64 * 1024)
const write = () => {
let more = true
while (more && !res.destroyed && written < 100 * 1024 * 1024) {
written += chunk.length
more = res.write(chunk)
}
if (!more) {
res.once('drain', write)
}
}
write()
}
const { connection } = createConnection({ requestTimeout: 5e3 })
await connection.connect()
const start = Date.now()
for (const call of [
() => connection.request({ path: '/flood' }),
() => connection.requestStream({ path: '/flood' }),
]) {
await assert.rejects(call(), (error: DockerError) => {
assert.equal(error.code, DOCKER_API_ERROR)
assert.equal(error.data!.statusCode, 500)
assert.ok(written < 10 * 1024 * 1024, `${written} bytes written by the daemon`)
assert.ok(error.message.length <= 1024, `message of ${error.message.length} chars`)
assert.ok((error.data!.message as string).length <= 1024)
return true
})
}
assert.ok(Date.now() - start < 2e3, 'does not wait for the whole body')
assert.ok(written < 10 * 1024 * 1024, `${written} bytes written by the daemon`)
await assert.rejects(connection.request({ path: '/object' }), (error: DockerError) => {
assert.equal(error.message, 'Docker API error 500')
assert.equal(error.data!.message, undefined)
return true
})
await assert.rejects(connection.request({ path: '/text' }), (error: DockerError) => {
assert.ok(error.message.length <= 1024)
assert.match(error.message, /^y+…$/)
return true
})
// still usable
handler = defaultHandler
await connection.request({ path: '/containers/json' })
await connection.close()
})
it('times out with TIMEOUT (requestTimeout)', async () => {
const { connection } = createConnection({ requestTimeout: 200 })
await connection.connect()
const start = Date.now()
await assert.rejects(connection.request({ path: '/hang' }), { code: TIMEOUT })
const duration = Date.now() - start
assert.ok(duration >= 150 && duration < 1e3, `${duration}ms`)
await assert.rejects(connection.requestStream({ path: '/hang' }), { code: TIMEOUT })
// the connection is still usable
await connection.request({ path: '/containers/json' })
await connection.close()
})
it('aborts with TIMEOUT (caller signal)', async () => {
const { connection } = createConnection({ requestTimeout: 10e3 })
await connection.connect()
const controller = new AbortController()
setTimeout(() => controller.abort(), 50)
await assert.rejects(connection.request({ path: '/hang', signal: controller.signal }), { code: TIMEOUT })
await assert.rejects(connection.request({ path: '/hang', signal: AbortSignal.abort() }), { code: TIMEOUT })
await connection.close()
})
it('maps channel open failures', async () => {
const { client, connection } = createConnection()
client.openError = Object.assign(new Error('(SSH) Channel open failure: open failed'), { reason: 2 })
await assert.rejects(connection.connect(), (error: DockerError) => {
assert.equal(error.code, DOCKER_SOCKET_UNREACHABLE)
assert.equal(error.data!.socketPath, socketPath)
assert.doesNotMatch(JSON.stringify(error.data), /secret/)
return true
})
await connection.close()
})
it('one instance = one SSH session: never reconnects after close()', async () => {
let clients = 0
const connection = new DockerConnection(
{ host: 'fake', username: 'user', hostKeyFingerprint: ED25519_FINGERPRINT, socketPath },
{
createClient: () => {
++clients
return new FakeSshClient()
},
}
)
await connection.request({ path: '/containers/json' })
await connection.close()
assert.equal(connection.closed, true)
await assert.rejects(connection.request({ path: '/containers/json' }), { code: CONNECTION_CLOSED })
await assert.rejects(connection.connect(), { code: CONNECTION_CLOSED })
assert.equal(clients, 1)
})
it('a lost SSH session closes the connection: requests fail with CONNECTION_CLOSED, onClose() is called once', async () => {
handler = (req: IncomingMessage, res: ServerResponse) =>
req.url === '/version' ? defaultHandler(req, res) : setTimeout(() => json(res, 200, {}), 300).unref()
let clients = 0
let client!: FakeSshClient
const connection = new DockerConnection(
{ host: 'fake', username: 'user', hostKeyFingerprint: ED25519_FINGERPRINT, socketPath, requestTimeout: 5e3 },
{
createClient: () => {
++clients
return (client = new FakeSshClient())
},
}
)
let closes = 0
connection.onClose(() => ++closes)
await connection.connect()
// in-flight (8) and queued (4) requests
const results = Array.from({ length: 12 }, () =>
connection.request({ path: '/slow' }).then(
() => 'ok',
error => error.code
)
)
await new Promise(resolve => setTimeout(resolve, 50))
client.emit('close')
assert.deepEqual(await Promise.all(results), Array(12).fill(CONNECTION_CLOSED))
assert.equal(connection.closed, true)
assert.deepEqual(connection.activeRequests, { requests: 0, streams: 0 })
await assert.rejects(connection.request({ path: '/containers/json' }), { code: CONNECTION_CLOSED })
await connection.close()
assert.equal(closes, 1)
assert.equal(clients, 1)
})
it('a failed SSH connection is not retried by the same instance', async () => {
let clients = 0
const connection = new DockerConnection(
{ host: 'fake', username: 'user', socketPath, hostKeyFingerprint: null },
{
createClient: () => {
++clients
return new FakeSshClient()
},
}
)
let closes = 0
connection.onClose(() => ++closes)
await assert.rejects(connection.connect(), { code: HOST_KEY_UNKNOWN })
await assert.rejects(connection.request({ path: '/containers/json' }), { code: HOST_KEY_UNKNOWN })
assert.equal(clients, 1)
await connection.close()
assert.equal(closes, 0)
})
})

View File

@@ -1,145 +0,0 @@
// Cooldown of the SSH attempts which failed in a way that OpenSSH (>= 9.8)
// penalizes with PerSourcePenalties: authentication failures, and handshakes
// aborted before authentication (host key refused, connection lost…).
//
// Too many of them in a short window make the SSH server refuse every
// connection from XO's address, for all the engines behind it. After such a
// failure, new manual attempts (create, update, test) with the *same*
// parameters are refused locally for `cooldown` ms (SSH_COOLDOWN); changing
// the parameters (e.g. fixing the key) is allowed right away.
//
// It also recognizes the symptom of a penalty: the server closing the
// connection before the handshake (`Connection lost before handshake`) soon
// after failures from XO → SSH_REFUSED_PENALTY with a hint.
//
// Keys are opaque strings (e.g. `engine:<id>`, `target:<host>:<port>`), the
// identity is an opaque hash of the attempt's parameters.
import {
DockerError,
HOST_KEY_MISMATCH,
HOST_KEY_UNKNOWN,
isDockerError,
SSH_AUTH_FAILED,
SSH_COOLDOWN,
SSH_ERROR,
SSH_REFUSED_PENALTY,
} from './errors.mjs'
export const DEFAULT_COOLDOWN = 10e3
// OpenSSH's default maximum penalty (`PerSourcePenalties max:600`)
export const DEFAULT_PENALTY_WINDOW = 10 * 60e3
// errors which, raised while connecting, arm the cooldown
const TRIGGER_CODES = new Set([HOST_KEY_MISMATCH, HOST_KEY_UNKNOWN, SSH_AUTH_FAILED, SSH_ERROR, SSH_REFUSED_PENALTY])
const PENALTY_HINT =
'the SSH server closed the connection before the handshake: the SSH server may be temporarily refusing this address (OpenSSH PerSourcePenalties), after recent failed attempts from XO'
const isHandshakeLoss = (error: unknown): boolean =>
isDockerError(error) &&
error.code === SSH_ERROR &&
typeof error.cause?.message === 'string' &&
error.cause.message.startsWith('Connection lost before handshake')
export class SshCooldown {
#cooldown: number
// key → { identity, code, until }
#entries = new Map<string, { identity: string; code: string; until: number }>()
// key → time of the last failure (any identity)
#lastFailures = new Map<string, number>()
#now: () => number
#penaltyWindow: number
/**
* @param opts.cooldown ms, 0 disables the refusal (not the SSH_REFUSED_PENALTY mapping)
* @param opts.penaltyWindow ms after a failure during which a lost handshake is reported as SSH_REFUSED_PENALTY
* @param opts.now for tests
*/
constructor({
cooldown = DEFAULT_COOLDOWN,
penaltyWindow = DEFAULT_PENALTY_WINDOW,
now = Date.now,
}: { cooldown?: number; penaltyWindow?: number; now?: () => number } = {}) {
this.#cooldown = cooldown
this.#penaltyWindow = penaltyWindow
this.#now = now
}
/** number of tracked keys, for tests */
get size(): number {
return new Set([...this.#entries.keys(), ...this.#lastFailures.keys()]).size
}
#prune(now: number) {
for (const [key, entry] of this.#entries) {
if (entry.until <= now) {
this.#entries.delete(key)
}
}
for (const [key, time] of this.#lastFailures) {
if (time + this.#penaltyWindow <= now) {
this.#lastFailures.delete(key)
}
}
}
/**
* @throws {DockerError} SSH_COOLDOWN if one of the keys failed recently with the same identity
*/
check(keys: string[], identity: string): void {
const now = this.#now()
this.#prune(now)
let until = 0
let code: string | undefined
for (const key of keys) {
const entry = this.#entries.get(key)
if (entry !== undefined && entry.identity === identity && entry.until > until) {
until = entry.until
code = entry.code
}
}
if (until !== 0) {
const retryAfter = Math.max(1, Math.ceil((until - now) / 1e3))
throw new DockerError(
SSH_COOLDOWN,
`a recent SSH attempt with the same parameters failed (${code}): retry in ${retryAfter} s, or change the parameters`,
{ data: { lastCode: code, retryAt: until, retryAfter } }
)
}
}
/**
* Record a connection failure, and convert it if it looks like a penalty.
*
* @returns the error to throw instead of `error`
*/
onFailure<E>(keys: string[], identity: string, error: E): E | DockerError {
if (!isDockerError(error) || !TRIGGER_CODES.has(error.code) || error.data?.failFast) {
return error
}
const now = this.#now()
this.#prune(now)
let result: DockerError = error
if (isHandshakeLoss(error) && keys.some(key => this.#lastFailures.has(key))) {
result = new DockerError(SSH_REFUSED_PENALTY, PENALTY_HINT, { data: error.data, cause: error.cause })
}
for (const key of keys) {
this.#lastFailures.set(key, now)
if (this.#cooldown > 0) {
this.#entries.set(key, { identity, code: result.code, until: now + this.#cooldown })
}
}
return result
}
/**
* Forget the cooldown of keys after a success (not the failure history: a
* penalty may still be running for other parameters).
*/
clear(keys: string[]): void {
for (const key of keys) {
this.#entries.delete(key)
}
}
}

View File

@@ -1,108 +0,0 @@
import assert from 'node:assert/strict'
import { describe, it } from 'node:test'
import { SshCooldown } from './cooldown.mjs'
import {
DOCKER_SOCKET_UNREACHABLE,
DockerError,
HOST_KEY_UNKNOWN,
SSH_AUTH_FAILED,
SSH_COOLDOWN,
SSH_ERROR,
SSH_REFUSED_PENALTY,
SSH_UNREACHABLE,
} from './errors.mjs'
const createClock = (start = 1e6) => {
const clock = () => clock.time
clock.time = start
return clock
}
const authFailed = () => new DockerError(SSH_AUTH_FAILED, 'SSH authentication failed')
const lostHandshake = () =>
new DockerError(SSH_ERROR, 'SSH error', { cause: new Error('Connection lost before handshake') })
describe('SshCooldown', () => {
it('refuses the same identity for the cooldown after an authentication failure, not another one', () => {
const now = createClock()
const cooldown = new SshCooldown({ cooldown: 10e3, now })
const keys = ['engine:a', 'target:h:22']
assert.equal(cooldown.onFailure(keys, 'id1', authFailed()).code, SSH_AUTH_FAILED)
now.time += 4e3
assert.throws(
() => cooldown.check(keys, 'id1'),
(error: DockerError) => {
assert.equal(error.code, SSH_COOLDOWN)
assert.equal(error.data!.lastCode, SSH_AUTH_FAILED)
assert.equal(error.data!.retryAfter, 6)
assert.equal(error.data!.retryAt, 1e6 + 10e3)
return true
}
)
// same address, other engine, same identity: refused through the target key
assert.throws(() => cooldown.check(['engine:b', 'target:h:22'], 'id1'), { code: SSH_COOLDOWN })
// parameters changed: allowed
cooldown.check(keys, 'id2')
now.time += 6e3
cooldown.check(keys, 'id1')
})
it('only authentication, host key and handshake failures arm it, and not the fail-fast copies', () => {
const cooldown = new SshCooldown({ now: createClock() })
for (const code of [SSH_UNREACHABLE, DOCKER_SOCKET_UNREACHABLE]) {
cooldown.onFailure(['k'], 'id', new DockerError(code, code))
}
cooldown.onFailure(['k'], 'id', new DockerError(SSH_AUTH_FAILED, 'x', { data: { failFast: true } }))
cooldown.onFailure(['k'], 'id', new Error('not a DockerError'))
cooldown.check(['k'], 'id')
cooldown.onFailure(['k'], 'id', new DockerError(HOST_KEY_UNKNOWN, 'unknown'))
assert.throws(() => cooldown.check(['k'], 'id'), { code: SSH_COOLDOWN })
})
it('a success clears it', () => {
const cooldown = new SshCooldown({ now: createClock() })
cooldown.onFailure(['k'], 'id', authFailed())
cooldown.clear(['k'])
cooldown.check(['k'], 'id')
})
it('cooldown 0 disables the refusal', () => {
const cooldown = new SshCooldown({ cooldown: 0, now: createClock() })
cooldown.onFailure(['k'], 'id', authFailed())
cooldown.check(['k'], 'id')
})
it('a handshake lost soon after failures → SSH_REFUSED_PENALTY with a hint, not without history', () => {
const now = createClock()
const cooldown = new SshCooldown({ cooldown: 0, penaltyWindow: 60e3, now })
// no history: kept as is
assert.equal(cooldown.onFailure(['target:h:22'], 'id', lostHandshake()).code, SSH_ERROR)
now.time += 61e3
cooldown.onFailure(['target:h:22'], 'id', authFailed())
now.time += 30e3
const error = cooldown.onFailure(['target:h:22', 'engine:x'], 'other', lostHandshake())
assert.equal(error.code, SSH_REFUSED_PENALTY)
assert.match(error.message, /temporarily refusing this address \(OpenSSH PerSourcePenalties\)/)
assert.equal(error.cause!.message, 'Connection lost before handshake')
// outside the window
now.time += 61e3
assert.equal(cooldown.onFailure(['target:h:22'], 'id', lostHandshake()).code, SSH_ERROR)
})
it('prunes the expired entries', () => {
const now = createClock()
const cooldown = new SshCooldown({ cooldown: 1e3, penaltyWindow: 5e3, now })
cooldown.onFailure(['a', 'b'], 'id', authFailed())
assert.equal(cooldown.size, 2)
now.time += 5e3
cooldown.check(['c'], 'id')
assert.equal(cooldown.size, 0)
})
})

File diff suppressed because it is too large Load Diff

View File

@@ -1,226 +0,0 @@
// Error codes of the Docker transport (SSH → docker.sock).
//
// They are stable identifiers meant to be consumed by the API/UI, the message
// is only informative.
export const SSH_AUTH_FAILED = 'SSH_AUTH_FAILED'
export const SSH_UNREACHABLE = 'SSH_UNREACHABLE'
// generic SSH failure which does not fit in a more specific code (protocol
// error, handshake failure, disconnection by the server…)
export const SSH_ERROR = 'SSH_ERROR'
// the SSH server closed the connection before the handshake shortly after
// other failures from XO: probably OpenSSH's PerSourcePenalties (>= 9.8)
// refusing XO's address for a while
export const SSH_REFUSED_PENALTY = 'SSH_REFUSED_PENALTY'
// refused locally, without connecting: a recent attempt with the same
// parameters failed (authentication, host key, handshake), see
// `docker.authFailureCooldown`; `data.retryAfter` is in seconds
export const SSH_COOLDOWN = 'SSH_COOLDOWN'
export const HOST_KEY_UNKNOWN = 'HOST_KEY_UNKNOWN'
export const HOST_KEY_MISMATCH = 'HOST_KEY_MISMATCH'
export const STREAM_LOCAL_FORWARDING_DISABLED = 'STREAM_LOCAL_FORWARDING_DISABLED'
export const DOCKER_SOCKET_UNREACHABLE = 'DOCKER_SOCKET_UNREACHABLE'
// the SSH server is not (detected as) OpenSSH, `direct-streamlocal@openssh.com`
// cannot be used
export const STREAM_LOCAL_UNSUPPORTED = 'STREAM_LOCAL_UNSUPPORTED'
export const DOCKER_API_ERROR = 'DOCKER_API_ERROR'
export const DOCKER_API_VERSION_UNSUPPORTED = 'DOCKER_API_VERSION_UNSUPPORTED'
export const TIMEOUT = 'TIMEOUT'
export const POOL_EXHAUSTED = 'POOL_EXHAUSTED'
// the request was interrupted (or never sent) because `close()` was called
export const CONNECTION_CLOSED = 'CONNECTION_CLOSED'
// raw passthrough: the request body exceeds `docker.maxRawRequestSize`
export const RAW_REQUEST_TOO_LARGE = 'RAW_REQUEST_TOO_LARGE'
// raw passthrough: the response exceeds `docker.maxRawResponseSize`
export const RAW_RESPONSE_TOO_LARGE = 'RAW_RESPONSE_TOO_LARGE'
// SSH_MSG_CHANNEL_OPEN_FAILURE reason codes (RFC 4254 § 5.1)
export const SSH_OPEN_ADMINISTRATIVELY_PROHIBITED = 1
export const SSH_OPEN_CONNECT_FAILED = 2
// keys which must never end up in an error (data or cause)
const SENSITIVE_KEYS = new Set(['passphrase', 'password', 'privateKey', 'authHandler', 'agent', 'sock'])
/**
* Returns a shallow copy of `value` without any sensitive entries.
*/
export function scrub(value: unknown): unknown {
if (value === null || typeof value !== 'object' || Buffer.isBuffer(value)) {
return value
}
if (Array.isArray(value)) {
return value.map(scrub)
}
const result: Record<string, unknown> = {}
for (const key of Object.keys(value)) {
if (!SENSITIVE_KEYS.has(key)) {
result[key] = scrub((value as Record<string, unknown>)[key])
}
}
return result
}
/**
* Error kept as the `cause` of a DockerError: a clean copy of the original one
* (see `sanitizeCause()`), with the diagnosis fields of ssh2 and Node errors
* (`code`, `level`, `reason`…).
*/
export type DockerErrorCause = Error & Record<string, unknown>
// fields of an ssh2 (or Node) error kept by `sanitizeCause()`
const CAUSE_KEYS = ['code', 'level', 'reason', 'description', 'errno', 'syscall', 'address', 'port', 'fatal'] as const
/**
* Copy of an ssh2 error that only keeps the fields useful for diagnosis.
*
* ssh2 errors do not reference the connection config in this version but
* nothing prevents a future version (or some intermediate code) to attach it,
* so rebuild a clean error instead of keeping the original object.
*/
function sanitizeCause(error: unknown): DockerErrorCause | undefined {
if (error === undefined || error === null) {
return undefined
}
if (!(error instanceof Error)) {
return new Error(String(error)) as DockerErrorCause
}
const copy = new Error(error.message) as DockerErrorCause
copy.name = error.name
copy.stack = error.stack
for (const key of CAUSE_KEYS) {
const value = (error as DockerErrorCause)[key]
if (value !== undefined) {
copy[key] = value
}
}
if (error.cause !== undefined) {
copy.cause = sanitizeCause(error.cause)
}
return copy
}
/** Non-sensitive details of a DockerError (sensitive keys are removed, see `scrub()`) */
export type DockerErrorData = Record<string, unknown>
export class DockerError extends Error {
// `declare`: no class fields, which would define the properties (even
// `undefined` ones) before the constructor assigns them
declare code: string
declare data?: DockerErrorData
declare cause?: DockerErrorCause
/**
* @param code one of the exported codes
*/
constructor(code: string, message: string, { data, cause }: { data?: object; cause?: unknown } = {}) {
const sanitizedCause = sanitizeCause(cause)
super(message, sanitizedCause === undefined ? undefined : { cause: sanitizedCause })
this.name = 'DockerError'
this.code = code
if (data !== undefined) {
this.data = scrub(data) as DockerErrorData
}
}
}
export const isDockerError = (error: unknown): error is DockerError => error instanceof DockerError
// the properties of an unknown error which are looked at (reading them on a
// primitive gives `undefined`)
type ErrorLike = { name?: unknown; message?: unknown; level?: unknown; reason?: unknown } | null | undefined
const isAbortOrTimeout = (error: unknown) =>
(error as ErrorLike)?.name === 'AbortError' || (error as ErrorLike)?.name === 'TimeoutError'
/**
* Convert an error raised by ssh2 (or by the transport around it) to a
* DockerError.
*
* Already converted errors are returned as is.
*
* @param context non-sensitive context added to `data`
*/
export function fromSshError(
error: unknown,
context: { host?: string; port?: number; socketPath?: string } = {}
): DockerError {
if (isDockerError(error)) {
return error
}
const data: DockerErrorData = { ...context }
const errorLike = error as ErrorLike
if (isAbortOrTimeout(error)) {
return new DockerError(TIMEOUT, 'operation timed out or was aborted', { data, cause: error })
}
const level = errorLike?.level
if (level === 'client-authentication') {
return new DockerError(SSH_AUTH_FAILED, 'SSH authentication failed', { data, cause: error })
}
if (level === 'client-timeout') {
// either the ready timeout (connect + handshake + auth) or the keepalive
// timeout
return new DockerError(SSH_UNREACHABLE, 'SSH server did not answer in time', { data, cause: error })
}
if (level === 'client-socket' || level === 'client-dns') {
return new DockerError(SSH_UNREACHABLE, 'SSH server is unreachable', { data, cause: error })
}
// channel open failure, see onChannelOpenFailure() in ssh2/lib/utils.js
//
// `reason` is the numeric code from SSH_MSG_CHANNEL_OPEN_FAILURE, or `''`
// when the server closed the channel instead of answering. The server's
// description is only available in the message (no dedicated property).
const reason = errorLike?.reason
if (reason !== undefined) {
data.reason = reason
data.description = String(errorLike!.message).replace(/^\(SSH\) Channel open failure: /, '')
if (reason === SSH_OPEN_ADMINISTRATIVELY_PROHIBITED) {
return new DockerError(
STREAM_LOCAL_FORWARDING_DISABLED,
'stream local forwarding is disabled on the SSH server',
{
data,
cause: error,
}
)
}
if (reason === SSH_OPEN_CONNECT_FAILED) {
// OpenSSH (checked with 10.0) answers CONNECT_FAILED with the
// description `open failed` in every case: missing socket, permission
// denied, *and* AllowStreamLocalForwarding/DisableForwarding (in
// serverloop.c, `reason` keeps its CONNECT_FAILED default for
// `direct-streamlocal@openssh.com`), so the cause cannot be
// distinguished from the client side.
//
// ADMINISTRATIVELY_PROHIBITED is still handled above for other servers.
return new DockerError(
DOCKER_SOCKET_UNREACHABLE,
'cannot open the Docker socket through SSH (missing socket, missing permission, or stream local forwarding disabled)',
{ data, cause: error }
)
}
return new DockerError(SSH_ERROR, 'SSH channel open failure', { data, cause: error })
}
// thrown synchronously by `Client#connect()` when the key cannot be used
// (unparsable, wrong passphrase…), the message does not contain the key
const message = errorLike?.message
if (
typeof message === 'string' &&
(message.startsWith('Cannot parse privateKey') || message.startsWith('privateKey value does not'))
) {
return new DockerError(SSH_AUTH_FAILED, 'the SSH private key cannot be used', { data, cause: error })
}
if (typeof message === 'string' && message.startsWith('strictVendor enabled')) {
return new DockerError(STREAM_LOCAL_UNSUPPORTED, 'the SSH server does not support stream local forwarding', {
data,
cause: error,
})
}
return new DockerError(SSH_ERROR, 'SSH error', { data, cause: error })
}

View File

@@ -1,118 +0,0 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import {
DOCKER_SOCKET_UNREACHABLE,
DockerError,
fromSshError,
scrub,
SSH_AUTH_FAILED,
SSH_ERROR,
SSH_UNREACHABLE,
STREAM_LOCAL_FORWARDING_DISABLED,
STREAM_LOCAL_UNSUPPORTED,
TIMEOUT,
} from './errors.mjs'
const { describe, it } = test
function sshError(message: string, props: object) {
return Object.assign(new Error(message), props)
}
describe('fromSshError()', () => {
const cases: [string, Error, string][] = [
[
'auth failure',
sshError('All configured authentication methods failed', { level: 'client-authentication' }),
SSH_AUTH_FAILED,
],
[
'socket error',
sshError('connect ECONNREFUSED 127.0.0.1:1', { level: 'client-socket', code: 'ECONNREFUSED' }),
SSH_UNREACHABLE,
],
['ready timeout', sshError('Timed out while waiting for handshake', { level: 'client-timeout' }), SSH_UNREACHABLE],
['DNS error', sshError('getaddrinfo ENOTFOUND foo', { level: 'client-dns', code: 'ENOTFOUND' }), SSH_UNREACHABLE],
[
'administratively prohibited',
sshError('(SSH) Channel open failure: ', { reason: 1 }),
STREAM_LOCAL_FORWARDING_DISABLED,
],
['connect failed', sshError('(SSH) Channel open failure: open failed', { reason: 2 }), DOCKER_SOCKET_UNREACHABLE],
[
'channel closed',
sshError('(SSH) Channel open failure: server closed channel unexpectedly', { reason: '' }),
SSH_ERROR,
],
[
'strict vendor',
new Error('strictVendor enabled and server is not OpenSSH or compatible version'),
STREAM_LOCAL_UNSUPPORTED,
],
['AbortError', new DOMException('This operation was aborted', 'AbortError'), TIMEOUT],
['TimeoutError', new DOMException('The operation was aborted due to timeout', 'TimeoutError'), TIMEOUT],
['handshake error', sshError('Host denied (verification failed)', { level: 'handshake' }), SSH_ERROR],
['unknown', new Error('something'), SSH_ERROR],
]
for (const [name, error, code] of cases) {
it(`maps ${name} to ${code}`, () => {
const result = fromSshError(error, { host: 'h', port: 22 })
assert.ok(result instanceof DockerError)
assert.equal(result.code, code)
assert.equal(result.data!.host, 'h')
assert.equal(result.cause!.message, error.message)
})
}
it('keeps the channel open failure details', () => {
const result = fromSshError(sshError('(SSH) Channel open failure: open failed', { reason: 2 }))
assert.equal(result.data!.reason, 2)
assert.equal(result.data!.description, 'open failed')
assert.equal(result.cause!.reason, 2)
})
it('returns DockerError as is', () => {
const error = new DockerError(TIMEOUT, 'foo')
assert.equal(fromSshError(error), error)
})
it('does not leak credentials attached to the original error', () => {
const error = sshError('All configured authentication methods failed', {
level: 'client-authentication',
config: { password: 'hunter2', privateKey: 'KEY' },
password: 'hunter2',
})
// the context is not supposed to contain credentials
const result = fromSshError(error, { host: 'h', password: 'hunter2', privateKey: 'KEY' } as { host: string })
const serialized = JSON.stringify({ data: result.data, cause: result.cause, ...result.cause })
assert.doesNotMatch(serialized, /hunter2|KEY/)
assert.equal(result.cause!.config, undefined)
assert.equal(result.cause!.password, undefined)
assert.equal(result.cause!.level, 'client-authentication')
})
})
describe('scrub()', () => {
it('removes sensitive keys recursively', () => {
assert.deepEqual(
scrub({ a: 1, password: 'x', nested: { privateKey: 'y', passphrase: 'z', b: [{ password: 1, c: 2 }] } }),
{
a: 1,
nested: { b: [{ c: 2 }] },
}
)
})
})
describe('DockerError', () => {
it('has code, data and a sanitized cause', () => {
const cause = Object.assign(new Error('boom'), { code: 'ECONNRESET', password: 'secret' })
const error = new DockerError(SSH_ERROR, 'msg', { data: { host: 'h', password: 'secret' }, cause })
assert.equal(error.name, 'DockerError')
assert.equal(error.code, SSH_ERROR)
assert.deepEqual(error.data, { host: 'h' })
assert.equal(error.cause!.code, 'ECONNRESET')
assert.equal(error.cause!.password, undefined)
})
})

File diff suppressed because it is too large Load Diff

View File

@@ -1,189 +0,0 @@
// Real payloads recorded from Docker Engine 29.8.1 (rootless, cgroup v2), at the
// negotiated API version 1.43 (`GET /v1.43/…`). Host-specific values (user
// name, host name, paths, engine ID) have been scrubbed. Do not edit by hand:
// re-record them instead.
import type { DockerInfo, DockerVersion } from '../wire.mjs'
export const INFO = {
Architecture: 'x86_64',
BridgeNfIp6tables: false,
BridgeNfIptables: false,
CDISpecDirs: ['/etc/cdi', '/var/run/cdi', '/home/docker/.config/cdi', '/home/docker/.docker-run/cdi'],
CPUSet: false,
CPUShares: true,
CgroupDriver: 'systemd',
CgroupVersion: '2',
ContainerdCommit: {
Expected: '1294c24a7da8e5a793ed378161673abe94118892',
ID: '1294c24a7da8e5a793ed378161673abe94118892',
},
Containers: 8,
ContainersPaused: 1,
ContainersRunning: 5,
ContainersStopped: 2,
CpuCfsPeriod: true,
CpuCfsQuota: true,
Debug: false,
DefaultRuntime: 'runc',
DockerRootDir: '/home/docker/.local/share/docker',
Driver: 'overlayfs',
DriverStatus: [['driver-type', 'io.containerd.snapshotter.v1']],
ExperimentalBuild: false,
GenericResources: null,
HttpProxy: '',
HttpsProxy: '',
ID: '00000000-0000-4000-8000-000000000000',
IPv4Forwarding: true,
Images: 3,
IndexServerAddress: 'https://index.docker.io/v1/',
InitBinary: 'docker-init',
InitCommit: {
Expected: 'de40ad0',
ID: 'de40ad0',
},
Isolation: '',
KernelVersion: '6.12.101+deb13-amd64',
Labels: [],
LiveRestoreEnabled: false,
LoggingDriver: 'json-file',
MemTotal: 5157838848,
MemoryLimit: true,
NCPU: 6,
NEventsListener: 0,
NFd: 156,
NGoroutines: 262,
Name: 'docker-host',
NoProxy: '',
OSType: 'linux',
OSVersion: '13',
OomKillDisable: false,
OperatingSystem: 'Debian GNU/Linux 13 (trixie)',
PidsLimit: true,
Plugins: {
Authorization: null,
Log: ['awslogs', 'fluentd', 'gcplogs', 'gelf', 'journald', 'json-file', 'local', 'splunk', 'syslog'],
Network: ['bridge', 'host', 'ipvlan', 'macvlan', 'null', 'overlay'],
Volume: ['local'],
},
ProductLicense: 'Community Engine',
RegistryConfig: {
AllowNondistributableArtifactsCIDRs: null,
AllowNondistributableArtifactsHostnames: null,
IndexConfigs: {
'docker.io': {
Mirrors: [],
Name: 'docker.io',
Official: true,
Secure: true,
},
},
InsecureRegistryCIDRs: ['::1/128', '127.0.0.0/8'],
Mirrors: [],
},
RuncCommit: {
Expected: 'v1.5.1-0-g8f2685a',
ID: 'v1.5.1-0-g8f2685a',
},
Runtimes: {
'io.containerd.runc.v2': {
path: 'runc',
},
runc: {
path: 'runc',
},
},
SecurityOptions: ['name=seccomp,profile=builtin', 'name=rootless', 'name=cgroupns'],
ServerVersion: '29.8.1',
SwapLimit: true,
Swarm: {
ControlAvailable: false,
Error: '',
LocalNodeState: 'inactive',
NodeAddr: '',
NodeID: '',
RemoteManagers: null,
},
SystemTime: '2026-09-24T16:56:16.993022218Z',
Warnings: [
'WARNING: No cpuset support',
'WARNING: No io.weight support',
'WARNING: No io.weight (per device) support',
'WARNING: No io.max (rbps) support',
'WARNING: No io.max (wbps) support',
'WARNING: No io.max (riops) support',
'WARNING: No io.max (wiops) support',
],
} satisfies DockerInfo
export const VERSION = {
Platform: {
Name: 'Docker Engine - Community',
},
Version: '29.8.1',
ApiVersion: '1.56',
MinAPIVersion: '1.40',
Os: 'linux',
Arch: 'amd64',
Components: [
{
Name: 'Engine',
Version: '29.8.1',
Details: {
ApiVersion: '1.56',
Arch: 'amd64',
BuildTime: '2026-09-15T16:27:24.000000000+00:00',
Experimental: 'false',
GitCommit: '464cd50',
GoVersion: 'go1.26.8',
KernelVersion: '6.12.101+deb13-amd64',
MinAPIVersion: '1.40',
Module: 'github.com/moby/moby/v2',
ModuleVersion: 'v2.0.0+unknown',
Os: 'linux',
},
},
{
Name: 'containerd',
Version: 'v2.3.5',
Details: {
GitCommit: '1294c24a7da8e5a793ed378161673abe94118892',
},
},
{
Name: 'runc',
Version: '1.5.1',
Details: {
GitCommit: 'v1.5.1-0-g8f2685a',
},
},
{
Name: 'docker-init',
Version: '0.19.0',
Details: {
GitCommit: 'de40ad0',
},
},
{
Name: 'rootlesskit',
Version: '3.1.0',
Details: {
ApiVersion: '1.1.2',
NetworkDriver: 'slirp4netns',
PortDriver: 'builtin',
StateDir: '/home/docker/.docker-run/dockerd-rootless',
},
},
{
Name: 'slirp4netns',
Version: '1.3.5',
Details: {
GitCommit: '7132ff3ba66cf0eebd8c9a83b9f23838bc84c518',
},
},
],
GitCommit: '464cd50',
GoVersion: 'go1.26.8',
KernelVersion: '6.12.101+deb13-amd64',
BuildTime: '2026-09-15T16:27:24.000000000+00:00',
} satisfies DockerVersion

View File

@@ -1,22 +0,0 @@
// Real payloads recorded from Docker Engine 29.8.1 (rootless, cgroup v2), at the
// negotiated API version 1.43 (`GET /v1.43/…`). Host-specific values (user
// name, host name, paths, engine ID) have been scrubbed. Do not edit by hand:
// re-record them instead.
//
// `GET /containers/{id}/logs?stdout=1&stderr=1&timestamps=1&tail=100`: the
// response `Content-Type` and the base64-encoded body.
export const LOGS_NGINX = {
contentType: 'application/vnd.docker.multiplexed-stream',
body: 'AQAAAAAAAIAyMDI2LTA5LTI0VDE2OjU0OjM3Ljc5NjMzMDIyMVogL2RvY2tlci1lbnRyeXBvaW50LnNoOiAvZG9ja2VyLWVudHJ5cG9pbnQuZC8gaXMgbm90IGVtcHR5LCB3aWxsIGF0dGVtcHQgdG8gcGVyZm9ybSBjb25maWd1cmF0aW9uCgEAAAAAAABpMjAyNi0wOS0yNFQxNjo1NDozNy43OTY0MDA2NTJaIC9kb2NrZXItZW50cnlwb2ludC5zaDogTG9va2luZyBmb3Igc2hlbGwgc2NyaXB0cyBpbiAvZG9ja2VyLWVudHJ5cG9pbnQuZC8KAQAAAAAAAHUyMDI2LTA5LTI0VDE2OjU0OjM3Ljc5ODY3MjU3NlogL2RvY2tlci1lbnRyeXBvaW50LnNoOiBMYXVuY2hpbmcgL2RvY2tlci1lbnRyeXBvaW50LmQvMTAtbGlzdGVuLW9uLWlwdjYtYnktZGVmYXVsdC5zaAoBAAAAAAAAfTIwMjYtMDktMjRUMTY6NTQ6MzcuODEyMDI1MzA1WiAxMC1saXN0ZW4tb24taXB2Ni1ieS1kZWZhdWx0LnNoOiBpbmZvOiBHZXR0aW5nIHRoZSBjaGVja3N1bSBvZiAvZXRjL25naW54L2NvbmYuZC9kZWZhdWx0LmNvbmYKAQAAAAAAAH8yMDI2LTA5LTI0VDE2OjU0OjM3Ljg1NjUyODE2NVogMTAtbGlzdGVuLW9uLWlwdjYtYnktZGVmYXVsdC5zaDogaW5mbzogRW5hYmxlZCBsaXN0ZW4gb24gSVB2NiBpbiAvZXRjL25naW54L2NvbmYuZC9kZWZhdWx0LmNvbmYKAQAAAAAAAG0yMDI2LTA5LTI0VDE2OjU0OjM3Ljg1Njc4MTc4M1ogL2RvY2tlci1lbnRyeXBvaW50LnNoOiBTb3VyY2luZyAvZG9ja2VyLWVudHJ5cG9pbnQuZC8xNS1sb2NhbC1yZXNvbHZlcnMuZW52c2gKAQAAAAAAAHEyMDI2LTA5LTI0VDE2OjU0OjM3Ljg1NzY0OTQwMVogL2RvY2tlci1lbnRyeXBvaW50LnNoOiBMYXVuY2hpbmcgL2RvY2tlci1lbnRyeXBvaW50LmQvMjAtZW52c3Vic3Qtb24tdGVtcGxhdGVzLnNoCgEAAAAAAABxMjAyNi0wOS0yNFQxNjo1NDozNy44NjY1NzE4MzNaIC9kb2NrZXItZW50cnlwb2ludC5zaDogTGF1bmNoaW5nIC9kb2NrZXItZW50cnlwb2ludC5kLzMwLXR1bmUtd29ya2VyLXByb2Nlc3Nlcy5zaAoBAAAAAAAAYTIwMjYtMDktMjRUMTY6NTQ6MzcuODcwMDc3Mjg5WiAvZG9ja2VyLWVudHJ5cG9pbnQuc2g6IENvbmZpZ3VyYXRpb24gY29tcGxldGU7IHJlYWR5IGZvciBzdGFydCB1cAoCAAAAAAAAYDIwMjYtMDktMjRUMTY6NTQ6MzcuODgzMjcwMTQ4WiAyMDI2LzA5LzI0IDE2OjU0OjM3IFtub3RpY2VdIDEjMTogdXNpbmcgdGhlICJlcG9sbCIgZXZlbnQgbWV0aG9kCgIAAAAAAABOMjAyNi0wOS0yNFQxNjo1NDozNy44ODMyOTEzMTBaIDIwMjYvMDkvMjQgMTY6NTQ6MzcgW25vdGljZV0gMSMxOiBuZ2lueC8xLjMxLjYKAgAAAAAAAGYyMDI2LTA5LTI0VDE2OjU0OjM3Ljg4MzI5ODM1N1ogMjAyNi8wOS8yNCAxNjo1NDozNyBbbm90aWNlXSAxIzE6IGJ1aWx0IGJ5IGdjYyAxNS4yLjAgKEFscGluZSAxNS4yLjApIAoCAAAAAAAAYDIwMjYtMDktMjRUMTY6NTQ6MzcuODgzMzA0Mzc5WiAyMDI2LzA5LzI0IDE2OjU0OjM3IFtub3RpY2VdIDEjMTogT1M6IExpbnV4IDYuMTIuMTAxK2RlYjEzLWFtZDY0CgIAAAAAAABnMjAyNi0wOS0yNFQxNjo1NDozNy44ODMzMTAzMjBaIDIwMjYvMDkvMjQgMTY6NTQ6MzcgW25vdGljZV0gMSMxOiBnZXRybGltaXQoUkxJTUlUX05PRklMRSk6IDEwMjQ6NTI0Mjg4CgIAAAAAAABYMjAyNi0wOS0yNFQxNjo1NDozNy44ODMzMjc5MzBaIDIwMjYvMDkvMjQgMTY6NTQ6MzcgW25vdGljZV0gMSMxOiBzdGFydCB3b3JrZXIgcHJvY2Vzc2VzCgIAAAAAAABZMjAyNi0wOS0yNFQxNjo1NDozNy44ODM1OTA1NTlaIDIwMjYvMDkvMjQgMTY6NTQ6MzcgW25vdGljZV0gMSMxOiBzdGFydCB3b3JrZXIgcHJvY2VzcyAzMAoCAAAAAAAAWTIwMjYtMDktMjRUMTY6NTQ6MzcuODgzNzU1OTk5WiAyMDI2LzA5LzI0IDE2OjU0OjM3IFtub3RpY2VdIDEjMTogc3RhcnQgd29ya2VyIHByb2Nlc3MgMzEKAgAAAAAAAFkyMDI2LTA5LTI0VDE2OjU0OjM3Ljg4NDY4NjA1MlogMjAyNi8wOS8yNCAxNjo1NDozNyBbbm90aWNlXSAxIzE6IHN0YXJ0IHdvcmtlciBwcm9jZXNzIDMyCgIAAAAAAABZMjAyNi0wOS0yNFQxNjo1NDozNy44ODQ2OTc4NjRaIDIwMjYvMDkvMjQgMTY6NTQ6MzcgW25vdGljZV0gMSMxOiBzdGFydCB3b3JrZXIgcHJvY2VzcyAzMwoCAAAAAAAAWTIwMjYtMDktMjRUMTY6NTQ6MzcuODg1MDA1ODQzWiAyMDI2LzA5LzI0IDE2OjU0OjM3IFtub3RpY2VdIDEjMTogc3RhcnQgd29ya2VyIHByb2Nlc3MgMzQKAgAAAAAAAFkyMDI2LTA5LTI0VDE2OjU0OjM3Ljg4NTAzNTMxMlogMjAyNi8wOS8yNCAxNjo1NDozNyBbbm90aWNlXSAxIzE6IHN0YXJ0IHdvcmtlciBwcm9jZXNzIDM1CgEAAAAAAAB6MjAyNi0wOS0yNFQxNjo1NjowNS41NzM0OTQwOTdaIDE3Mi4xNy4wLjEgLSAtIFsyNC9TZXAvMjAyNjoxNjo1NjowNSArMDAwMF0gIkdFVCAvIEhUVFAvMS4xIiAyMDAgODk2ICItIiAiY3VybC84LjE0LjEiICItIgoBAAAAAAAAgTIwMjYtMDktMjRUMTY6NTY6MDUuNTg3OTY2NzI5WiAxNzIuMTcuMC4xIC0gLSBbMjQvU2VwLzIwMjY6MTY6NTY6MDUgKzAwMDBdICJHRVQgL21pc3NpbmcgSFRUUC8xLjEiIDQwNCAxNTMgIi0iICJjdXJsLzguMTQuMSIgIi0iCgIAAAAAAADzMjAyNi0wOS0yNFQxNjo1NjowNS41ODc5NjU3MjNaIDIwMjYvMDkvMjQgMTY6NTY6MDUgW2Vycm9yXSAzMyMzMzogKjIgb3BlbigpICIvdXNyL3NoYXJlL25naW54L2h0bWwvbWlzc2luZyIgZmFpbGVkICgyOiBObyBzdWNoIGZpbGUgb3IgZGlyZWN0b3J5KSwgY2xpZW50OiAxNzIuMTcuMC4xLCBzZXJ2ZXI6IGxvY2FsaG9zdCwgcmVxdWVzdDogIkdFVCAvbWlzc2luZyBIVFRQLzEuMSIsIGhvc3Q6ICIxMjcuMC4wLjE6ODA4MCIK',
}
export const LOGS_EXITED = {
contentType: 'application/vnd.docker.multiplexed-stream',
body: 'AQAAAAAAADIyMDI2LTA5LTI0VDE2OjU0OjM4LjM3NzE3Mzk2OFogZmFpbGluZyBvbiBwdXJwb3NlCg==',
}
export const LOGS_TTY = {
contentType: 'application/vnd.docker.raw-stream',
body: 'MjAyNi0wOS0yNFQxNjo1NjowNS4xMTAzNTUwMzBaIHR0eSBsaW5lIG9uZQ0KMjAyNi0wOS0yNFQxNjo1NjowNS4xMTA5ODg5OTlaIHR0eSBsaW5lIHR3bw0KMjAyNi0wOS0yNFQxNjo1NjowNS4xNzA2MDM4OTlaIG5vIG5ld2xpbmUgYXQgZW5k',
}

View File

@@ -1,560 +0,0 @@
// Real payloads recorded from Docker Engine 29.8.1 (rootless, cgroup v2), at the
// negotiated API version 1.43 (`GET /v1.43/…`). Host-specific values (user
// name, host name, paths, engine ID) have been scrubbed. Do not edit by hand:
// re-record them instead.
//
// `STATS_BUSY` is a container running a busy loop (one full core).
// `STATS_STREAM_NGINX` are the first two objects of `?stream=true`: the first one
// has no `precpu_stats.system_cpu_usage`.
import type { DockerStatsSample } from '../wire.mjs'
export const STATS_NGINX_IDLE = {
id: '0f5359257668ff1fd83db09c2c906d810a4363ebeeffdf02f8a9e47faf41f731',
name: '/xo-nginx',
os_type: 'linux',
read: '2026-09-24T16:56:14.968764848Z',
cpu_stats: {
cpu_usage: {
total_usage: 115914000,
usage_in_kernelmode: 60038000,
usage_in_usermode: 55876000,
},
system_cpu_usage: 15705826330000000,
online_cpus: 6,
throttling_data: {
periods: 0,
throttled_periods: 0,
throttled_time: 0,
},
},
memory_stats: {
usage: 8650752,
stats: {
active_anon: 5148672,
active_file: 1650688,
anon: 5144576,
anon_thp: 0,
file: 2301952,
file_dirty: 0,
file_mapped: 282624,
file_writeback: 0,
inactive_anon: 0,
inactive_file: 647168,
kernel_stack: 114688,
pgactivate: 0,
pgdeactivate: 0,
pgfault: 4588,
pglazyfree: 0,
pglazyfreed: 0,
pgmajfault: 14,
pgrefill: 0,
pgscan: 0,
pgsteal: 0,
shmem: 4096,
slab: 545152,
slab_reclaimable: 201448,
slab_unreclaimable: 343704,
sock: 0,
thp_collapse_alloc: 0,
thp_fault_alloc: 2,
unevictable: 0,
workingset_activate: 0,
workingset_nodereclaim: 0,
workingset_refault: 0,
},
limit: 5157838848,
},
networks: {
eth0: {
rx_bytes: 2357,
rx_packets: 33,
rx_errors: 0,
rx_dropped: 0,
tx_bytes: 2220,
tx_packets: 13,
tx_errors: 0,
tx_dropped: 0,
},
},
pids_stats: {
current: 7,
limit: 5851,
},
blkio_stats: {
io_service_bytes_recursive: null,
io_serviced_recursive: null,
io_queue_recursive: null,
io_service_time_recursive: null,
io_wait_time_recursive: null,
io_merged_recursive: null,
io_time_recursive: null,
sectors_recursive: null,
},
num_procs: 0,
storage_stats: {},
preread: '2026-09-24T16:56:13.963804807Z',
precpu_stats: {
cpu_usage: {
total_usage: 115914000,
usage_in_kernelmode: 60038000,
usage_in_usermode: 55876000,
},
system_cpu_usage: 15705820350000000,
online_cpus: 6,
throttling_data: {
periods: 0,
throttled_periods: 0,
throttled_time: 0,
},
},
} satisfies DockerStatsSample
export const STATS_BUSY = {
id: '109f6bbd3d699034fd925bff4eef8e606102d33a1ce108b3f16957298c7f528f',
name: '/xo-cap-busy',
os_type: 'linux',
read: '2026-09-24T16:56:53.616857151Z',
cpu_stats: {
cpu_usage: {
total_usage: 4628010000,
usage_in_kernelmode: 19989000,
usage_in_usermode: 4608020000,
},
system_cpu_usage: 15706056470000000,
online_cpus: 6,
throttling_data: {
periods: 0,
throttled_periods: 0,
throttled_time: 0,
},
},
memory_stats: {
usage: 368640,
stats: {
active_anon: 65536,
active_file: 0,
anon: 65536,
anon_thp: 0,
file: 4096,
file_dirty: 0,
file_mapped: 0,
file_writeback: 0,
inactive_anon: 0,
inactive_file: 4096,
kernel_stack: 16384,
pgactivate: 0,
pgdeactivate: 0,
pgfault: 722,
pglazyfree: 0,
pglazyfreed: 0,
pgmajfault: 0,
pgrefill: 0,
pgscan: 0,
pgsteal: 0,
shmem: 0,
slab: 205112,
slab_reclaimable: 73768,
slab_unreclaimable: 131344,
sock: 0,
thp_collapse_alloc: 0,
thp_fault_alloc: 2,
unevictable: 0,
workingset_activate: 0,
workingset_nodereclaim: 0,
workingset_refault: 0,
},
limit: 5157838848,
},
networks: {
eth0: {
rx_bytes: 816,
rx_packets: 8,
rx_errors: 0,
rx_dropped: 0,
tx_bytes: 126,
tx_packets: 3,
tx_errors: 0,
tx_dropped: 0,
},
},
pids_stats: {
current: 1,
limit: 5851,
},
blkio_stats: {
io_service_bytes_recursive: null,
io_serviced_recursive: null,
io_queue_recursive: null,
io_service_time_recursive: null,
io_wait_time_recursive: null,
io_merged_recursive: null,
io_time_recursive: null,
sectors_recursive: null,
},
num_procs: 0,
storage_stats: {},
preread: '2026-09-24T16:56:52.61298099Z',
precpu_stats: {
cpu_usage: {
total_usage: 3624588000,
usage_in_kernelmode: 19989000,
usage_in_usermode: 3604599000,
},
system_cpu_usage: 15706050480000000,
online_cpus: 6,
throttling_data: {
periods: 0,
throttled_periods: 0,
throttled_time: 0,
},
},
} satisfies DockerStatsSample
export const STATS_PAUSED = {
id: '20fc8ce5f266072556c77fbacb4a010b6ca5da1d281317c5118b824932b53537',
name: '/xo-paused',
os_type: 'linux',
read: '2026-09-24T16:56:16.975869586Z',
cpu_stats: {
cpu_usage: {
total_usage: 59056000,
usage_in_kernelmode: 27780000,
usage_in_usermode: 31275000,
},
system_cpu_usage: 15705838330000000,
online_cpus: 6,
throttling_data: {
periods: 0,
throttled_periods: 0,
throttled_time: 0,
},
},
memory_stats: {
usage: 348160,
stats: {
active_anon: 49152,
active_file: 0,
anon: 49152,
anon_thp: 0,
file: 0,
file_dirty: 0,
file_mapped: 0,
file_writeback: 0,
inactive_anon: 0,
inactive_file: 0,
kernel_stack: 16384,
pgactivate: 0,
pgdeactivate: 0,
pgfault: 718,
pglazyfree: 0,
pglazyfreed: 0,
pgmajfault: 0,
pgrefill: 0,
pgscan: 0,
pgsteal: 0,
shmem: 0,
slab: 199672,
slab_reclaimable: 69576,
slab_unreclaimable: 130096,
sock: 0,
thp_collapse_alloc: 0,
thp_fault_alloc: 2,
unevictable: 0,
workingset_activate: 0,
workingset_nodereclaim: 0,
workingset_refault: 0,
},
limit: 5157838848,
},
networks: {
eth0: {
rx_bytes: 1194,
rx_packets: 17,
rx_errors: 0,
rx_dropped: 0,
tx_bytes: 126,
tx_packets: 3,
tx_errors: 0,
tx_dropped: 0,
},
},
pids_stats: {
current: 1,
limit: 5851,
},
blkio_stats: {
io_service_bytes_recursive: null,
io_serviced_recursive: null,
io_queue_recursive: null,
io_service_time_recursive: null,
io_wait_time_recursive: null,
io_merged_recursive: null,
io_time_recursive: null,
sectors_recursive: null,
},
num_procs: 0,
storage_stats: {},
preread: '2026-09-24T16:56:15.97180589Z',
precpu_stats: {
cpu_usage: {
total_usage: 59056000,
usage_in_kernelmode: 27780000,
usage_in_usermode: 31275000,
},
system_cpu_usage: 15705832320000000,
online_cpus: 6,
throttling_data: {
periods: 0,
throttled_periods: 0,
throttled_time: 0,
},
},
} satisfies DockerStatsSample
export const STATS_EXITED = {
id: '42af13ee1713b7f4e51e3704da91f4c4eba213b28dce23a94be7f5a63bd251fe',
name: '/xo-exited',
os_type: 'linux',
read: '0001-01-01T00:00:00Z',
cpu_stats: {
cpu_usage: {
total_usage: 0,
usage_in_kernelmode: 0,
usage_in_usermode: 0,
},
throttling_data: {
periods: 0,
throttled_periods: 0,
throttled_time: 0,
},
},
memory_stats: {},
pids_stats: {},
blkio_stats: {
io_service_bytes_recursive: null,
io_serviced_recursive: null,
io_queue_recursive: null,
io_service_time_recursive: null,
io_wait_time_recursive: null,
io_merged_recursive: null,
io_time_recursive: null,
sectors_recursive: null,
},
num_procs: 0,
storage_stats: {},
preread: '0001-01-01T00:00:00Z',
precpu_stats: {
cpu_usage: {
total_usage: 0,
usage_in_kernelmode: 0,
usage_in_usermode: 0,
},
throttling_data: {
periods: 0,
throttled_periods: 0,
throttled_time: 0,
},
},
} satisfies DockerStatsSample
export const STATS_STREAM_NGINX = [
{
id: '0f5359257668ff1fd83db09c2c906d810a4363ebeeffdf02f8a9e47faf41f731',
name: '/xo-nginx',
os_type: 'linux',
read: '2026-09-24T16:56:54.620055649Z',
cpu_stats: {
cpu_usage: {
total_usage: 115914000,
usage_in_kernelmode: 60038000,
usage_in_usermode: 55876000,
},
system_cpu_usage: 15706062390000000,
online_cpus: 6,
throttling_data: {
periods: 0,
throttled_periods: 0,
throttled_time: 0,
},
},
memory_stats: {
usage: 8650752,
stats: {
active_anon: 5148672,
active_file: 1650688,
anon: 5144576,
anon_thp: 0,
file: 2301952,
file_dirty: 0,
file_mapped: 262144,
file_writeback: 0,
inactive_anon: 0,
inactive_file: 647168,
kernel_stack: 114688,
pgactivate: 0,
pgdeactivate: 0,
pgfault: 4588,
pglazyfree: 0,
pglazyfreed: 0,
pgmajfault: 14,
pgrefill: 0,
pgscan: 0,
pgsteal: 0,
shmem: 4096,
slab: 545152,
slab_reclaimable: 201448,
slab_unreclaimable: 343704,
sock: 0,
thp_collapse_alloc: 0,
thp_fault_alloc: 2,
unevictable: 0,
workingset_activate: 0,
workingset_nodereclaim: 0,
workingset_refault: 0,
},
limit: 5157838848,
},
networks: {
eth0: {
rx_bytes: 2483,
rx_packets: 36,
rx_errors: 0,
rx_dropped: 0,
tx_bytes: 2220,
tx_packets: 13,
tx_errors: 0,
tx_dropped: 0,
},
},
pids_stats: {
current: 7,
limit: 5851,
},
blkio_stats: {
io_service_bytes_recursive: null,
io_serviced_recursive: null,
io_queue_recursive: null,
io_service_time_recursive: null,
io_wait_time_recursive: null,
io_merged_recursive: null,
io_time_recursive: null,
sectors_recursive: null,
},
num_procs: 0,
storage_stats: {},
preread: '0001-01-01T00:00:00Z',
precpu_stats: {
cpu_usage: {
total_usage: 0,
usage_in_kernelmode: 0,
usage_in_usermode: 0,
},
throttling_data: {
periods: 0,
throttled_periods: 0,
throttled_time: 0,
},
},
},
{
id: '0f5359257668ff1fd83db09c2c906d810a4363ebeeffdf02f8a9e47faf41f731',
name: '/xo-nginx',
os_type: 'linux',
read: '2026-09-24T16:56:55.625086818Z',
cpu_stats: {
cpu_usage: {
total_usage: 115914000,
usage_in_kernelmode: 60038000,
usage_in_usermode: 55876000,
},
system_cpu_usage: 15706068340000000,
online_cpus: 6,
throttling_data: {
periods: 0,
throttled_periods: 0,
throttled_time: 0,
},
},
memory_stats: {
usage: 8650752,
stats: {
active_anon: 5148672,
active_file: 1650688,
anon: 5144576,
anon_thp: 0,
file: 2301952,
file_dirty: 0,
file_mapped: 262144,
file_writeback: 0,
inactive_anon: 0,
inactive_file: 647168,
kernel_stack: 114688,
pgactivate: 0,
pgdeactivate: 0,
pgfault: 4588,
pglazyfree: 0,
pglazyfreed: 0,
pgmajfault: 14,
pgrefill: 0,
pgscan: 0,
pgsteal: 0,
shmem: 4096,
slab: 545152,
slab_reclaimable: 201448,
slab_unreclaimable: 343704,
sock: 0,
thp_collapse_alloc: 0,
thp_fault_alloc: 2,
unevictable: 0,
workingset_activate: 0,
workingset_nodereclaim: 0,
workingset_refault: 0,
},
limit: 5157838848,
},
networks: {
eth0: {
rx_bytes: 2483,
rx_packets: 36,
rx_errors: 0,
rx_dropped: 0,
tx_bytes: 2220,
tx_packets: 13,
tx_errors: 0,
tx_dropped: 0,
},
},
pids_stats: {
current: 7,
limit: 5851,
},
blkio_stats: {
io_service_bytes_recursive: null,
io_serviced_recursive: null,
io_queue_recursive: null,
io_service_time_recursive: null,
io_wait_time_recursive: null,
io_merged_recursive: null,
io_time_recursive: null,
sectors_recursive: null,
},
num_procs: 0,
storage_stats: {},
preread: '2026-09-24T16:56:54.620055649Z',
precpu_stats: {
cpu_usage: {
total_usage: 115914000,
usage_in_kernelmode: 60038000,
usage_in_usermode: 55876000,
},
system_cpu_usage: 15706062390000000,
online_cpus: 6,
throttling_data: {
periods: 0,
throttled_periods: 0,
throttled_time: 0,
},
},
},
] satisfies DockerStatsSample[]

View File

@@ -1,23 +0,0 @@
// Docker Engine API client reaching the Docker socket of a remote host through
// SSH (`direct-streamlocal@openssh.com` channels), with nothing to install on
// the host. The normalizers produce the `XoDocker*` types of `@vates/types`,
// the XO records, permissions and configuration are in xo-server's
// `xo-mixins/docker.mjs`.
export * from './connection.mjs'
export * from './cooldown.mjs'
export * from './errors.mjs'
export * from './normalize.mjs'
// not `export *`: both export a `DEFAULT_IDLE_TIMEOUT`
export {
DockerConnectionPool,
type DockerConnectionFacade,
type DockerConnectionState,
type PoolableConnection,
} from './pool.mjs'
export * from './requests.mjs'
export { DockerStatsSampler, type DockerStatsSamplerOptions } from './stats-sampler.mjs'
export * from './ssh-http-agent.mjs'
export * from './stdcopy.mjs'
export * from './ttl-cache.mjs'
export type * from './wire.mjs'

View File

@@ -1,206 +0,0 @@
// Integration tests of the logs demuxing and of the normalization against a
// real Docker daemon reached through a real SSH server.
//
// Same environment variables as `connection.integ.mjs` (skipped
// unless XO_DOCKER_TEST_SSH_HOST is set), and these containers on the daemon:
//
// - `xo-nginx`: running `nginx:alpine`, port 80 published on 8080
// - `xo-exited`: `alpine sh -c 'echo failing on purpose; exit 3'`, exited
// - `xo-tty`: `alpine` run with `-t`, exited, which printed `tty line one`,
// `tty line two` (on stderr) and `no newline at end`
import assert from 'node:assert/strict'
import { readFileSync } from 'node:fs'
import { pipeline } from 'node:stream/promises'
import test from 'node:test'
import type { XoDockerContainerStats } from '@vates/types'
import { DockerConnection } from './connection.mjs'
import { normalizeContainerInspect, normalizeContainerListEntry, normalizeContainerStats } from './normalize.mjs'
import { createLogLineParser, createStdcopyDemuxer, isMultiplexedStream, type DockerLogLine } from './stdcopy.mjs'
import type { DockerContainerSummary, DockerInspect } from './wire.mjs'
const { after, before, describe, it } = test
const {
XO_DOCKER_TEST_SSH_HOST: host,
XO_DOCKER_TEST_SSH_PORT: port = '22',
XO_DOCKER_TEST_SSH_USER: username,
XO_DOCKER_TEST_SSH_KEY: keyPath,
XO_DOCKER_TEST_SSH_FINGERPRINT: fingerprint,
XO_DOCKER_TEST_SOCKET: socketPath,
} = process.env
const skip = host === undefined ? 'XO_DOCKER_TEST_SSH_HOST is not set' : false
describe('logs and stats (real SSH + dockerd)', { skip }, () => {
let connection: DockerConnection
// `!`: the environment is set, the tests are skipped otherwise
before(async () => {
connection = new DockerConnection({
host: host!,
port: Number(port),
username: username!,
privateKey: readFileSync(keyPath!),
socketPath,
hostKeyFingerprint: fingerprint,
connectTimeout: 5e3,
requestTimeout: 10e3,
})
await connection.connect()
})
after(async () => {
await connection?.close()
})
async function inspect(name: string) {
const { body } = await connection.request({ path: `/containers/${name}/json` })
return normalizeContainerInspect(body as DockerInspect)
}
async function getLogs(name: string, query: Record<string, unknown> = {}) {
const container = await inspect(name)
const response = await connection.requestStream({
path: `/containers/${name}/logs`,
query: { stdout: 1, stderr: 1, timestamps: 1, tail: 100, ...query },
})
const tty = !isMultiplexedStream(response.headers['content-type'], container.tty, connection.apiVersion)
assert.equal(tty, container.tty, 'the content type agrees with Config.Tty')
const demuxer = createStdcopyDemuxer({ tty })
const entries: DockerLogLine[] = []
await pipeline(response, demuxer, createLogLineParser(), async (source: AsyncIterable<DockerLogLine>) => {
for await (const entry of source) {
entries.push(entry)
}
})
assert.equal(demuxer.truncated, false)
return { entries, contentType: response.headers['content-type'] }
}
const assertTimestamp = (timestamp: string | undefined, since: number) => {
assert.match(timestamp!, /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,9})?Z$/)
const time = Date.parse(timestamp!)
assert.ok(time >= since && time <= Date.now() + 60e3, timestamp)
}
it('reads the logs of xo-exited', async () => {
const container = await inspect('xo-exited')
const { entries, contentType } = await getLogs('xo-exited')
assert.equal(contentType, 'application/vnd.docker.multiplexed-stream')
assert.equal(entries.length, 1)
const [{ stream, timestamp, message }] = entries
assert.equal(stream, 'stdout')
assert.equal(message, 'failing on purpose')
assertTimestamp(timestamp, container.startedAt! - 1e3)
})
it('reads the logs of xo-nginx, stdout and stderr', async () => {
const container = await inspect('xo-nginx')
const { entries } = await getLogs('xo-nginx')
assert.ok(entries.length > 5)
for (const { stream, timestamp, message } of entries) {
assert.ok(stream === 'stdout' || stream === 'stderr')
// since its creation: it may have been restarted (e.g. by the REST proof)
assertTimestamp(timestamp, container.createdAt! - 1e3)
assert.equal(typeof message, 'string')
assert.ok(!message.includes('\n'))
}
// the entrypoint writes on stdout, nginx notices go to stderr
assert.ok(entries.some(_ => _.stream === 'stdout' && _.message.includes('/docker-entrypoint.sh')))
assert.ok(entries.some(_ => _.stream === 'stderr' && _.message.includes('[notice]')))
})
it('honours tail', async () => {
const { entries } = await getLogs('xo-nginx', { tail: 2 })
assert.equal(entries.length, 2)
})
it('reads the logs of a TTY container', async () => {
const container = await inspect('xo-tty')
const { entries, contentType } = await getLogs('xo-tty')
assert.equal(contentType, 'application/vnd.docker.raw-stream')
assert.deepEqual(
entries.map(({ stream, message }) => [stream, message]),
[
['stdout', 'tty line one'],
['stdout', 'tty line two'],
['stdout', 'no newline at end'],
]
)
for (const { timestamp } of entries) {
assertTimestamp(timestamp, container.startedAt! - 1e3)
}
})
it('reads and normalizes the stats of xo-nginx (stream=false)', async () => {
const container = await inspect('xo-nginx')
const start = Date.now()
const { body } = await connection.request({ path: '/containers/xo-nginx/stats', query: { stream: false } })
const stats = normalizeContainerStats(body)
// `!`: checked by the assertions (a `null` compares as 0, an `undefined` as NaN)
// dockerd pre-reads a sample, precpu_stats is valid
assert.equal(typeof stats.cpuPercent, 'number')
assert.ok(stats.cpuPercent! >= 0 && stats.cpuPercent! <= 100 * stats.onlineCpus!, String(stats.cpuPercent))
assert.ok(stats.onlineCpus! >= 1)
assert.ok(
stats.memoryUsage! > 0 && stats.memoryUsage! <= (body as { memory_stats: { usage: number } }).memory_stats.usage
)
assert.ok(stats.memoryLimit! >= stats.memoryUsage!)
assert.ok(stats.memoryPercent! > 0 && stats.memoryPercent! <= 100)
assert.ok(stats.pids! >= 1)
assert.ok(stats.networkRx! >= 0)
assert.ok(stats.sampledAt! >= Math.max(container.startedAt!, start - 5e3) && stats.sampledAt! <= Date.now() + 60e3)
})
it('reads and normalizes streamed stats of xo-nginx (stream=true)', async () => {
const controller = new AbortController()
const response = await connection.requestStream({
path: '/containers/xo-nginx/stats',
query: { stream: true },
signal: controller.signal,
})
const samples: XoDockerContainerStats[] = []
try {
let buffer = ''
for await (const chunk of response) {
buffer += chunk
let i
while ((i = buffer.indexOf('\n')) !== -1) {
samples.push(normalizeContainerStats(JSON.parse(buffer.slice(0, i))))
buffer = buffer.slice(i + 1)
}
if (samples.length >= 2) {
break
}
}
} finally {
controller.abort()
}
const [first, second] = samples
// the first object of a stream has no previous CPU sample
assert.equal(first.cpuPercent, null)
assert.equal(typeof second.cpuPercent, 'number')
assert.ok(second.sampledAt! > first.sampledAt!)
assert.ok(second.memoryUsage! > 0)
})
it('normalizes the real container list', async () => {
const { body } = await connection.request({ path: '/containers/json', query: { all: 1 } })
const containers = new Map(
(body as DockerContainerSummary[]).map(normalizeContainerListEntry).map(container => [container.name, container])
)
const nginx = containers.get('xo-nginx')!
assert.equal(nginx.state, 'running')
assert.deepEqual(nginx.ports, [{ ip: '0.0.0.0', privatePort: 80, publicPort: 8080, protocol: 'tcp' }])
assert.deepEqual((await inspect('xo-nginx')).ports, nginx.ports)
const exited = containers.get('xo-exited')!
assert.equal(exited.state, 'exited')
assert.equal(exited.exitCode, 3)
assert.equal((await inspect('xo-exited')).exitCode, 3)
})
})

View File

@@ -1,599 +0,0 @@
// Docker Engine API wire shapes → XO DTOs.
//
// Pure functions, written against API 1.44 (`MAX_API_VERSION`) and tolerant of
// fields missing in older versions. Timestamps are converted to ms since the
// epoch. Optional values which do not apply are left `undefined` (so they are
// omitted from JSON), except the stats values which are `null` when they cannot
// be computed.
//
// The container environment (`Config.Env`) is deliberately never exposed: it
// routinely contains secrets.
import type {
XoDockerCompose,
XoDockerContainer,
XoDockerContainerHealth,
XoDockerContainerStats,
XoDockerEngineInfoConnected,
XoDockerEngineKind,
XoDockerMount,
XoDockerNetwork,
XoDockerPort,
} from '@vates/types'
import type {
DockerBlkioStats,
DockerContainerConfig,
DockerContainerStateInfo,
DockerContainerSummary,
DockerCpuStats,
DockerEndpointSettings,
DockerInfo,
DockerInspect,
DockerMemoryStats,
DockerMountPoint,
DockerPort,
DockerPortMap,
DockerStatsSample,
DockerVersion,
} from './wire.mjs'
/**
* A container as normalized from the daemon: without the fields added by XO
* (`id`, `$engine`…).
*/
export type NormalizedDockerContainer = Omit<
XoDockerContainer,
'id' | '$engine' | '$VM' | '$pool' | 'stats' | 'statsPending'
>
/**
* `GET /info` (and `GET /version`) normalized: `XoDockerEngineInfoConnected`
* without the fields added by XO, and with the daemon's ID (`id`) and newest
* API version (`apiVersion`).
*/
export type NormalizedDockerEngineInfo = Omit<
XoDockerEngineInfoConnected,
'status' | 'asOf' | 'daemonId' | 'daemonApiVersion' | 'compose'
> & {
/** the daemon's ID */
id?: string
}
// Go's zero `time.Time`, used by dockerd for dates which are not set
const ZERO_DATE_RE = /^0001-01-01T00:00:00(?:\.0+)?Z$/
/**
* @param date RFC 3339 date
* @returns ms since the epoch
*/
export function parseDockerDate(date: unknown): number | undefined {
if (typeof date !== 'string' || date === '' || ZERO_DATE_RE.test(date)) {
return undefined
}
const time = Date.parse(date)
return Number.isNaN(time) ? undefined : time
}
// === Container name, state, status
/**
* Primary name of a container, without its leading `/`.
*
* With legacy links, `Names` also contains aliases like `/other/alias`: the
* primary name is the one without any other `/` (what the Docker CLI shows).
*/
export function getContainerName(names: string[] | undefined): string | undefined {
if (names === undefined || names.length === 0) {
return undefined
}
const name = names.find(name => name.lastIndexOf('/') === 0) ?? names[0]
return name.startsWith('/') ? name.slice(1) : name
}
/**
* Parse the human readable `Status` of a list entry, e.g. `Exited (3) 2 hours
* ago`, `Up 5 minutes (healthy)`, `Up 1 second (health: starting)`,
* `Restarting (1) 3 seconds ago`, `Up 3 hours (Paused)`.
*/
export function parseContainerStatus(status: string | undefined): {
exitCode?: number
health?: XoDockerContainerHealth
} {
const result: { exitCode?: number; health?: XoDockerContainerHealth } = {}
if (typeof status !== 'string') {
return result
}
const exitCodeMatch = /^(?:Exited|Restarting) \((-?\d+)\)/.exec(status)
if (exitCodeMatch !== null) {
result.exitCode = Number(exitCodeMatch[1])
}
const healthMatch = /\((healthy|unhealthy|health: starting)\)/.exec(status)
if (healthMatch !== null) {
result.health = healthMatch[1] === 'health: starting' ? 'starting' : (healthMatch[1] as 'healthy' | 'unhealthy')
}
return result
}
/**
* @param status `State.Health.Status`
* @returns `undefined` if the container has no health check
*/
function normalizeHealthStatus(status: string | undefined): XoDockerContainerHealth | undefined {
return status === 'starting' || status === 'healthy' || status === 'unhealthy' ? status : undefined
}
// === Ports
const WILDCARD_IPV4 = '0.0.0.0'
const WILDCARD_IPV6 = '::'
/**
* Normalize, dedupe and sort ports.
*
* When a port is published on all interfaces, dockerd reports it twice: once
* for `0.0.0.0` and once for `::`. The `::` entry is dropped in that case (the
* port stays reported as `0.0.0.0`). An IPv6-only binding keeps `::`.
*/
function dedupePorts(ports: XoDockerPort[]): XoDockerPort[] {
const byKey = new Map<string, XoDockerPort>()
for (const port of ports) {
byKey.set(`${port.privatePort}/${port.protocol}/${port.publicPort}/${port.ip}`, port)
}
const result: XoDockerPort[] = []
for (const port of byKey.values()) {
if (
port.ip === WILDCARD_IPV6 &&
byKey.has(`${port.privatePort}/${port.protocol}/${port.publicPort}/${WILDCARD_IPV4}`)
) {
continue
}
result.push(port)
}
return result.sort(
(a, b) =>
a.privatePort - b.privatePort ||
a.protocol.localeCompare(b.protocol) ||
(a.publicPort ?? 0) - (b.publicPort ?? 0) ||
(a.ip ?? '').localeCompare(b.ip ?? '')
)
}
function makePort({
ip,
privatePort,
publicPort,
protocol = 'tcp',
}: {
ip?: string
privatePort: number
publicPort?: number
protocol?: string
}): XoDockerPort {
const port: XoDockerPort = { privatePort, protocol }
if (publicPort !== undefined && publicPort !== 0) {
port.publicPort = publicPort
if (ip !== undefined && ip !== '') {
port.ip = ip
}
}
return port
}
/**
* Ports of a container list entry (`Ports`).
*/
export function normalizeListPorts(ports: DockerPort[] | undefined): XoDockerPort[] {
return dedupePorts(
(ports ?? []).map(({ IP, PrivatePort, PublicPort, Type }) =>
makePort({ ip: IP, privatePort: PrivatePort, publicPort: PublicPort, protocol: Type })
)
)
}
/**
* Ports of an inspected container (`NetworkSettings.Ports`), e.g.
* `{ "80/tcp": [{ "HostIp": "0.0.0.0", "HostPort": "8080" }], "443/tcp": null }`.
*/
export function normalizeInspectPorts(ports: DockerPortMap | undefined): XoDockerPort[] {
const result: XoDockerPort[] = []
for (const [key, bindings] of Object.entries(ports ?? {})) {
const [privatePort, protocol = 'tcp'] = key.split('/')
if (bindings === null || bindings.length === 0) {
result.push(makePort({ privatePort: Number(privatePort), protocol }))
} else {
for (const { HostIp, HostPort } of bindings) {
result.push(makePort({ ip: HostIp, privatePort: Number(privatePort), publicPort: Number(HostPort), protocol }))
}
}
}
return dedupePorts(result)
}
// === Labels, networks, mounts
const COMPOSE_LABEL_PREFIX = 'com.docker.compose.'
/**
* Docker Compose project and service of a container, from its labels.
*/
export function getComposeInfo(labels: Record<string, string> | undefined): XoDockerCompose | undefined {
const project = labels?.[COMPOSE_LABEL_PREFIX + 'project']
if (project === undefined || project === '') {
return undefined
}
const get = (name: string): string | undefined => {
// `labels!`: set, it contains the project
const value = labels![COMPOSE_LABEL_PREFIX + name]
return value === '' ? undefined : value
}
const compose: XoDockerCompose = { project }
const service = get('service')
if (service !== undefined) {
compose.service = service
}
const containerNumber = Number(get('container-number'))
if (Number.isInteger(containerNumber)) {
compose.containerNumber = containerNumber
}
const oneOff = get('oneoff')
if (oneOff !== undefined) {
compose.oneOff = oneOff.toLowerCase() === 'true'
}
const workingDir = get('project.working_dir')
if (workingDir !== undefined) {
compose.workingDir = workingDir
}
const configFiles = get('project.config_files')
if (configFiles !== undefined) {
compose.configFiles = configFiles.split(',')
}
return compose
}
/**
* @param networks `NetworkSettings.Networks`
*/
export function normalizeNetworks(networks: Record<string, DockerEndpointSettings> | undefined): XoDockerNetwork[] {
return Object.entries(networks ?? {}).map(([name, { IPAddress, GlobalIPv6Address }]) => {
const network: XoDockerNetwork = { name }
if (IPAddress) {
network.ipAddress = IPAddress
}
if (GlobalIPv6Address) {
network.ipv6Address = GlobalIPv6Address
}
return network
})
}
export function normalizeMounts(mounts: DockerMountPoint[] | undefined): XoDockerMount[] {
return (mounts ?? []).map(({ Type, Name, Source, Destination, RW }) => {
const mount: XoDockerMount = { type: Type, source: Source, destination: Destination, readOnly: !RW }
if (Name) {
mount.name = Name
}
return mount
})
}
// === Containers
/**
* Entry of `GET /containers/json`.
*/
export function normalizeContainerListEntry(entry: DockerContainerSummary): NormalizedDockerContainer {
const labels = entry.Labels ?? {}
const { exitCode, health } = parseContainerStatus(entry.Status)
const container: NormalizedDockerContainer = {
dockerId: entry.Id,
name: getContainerName(entry.Names),
image: entry.Image,
imageId: entry.ImageID,
command: entry.Command,
createdAt: entry.Created * 1e3,
state: entry.State,
status: entry.Status,
exitCode: entry.State === 'exited' || entry.State === 'dead' || entry.State === 'restarting' ? exitCode : undefined,
health,
ports: normalizeListPorts(entry.Ports),
labels,
compose: getComposeInfo(labels),
networks: normalizeNetworks(entry.NetworkSettings?.Networks),
mounts: normalizeMounts(entry.Mounts),
}
return container
}
// same format as the `Command` of list entries: arguments containing a space
// are single-quoted (without any escaping, like dockerd does)
function formatCommand(path: string, args: string[] = []): string {
return [path, ...args.map(arg => (arg.includes(' ') ? `'${arg}'` : arg))].join(' ')
}
/**
* `GET /containers/{id}/json`.
*
* Contains the same fields as a list entry (except `status`, the human readable
* one), plus the details only available from an inspection.
*/
export function normalizeContainerInspect(data: DockerInspect): NormalizedDockerContainer {
const {
// typed as complete objects: dockerd always sends `Config.Image` and
// `State.Status`
Config: config = {} as DockerContainerConfig,
HostConfig: hostConfig = {},
NetworkSettings: networkSettings = {},
State: state = {} as DockerContainerStateInfo,
} = data
const labels = config.Labels ?? {}
const status = state.Status
const health = state.Health
const lastHealthCheck = health?.Log?.at(-1)
const restartPolicy = hostConfig.RestartPolicy
const container: NormalizedDockerContainer = {
dockerId: data.Id,
name: getContainerName([data.Name]),
image: config.Image,
imageId: data.Image,
command: formatCommand(data.Path, data.Args),
createdAt: parseDockerDate(data.Created),
state: status,
exitCode: status === 'exited' || status === 'dead' || status === 'restarting' ? state.ExitCode : undefined,
health: normalizeHealthStatus(health?.Status),
ports: normalizeInspectPorts(networkSettings.Ports),
labels,
compose: getComposeInfo(labels),
networks: normalizeNetworks(networkSettings.Networks),
mounts: normalizeMounts(data.Mounts),
startedAt: parseDockerDate(state.StartedAt),
finishedAt: parseDockerDate(state.FinishedAt),
oomKilled: state.OOMKilled,
error: state.Error || undefined,
healthCheck:
health === undefined || normalizeHealthStatus(health.Status) === undefined
? undefined
: {
failingStreak: health.FailingStreak,
lastCheckAt: parseDockerDate(lastHealthCheck?.End ?? lastHealthCheck?.Start),
lastExitCode: lastHealthCheck?.ExitCode,
},
restartPolicy: {
// `Name` is empty when the container was created without restart policy
name: restartPolicy?.Name || 'no',
maximumRetryCount: restartPolicy?.MaximumRetryCount ?? 0,
},
restartCount: data.RestartCount,
tty: config.Tty === true,
hostname: config.Hostname,
workingDir: config.WorkingDir || undefined,
user: config.User || undefined,
}
return container
}
// === Stats
// every stats value comes from the daemon: only finite numbers are accepted,
// never numeric strings (which the sums would concatenate), objects, NaN or
// Infinity, and every computed value is checked again (huge values overflow)
const isNumber = (value: unknown): value is number => typeof value === 'number' && Number.isFinite(value)
// byte, page, process counters
const isCounter = (value: unknown): value is number => isNumber(value) && value >= 0
const finiteOrNull = (value: unknown): number | null => (isNumber(value) ? value : null)
// arrays included: their properties are read like the ones of any object
const isObject = (value: unknown): value is Record<string, unknown> => typeof value === 'object' && value !== null
/**
* CPU usage in percent, like `docker stats`: 100 means one full CPU, so the
* value can go up to `100 * onlineCpus`.
*
* `null` when it cannot be computed: first sample of a stream, or of a
* container which is not running (no `precpu_stats.system_cpu_usage`), no
* elapsed system time (would give `Infinity`/`NaN`) or counters which went
* backwards (container restarted between the samples).
*
* @param cpuStats `cpu_stats`
* @param precpuStats `precpu_stats`
*/
export function computeCpuPercent(
cpuStats: DockerCpuStats | undefined,
precpuStats: DockerCpuStats | undefined
): { cpuPercent: number | null; onlineCpus: number | undefined } {
const onlineCpusValue = cpuStats?.online_cpus
const percpuUsage = cpuStats?.cpu_usage?.percpu_usage
const onlineCpus =
// `as number`: a safe integer
Number.isSafeInteger(onlineCpusValue) && (onlineCpusValue as number) > 0
? (onlineCpusValue as number)
: (Array.isArray(percpuUsage) && percpuUsage.length) || undefined
const total = cpuStats?.cpu_usage?.total_usage
const preTotal = precpuStats?.cpu_usage?.total_usage
const system = cpuStats?.system_cpu_usage
const preSystem = precpuStats?.system_cpu_usage
if (
onlineCpus === undefined ||
!isCounter(total) ||
!isCounter(preTotal) ||
!isCounter(system) ||
!isCounter(preSystem) ||
!(preSystem > 0)
) {
return { cpuPercent: null, onlineCpus }
}
const cpuDelta = total - preTotal
const systemDelta = system - preSystem
if (!(systemDelta > 0) || cpuDelta < 0) {
return { cpuPercent: null, onlineCpus }
}
return { cpuPercent: finiteOrNull((cpuDelta / systemDelta) * onlineCpus * 100), onlineCpus }
}
/**
* Memory used by a container, without the page cache which can be reclaimed,
* like `docker stats`:
*
* - cgroup v1: `usage - total_inactive_file` (Docker CLI ≥ 20.10), or
* `usage - cache` with daemons which do not report `total_inactive_file`
* - cgroup v2: `usage - inactive_file`
*
* @param memoryStats `memory_stats`
* @returns bytes
*/
export function computeMemoryUsage(memoryStats: DockerMemoryStats | undefined): number | null {
const usage = memoryStats?.usage
if (!isCounter(usage)) {
return null
}
// `memoryStats!`: set, it has a `usage`
const stats = isObject(memoryStats!.stats) ? memoryStats!.stats : {}
let cache
if ('total_inactive_file' in stats) {
cache = stats.total_inactive_file // cgroup v1
} else if ('inactive_file' in stats) {
cache = stats.inactive_file // cgroup v2
} else {
cache = stats.cache // cgroup v1 (old daemons)
}
return isCounter(cache) && cache < usage ? usage - cache : usage
}
/**
* Sum of the bytes read and written, from `blkio_stats.io_service_bytes_recursive`.
*/
function computeBlockIo(blkioStats: DockerBlkioStats | undefined): {
blockRead: number | null
blockWrite: number | null
} {
const entries = blkioStats?.io_service_bytes_recursive
if (!Array.isArray(entries)) {
return { blockRead: null, blockWrite: null }
}
let blockRead = 0
let blockWrite = 0
for (const entry of entries) {
if (!isObject(entry) || typeof entry.op !== 'string' || !isCounter(entry.value)) {
continue
}
// `Read`/`Write` on cgroup v1, `read`/`write` on cgroup v2
const lowerOp = entry.op.toLowerCase()
if (lowerOp === 'read') {
blockRead += entry.value
} else if (lowerOp === 'write') {
blockWrite += entry.value
}
}
return { blockRead: finiteOrNull(blockRead), blockWrite: finiteOrNull(blockWrite) }
}
function computeNetworkIo(networks: unknown): { networkRx: number | null; networkTx: number | null } {
if (!isObject(networks)) {
return { networkRx: null, networkTx: null }
}
let networkRx = 0
let networkTx = 0
for (const network of Object.values(networks)) {
if (!isObject(network)) {
continue
}
if (isCounter(network.rx_bytes)) {
networkRx += network.rx_bytes
}
if (isCounter(network.tx_bytes)) {
networkTx += network.tx_bytes
}
}
return { networkRx: finiteOrNull(networkRx), networkTx: finiteOrNull(networkTx) }
}
/**
* One object of `GET /containers/{id}/stats` (`stream=false`, or each object
* of `stream=true`). Never send `one-shot=true`: `precpu_stats` would be empty.
*
* Linux containers only: Windows ones have a different CPU accounting, and get
* a `null` `cpuPercent`.
*
* @param value anything: it comes from the daemon, every value is checked
*/
export function normalizeContainerStats(value: unknown): XoDockerContainerStats {
if (!isObject(value) || Array.isArray(value)) {
throw new TypeError('stats must be an object')
}
// see `DockerStatsSample`: the values are `unknown`
const stats = value as DockerStatsSample
const isWindows = stats.os_type === 'windows'
const { cpuPercent, onlineCpus } = isWindows
? { cpuPercent: null, onlineCpus: undefined }
: computeCpuPercent(stats.cpu_stats, stats.precpu_stats)
const memoryStats: DockerMemoryStats | undefined = isObject(stats.memory_stats) ? stats.memory_stats : undefined
const memoryUsage = isWindows
? isCounter(memoryStats?.privateworkingset)
? memoryStats.privateworkingset
: null
: computeMemoryUsage(memoryStats)
const memoryLimit = isCounter(memoryStats?.limit) && memoryStats.limit > 0 ? memoryStats.limit : null
return {
sampledAt: parseDockerDate(stats.read) ?? null,
cpuPercent,
onlineCpus,
memoryUsage,
memoryLimit,
memoryPercent:
memoryUsage !== null && memoryLimit !== null ? finiteOrNull((memoryUsage / memoryLimit) * 100) : null,
...computeNetworkIo(stats.networks),
...computeBlockIo(stats.blkio_stats),
pids: isCounter(stats.pids_stats?.current) ? stats.pids_stats.current : null,
}
}
// === Engine
const PODMAN_RE = /podman/i
/**
* Podman's Docker-compatible API is told from Docker by the components and the
* platform of its `GET /version` (e.g. `Podman Engine`).
*/
export function getEngineKind(version: DockerVersion | undefined): XoDockerEngineKind {
const components = Array.isArray(version?.Components) ? version.Components : []
return components.some(component => PODMAN_RE.test(String(component?.Name))) ||
PODMAN_RE.test(String(version?.Platform?.Name))
? 'podman'
: 'docker'
}
/**
* `GET /info`, and optionally `GET /version` for the daemon's API versions.
*/
export function normalizeEngineInfo(info: DockerInfo, version?: DockerVersion): NormalizedDockerEngineInfo {
const securityOptions = info.SecurityOptions ?? []
return {
id: info.ID,
kind: getEngineKind(version),
name: info.Name,
engineVersion: info.ServerVersion ?? version?.Version,
apiVersion: version?.ApiVersion,
minApiVersion: version?.MinAPIVersion,
operatingSystem: info.OperatingSystem,
osType: info.OSType,
kernelVersion: info.KernelVersion,
architecture: info.Architecture,
cpus: info.NCPU,
memory: info.MemTotal,
storageDriver: info.Driver,
loggingDriver: info.LoggingDriver,
cgroupDriver: info.CgroupDriver,
cgroupVersion: info.CgroupVersion,
rootless: securityOptions.some(option => option === 'name=rootless' || option.startsWith('name=rootless,')),
containers: {
total: info.Containers,
running: info.ContainersRunning,
paused: info.ContainersPaused,
stopped: info.ContainersStopped,
},
images: info.Images,
warnings: info.Warnings ?? [],
}
}

View File

@@ -1,693 +0,0 @@
import assert from 'node:assert/strict'
import test from 'node:test'
import { CONTAINER_LIST, INSPECT_BY_NAME } from './fixtures/containers.fixture.mjs'
import { INFO, VERSION } from './fixtures/engine.fixture.mjs'
import {
STATS_BUSY,
STATS_EXITED,
STATS_NGINX_IDLE,
STATS_PAUSED,
STATS_STREAM_NGINX,
} from './fixtures/stats.fixture.mjs'
import {
computeCpuPercent,
computeMemoryUsage,
getComposeInfo,
getContainerName,
getEngineKind,
normalizeContainerInspect,
normalizeContainerListEntry,
normalizeContainerStats,
normalizeEngineInfo,
normalizeInspectPorts,
normalizeListPorts,
parseContainerStatus,
parseDockerDate,
} from './normalize.mjs'
import type { DockerCpuStats, DockerPort, DockerStatsSample } from './wire.mjs'
const { describe, it } = test
// the copies of stats are typed `DockerStatsSample`, whose values are `unknown`:
// the tests change them like a hostile daemon would
const clone = <T,>(value: T): T => JSON.parse(JSON.stringify(value))
// `!`: the fixtures contain these containers
const listEntry = (name: string) => CONTAINER_LIST.find(entry => entry.Names!.includes('/' + name))!
const listed = (name: string) => normalizeContainerListEntry(listEntry(name))
const inspected = (name: string) => normalizeContainerInspect(INSPECT_BY_NAME[name])
describe('parseDockerDate()', () => {
it('parses RFC 3339 dates with nanoseconds', () => {
assert.equal(parseDockerDate('2026-09-24T16:54:40.2704229Z'), Date.UTC(2026, 8, 24, 16, 54, 40, 270))
})
it('returns undefined for Go zero dates and invalid values', () => {
assert.equal(parseDockerDate('0001-01-01T00:00:00Z'), undefined)
assert.equal(parseDockerDate(''), undefined)
assert.equal(parseDockerDate(undefined), undefined)
assert.equal(parseDockerDate('not a date'), undefined)
})
})
describe('getContainerName()', () => {
it('strips the leading slash', () => {
assert.equal(getContainerName(['/xo-nginx']), 'xo-nginx')
})
it('ignores legacy link aliases', () => {
assert.equal(getContainerName(['/web/db', '/db']), 'db')
})
it('handles missing names', () => {
assert.equal(getContainerName([]), undefined)
assert.equal(getContainerName(undefined), undefined)
})
})
describe('parseContainerStatus()', () => {
const cases: [string | undefined, object][] = [
['Exited (3) 2 minutes ago', { exitCode: 3 }],
['Exited (0) 8 seconds ago', { exitCode: 0 }],
['Exited (137) About an hour ago', { exitCode: 137 }],
['Exited (-1) 1 second ago', { exitCode: -1 }],
['Restarting (1) 3 seconds ago', { exitCode: 1 }],
['Up 2 minutes', {}],
['Up 2 minutes (healthy)', { health: 'healthy' }],
['Up 2 minutes (unhealthy)', { health: 'unhealthy' }],
['Up 1 second (health: starting)', { health: 'starting' }],
['Up 2 minutes (Paused)', {}],
['Created', {}],
['Dead', {}],
['Removal In Progress', {}],
[undefined, {}],
]
for (const [status, expected] of cases) {
it(String(status), () => {
assert.deepEqual(parseContainerStatus(status), expected)
})
}
it('parses the real statuses', () => {
for (const entry of CONTAINER_LIST) {
const { exitCode } = parseContainerStatus(entry.Status)
const inspect = INSPECT_BY_NAME[getContainerName(entry.Names)!]
if (entry.State === 'exited') {
assert.equal(exitCode, inspect.State!.ExitCode)
} else {
assert.equal(exitCode, undefined)
}
}
})
})
describe('ports', () => {
it('dedupes 0.0.0.0 and :: bindings of the same port', () => {
assert.deepEqual(listed('xo-nginx').ports, [{ ip: '0.0.0.0', privatePort: 80, publicPort: 8080, protocol: 'tcp' }])
assert.deepEqual(inspected('xo-nginx').ports, listed('xo-nginx').ports)
})
it('keeps loopback, UDP and unpublished ports, sorted', () => {
const expected = [
{ ip: '0.0.0.0', privatePort: 53, publicPort: 5353, protocol: 'udp' },
{ ip: '127.0.0.1', privatePort: 80, publicPort: 9090, protocol: 'tcp' },
]
assert.deepEqual(listed('xo-cap-busy').ports, expected)
assert.deepEqual(inspected('xo-cap-busy').ports, expected)
// exposed, not published
assert.deepEqual(listed('demo-cache-1').ports, [{ privatePort: 6379, protocol: 'tcp' }])
assert.deepEqual(inspected('xo-healthy').ports, [{ privatePort: 80, protocol: 'tcp' }])
})
it('keeps IPv6-only bindings and specific addresses', () => {
assert.deepEqual(
normalizeListPorts([
{ IP: '::', PrivatePort: 80, PublicPort: 8080, Type: 'tcp' },
{ IP: '192.0.2.1', PrivatePort: 80, PublicPort: 8081, Type: 'tcp' },
{ IP: '::1', PrivatePort: 80, PublicPort: 8081, Type: 'tcp' },
// the IPv4 wildcard of another public port does not hide it
{ IP: '0.0.0.0', PrivatePort: 80, PublicPort: 8082, Type: 'tcp' },
]),
[
{ ip: '::', privatePort: 80, publicPort: 8080, protocol: 'tcp' },
{ ip: '::1', privatePort: 80, publicPort: 8081, protocol: 'tcp' },
{ ip: '192.0.2.1', privatePort: 80, publicPort: 8081, protocol: 'tcp' },
{ ip: '0.0.0.0', privatePort: 80, publicPort: 8082, protocol: 'tcp' },
]
)
})
it('removes exact duplicates and handles missing values', () => {
const port: DockerPort = { IP: '0.0.0.0', PrivatePort: 80, PublicPort: 8080, Type: 'tcp' }
assert.deepEqual(normalizeListPorts([port, { ...port }]), [
{ ip: '0.0.0.0', privatePort: 80, publicPort: 8080, protocol: 'tcp' },
])
assert.deepEqual(normalizeListPorts(undefined), [])
assert.deepEqual(normalizeInspectPorts(undefined), [])
assert.deepEqual(normalizeInspectPorts({ '80/tcp': [], 443: null }), [
{ privatePort: 80, protocol: 'tcp' },
{ privatePort: 443, protocol: 'tcp' },
])
})
})
describe('getComposeInfo()', () => {
it('extracts the project and service', () => {
assert.deepEqual(listed('demo-web-1').compose, {
project: 'demo',
service: 'web',
containerNumber: 1,
oneOff: false,
workingDir: '/srv/compose-demo',
configFiles: ['/srv/compose-demo/compose.yaml'],
})
assert.deepEqual(inspected('demo-web-1').compose, listed('demo-web-1').compose)
assert.equal(listed('demo-cache-1').compose!.service, 'cache')
})
it('is undefined outside of a Compose project', () => {
assert.equal(listed('xo-nginx').compose, undefined)
assert.equal(getComposeInfo(undefined), undefined)
assert.equal(getComposeInfo({ 'com.docker.compose.project': '' }), undefined)
})
it('only requires the project label', () => {
assert.deepEqual(
getComposeInfo({
'com.docker.compose.project': 'p',
'com.docker.compose.oneoff': 'True',
'com.docker.compose.project.config_files': 'a.yaml,b.yaml',
}),
{ project: 'p', oneOff: true, configFiles: ['a.yaml', 'b.yaml'] }
)
})
})
describe('normalizeContainerListEntry()', () => {
it('normalizes a running container', () => {
const entry = listEntry('xo-nginx')
assert.deepEqual(listed('xo-nginx'), {
dockerId: entry.Id,
name: 'xo-nginx',
image: 'nginx:alpine',
imageId: entry.ImageID,
command: "/docker-entrypoint.sh nginx -g 'daemon off;'",
createdAt: entry.Created * 1e3,
state: 'running',
status: entry.Status,
exitCode: undefined,
health: undefined,
ports: [{ ip: '0.0.0.0', privatePort: 80, publicPort: 8080, protocol: 'tcp' }],
labels: entry.Labels,
compose: undefined,
networks: [{ name: 'bridge', ipAddress: '172.17.0.2' }],
mounts: [],
})
})
it('gives the exit code of exited containers only', () => {
assert.equal(listed('xo-exited').state, 'exited')
assert.equal(listed('xo-exited').exitCode, 3)
assert.equal(listed('xo-tty').exitCode, 0)
assert.equal(listed('xo-cap-created').state, 'created')
assert.equal(listed('xo-cap-created').exitCode, undefined)
})
it('gives the health status', () => {
assert.equal(listed('xo-healthy').health, 'healthy')
assert.equal(listed('xo-unhealthy').health, 'unhealthy')
assert.equal(listed('xo-paused').state, 'paused')
assert.equal(listed('xo-paused').health, undefined)
})
it('normalizes mounts', () => {
assert.deepEqual(listed('xo-cap-busy').mounts, [
{
type: 'volume',
name: 'xo-cap-vol',
source: '/home/docker/.local/share/docker/volumes/xo-cap-vol/_data',
destination: '/data',
readOnly: false,
},
{ type: 'bind', source: '/etc/hostname', destination: '/host-hostname', readOnly: true },
])
assert.deepEqual(inspected('xo-cap-busy').mounts, listed('xo-cap-busy').mounts)
})
it('only gives known states', () => {
for (const entry of CONTAINER_LIST) {
assert.ok(
['created', 'running', 'paused', 'restarting', 'removing', 'exited', 'dead'].includes(
normalizeContainerListEntry(entry).state
)
)
}
})
})
describe('normalizeContainerInspect()', () => {
it('is consistent with the list entry', () => {
for (const entry of CONTAINER_LIST) {
const name = getContainerName(entry.Names)!
const { status, createdAt, ...fromList } = normalizeContainerListEntry(entry)
const fromInspect = inspected(name)
for (const [key, value] of Object.entries(fromList)) {
assert.deepEqual(fromInspect[key as keyof typeof fromInspect], value, `${name}: ${key}`)
}
assert.equal(Math.floor(fromInspect.createdAt! / 1e3) * 1e3, createdAt)
}
})
it('gives the details of a running container', () => {
const container = inspected('xo-cap-busy')
assert.equal(container.startedAt, Date.parse(INSPECT_BY_NAME['xo-cap-busy'].State!.StartedAt!))
assert.equal(container.finishedAt, undefined)
assert.deepEqual(container.restartPolicy, { name: 'unless-stopped', maximumRetryCount: 0 })
assert.equal(container.restartCount, 0)
assert.equal(container.tty, false)
assert.equal(container.oomKilled, false)
assert.equal(container.error, undefined)
assert.equal(container.healthCheck, undefined)
})
it('never exposes the environment', () => {
assert.ok(INSPECT_BY_NAME['xo-cap-busy'].Config!.Env!.includes('SECRET_TOKEN=hunter2'))
assert.doesNotMatch(JSON.stringify(inspected('xo-cap-busy')), /hunter2|SECRET_TOKEN/)
assert.doesNotMatch(JSON.stringify(listed('xo-cap-busy')), /hunter2|SECRET_TOKEN/)
})
it('gives the exit code and dates of an exited container', () => {
const container = inspected('xo-exited')
assert.equal(container.exitCode, 3)
assert.equal(container.startedAt, Date.parse('2026-09-24T16:54:38.102Z'))
assert.equal(container.finishedAt, Date.parse('2026-09-24T16:54:38.379Z'))
assert.deepEqual(container.restartPolicy, { name: 'no', maximumRetryCount: 0 })
})
it('handles a created container', () => {
const container = inspected('xo-cap-created')
assert.equal(container.state, 'created')
assert.equal(container.exitCode, undefined)
assert.equal(container.startedAt, undefined)
})
it('detects TTY containers', () => {
assert.equal(inspected('xo-tty').tty, true)
assert.equal(inspected('xo-nginx').tty, false)
})
it('gives the health check status', () => {
const healthy = inspected('xo-healthy')
const log = INSPECT_BY_NAME['xo-healthy'].State!.Health!.Log!
assert.equal(healthy.health, 'healthy')
assert.deepEqual(healthy.healthCheck, {
failingStreak: 0,
lastCheckAt: Date.parse(log.at(-1)!.End!),
lastExitCode: 0,
})
const unhealthy = inspected('xo-unhealthy')
assert.equal(unhealthy.health, 'unhealthy')
assert.ok(unhealthy.healthCheck!.failingStreak > 0)
assert.equal(unhealthy.healthCheck!.lastExitCode, 1)
})
it('handles missing optional parts (old API versions)', () => {
const data = clone(INSPECT_BY_NAME['xo-nginx'])
delete data.HostConfig!.RestartPolicy
delete data.NetworkSettings
delete data.Mounts
delete data.Config!.Labels
const container = normalizeContainerInspect(data)
assert.deepEqual(container.restartPolicy, { name: 'no', maximumRetryCount: 0 })
assert.deepEqual(container.ports, [])
assert.deepEqual(container.networks, [])
assert.deepEqual(container.mounts, [])
assert.deepEqual(container.labels, {})
})
})
describe('computeCpuPercent()', () => {
it('computes the CPU usage of a busy container (one full core)', () => {
const { cpuPercent, onlineCpus } = computeCpuPercent(STATS_BUSY.cpu_stats, STATS_BUSY.precpu_stats)
assert.equal(onlineCpus, 6)
const { cpu_stats: cpu, precpu_stats: precpu } = STATS_BUSY
assert.equal(
cpuPercent,
((cpu.cpu_usage.total_usage - precpu.cpu_usage.total_usage) / (cpu.system_cpu_usage - precpu.system_cpu_usage)) *
6 *
100
)
assert.ok(cpuPercent! > 95 && cpuPercent! < 105, String(cpuPercent))
})
it('gives 0 for an idle container', () => {
assert.equal(computeCpuPercent(STATS_NGINX_IDLE.cpu_stats, STATS_NGINX_IDLE.precpu_stats).cpuPercent, 0)
assert.equal(computeCpuPercent(STATS_PAUSED.cpu_stats, STATS_PAUSED.precpu_stats).cpuPercent, 0)
})
it('falls back to percpu_usage when online_cpus is missing', () => {
const cpu = clone<DockerCpuStats>(STATS_BUSY.cpu_stats)
const precpu = clone<DockerCpuStats>(STATS_BUSY.precpu_stats)
delete cpu.online_cpus
delete precpu.online_cpus
cpu.cpu_usage!.percpu_usage = [1, 2, 3, 4]
const { cpuPercent, onlineCpus } = computeCpuPercent(cpu, precpu)
assert.equal(onlineCpus, 4)
const expected = (computeCpuPercent(STATS_BUSY.cpu_stats, STATS_BUSY.precpu_stats).cpuPercent! * 4) / 6
assert.ok(Math.abs(cpuPercent! - expected) < 1e-9, `${cpuPercent} ≠ ${expected}`)
delete cpu.cpu_usage!.percpu_usage
assert.deepEqual(computeCpuPercent(cpu, precpu), { cpuPercent: null, onlineCpus: undefined })
})
it('gives null, not Infinity, when system_cpu_usage is 0', () => {
const cpu = clone<DockerCpuStats>(STATS_BUSY.cpu_stats)
const precpu = clone<DockerCpuStats>(STATS_BUSY.precpu_stats)
precpu.system_cpu_usage = 0
assert.equal(computeCpuPercent(cpu, precpu).cpuPercent, null)
precpu.system_cpu_usage = cpu.system_cpu_usage
assert.equal(computeCpuPercent(cpu, precpu).cpuPercent, null)
cpu.system_cpu_usage = 0
precpu.system_cpu_usage = 0
assert.equal(computeCpuPercent(cpu, precpu).cpuPercent, null)
})
it('gives null for the first object of a stream (no precpu_stats.system_cpu_usage)', () => {
const [first, second] = STATS_STREAM_NGINX
assert.equal(first.precpu_stats.system_cpu_usage, undefined)
assert.equal(computeCpuPercent(first.cpu_stats, first.precpu_stats).cpuPercent, null)
assert.equal(computeCpuPercent(second.cpu_stats, second.precpu_stats).cpuPercent, 0)
})
it('gives null when the counters went backwards', () => {
const cpu = clone<DockerCpuStats>(STATS_BUSY.cpu_stats)
cpu.cpu_usage!.total_usage = 0
assert.equal(computeCpuPercent(cpu, STATS_BUSY.precpu_stats).cpuPercent, null)
})
it('gives null without any data', () => {
assert.equal(computeCpuPercent(STATS_EXITED.cpu_stats, STATS_EXITED.precpu_stats).cpuPercent, null)
assert.equal(computeCpuPercent(undefined, undefined).cpuPercent, null)
})
})
describe('computeMemoryUsage()', () => {
it('subtracts inactive_file on cgroup v2', () => {
const { usage, stats } = STATS_NGINX_IDLE.memory_stats
assert.equal(computeMemoryUsage(STATS_NGINX_IDLE.memory_stats), usage - stats.inactive_file)
})
// cgroup v1 shape (`docker stats` from a cgroup v1 host, Docker 24)
const V1 = {
usage: 104857600,
max_usage: 209715200,
limit: 2147483648,
stats: {
active_anon: 50331648,
active_file: 16777216,
cache: 41943040,
inactive_anon: 0,
inactive_file: 25165824,
rss: 52428800,
total_active_file: 16777216,
total_cache: 41943040,
total_inactive_file: 20971520,
total_rss: 52428800,
},
}
it('subtracts total_inactive_file on cgroup v1', () => {
assert.equal(computeMemoryUsage(V1), V1.usage - V1.stats.total_inactive_file)
})
it('subtracts cache on cgroup v1 without total_inactive_file', () => {
const memoryStats = { usage: V1.usage, stats: { cache: V1.stats.cache, rss: V1.stats.rss } }
assert.equal(computeMemoryUsage(memoryStats), V1.usage - V1.stats.cache)
})
it('does not return a negative value', () => {
assert.equal(computeMemoryUsage({ usage: 1000, stats: { inactive_file: 2000 } }), 1000)
assert.equal(computeMemoryUsage({ usage: 1000 }), 1000)
})
it('gives null without data', () => {
assert.equal(computeMemoryUsage(STATS_EXITED.memory_stats), null)
assert.equal(computeMemoryUsage(undefined), null)
})
})
describe('normalizeContainerStats()', () => {
it('normalizes the stats of a running container', () => {
const { memory_stats: memory } = STATS_NGINX_IDLE
const memoryUsage = memory.usage - memory.stats.inactive_file
assert.deepEqual(normalizeContainerStats(STATS_NGINX_IDLE), {
sampledAt: Date.parse(STATS_NGINX_IDLE.read),
cpuPercent: 0,
onlineCpus: 6,
memoryUsage,
memoryLimit: memory.limit,
memoryPercent: (memoryUsage / memory.limit) * 100,
networkRx: STATS_NGINX_IDLE.networks.eth0.rx_bytes,
networkTx: STATS_NGINX_IDLE.networks.eth0.tx_bytes,
// no io controller delegated to the rootless daemon
blockRead: null,
blockWrite: null,
pids: 7,
})
})
it('gives nulls for a stopped container', () => {
assert.deepEqual(normalizeContainerStats(STATS_EXITED), {
sampledAt: null,
cpuPercent: null,
onlineCpus: undefined,
memoryUsage: null,
memoryLimit: null,
memoryPercent: null,
networkRx: null,
networkTx: null,
blockRead: null,
blockWrite: null,
pids: null,
})
})
it('never gives NaN or Infinity (which would serialize to null)', () => {
for (const stats of [STATS_BUSY, STATS_EXITED, STATS_PAUSED, ...STATS_STREAM_NGINX]) {
const normalized = normalizeContainerStats(stats)
for (const value of Object.values(normalized)) {
assert.ok(value === null || value === undefined || Number.isFinite(value))
}
}
})
it('sums the block I/O (cgroup v1 and v2 op names) and the network interfaces', () => {
const stats = clone<DockerStatsSample>(STATS_NGINX_IDLE)
stats.blkio_stats!.io_service_bytes_recursive = [
{ major: 8, minor: 0, op: 'Read', value: 100 },
{ major: 8, minor: 0, op: 'Write', value: 10 },
{ major: 8, minor: 16, op: 'read', value: 200 },
{ major: 8, minor: 16, op: 'write', value: 20 },
{ major: 8, minor: 16, op: 'Total', value: 330 },
]
;(stats.networks as Record<string, unknown>).eth1 = { rx_bytes: 1, tx_bytes: 2 }
const { blockRead, blockWrite, networkRx, networkTx } = normalizeContainerStats(stats)
assert.deepEqual(
{ blockRead, blockWrite, networkRx, networkTx },
{
blockRead: 300,
blockWrite: 30,
networkRx: STATS_NGINX_IDLE.networks.eth0.rx_bytes + 1,
networkTx: STATS_NGINX_IDLE.networks.eth0.tx_bytes + 2,
}
)
})
it('does not compute the CPU usage of Windows containers', () => {
const stats = { ...clone(STATS_BUSY), os_type: 'windows', memory_stats: { privateworkingset: 1234 } }
const normalized = normalizeContainerStats(stats)
assert.equal(normalized.cpuPercent, null)
assert.equal(normalized.memoryUsage, 1234)
})
// a hostile (or buggy) daemon controls every value: only finite numbers may
// come out, never strings (concatenated by the sums), objects or NaN/Infinity
describe('hostile values', () => {
const HOSTILE = ['1000', '', 'x', NaN, Infinity, -Infinity, { valueOf: 1 }, [1], true, null, 1e308]
const assertOnlyFinite = (normalized: object) => {
for (const [key, value] of Object.entries(normalized)) {
assert.ok(
value === null || value === undefined || (typeof value === 'number' && Number.isFinite(value)),
`${key}: ${typeof value} ${String(value)}`
)
}
}
it('in the block I/O and network sums', () => {
for (const hostile of HOSTILE) {
const stats = clone<DockerStatsSample>(STATS_NGINX_IDLE)
stats.blkio_stats!.io_service_bytes_recursive = [
{ op: 'Read', value: 100 },
{ op: 'Read', value: hostile },
{ op: 'Write', value: hostile },
{ op: 'Write', value: 1e308 },
]
stats.networks = { eth0: { rx_bytes: 10, tx_bytes: hostile }, eth1: { rx_bytes: hostile, tx_bytes: 1e308 } }
const normalized = normalizeContainerStats(stats)
assertOnlyFinite(normalized)
if (typeof hostile === 'number' && Number.isFinite(hostile)) {
continue // 1e308: the sums overflow, checked by assertOnlyFinite
}
assert.equal(normalized.blockRead, 100, String(hostile))
assert.equal(normalized.networkRx, 10, String(hostile))
}
})
it('in the entries themselves (non-object entries, op not a string)', () => {
const stats = clone<DockerStatsSample>(STATS_NGINX_IDLE)
stats.blkio_stats!.io_service_bytes_recursive = [null, 'x', 1, { op: 1, value: 1 }, { op: 'read', value: 2 }]
stats.networks = { eth0: null, eth1: 'x', eth2: { rx_bytes: 3, tx_bytes: 4 } }
const normalized = normalizeContainerStats(stats)
assert.equal(normalized.blockRead, 2)
assert.equal(normalized.networkRx, 3)
assert.equal(normalized.networkTx, 4)
stats.networks = 'eth0'
assertOnlyFinite(normalizeContainerStats(stats))
})
it('in privateworkingset (Windows)', () => {
for (const hostile of HOSTILE) {
const stats = { os_type: 'windows', memory_stats: { privateworkingset: hostile, limit: 1e-300 } }
assertOnlyFinite(normalizeContainerStats(stats))
}
})
it('in the CPU and memory counters, online_cpus and pids', () => {
for (const hostile of HOSTILE) {
for (const set of [
(s: DockerStatsSample) => (s.cpu_stats!.online_cpus = hostile),
(s: DockerStatsSample) => (s.cpu_stats!.cpu_usage!.total_usage = hostile),
(s: DockerStatsSample) => (s.precpu_stats!.cpu_usage!.total_usage = hostile),
(s: DockerStatsSample) => (s.cpu_stats!.system_cpu_usage = hostile),
(s: DockerStatsSample) => (s.precpu_stats!.system_cpu_usage = hostile),
(s: DockerStatsSample) => (s.cpu_stats!.cpu_usage!.percpu_usage = hostile),
(s: DockerStatsSample) => (s.memory_stats!.usage = hostile),
(s: DockerStatsSample) => (s.memory_stats!.limit = hostile),
(s: DockerStatsSample) => ((s.memory_stats!.stats as Record<string, unknown>).inactive_file = hostile),
(s: DockerStatsSample) => (s.pids_stats!.current = hostile),
(s: DockerStatsSample) => (s.read = hostile),
]) {
const stats = clone<DockerStatsSample>(STATS_BUSY)
set(stats)
assertOnlyFinite(normalizeContainerStats(stats))
}
}
})
it('does not accept numeric strings for online_cpus', () => {
const stats = clone<DockerStatsSample>(STATS_BUSY)
stats.cpu_stats!.online_cpus = '4'
delete stats.cpu_stats!.cpu_usage!.percpu_usage
const normalized = normalizeContainerStats(stats)
assert.equal(normalized.onlineCpus, undefined)
assert.equal(normalized.cpuPercent, null)
})
it('huge values which overflow give null, not Infinity', () => {
const stats = clone<DockerStatsSample>(STATS_BUSY)
stats.cpu_stats!.online_cpus = 1e308
stats.memory_stats = { usage: 1e308, limit: 1e-300, stats: {} }
const normalized = normalizeContainerStats(stats)
assertOnlyFinite(normalized)
assert.equal(normalized.cpuPercent, null)
assert.equal(normalized.memoryPercent, null)
})
it('a non-object stats value throws (the sampler drops the stream)', () => {
for (const value of [null, 1, 'x']) {
assert.throws(() => normalizeContainerStats(value))
}
})
})
})
// `GET /version` of Podman 5 (Docker-compatible API)
const PODMAN_VERSION = {
Platform: { Name: 'linux/amd64/debian-13' },
Components: [
{
Name: 'Podman Engine',
Version: '5.4.2',
Details: {
APIVersion: '5.4.2',
Arch: 'amd64',
BuildTime: '2025-04-30T00:00:00Z',
Experimental: 'false',
GitCommit: '',
GoVersion: 'go1.24.2',
KernelVersion: '6.12.101+deb13-amd64',
MinAPIVersion: '4.0.0',
Os: 'linux',
},
},
],
Version: '5.4.2',
ApiVersion: '1.41',
MinAPIVersion: '1.24',
Os: 'linux',
Arch: 'amd64',
}
describe('getEngineKind()', () => {
it('tells Podman from Docker', () => {
assert.equal(getEngineKind(VERSION), 'docker')
assert.equal(getEngineKind(PODMAN_VERSION), 'podman')
})
it('from the platform alone, defaults to docker', () => {
assert.equal(getEngineKind({ Platform: { Name: 'Podman Engine' } }), 'podman')
assert.equal(getEngineKind(undefined), 'docker')
assert.equal(getEngineKind({ Components: 'garbage' } as never), 'docker')
assert.equal(getEngineKind({ Components: [null] } as never), 'docker')
})
})
describe('normalizeEngineInfo()', () => {
it('normalizes /info and /version', () => {
assert.deepEqual(normalizeEngineInfo(INFO, VERSION), {
id: INFO.ID,
kind: 'docker',
name: 'docker-host',
engineVersion: '29.8.1',
apiVersion: '1.56',
minApiVersion: '1.40',
operatingSystem: 'Debian GNU/Linux 13 (trixie)',
osType: 'linux',
kernelVersion: INFO.KernelVersion,
architecture: 'x86_64',
cpus: 6,
memory: INFO.MemTotal,
storageDriver: 'overlayfs',
loggingDriver: 'json-file',
cgroupDriver: 'systemd',
cgroupVersion: '2',
rootless: true,
containers: { total: 8, running: 5, paused: 1, stopped: 2 },
images: 3,
warnings: INFO.Warnings,
})
})
it('works without /version and on a rootful daemon', () => {
const info = normalizeEngineInfo({ ...INFO, SecurityOptions: ['name=seccomp,profile=builtin'], Warnings: null })
assert.equal(info.engineVersion, '29.8.1')
assert.equal(info.apiVersion, undefined)
assert.equal(info.rootless, false)
assert.deepEqual(info.warnings, [])
})
it('tells Podman', () => {
assert.equal(normalizeEngineInfo(INFO, PODMAN_VERSION).kind, 'podman')
})
})

View File

@@ -1,504 +0,0 @@
// Pool of Docker connections, one per engine.
//
// - key = engine id + revision: bumping the revision (credential/host update)
// makes the pool open a new connection instead of reusing the old one; the
// revision is opaque, e.g. a hash of the connection parameters, so that a
// connection can never serve other parameters than the ones it was opened
// with
// - concurrent first uses of an engine share one SSH handshake
// - a connection whose SSH session ends (lost, or closed) is removed: the next
// use opens a new one, through `createConnection` and the negative cache
// - idle connections are closed after `idleTimeout` by one shared, unref'd
// sweeper
// - at most `maxConnections`: the least recently used idle connection is
// evicted, and POOL_EXHAUSTED is thrown when all of them are busy
// - negative cache: after a connection failure, uses of the engine fail fast
// for `failureTtl`, and the last error stays available (`getState()`) until a
// connection succeeds or the engine is invalidated
//
// No XO concepts here: the caller provides the connection factory.
import { createLogger } from '@xen-orchestra/log'
import type { XoDockerEngineKind } from '@vates/types'
import type { DockerConnection } from './connection.mjs'
import {
CONNECTION_CLOSED,
DOCKER_API_VERSION_UNSUPPORTED,
DOCKER_SOCKET_UNREACHABLE,
DockerError,
HOST_KEY_MISMATCH,
HOST_KEY_UNKNOWN,
isDockerError,
POOL_EXHAUSTED,
SSH_AUTH_FAILED,
SSH_ERROR,
SSH_REFUSED_PENALTY,
SSH_UNREACHABLE,
STREAM_LOCAL_FORWARDING_DISABLED,
STREAM_LOCAL_UNSUPPORTED,
} from './errors.mjs'
const { debug, warn } = createLogger('xo:docker-ssh:pool')
export const DEFAULT_MAX_CONNECTIONS = 20
export const DEFAULT_IDLE_TIMEOUT = 5 * 60e3
export const DEFAULT_FAILURE_TTL = 30e3
export const DEFAULT_SWEEP_INTERVAL = 30e3
// errors raised while using an established connection which mean that the
// engine itself is unusable: they evict the connection and are negatively
// cached, like connection failures
//
// Not included: Docker API errors (4xx/5xx of one request), TIMEOUT (one slow
// request), POOL_EXHAUSTED and CONNECTION_CLOSED (local conditions)
const ENGINE_FAILURE_CODES = new Set([
DOCKER_API_VERSION_UNSUPPORTED,
DOCKER_SOCKET_UNREACHABLE,
HOST_KEY_MISMATCH,
HOST_KEY_UNKNOWN,
SSH_AUTH_FAILED,
SSH_ERROR,
SSH_REFUSED_PENALTY,
SSH_UNREACHABLE,
STREAM_LOCAL_FORWARDING_DISABLED,
STREAM_LOCAL_UNSUPPORTED,
])
const LOCAL_CODES = new Set([CONNECTION_CLOSED, POOL_EXHAUSTED])
const isEngineFailure = (error: unknown): error is DockerError =>
isDockerError(error) && ENGINE_FAILURE_CODES.has(error.code)
// what is exposed of an error in `getState()`
const summarizeError = (error: unknown): { code: string; message: string } => ({
code: isDockerError(error) ? error.code : 'UNKNOWN_ERROR',
message: String((error as { message?: unknown } | null | undefined)?.message ?? error),
})
const makeKey = (id: string, revision: number | string | undefined) => `${id}:${revision ?? 0}`
/**
* What the users of a pooled connection get, see `createFacade()`.
*/
export type DockerConnectionFacade = Pick<
DockerConnection,
'apiVersion' | 'engineKind' | 'engineVersion' | 'observedHostKey' | 'request' | 'requestStream' | 'exec'
>
/**
* What the pool uses of a connection: a `DockerConnection`, or a stand-in in
* tests.
*/
export type PoolableConnection = DockerConnectionFacade & Pick<DockerConnection, 'connect' | 'close' | 'onClose'>
/** State of an engine's connection, see `getState()` */
export type DockerConnectionState = {
status: 'idle' | 'connected' | 'error'
error?: { code: string; message: string }
/** only when connected */
kind?: XoDockerEngineKind
}
type Entry = {
closed: boolean
closing?: Promise<void>
connected: boolean
connection: PoolableConnection | undefined
facade: DockerConnectionFacade | undefined
id: string
key: string
lastUsed: number
ready: Promise<void>
refs: number
}
// a failure is anything a connection attempt threw, a DockerError in practice
type Failure = { error: unknown; until: number }
/**
* Facade given to the users of a pooled connection: neither `connect()` nor
* `close()`, and new requests are refused once the pool has closed the
* connection (eviction, invalidation, destroy).
*/
function createFacade(entry: Entry): DockerConnectionFacade {
// set before the facade is created
const { connection } = entry as Entry & { connection: PoolableConnection }
const assertOpen = () => {
if (entry.closed) {
throw new DockerError(CONNECTION_CLOSED, 'the Docker connection has been closed')
}
}
return {
get apiVersion() {
return connection.apiVersion
},
get engineKind() {
return connection.engineKind
},
get engineVersion() {
return connection.engineVersion
},
get observedHostKey() {
return connection.observedHostKey
},
async request(opts) {
assertOpen()
return connection.request(opts)
},
async requestStream(opts) {
assertOpen()
return connection.requestStream(opts)
},
async exec(command, opts) {
assertOpen()
return connection.exec(command, opts)
},
}
}
export class DockerConnectionPool {
#destroyed = false
// key → entry
#entries = new Map<string, Entry>()
// key → { error, until }
#failures = new Map<string, Failure>()
#failureTtl: number
#idleTimeout: number
#maxConnections: number
#now: () => number
#onSweep: (() => void) | undefined
#sweeper: NodeJS.Timeout | undefined
#sweepInterval: number
/**
* @param opts.idleTimeout ms
* @param opts.failureTtl ms
* @param opts.sweepInterval ms
* @param opts.onSweep called on each sweep, e.g. to clean caches
* @param opts.now for tests
*/
constructor({
maxConnections = DEFAULT_MAX_CONNECTIONS,
idleTimeout = DEFAULT_IDLE_TIMEOUT,
failureTtl = DEFAULT_FAILURE_TTL,
sweepInterval = DEFAULT_SWEEP_INTERVAL,
onSweep,
now = Date.now,
}: {
maxConnections?: number
idleTimeout?: number
failureTtl?: number
sweepInterval?: number
onSweep?: () => void
now?: () => number
} = {}) {
this.#failureTtl = failureTtl
this.#idleTimeout = idleTimeout
this.#maxConnections = maxConnections
this.#now = now
this.#onSweep = onSweep
this.#sweepInterval = sweepInterval
}
/** number of connections (established or being established) */
get size(): number {
return this.#entries.size
}
/**
* Passive state of an engine's connection, never connects.
*/
getState(id: string, revision?: number | string): DockerConnectionState {
const key = makeKey(id, revision)
const failure = this.#failures.get(key)
if (failure !== undefined) {
return { status: 'error', error: summarizeError(failure.error) }
}
const entry = this.#entries.get(key)
if (!entry?.connected) {
return { status: 'idle' }
}
const kind = entry.connection?.engineKind
return kind === undefined ? { status: 'connected' } : { status: 'connected', kind }
}
/**
* Forget the last failure of an engine (e.g. after a successful manual test).
*/
clearFailure(id: string): void {
this.#deleteFailures(id)
}
/**
* Run `fn` with the connection of an engine, connecting if necessary.
*
* The connection is considered busy (never evicted) while `fn` runs.
*
* @param createConnection returns a new, not yet connected, connection
*/
async use<T>(
engine: { id: string; revision?: number | string },
createConnection: () => Promise<PoolableConnection> | PoolableConnection,
fn: (connection: DockerConnectionFacade) => Promise<T> | T
): Promise<T> {
const { connection, release } = await this.hold(engine, createConnection)
try {
const result = await fn(connection)
release()
return result
} catch (error) {
release(error)
throw error
}
}
/**
* Same as `use()` for a connection held across calls (e.g. by a stats
* sampler): busy (never evicted) until `release()` is called.
*
* `release(error)` with an engine failure evicts the connection and
* negatively caches the failure, like an error thrown by the `fn` of `use()`.
*
* @returns `release` is idempotent
*/
async hold(
{ id, revision }: { id: string; revision?: number | string },
createConnection: () => Promise<PoolableConnection> | PoolableConnection
): Promise<{ connection: DockerConnectionFacade; release: (error?: unknown) => void }> {
const entry = await this.#acquire(id, revision, createConnection)
let released = false
return {
// set once the entry is ready
connection: entry.facade!,
release: error => {
if (released) {
return
}
released = true
if (isEngineFailure(error) && this.#entries.get(entry.key) === entry) {
debug('engine failure while using a connection', { id, code: error.code })
this.#setFailure(entry.key, error)
this.#close(entry)
}
--entry.refs
entry.lastUsed = this.#now()
},
}
}
async #acquire(
id: string,
revision: number | string | undefined,
createConnection: () => Promise<PoolableConnection> | PoolableConnection
): Promise<Entry> {
if (this.#destroyed) {
throw new DockerError(CONNECTION_CLOSED, 'the Docker connection pool has been destroyed')
}
const key = makeKey(id, revision)
const failure = this.#failures.get(key)
if (failure !== undefined && failure.until > this.#now()) {
// a DockerError in practice, anything else is reported as SSH_ERROR
const error = failure.error as { code?: string; message: string; data?: object }
throw new DockerError(error.code ?? SSH_ERROR, error.message, {
data: { ...error.data, failFast: true, retryAt: failure.until },
cause: error,
})
}
let entry = this.#entries.get(key)
if (entry === undefined) {
entry = this.#create(id, key, createConnection)
}
++entry.refs
entry.lastUsed = this.#now()
try {
await entry.ready
} catch (error) {
--entry.refs
throw error
}
if (entry.closed) {
--entry.refs
throw new DockerError(CONNECTION_CLOSED, 'the Docker connection has been closed')
}
return entry
}
#create(id: string, key: string, createConnection: () => Promise<PoolableConnection> | PoolableConnection): Entry {
if (this.#entries.size >= this.#maxConnections) {
this.#evictOne()
}
// the failures of the other revisions of an engine are stale: they would
// otherwise stay in memory until the engine is invalidated
this.#deleteFailures(id, key)
const entry: Entry = {
closed: false,
connected: false,
connection: undefined,
facade: undefined,
id,
key,
lastUsed: this.#now(),
// replaced right below, `entry` must exist before the promise runs
ready: undefined as unknown as Promise<void>,
refs: 0,
}
entry.ready = (async () => {
const connection = await createConnection()
entry.connection = connection
entry.facade = createFacade(entry)
connection.onClose(() => {
if (this.#entries.get(key) === entry) {
debug('Docker connection closed, removed from the pool', { id })
}
this.#close(entry)
})
if (entry.closed) {
throw new DockerError(CONNECTION_CLOSED, 'the Docker connection has been closed')
}
await connection.connect()
})().then(
() => {
entry.connected = true
if (this.#entries.get(key) === entry) {
this.#failures.delete(key)
}
},
error => {
if (this.#entries.get(key) === entry) {
this.#entries.delete(key)
if (!(isDockerError(error) && LOCAL_CODES.has(error.code))) {
this.#setFailure(key, error)
}
}
entry.closed = true
entry.connection?.close().catch(error => warn('failed to close a Docker connection', { error }))
throw error
}
)
// unhandled rejections are prevented: waiters handle it
entry.ready.catch(() => {})
this.#entries.set(key, entry)
this.#startSweeper()
return entry
}
#setFailure(key: string, error: unknown): void {
this.#failures.set(key, { error, until: this.#now() + this.#failureTtl })
}
// failures of all the revisions of an engine, except `keep`
#deleteFailures(id: string, keep?: string): void {
for (const key of this.#failures.keys()) {
if (key !== keep && key.startsWith(id + ':')) {
this.#failures.delete(key)
}
}
}
#evictOne(): void {
let lru: Entry | undefined
for (const entry of this.#entries.values()) {
if (entry.refs === 0 && entry.connected && (lru === undefined || entry.lastUsed < lru.lastUsed)) {
lru = entry
}
}
if (lru === undefined) {
throw new DockerError(POOL_EXHAUSTED, 'too many Docker connections in use', {
data: { maxConnections: this.#maxConnections },
})
}
debug('evicting the least recently used Docker connection', { id: lru.id })
this.#close(lru)
}
/**
* Remove an entry from the pool and close its connection.
*
* @returns never rejects
*/
#close(entry: Entry): Promise<void> {
if (this.#entries.get(entry.key) === entry) {
this.#entries.delete(entry.key)
}
if (this.#entries.size === 0) {
this.#stopSweeper()
}
if (entry.closed && entry.closing !== undefined) {
return entry.closing
}
entry.closed = true
entry.closing = entry.ready
.catch(() => {})
.then(() => entry.connection?.close())
.catch(error => warn('failed to close a Docker connection', { id: entry.id, error }))
return entry.closing
}
#startSweeper(): void {
if (this.#sweeper === undefined && !this.#destroyed) {
this.#sweeper = setInterval(() => this.sweep(), this.#sweepInterval)
this.#sweeper.unref()
}
}
#stopSweeper(): void {
if (this.#sweeper !== undefined) {
clearInterval(this.#sweeper)
this.#sweeper = undefined
}
}
/**
* Close the connections idle for more than `idleTimeout`.
*
* Called periodically while the pool has connections, exposed for tests.
*/
sweep(): void {
const limit = this.#now() - this.#idleTimeout
for (const entry of Array.from(this.#entries.values())) {
if (entry.refs === 0 && entry.connected && entry.lastUsed <= limit) {
debug('closing an idle Docker connection', { id: entry.id })
this.#close(entry)
}
}
try {
this.#onSweep?.()
} catch (error) {
warn('onSweep', { error })
}
}
/**
* Close the connections of an engine (all revisions) and forget its last
* failure.
*/
async invalidate(id: string): Promise<void> {
this.clearFailure(id)
const promises: Promise<void>[] = []
for (const entry of Array.from(this.#entries.values())) {
if (entry.id === id) {
promises.push(this.#close(entry))
}
}
await Promise.all(promises)
}
/**
* Close every connection, the pool cannot be used afterwards.
*/
async destroy(): Promise<void> {
this.#destroyed = true
this.#stopSweeper()
this.#failures.clear()
await Promise.all(Array.from(this.#entries.values(), entry => this.#close(entry)))
}
}

View File

@@ -1,454 +0,0 @@
import assert from 'node:assert/strict'
import { describe, it } from 'node:test'
import {
CONNECTION_CLOSED,
DOCKER_API_ERROR,
DockerError,
POOL_EXHAUSTED,
SSH_AUTH_FAILED,
SSH_UNREACHABLE,
} from './errors.mjs'
import type { DockerRequestOptions } from './connection.mjs'
import { type DockerConnectionFacade, DockerConnectionPool } from './pool.mjs'
class FakeConnection {
static instances: FakeConnection[] = []
closed = 0
connected = false
connects = 0
connectDelay: number
connectError: DockerError | undefined
onCloseListener: (() => void) | undefined
constructor({ connectError, connectDelay = 0 }: { connectError?: DockerError; connectDelay?: number } = {}) {
this.connectDelay = connectDelay
this.connectError = connectError
FakeConnection.instances.push(this)
}
engineKind: 'docker' | 'podman' | undefined = undefined
get apiVersion() {
return '1.43'
}
async connect() {
++this.connects
await new Promise(resolve => setTimeout(resolve, this.connectDelay))
if (this.connectError !== undefined) {
throw this.connectError
}
this.connected = true
}
async close() {
++this.closed
this.connected = false
}
onClose(listener: () => void) {
this.onCloseListener = listener
}
// the SSH session ends on its own (network failure, server restart…)
simulateLoss() {
this.connected = false
this.onCloseListener?.()
}
async request({ path }: DockerRequestOptions) {
return { statusCode: 200, headers: {}, body: path }
}
// not used by these tests, but part of `PoolableConnection`
get engineVersion() {
return undefined
}
get observedHostKey() {
return undefined
}
async requestStream(): Promise<never> {
throw new Error('not implemented')
}
async exec(): Promise<never> {
throw new Error('not implemented')
}
}
const createClock = (start = 1e6) => {
const clock = () => clock.time
clock.time = start
return clock
}
const engine = (id: string, revision: number | string = 0) => ({ id, revision })
const idle = () => {}
describe('DockerConnectionPool', () => {
it('shares one handshake between concurrent first uses', async () => {
const pool = new DockerConnectionPool()
let created = 0
const create = () => {
++created
return new FakeConnection({ connectDelay: 20 })
}
const results = await Promise.all(
Array.from({ length: 10 }, (_, i) => pool.use(engine('a'), create, c => c.request({ path: '/' + i })))
)
assert.equal(created, 1)
assert.deepEqual(
results.map(_ => _.body),
Array.from({ length: 10 }, (_, i) => '/' + i)
)
assert.deepEqual(pool.getState('a', 0), { status: 'connected' })
await pool.destroy()
})
it('reuses the connection for later uses and uses a new one for a new revision', async () => {
const pool = new DockerConnectionPool()
const connections = []
const create = () => {
const connection = new FakeConnection()
connections.push(connection)
return connection
}
await pool.use(engine('a', 0), create, idle)
await pool.use(engine('a', 0), create, idle)
assert.equal(connections.length, 1)
await pool.use(engine('a', 1), create, idle)
assert.equal(connections.length, 2)
assert.deepEqual(pool.getState('a', 0), { status: 'connected' })
assert.deepEqual(pool.getState('b', 0), { status: 'idle' })
await pool.destroy()
})
it('getState() gives the kind of a connected engine', async () => {
const pool = new DockerConnectionPool()
await pool.use(engine('a'), () => Object.assign(new FakeConnection(), { engineKind: 'podman' as const }), idle)
assert.deepEqual(pool.getState('a', 0), { status: 'connected', kind: 'podman' })
await pool.destroy()
})
it('negative cache: fails fast after a connection failure, then retries after failureTtl', async () => {
const now = createClock()
const pool = new DockerConnectionPool({ failureTtl: 30e3, now })
let created = 0
const create = () => {
++created
return new FakeConnection({ connectError: new DockerError(SSH_UNREACHABLE, 'unreachable') })
}
await assert.rejects(pool.use(engine('a'), create, idle), { code: SSH_UNREACHABLE })
assert.equal(created, 1)
assert.equal(FakeConnection.instances.at(-1)!.closed, 1, 'the failed connection is closed')
now.time += 10e3
await assert.rejects(pool.use(engine('a'), create, idle), (error: DockerError) => {
assert.equal(error.code, SSH_UNREACHABLE)
assert.equal(error.data!.failFast, true)
assert.equal(error.data!.retryAt, 1e6 + 30e3)
return true
})
assert.equal(created, 1, 'no new attempt during failureTtl')
// the error is exposed passively, without connecting
assert.deepEqual(pool.getState('a', 0), {
status: 'error',
error: { code: SSH_UNREACHABLE, message: 'unreachable' },
})
now.time += 25e3
await assert.rejects(pool.use(engine('a'), create, idle), { code: SSH_UNREACHABLE })
assert.equal(created, 2, 'retried after failureTtl')
await pool.destroy()
})
it('keeps reporting the last error after failureTtl, until a connection succeeds', async () => {
const now = createClock()
const pool = new DockerConnectionPool({ failureTtl: 30e3, now })
let error: DockerError | undefined = new DockerError(SSH_AUTH_FAILED, 'bad key')
const create = () => new FakeConnection({ connectError: error })
await assert.rejects(pool.use(engine('a'), create, idle))
now.time += 60e3
assert.equal(pool.getState('a').status, 'error')
error = undefined
await pool.use(engine('a'), create, idle)
assert.deepEqual(pool.getState('a'), { status: 'connected' })
await pool.destroy()
})
it('an engine failure while using a connection evicts it and is negatively cached', async () => {
const pool = new DockerConnectionPool()
const create = () => new FakeConnection()
await pool.use(engine('a'), create, idle)
const [connection] = FakeConnection.instances.slice(-1)
await assert.rejects(
pool.use(engine('a'), create, () => {
throw new DockerError(SSH_UNREACHABLE, 'connection lost')
}),
{ code: SSH_UNREACHABLE }
)
assert.equal(pool.size, 0)
assert.equal(connection.closed, 1)
assert.equal(pool.getState('a').status, 'error')
await assert.rejects(pool.use(engine('a'), create, idle), (error: DockerError) => error.data!.failFast === true)
await pool.destroy()
})
it('a Docker API error does not evict the connection', async () => {
const pool = new DockerConnectionPool()
const create = () => new FakeConnection()
await assert.rejects(
pool.use(engine('a'), create, () => {
throw new DockerError(DOCKER_API_ERROR, 'no such container', { data: { statusCode: 404 } })
}),
{ code: DOCKER_API_ERROR }
)
assert.equal(pool.size, 1)
assert.deepEqual(pool.getState('a'), { status: 'connected' })
await pool.destroy()
})
it('idle GC closes the connections unused for idleTimeout, not the busy ones', async () => {
const now = createClock()
const pool = new DockerConnectionPool({ idleTimeout: 5 * 60e3, now })
const create = () => new FakeConnection()
await pool.use(engine('idle'), create, idle)
const idleConnection = FakeConnection.instances.at(-1)!
let finish: (() => void) | undefined
const busy = pool.use(engine('busy'), create, () => new Promise<void>(resolve => (finish = resolve)))
await new Promise(resolve => setTimeout(resolve, 5))
const busyConnection = FakeConnection.instances.at(-1)!
now.time += 4 * 60e3
pool.sweep()
assert.equal(pool.size, 2, 'not idle long enough')
now.time += 2 * 60e3
pool.sweep()
await new Promise(resolve => setImmediate(resolve))
assert.equal(idleConnection.closed, 1)
assert.equal(busyConnection.closed, 0, 'busy connections are never collected')
assert.equal(pool.size, 1)
assert.deepEqual(pool.getState('idle'), { status: 'idle' })
finish!()
await busy
now.time += 6 * 60e3
pool.sweep()
assert.equal(pool.size, 0)
await pool.destroy()
})
it('the sweeper runs periodically, calls onSweep and stops on destroy', async () => {
let sweeps = 0
const pool = new DockerConnectionPool({ sweepInterval: 10, onSweep: () => ++sweeps })
await pool.use(engine('a'), () => new FakeConnection(), idle)
await new Promise(resolve => setTimeout(resolve, 35))
assert.ok(sweeps >= 2, `${sweeps} sweeps`)
await pool.destroy()
const count = sweeps
await new Promise(resolve => setTimeout(resolve, 25))
assert.equal(sweeps, count, 'no sweeps after destroy')
})
it('caps the connections: evicts the least recently used idle one', async () => {
const now = createClock()
const pool = new DockerConnectionPool({ maxConnections: 2, now })
const byId: Record<string, FakeConnection> = {}
const create = (id: string) => () => (byId[id] = new FakeConnection())
await pool.use(engine('a'), create('a'), idle)
now.time += 1e3
await pool.use(engine('b'), create('b'), idle)
now.time += 1e3
await pool.use(engine('a'), create('a2'), idle) // a is now the most recently used
assert.equal(byId.a2, undefined)
now.time += 1e3
await pool.use(engine('c'), create('c'), idle)
await new Promise(resolve => setImmediate(resolve))
assert.equal(pool.size, 2)
assert.equal(byId.b.closed, 1, 'b was the LRU')
assert.equal(byId.a.closed, 0)
assert.deepEqual(pool.getState('b'), { status: 'idle' })
await pool.destroy()
})
it('throws POOL_EXHAUSTED when all the connections are busy', async () => {
const pool = new DockerConnectionPool({ maxConnections: 2 })
const create = () => new FakeConnection()
const finishes: (() => void)[] = []
const busy = ['a', 'b'].map(id =>
pool.use(engine(id), create, () => new Promise<void>(resolve => finishes.push(resolve)))
)
await new Promise(resolve => setTimeout(resolve, 5))
let created = 0
await assert.rejects(
pool.use(
engine('c'),
() => {
++created
return new FakeConnection()
},
idle
),
{ code: POOL_EXHAUSTED }
)
assert.equal(created, 0)
// not an engine failure: not negatively cached
assert.deepEqual(pool.getState('c'), { status: 'idle' })
// a busy engine can still be used
await pool.use(engine('a'), create, idle)
finishes.forEach(finish => finish())
await Promise.all(busy)
await pool.use(engine('c'), create, idle)
await pool.destroy()
})
it('prunes the failures of the other revisions of an engine (fixes)', async () => {
const pool = new DockerConnectionPool()
const error = new DockerError(SSH_AUTH_FAILED, 'nope')
await assert.rejects(
pool.use(engine('a', 'old'), () => new FakeConnection({ connectError: error }), idle),
{ code: SSH_AUTH_FAILED }
)
assert.equal(pool.getState('a', 'old').status, 'error')
await pool.use(engine('a', 'new'), () => new FakeConnection(), idle)
assert.deepEqual(pool.getState('a', 'old'), { status: 'idle' })
assert.deepEqual(pool.getState('a', 'new'), { status: 'connected' })
await pool.destroy()
})
it('invalidate() closes the connections of an engine and forgets its failure', async () => {
const pool = new DockerConnectionPool()
await pool.use(engine('a'), () => new FakeConnection(), idle)
const connection = FakeConnection.instances.at(-1)!
await assert.rejects(
pool.use(engine('b'), () => new FakeConnection({ connectError: new DockerError(SSH_AUTH_FAILED, 'x') }), idle)
)
await pool.invalidate('a')
assert.equal(connection.closed, 1)
assert.equal(pool.size, 0)
await pool.invalidate('b')
assert.deepEqual(pool.getState('b'), { status: 'idle' })
await pool.destroy()
})
it('a connection closed by the pool refuses new requests', async () => {
const pool = new DockerConnectionPool()
let facade: DockerConnectionFacade | undefined
let started: (() => void) | undefined
let finish: (() => void) | undefined
const running = new Promise<void>(resolve => (started = resolve))
const done = pool.use(
engine('a'),
() => new FakeConnection(),
async connection => {
facade = connection
started!()
await new Promise<void>(resolve => (finish = resolve))
}
)
await running
await pool.invalidate('a')
await assert.rejects(facade!.request({ path: '/info' }), { code: CONNECTION_CLOSED })
finish!()
await done
await pool.destroy()
})
it('invalidation while connecting: the waiters get CONNECTION_CLOSED and the connection is closed', async () => {
const pool = new DockerConnectionPool()
const promise = pool.use(engine('a'), () => new FakeConnection({ connectDelay: 200 }), idle)
await new Promise(resolve => setTimeout(resolve, 2))
const connection = FakeConnection.instances.at(-1)!
await pool.invalidate('a')
await assert.rejects(promise, { code: CONNECTION_CLOSED })
assert.ok(connection.closed >= 1)
assert.deepEqual(pool.getState('a'), { status: 'idle' })
await pool.destroy()
})
it('a lost connection is removed: not reported connected, the next use opens a new one', async () => {
const pool = new DockerConnectionPool()
await pool.use(engine('a'), () => new FakeConnection(), idle)
const lost = FakeConnection.instances.at(-1)!
assert.deepEqual(pool.getState('a'), { status: 'connected' })
lost.simulateLoss()
assert.deepEqual(pool.getState('a'), { status: 'idle' })
assert.equal(pool.size, 0)
// not negatively cached: a lost session is not a connection failure
let created = 0
await pool.use(
engine('a'),
() => (++created, new FakeConnection()),
() => {}
)
assert.equal(created, 1)
assert.notEqual(FakeConnection.instances.at(-1), lost)
assert.ok(lost.closed >= 1)
await pool.destroy()
})
it('hold(): busy until released (idempotent), release(error) with an engine failure evicts and caches it', async () => {
const clock = createClock()
const pool = new DockerConnectionPool({ idleTimeout: 1e3, now: clock })
const held = await pool.hold(engine('a'), () => new FakeConnection())
const connection = FakeConnection.instances.at(-1)!
assert.equal((await held.connection.request({ path: '/info' })).body, '/info')
clock.time += 2e3
pool.sweep()
assert.equal(connection.closed, 0)
held.release()
held.release()
clock.time += 2e3
pool.sweep()
await new Promise(resolve => setImmediate(resolve))
assert.equal(connection.closed, 1)
const again = await pool.hold(engine('a'), () => new FakeConnection())
again.release(new DockerError(SSH_UNREACHABLE, 'lost'))
assert.equal(pool.getState('a').status, 'error')
await assert.rejects(
pool.hold(engine('a'), () => new FakeConnection()),
{ code: SSH_UNREACHABLE }
)
await pool.destroy()
})
it('destroy() closes everything, including pending connections, and refuses new uses', async () => {
const pool = new DockerConnectionPool()
await pool.use(engine('a'), () => new FakeConnection(), idle)
const established = FakeConnection.instances.at(-1)!
const pending = pool.use(engine('b'), () => new FakeConnection({ connectDelay: 200 }), idle)
await new Promise(resolve => setTimeout(resolve, 2))
const connecting = FakeConnection.instances.at(-1)!
await pool.destroy()
assert.equal(established.closed, 1)
assert.ok(connecting.closed >= 1)
await assert.rejects(pending, { code: CONNECTION_CLOSED })
assert.equal(pool.size, 0)
await assert.rejects(
pool.use(engine('a'), () => new FakeConnection(), idle),
{ code: CONNECTION_CLOSED }
)
})
})

View File

@@ -1,313 +0,0 @@
// Bounded requests built on a connection: container logs and the raw API
// passthrough. No XO concepts here: the caller validates the parameters,
// provides the limits and maps the errors (e.g. 404).
import { once } from 'node:events'
import type { IncomingHttpHeaders, IncomingMessage } from 'node:http'
import { type Readable, Transform } from 'node:stream'
import { finished } from 'node:stream/promises'
import type { XoDockerLogEntry, XoDockerLogs } from '@vates/types'
import { compareApiVersions, type DockerConnection } from './connection.mjs'
import { DOCKER_API_ERROR, DockerError, RAW_REQUEST_TOO_LARGE, RAW_RESPONSE_TOO_LARGE } from './errors.mjs'
import { normalizeContainerInspect } from './normalize.mjs'
import { createLogLineParser, createStdcopyDemuxer, isMultiplexedStream } from './stdcopy.mjs'
import type { DockerInspect } from './wire.mjs'
type Connection = Pick<DockerConnection, 'apiVersion' | 'request' | 'requestStream'>
export type ContainerLogsOptions = {
/** number of lines from the end */
tail: number
/** Docker timestamp (seconds since the epoch, fractional part allowed) */
since?: string
/** Docker timestamp (seconds since the epoch, fractional part allowed) */
until?: string
stdout?: boolean
stderr?: boolean
timestamps?: boolean
/** `Config.Tty` of the container if known, only used before API 1.42 (else inspected) */
tty?: boolean
/** max bytes read from the response, `truncated` above */
maxSize: number
/** max entries returned (dockerd splits lines over 64 KiB), `truncated` above */
maxEntries: number
/** max duration of the whole read (ms), `truncated` and `timedOut` above */
timeout: number
/** max duration without data (ms), `truncated` and `timedOut` above */
idleTimeout: number
}
/**
* Logs of a container, bounded in size, entries and time: on expiry, what has
* been read so far is returned.
*
* @throws {DockerError} e.g. DOCKER_API_ERROR with `data.statusCode` 404 for an unknown container
*/
export async function readContainerLogs(
connection: Connection,
dockerId: string,
{
tail,
since,
until,
stdout = true,
stderr = true,
timestamps = true,
tty,
maxSize,
maxEntries,
timeout,
idleTimeout,
}: ContainerLogsOptions
): Promise<XoDockerLogs> {
const path = `/containers/${encodeURIComponent(dockerId)}`
const query = {
// dockerd answers 400 without any of them: always ask for both, and
// filter afterwards
stdout: 1,
stderr: 1,
// always requested: without them, a message starting with something
// looking like a timestamp would be mangled by the line parser
timestamps: 1,
tail,
since,
until,
}
// the content type is only reliable from API 1.42, before that the TTY
// setting of the container decides
if (connection.apiVersion === undefined || compareApiVersions(connection.apiVersion, '1.42') < 0) {
if (tty === undefined) {
const { body } = await connection.request({ path: path + '/json' })
try {
tty = normalizeContainerInspect(body as DockerInspect).tty
} catch (error) {
throw new DockerError(DOCKER_API_ERROR, 'invalid answer from the Docker daemon', { cause: error })
}
}
} else {
tty = undefined
}
const asOf = Date.now()
const controller = new AbortController()
// the body is bounded in time too: dockerd may stall or trickle, which
// would keep the connection busy forever
const TIMED_OUT = new Error('logs deadline')
const ENOUGH = new Error('enough log entries')
let timedOut = false
let response: IncomingMessage | undefined
const expire = () => {
timedOut = true
if (response === undefined) {
controller.abort(new DOMException('Docker logs request timed out', 'TimeoutError'))
} else {
response.destroy(TIMED_OUT)
}
}
const deadline = setTimeout(expire, timeout)
let idleTimer: NodeJS.Timeout | undefined
const resetIdle = () => {
clearTimeout(idleTimer)
idleTimer = setTimeout(expire, idleTimeout)
}
try {
response = await connection.requestStream({ path: path + '/logs', query, signal: controller.signal })
// not reassigned below, for the closures
const body = response
resetIdle()
const demuxer = createStdcopyDemuxer({
tty: !isMultiplexedStream(body.headers['content-type'], tty, connection.apiVersion),
})
const parser = createLogLineParser()
const entries: XoDockerLogEntry[] = []
const streams = new Set([stdout && 'stdout', stderr && 'stderr'])
demuxer.pipe(parser)
demuxer.on('error', error => {
parser.destroy(error)
// interrupts the read loop below
body.destroy(error)
})
let tooManyEntries = false
const collected = (async () => {
for await (const entry of parser) {
if (!streams.has(entry.stream) || tooManyEntries) {
continue
}
if (entries.length === maxEntries) {
tooManyEntries = true
// stops the read loop below, what is still in the parser is
// drained (and dropped)
body.destroy(ENOUGH)
continue
}
entries.push(timestamps ? entry : { ...entry, timestamp: undefined })
}
})()
// awaited below, avoids an unhandled rejection meanwhile
collected.catch(() => {})
let truncated = false
try {
let size = 0
for await (const chunk of body) {
resetIdle()
if (size + chunk.length > maxSize) {
demuxer.write(chunk.subarray(0, maxSize - size))
truncated = true
break
}
size += chunk.length
if (!demuxer.write(chunk)) {
// rejects if the demuxer fails (e.g. invalid frame)
await once(demuxer, 'drain')
}
}
} catch (error) {
if (error !== TIMED_OUT && error !== ENOUGH) {
throw error
}
} finally {
clearTimeout(idleTimer)
// stops reading the response (and frees the channel) when truncated or
// timed out
body.destroy()
controller.abort()
demuxer.end()
}
await collected
return { entries, truncated: truncated || tooManyEntries || timedOut || demuxer.truncated, timedOut, asOf }
} finally {
clearTimeout(deadline)
clearTimeout(idleTimer)
}
}
/**
* Pass-through stream which fails with a DockerError of `code` once more than
* `maxSize` bytes went through.
*/
function createSizeLimiter(maxSize: number, code: string, message: string): Transform {
let size = 0
return new Transform({
transform(chunk, encoding, callback) {
size += chunk.length
if (size > maxSize) {
callback(new DockerError(code, message, { data: { maxSize } }))
} else {
callback(null, chunk)
}
},
})
}
export type RawRequestOptions = {
method: string
/** with its query string, prefixed with the negotiated API version unless it starts with `/v<version>/` */
path: string
/** sent as is */
headers?: Record<string, string>
body?: Readable
/** aborts the request and the response */
signal?: AbortSignal
/** the request body fails with RAW_REQUEST_TOO_LARGE above */
maxRequestSize: number
/** RAW_RESPONSE_TOO_LARGE above: thrown if announced by `content-length`, else the response body fails */
maxResponseSize: number
/** whole request, response body included (ms), 0 disables it */
timeout: number
}
export type RawResponse = {
statusCode: number
headers: IncomingHttpHeaders
body: Readable
/** resolves once the response body is done (consumed, failed or destroyed), never rejects */
done: Promise<void>
}
/**
* Raw Docker Engine API request (passthrough): sent on a dedicated channel
* (outside of the limit of concurrent requests), error responses are returned.
*
* On failure, the request body is not sent and what is still received from it
* is discarded: it is neither destroyed nor left piped.
*
* @throws {DockerError}
*/
export async function rawRequest(
connection: Connection,
{ method, path, headers = {}, body, signal, maxRequestSize, maxResponseSize, timeout }: RawRequestOptions
): Promise<RawResponse> {
// the whole lifetime of the request, response body included (e.g. `/events`
// or `logs?follow=1` would otherwise stay open as long as the client)
const controller = new AbortController()
const timer =
timeout > 0
? setTimeout(
() => controller.abort(new DOMException('raw Docker API request timed out', 'TimeoutError')),
timeout
)
: undefined
timer?.unref()
const requestSignal = AbortSignal.any([controller.signal, signal].filter(signal => signal !== undefined))
let requestBody: Transform | undefined
if (body !== undefined) {
const limiter = (requestBody = createSizeLimiter(
maxRequestSize,
RAW_REQUEST_TOO_LARGE,
'the request body is too large (docker.maxRawRequestSize)'
))
body.on('error', error => limiter.destroy(error))
body.pipe(limiter)
}
try {
const response = await connection.requestStream({
method,
path,
headers,
body: requestBody,
signal: requestSignal,
raw: true,
longLived: true,
})
const length = response.headers['content-length']
if (length !== undefined && Number(length) > maxResponseSize) {
response.destroy()
throw new DockerError(RAW_RESPONSE_TOO_LARGE, 'the response is too large (docker.maxRawResponseSize)', {
data: { maxSize: maxResponseSize, statusCode: response.statusCode },
})
}
const limited = createSizeLimiter(
maxResponseSize,
RAW_RESPONSE_TOO_LARGE,
'the response is too large (docker.maxRawResponseSize)'
)
response.on('error', error => limited.destroy(error))
limited.on('close', () => response.destroy())
response.pipe(limited)
return {
// always set on a client response
statusCode: response.statusCode!,
headers: response.headers,
body: limited,
done: finished(limited).then(
() => clearTimeout(timer),
() => clearTimeout(timer)
),
}
} catch (error) {
clearTimeout(timer)
if (requestBody !== undefined) {
body!.unpipe(requestBody)
requestBody.destroy()
body!.resume()
}
throw error
}
}

View File

@@ -1,241 +0,0 @@
import assert from 'node:assert/strict'
import type { IncomingMessage } from 'node:http'
import { PassThrough, Readable } from 'node:stream'
import { describe, it } from 'node:test'
import type { DockerBufferedRequestOptions, DockerResponse, DockerStreamRequestOptions } from './connection.mjs'
import { INSPECT_BY_NAME } from './fixtures/containers.fixture.mjs'
import { DOCKER_API_ERROR, DockerError, RAW_REQUEST_TOO_LARGE, RAW_RESPONSE_TOO_LARGE, TIMEOUT } from './errors.mjs'
import { type ContainerLogsOptions, rawRequest, readContainerLogs } from './requests.mjs'
const DOCKER_ID = 'a'.repeat(64)
// a multiplexed frame (stdout = 1, stderr = 2)
const frame = (text: string, stream = 1) => {
const payload = Buffer.from(text)
const header = Buffer.from([stream, 0, 0, 0, 0, 0, 0, 0])
header.writeUInt32BE(payload.length, 4)
return Buffer.concat([header, payload])
}
// a response body (`IncomingMessage` stand-in) fed by the test
const createBody = (headers: Record<string, string>, statusCode = 200) =>
Object.assign(new Readable({ read() {} }), { headers, statusCode }) as Readable & IncomingMessage
class FakeConnection {
apiVersion: string | undefined = '1.44'
requests: DockerBufferedRequestOptions[] = []
streams: DockerStreamRequestOptions[] = []
inspect: unknown = INSPECT_BY_NAME['xo-nginx']
respond: (opts: DockerStreamRequestOptions) => Promise<IncomingMessage> = async () => {
throw new Error('not implemented')
}
async request(opts: DockerBufferedRequestOptions): Promise<DockerResponse> {
this.requests.push(opts)
return { statusCode: 200, headers: {}, body: this.inspect }
}
requestStream(opts: DockerStreamRequestOptions): Promise<IncomingMessage> {
this.streams.push(opts)
return this.respond(opts)
}
}
const LIMITS: Omit<ContainerLogsOptions, 'tail'> = {
maxSize: 1024 * 1024,
maxEntries: 1000,
timeout: 5e3,
idleTimeout: 5e3,
}
describe('readContainerLogs()', () => {
it('requests both streams with timestamps, filters and strips them afterwards', async () => {
const connection = new FakeConnection()
connection.respond = async () => {
const body = createBody({ 'content-type': 'application/vnd.docker.multiplexed-stream' })
body.push(frame('2026-09-24T12:00:00.000000000Z out\n'))
body.push(frame('2026-09-24T12:00:01.000000000Z err\n', 2))
body.push(null)
return body
}
const logs = await readContainerLogs(connection, DOCKER_ID, {
...LIMITS,
tail: 10,
since: '1.5',
stderr: false,
timestamps: false,
})
assert.deepEqual(logs.entries, [{ stream: 'stdout', timestamp: undefined, message: 'out' }])
assert.equal(logs.truncated, false)
assert.equal(logs.timedOut, false)
assert.deepEqual(connection.streams[0].query, {
stdout: 1,
stderr: 1,
timestamps: 1,
tail: 10,
since: '1.5',
until: undefined,
})
assert.equal(connection.streams[0].path, `/containers/${DOCKER_ID}/logs`)
// API ≥ 1.42: the content type is reliable, no inspection
assert.equal(connection.requests.length, 0)
})
it('before API 1.42: inspects the container for its TTY setting unless given', async () => {
const connection = new FakeConnection()
connection.apiVersion = '1.41'
const nginx = INSPECT_BY_NAME['xo-nginx']
connection.inspect = { ...nginx, Config: { ...nginx.Config, Tty: true } }
connection.respond = async () => {
const body = createBody({ 'content-type': 'application/vnd.docker.raw-stream' })
body.push('2026-09-24T12:00:00.000000000Z raw\n')
body.push(null)
return body
}
const logs = await readContainerLogs(connection, DOCKER_ID, { ...LIMITS, tail: 10 })
assert.deepEqual(
logs.entries.map(_ => _.message),
['raw']
)
assert.equal(connection.requests[0].path, `/containers/${DOCKER_ID}/json`)
await readContainerLogs(connection, DOCKER_ID, { ...LIMITS, tail: 10, tty: true })
assert.equal(connection.requests.length, 1)
connection.inspect = 'garbage'
await assert.rejects(readContainerLogs(connection, DOCKER_ID, { ...LIMITS, tail: 10 }), {
code: DOCKER_API_ERROR,
})
})
it('cuts at maxSize and at maxEntries (truncated)', async () => {
const connection = new FakeConnection()
connection.respond = async () => {
const body = createBody({ 'content-type': 'application/vnd.docker.multiplexed-stream' })
for (let i = 0; i < 10; ++i) {
body.push(frame(`2026-09-24T12:00:00Z line ${i}\n`))
}
body.push(null)
return body
}
let logs = await readContainerLogs(connection, DOCKER_ID, { ...LIMITS, tail: 10, maxEntries: 3 })
assert.equal(logs.entries.length, 3)
assert.equal(logs.truncated, true)
logs = await readContainerLogs(connection, DOCKER_ID, { ...LIMITS, tail: 10, maxSize: frame('x').length * 2 })
assert.ok(logs.entries.length < 10)
assert.equal(logs.truncated, true)
assert.equal(logs.timedOut, false)
})
it('stops after idleTimeout without data, with what has been read', async () => {
const connection = new FakeConnection()
let body: Readable | undefined
connection.respond = async () => {
body = createBody({ 'content-type': 'application/vnd.docker.multiplexed-stream' })
body.push(frame('2026-09-24T12:00:00Z only\n'))
return body as IncomingMessage
}
const start = Date.now()
const logs = await readContainerLogs(connection, DOCKER_ID, { ...LIMITS, tail: 10, idleTimeout: 100 })
assert.ok(Date.now() - start < 1e3)
assert.deepEqual(
{ timedOut: logs.timedOut, truncated: logs.truncated, messages: logs.entries.map(_ => _.message) },
{ timedOut: true, truncated: true, messages: ['only'] }
)
assert.equal(body!.destroyed, true)
})
it('aborts the request itself after timeout', async () => {
const connection = new FakeConnection()
connection.respond = ({ signal }) =>
new Promise((resolve, reject) => signal!.addEventListener('abort', () => reject(signal!.reason)))
await assert.rejects(readContainerLogs(connection, DOCKER_ID, { ...LIMITS, tail: 10, timeout: 50 }), {
name: 'TimeoutError',
})
})
})
describe('rawRequest()', () => {
const OPTS = { method: 'GET', path: '/info', maxRequestSize: 10, maxResponseSize: 10, timeout: 0 }
it('sends a raw long-lived request and passes the response through', async () => {
const connection = new FakeConnection()
connection.respond = async () => {
const body = createBody({ 'content-type': 'text/plain' }, 418)
body.push('teapot')
body.push(null)
return body
}
const response = await rawRequest(connection, { ...OPTS, headers: { 'x-a': 'b' } })
assert.equal(response.statusCode, 418)
assert.equal((await response.body.toArray()).join(''), 'teapot')
await response.done
const { raw, longLived, headers, path, method } = connection.streams[0]
assert.deepEqual(
{ raw, longLived, headers, path, method },
{
raw: true,
longLived: true,
headers: { 'x-a': 'b' },
path: '/info',
method: 'GET',
}
)
})
it('caps the response: announced size thrown, streamed size fails the body', async () => {
const connection = new FakeConnection()
let response: Readable | undefined
connection.respond = async () => (response = createBody({ 'content-length': '11' }))
await assert.rejects(rawRequest(connection, OPTS), { code: RAW_RESPONSE_TOO_LARGE })
assert.equal(response!.destroyed, true)
connection.respond = async () => {
const body = createBody({})
body.push('x'.repeat(11))
return body
}
const { body, done } = await rawRequest(connection, OPTS)
await assert.rejects(body.toArray(), { code: RAW_RESPONSE_TOO_LARGE })
await done
})
it('caps the request body', async () => {
const connection = new FakeConnection()
let sent: Readable | undefined
connection.respond = async ({ body }) => {
sent = body as Readable
return createBody({})
}
const body = new PassThrough()
await rawRequest(connection, { ...OPTS, method: 'POST', body })
body.end('x'.repeat(11))
await assert.rejects(sent!.toArray(), { code: RAW_REQUEST_TOO_LARGE })
})
it('on failure: the caller body is unpiped and drained, not destroyed', async () => {
const connection = new FakeConnection()
connection.respond = async () => {
throw new DockerError(TIMEOUT, 'no')
}
const body = new PassThrough()
await assert.rejects(rawRequest(connection, { ...OPTS, method: 'POST', body }), { code: TIMEOUT })
assert.equal(body.destroyed, false)
// drained: writing does not stall
assert.equal(body.write('x'), true)
})
it('the timeout covers the response body', async () => {
const connection = new FakeConnection()
connection.respond = async ({ signal }) => {
const body = createBody({})
signal!.addEventListener('abort', () => body.destroy(signal!.reason))
return body
}
const { body, done } = await rawRequest(connection, { ...OPTS, timeout: 50 })
await assert.rejects(body.toArray(), { name: 'TimeoutError' })
await done
})
})

View File

@@ -1,207 +0,0 @@
import { Agent, type AgentOptions, type ClientRequestArgs } from 'node:http'
import type { Socket } from 'node:net'
import type { Duplex } from 'node:stream'
import { createLogger } from '@xen-orchestra/log'
import { DockerError, fromSshError, SSH_UNREACHABLE, TIMEOUT } from './errors.mjs'
const { debug } = createLogger('xo:docker-ssh:ssh-http-agent')
function noop() {}
/**
* The `net.Socket` methods added by `decorateStream()`.
*/
export type DecoratedStream = Duplex & {
setKeepAlive(): void
setNoDelay(): void
setTimeout(): void
ref(): void
unref(): void
destroySoon: Duplex['destroy']
}
/**
* Make an ssh2 channel usable as an HTTP socket.
*
* Port of `decorateStream()` from `ssh2/lib/http-agents.js` (HTTP case): the
* HTTP client and the agent call these `net.Socket` methods which do not
* exist on a channel.
*
* Note: `setTimeout` is a no-op, therefore the `timeout` option of the agent
* and `req.setTimeout()` have no effect on these sockets, timeouts must be
* handled with an `AbortSignal`.
*/
export function decorateStream(duplex: Duplex): DecoratedStream {
// decorated in place: the methods are added below
const stream = duplex as DecoratedStream
stream.setKeepAlive = noop
stream.setNoDelay = noop
stream.setTimeout = noop
stream.ref = noop
stream.unref = noop
// Addition to ssh2's version: once the SSH connection is lost,
// Channel#destroy() emits neither `close` nor `error`, the agent would then
// keep counting the channel as an active socket forever (and eventually
// hit `maxSockets`). Make sure the agent forgets a destroyed channel.
let closed = false
let removed = false
stream.once('close', () => {
closed = true
})
const { destroy } = stream
stream.destroy = function (this: Duplex, ...args: Parameters<Duplex['destroy']>) {
const result = destroy.apply(this, args)
if (!removed) {
removed = true
// deferred: the agent may be iterating over its sockets (Agent#destroy())
process.nextTick(() => {
if (!closed) {
// handled by `installListeners()` in Node's lib/_http_agent.js
this.emit('agentRemove')
}
})
}
return result
}
stream.destroySoon = stream.destroy
return stream
}
/**
* HTTP agent sending requests to a Unix socket on a remote host through an
* already established SSH connection (`direct-streamlocal@openssh.com`
* channels).
*
* Unlike ssh2's own `HTTPAgent` which opens one SSH connection per socket,
* all channels are multiplexed on a single, shared, `ssh2.Client`.
*
* The `host` and `port` of the requests are ignored.
*/
/**
* What the agent needs of an `ssh2.Client` (its `openssh_forwardOutStreamLocal()`).
*/
export interface ForwardOutStreamLocalClient {
openssh_forwardOutStreamLocal(
socketPath: string,
callback: (error: Error | undefined, channel: Duplex) => void
): unknown
}
export class SshHttpAgent extends Agent {
#connectTimeout: number
#getClient: () => Promise<ForwardOutStreamLocalClient>
#socketPath: string
/**
* @param opts.getClient returns a connected (ready) client, must enforce its own timeout
* @param opts.socketPath path of the Unix socket on the remote host
* @param opts.connectTimeout max duration to open a channel once the client is ready (ms)
*/
constructor(
{
getClient,
socketPath,
connectTimeout,
}: { getClient: () => Promise<ForwardOutStreamLocalClient>; socketPath: string; connectTimeout: number },
agentOptions?: AgentOptions
) {
super({
keepAlive: true,
keepAliveMsecs: 10e3,
maxSockets: 8,
maxFreeSockets: 2,
...agentOptions,
})
this.#connectTimeout = connectTimeout
this.#getClient = getClient
this.#socketPath = socketPath
}
/**
* `http.Agent#removeSocket()` only removes a socket from the free list when
* it is no longer writable, but an ssh2 channel closed because the SSH
* connection has been lost stays writable: it would be reused and requests
* sent on it would never complete. Always remove it from the free list.
*/
removeSocket(socket: Duplex, options: ClientRequestArgs): void {
const name = this.getName(options)
const freeSockets = this.freeSockets[name]
if (freeSockets !== undefined) {
// the sockets of this agent are ssh2 channels, typed as `net.Socket` by @types/node
const index = freeSockets.indexOf(socket as Socket)
if (index !== -1) {
freeSockets.splice(index, 1)
if (freeSockets.length === 0) {
// `freeSockets` is only read-only in @types/node, `http.Agent` itself deletes its keys
delete (this.freeSockets as NodeJS.Dict<Socket[]>)[name]
}
}
}
// @ts-expect-error `removeSocket()` is internal to `http.Agent` (Node's lib/_http_agent.js), missing from @types/node
return super.removeSocket(socket, options)
}
/**
* Called by `http.Agent` when a new socket is needed.
*
* Async form: returns nothing and calls `cb` once.
*
* @param _options ignored (host/port are meaningless here)
*/
createConnection(_options: ClientRequestArgs, cb: (error: Error | null, socket?: Duplex) => void): undefined {
const socketPath = this.#socketPath
let settled = false
const settle = (error: unknown, stream?: Duplex) => {
if (settled) {
// too late: the caller already received an error, release the channel
stream?.destroy()
return
}
settled = true
clearTimeout(timer)
if (error == null) {
// no error: ssh2 gives a channel
cb(null, decorateStream(stream as Duplex))
} else {
cb(fromSshError(error, { socketPath }))
}
}
let timer: NodeJS.Timeout | undefined
this.#getClient().then(
client => {
if (settled) {
return
}
// started only once the client is ready so that a slow SSH connection
// is reported with its own error (see `getClient`)
timer = setTimeout(() => {
settle(
new DockerError(TIMEOUT, 'timed out while opening an SSH channel to the Docker socket', {
data: { socketPath, timeout: this.#connectTimeout },
})
)
}, this.#connectTimeout)
try {
client.openssh_forwardOutStreamLocal(socketPath, (error, stream) => {
if (error == null) {
debug('channel opened', { socketPath })
}
settle(error, stream)
})
} catch (error) {
// thrown synchronously when the client is not connected (anymore)
settle(
new DockerError(SSH_UNREACHABLE, 'the SSH connection is closed', { data: { socketPath }, cause: error })
)
}
},
error => settle(error)
)
}
}

View File

@@ -1,356 +0,0 @@
// Container stats, never blocking the listing.
//
// One sampler per engine, started by the first request asking for stats and
// stopped after `idleTimeout` without any reader. While alive, it holds one
// streaming `GET /containers/{id}/stats?stream=true` per running container (at
// most `maxContainers`) and keeps only the latest normalized sample of each:
// bounded memory, no history.
//
// dockerd pushes one JSON object per second per stream, each carrying its own
// `precpu_stats`, except the first one which has no previous sample
// (`cpuPercent: null`): a container is "pending" until its second sample.
//
// No XO concepts here: the caller provides `openStream()`, and tells which
// containers are running with `sync()` on each list refresh.
import type { Readable } from 'node:stream'
import type { XoDockerContainerStats } from '@vates/types'
import { createLogger } from '@xen-orchestra/log'
import { DOCKER_API_ERROR, isDockerError, POOL_EXHAUSTED, TIMEOUT } from './errors.mjs'
import { normalizeContainerStats } from './normalize.mjs'
const { debug, warn } = createLogger('xo:docker-ssh:stats-sampler')
export const DEFAULT_IDLE_TIMEOUT = 90e3
export const DEFAULT_MAX_CONTAINERS = 100
// a stats object is a few KiB, even with many networks and block devices
export const DEFAULT_MAX_OBJECT_SIZE = 256 * 1024
// a container whose stream failed or ended is not reopened before this delay
export const DEFAULT_RETRY_DELAY = 5e3
// dockerd sends one object per second: a daemon sending more (hostile or
// buggy) must not make us parse more, only the latest object is kept
export const DEFAULT_PARSE_INTERVAL = 1e3
// errors of one stream which do not concern the engine: the stream is dropped
// (and retried by a later `sync()` after `retryDelay`), the other streams are
// kept. Any other error (SSH failure, closed connection…) stops the sampler.
const isStreamError = (error: unknown): boolean =>
!isDockerError(error) || error.code === DOCKER_API_ERROR || error.code === TIMEOUT || error.code === POOL_EXHAUSTED
type StreamEntry = {
controller: AbortController
stream: Readable | undefined
stats: XoDockerContainerStats | undefined
samples: number
lastParse: number
pendingLine: string | undefined
parseTimer: NodeJS.Timeout | undefined
}
export type DockerStatsSamplerOptions = {
/** opens `GET /containers/{id}/stats?stream=true` (newline-delimited JSON objects) */
openStream: (dockerId: string, signal: AbortSignal) => Promise<Readable>
/** ms without `sync()`/`get()` after which the sampler stops */
idleTimeout?: number
/** max number of streams */
maxContainers?: number
/**
* max size of one JSON object (UTF-16 code units, roughly bytes), the stream is dropped above; checked on the
* pending partial object plus each received chunk, before scanning
*/
maxObjectSize?: number
/**
* min ms between two parsed objects of a stream, the latest one received in the meantime is parsed at the end of
* the interval
*/
parseInterval?: number
/** ms before reopening the stream of a container after a failure or an end */
retryDelay?: number
/** called once, with the error which stopped the sampler if any */
onStop?: (error?: unknown) => void
/** for tests */
now?: () => number
}
export class DockerStatsSampler {
#failures = new Map<string, number>() // Docker id → time after which it may be reopened
#idleTimeout: number
#idleTimer: NodeJS.Timeout | undefined
#lastRead: number
#maxContainers: number
#maxObjectSize: number
#now: () => number
#onStop: ((error?: unknown) => void) | undefined
#openStream: (dockerId: string, signal: AbortSignal) => Promise<Readable>
#parseInterval: number
#retryDelay: number
#stopped = false
#streams = new Map<string, StreamEntry>() // Docker id → { controller, stream, stats, samples, lastParse, pendingLine, parseTimer }
constructor({
openStream,
idleTimeout = DEFAULT_IDLE_TIMEOUT,
maxContainers = DEFAULT_MAX_CONTAINERS,
maxObjectSize = DEFAULT_MAX_OBJECT_SIZE,
retryDelay = DEFAULT_RETRY_DELAY,
parseInterval = DEFAULT_PARSE_INTERVAL,
onStop,
now = Date.now,
}: DockerStatsSamplerOptions) {
this.#openStream = openStream
this.#idleTimeout = idleTimeout
this.#maxContainers = maxContainers
this.#maxObjectSize = maxObjectSize
this.#retryDelay = retryDelay
this.#parseInterval = parseInterval
this.#onStop = onStop
this.#now = now
this.#lastRead = now()
this.#scheduleIdleCheck(idleTimeout)
}
get stopped(): boolean {
return this.#stopped
}
/** number of streams (opening or open) */
get size(): number {
return this.#streams.size
}
/**
* Streams the given containers, and only them: new ones are opened (up to
* `maxContainers`, the already streamed ones are kept first), the others are
* closed.
*
* @param dockerIds the running containers
*/
sync(dockerIds: Iterable<string>): void {
if (this.#stopped) {
return
}
this.#touch()
const ids = Array.from(new Set(dockerIds))
const now = this.#now()
const wanted = new Set<string>()
// the containers already streamed are kept first, to avoid churn when the
// cap is reached
for (const id of ids) {
if (this.#streams.has(id) && wanted.size < this.#maxContainers) {
wanted.add(id)
}
}
for (const id of ids) {
if (wanted.size >= this.#maxContainers) {
break
}
const retryAt = this.#failures.get(id)
if (retryAt === undefined || retryAt <= now) {
wanted.add(id)
}
}
for (const id of Array.from(this.#streams.keys())) {
if (!wanted.has(id)) {
this.#close(id)
}
}
// forget the failures of the containers which are gone
for (const id of Array.from(this.#failures.keys())) {
// `get(id)!`: `id` is a key
if (!ids.includes(id) || this.#failures.get(id)! <= now) {
this.#failures.delete(id)
}
}
for (const id of wanted) {
if (!this.#streams.has(id)) {
this.#open(id)
}
}
}
/**
* Latest sample of a container.
*
* @returns `undefined` if not streamed, `pending` until the second sample (the first one has no CPU usage)
*/
get(dockerId: string): { stats: XoDockerContainerStats | undefined; pending: boolean } | undefined {
if (this.#stopped) {
return
}
this.#touch()
const entry = this.#streams.get(dockerId)
if (entry === undefined) {
return
}
return { stats: entry.stats, pending: entry.samples < 2 }
}
/**
* Close every stream, the sampler cannot be used afterwards.
*
* @param error reason, passed to `onStop`
*/
stop(error?: unknown): void {
if (this.#stopped) {
return
}
this.#stopped = true
clearTimeout(this.#idleTimer)
for (const id of Array.from(this.#streams.keys())) {
this.#close(id)
}
this.#failures.clear()
debug('stopped', { error })
try {
this.#onStop?.(error)
} catch (error) {
warn('onStop', { error })
}
}
#touch() {
this.#lastRead = this.#now()
}
#scheduleIdleCheck(delay: number): void {
this.#idleTimer = setTimeout(() => {
const idle = this.#now() - this.#lastRead
if (idle >= this.#idleTimeout) {
debug('no reader, stopping')
this.stop()
} else {
this.#scheduleIdleCheck(this.#idleTimeout - idle)
}
}, delay)
this.#idleTimer.unref?.()
}
#close(id: string): void {
const entry = this.#streams.get(id)
if (entry !== undefined) {
this.#streams.delete(id)
clearTimeout(entry.parseTimer)
entry.pendingLine = undefined
entry.controller.abort()
entry.stream?.destroy()
}
}
// the stream of a container failed or ended on its own
#drop(id: string, entry: StreamEntry, error?: unknown): void {
if (this.#streams.get(id) !== entry) {
return
}
this.#close(id)
if (error !== undefined && !isStreamError(error)) {
this.stop(error)
return
}
this.#failures.set(id, this.#now() + this.#retryDelay)
if (error !== undefined && !(isDockerError(error) && error.code === DOCKER_API_ERROR)) {
debug('stats stream failed', { container: id, error })
}
}
#open(id: string): void {
const entry: StreamEntry = {
controller: new AbortController(),
stream: undefined,
stats: undefined,
samples: 0,
lastParse: -Infinity,
pendingLine: undefined,
parseTimer: undefined,
}
this.#streams.set(id, entry)
this.#openStream(id, entry.controller.signal).then(
stream => {
if (this.#streams.get(id) !== entry) {
// closed meanwhile
stream.destroy()
return
}
entry.stream = stream
this.#consume(id, entry, stream)
},
error => {
if (!entry.controller.signal.aborted) {
this.#drop(id, entry, error)
}
}
)
}
// parses the latest complete line received, unless one was parsed less than
// `parseInterval` ago: it is then parsed at the end of the interval (unless a
// newer one replaces it meanwhile)
#parse(id: string, entry: StreamEntry): void {
const line = entry.pendingLine
if (line === undefined || this.#streams.get(id) !== entry) {
return
}
const wait = entry.lastParse + this.#parseInterval - this.#now()
if (wait > 0) {
if (entry.parseTimer === undefined) {
entry.parseTimer = setTimeout(() => {
entry.parseTimer = undefined
this.#parse(id, entry)
}, wait)
entry.parseTimer.unref?.()
}
return
}
entry.pendingLine = undefined
entry.lastParse = this.#now()
let stats
try {
stats = normalizeContainerStats(JSON.parse(line))
} catch (error) {
this.#drop(id, entry, new Error('invalid stats object', { cause: error }))
return
}
entry.stats = stats
++entry.samples
}
#consume(id: string, entry: StreamEntry, stream: Readable): void {
// partial line after the last newline received
let buffer = ''
stream.setEncoding('utf8')
// strings: the encoding is set
stream.on('data', (chunk: string) => {
// checked before any scanning: a daemon cannot make us buffer or scan
// more than the cap, whatever the number of lines (a legitimate stream
// sends a few KiB per second, and a chunk is at most 64 KiB)
if (buffer.length + chunk.length > this.#maxObjectSize) {
this.#drop(id, entry, new Error('stats object too large'))
return
}
// only the latest complete line matters: the objects before it are
// older samples, never parsed
const last = chunk.lastIndexOf('\n')
if (last === -1) {
buffer += chunk
return
}
const previous = chunk.lastIndexOf('\n', last - 1)
const line = (previous === -1 ? buffer + chunk.slice(0, last) : chunk.slice(previous + 1, last)).trim()
buffer = chunk.slice(last + 1)
if (line !== '') {
entry.pendingLine = line
this.#parse(id, entry)
}
})
// `close` is always emitted, after `error` if any: the stream ended
// (container stopped) or its channel failed; if the whole connection is
// gone, the next `openStream()` fails with CONNECTION_CLOSED (or an SSH
// error) and stops the sampler
stream.on('error', error => {
debug('stats stream error', { container: id, error })
})
stream.on('close', () => this.#drop(id, entry))
}
}

View File

@@ -1,450 +0,0 @@
import assert from 'node:assert/strict'
import { once } from 'node:events'
import { mkdtemp, rm } from 'node:fs/promises'
import { createServer, get as httpGet, type IncomingMessage, type Server, type ServerResponse } from 'node:http'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { PassThrough } from 'node:stream'
import { after, before, describe, it } from 'node:test'
import { DockerError } from './errors.mjs'
import { DockerStatsSampler } from './stats-sampler.mjs'
import type { DockerCpuStats, DockerStatsSample } from './wire.mjs'
const sleep = (ms: number) => new Promise(resolve => setTimeout(resolve, ms))
const tick = () => new Promise(resolve => setImmediate(resolve))
// a Docker stats object: `total` / `system` are the cumulated CPU counters,
// `pre` the previous ones (absent on the first object of a stream)
const statsObject = ({
total,
system,
pre,
memory = 100e6,
}: {
total: number
system: number
pre?: DockerCpuStats
memory?: number
}): DockerStatsSample => ({
read: '2026-09-24T12:00:00.000000000Z',
cpu_stats: { cpu_usage: { total_usage: total }, system_cpu_usage: system, online_cpus: 2 },
precpu_stats: pre === undefined ? { cpu_usage: { total_usage: 0 } } : pre,
memory_stats: { usage: memory, limit: 1e9, stats: { inactive_file: 0 } },
pids_stats: { current: 3 },
})
/**
* Fake `openStream()`: one PassThrough per call, controllable from the test.
*/
function createFakeDocker() {
const streams = new Map<string, PassThrough>()
const opened: string[] = []
const fake = {
opened,
streams,
fail: undefined as ((dockerId: string) => Error | undefined) | undefined,
openStream: async (dockerId: string, signal: AbortSignal) => {
opened.push(dockerId)
await tick()
const error = fake.fail?.(dockerId)
if (error !== undefined) {
throw error
}
const stream = new PassThrough()
signal.addEventListener('abort', () => stream.destroy(), { once: true })
streams.set(dockerId, stream)
return stream
},
push(dockerId: string, object: object) {
streams.get(dockerId)!.write(JSON.stringify(object) + '\n')
},
isOpen(dockerId: string) {
const stream = streams.get(dockerId)
return stream !== undefined && !stream.destroyed
},
}
return fake
}
describe('DockerStatsSampler', () => {
it('warms up: pending until the second sample, which has the CPU usage', async () => {
const fake = createFakeDocker()
const sampler = new DockerStatsSampler({ openStream: fake.openStream, parseInterval: 0 })
try {
sampler.sync(['a'])
// never blocks: known but no sample yet
assert.deepEqual(sampler.get('a'), { stats: undefined, pending: true })
await tick()
await tick()
fake.push('a', statsObject({ total: 1e9, system: 100e9 }))
await tick()
let sample = sampler.get('a')
assert.equal(sample!.pending, true)
assert.equal(sample!.stats!.cpuPercent, null)
assert.equal(sample!.stats!.memoryUsage, 100e6)
// 0.5 s of CPU over 10 s of system time on 2 CPUs → 10 %
fake.push(
'a',
statsObject({
total: 1.5e9,
system: 110e9,
pre: { cpu_usage: { total_usage: 1e9 }, system_cpu_usage: 100e9 },
})
)
await tick()
sample = sampler.get('a')
assert.equal(sample!.pending, false)
assert.equal(sample!.stats!.cpuPercent, 10)
assert.equal(sampler.get('unknown'), undefined)
} finally {
sampler.stop()
}
})
it('keeps only the latest sample, and handles objects split across chunks', async () => {
const fake = createFakeDocker()
const sampler = new DockerStatsSampler({ openStream: fake.openStream, parseInterval: 0 })
try {
sampler.sync(['a'])
await tick()
await tick()
const line = JSON.stringify(statsObject({ total: 1, system: 1, memory: 42 })) + '\n'
const stream = fake.streams.get('a')!
for (let i = 0; i < line.length; i += 7) {
stream.write(line.slice(i, i + 7))
await tick()
}
assert.equal(sampler.get('a')!.stats!.memoryUsage, 42)
fake.push('a', statsObject({ total: 2, system: 2, memory: 43 }))
await tick()
assert.equal(sampler.get('a')!.stats!.memoryUsage, 43)
} finally {
sampler.stop()
}
})
it('follows the containers: new streams opened, stopped ones closed', async () => {
const fake = createFakeDocker()
const sampler = new DockerStatsSampler({ openStream: fake.openStream })
try {
sampler.sync(['a', 'b'])
await tick()
await tick()
assert.deepEqual(fake.opened, ['a', 'b'])
assert.equal(sampler.size, 2)
sampler.sync(['b', 'c'])
await tick()
await tick()
assert.deepEqual(fake.opened, ['a', 'b', 'c'], 'b is not reopened')
assert.equal(fake.isOpen('a'), false, 'a is closed')
assert.equal(fake.isOpen('b'), true)
assert.equal(fake.isOpen('c'), true)
assert.equal(sampler.get('a'), undefined)
assert.equal(sampler.size, 2)
} finally {
sampler.stop()
}
})
it('a stream which ends (container stopped) is dropped, and reopened only after retryDelay', async () => {
const fake = createFakeDocker()
const sampler = new DockerStatsSampler({ openStream: fake.openStream, retryDelay: 50 })
try {
sampler.sync(['a'])
await tick()
await tick()
fake.streams.get('a')!.end()
await tick()
await tick()
assert.equal(sampler.get('a'), undefined)
sampler.sync(['a'])
assert.equal(sampler.get('a'), undefined, 'not retried right away')
await sleep(60)
sampler.sync(['a'])
assert.notEqual(sampler.get('a'), undefined)
assert.deepEqual(fake.opened, ['a', 'a'])
} finally {
sampler.stop()
}
})
it('a Docker API error (e.g. 404) drops only that container', async () => {
const fake = createFakeDocker()
fake.fail = id => (id === 'gone' ? new DockerError('DOCKER_API_ERROR', 'no such container') : undefined)
const sampler = new DockerStatsSampler({ openStream: fake.openStream })
try {
sampler.sync(['gone', 'a'])
await tick()
await tick()
assert.equal(sampler.stopped, false)
assert.equal(sampler.get('gone'), undefined)
assert.notEqual(sampler.get('a'), undefined)
} finally {
sampler.stop()
}
})
it('an engine failure stops the sampler, onStop gets the error', async () => {
const fake = createFakeDocker()
const error = new DockerError('SSH_UNREACHABLE', 'connection lost')
fake.fail = () => error
let stopError: unknown = 'not called'
const sampler = new DockerStatsSampler({
openStream: fake.openStream,
onStop: error => {
stopError = error
},
})
sampler.sync(['a', 'b'])
await tick()
await tick()
assert.equal(sampler.stopped, true)
assert.equal(stopError, error)
assert.equal(sampler.size, 0)
})
it('at most maxContainers streams, already streamed containers are kept first', async () => {
const fake = createFakeDocker()
const sampler = new DockerStatsSampler({ openStream: fake.openStream, maxContainers: 2 })
try {
sampler.sync(['a', 'b', 'c'])
await tick()
await tick()
assert.deepEqual(fake.opened, ['a', 'b'])
assert.equal(sampler.get('c'), undefined)
// c comes first now, but a and b are kept
sampler.sync(['c', 'b', 'a'])
await tick()
assert.deepEqual(fake.opened, ['a', 'b'])
// a is gone: c takes its place
sampler.sync(['c', 'b'])
await tick()
await tick()
assert.deepEqual(fake.opened, ['a', 'b', 'c'])
assert.equal(sampler.size, 2)
} finally {
sampler.stop()
}
})
it('an oversized object drops the stream (bounded memory)', async () => {
const fake = createFakeDocker()
const sampler = new DockerStatsSampler({ openStream: fake.openStream, maxObjectSize: 100 })
try {
sampler.sync(['a'])
await tick()
await tick()
fake.streams.get('a')!.write('x'.repeat(200))
await tick()
await tick()
assert.equal(sampler.get('a'), undefined)
assert.equal(fake.isOpen('a'), false)
} finally {
sampler.stop()
}
})
it('stops after idleTimeout without reader, readers keep it alive', async () => {
const fake = createFakeDocker()
let stops = 0
const sampler = new DockerStatsSampler({
openStream: fake.openStream,
idleTimeout: 80,
onStop: () => ++stops,
})
sampler.sync(['a'])
await tick()
await tick()
for (let i = 0; i < 4; ++i) {
await sleep(40)
sampler.get('a')
}
assert.equal(sampler.stopped, false, 'kept alive by get()')
await sleep(150)
assert.equal(sampler.stopped, true)
assert.equal(stops, 1)
assert.equal(fake.isOpen('a'), false, 'streams closed')
// no effect once stopped
sampler.sync(['a'])
assert.equal(sampler.get('a'), undefined)
assert.deepEqual(fake.opened, ['a'])
})
it('stop() closes every stream, including the ones being opened', async () => {
const fake = createFakeDocker()
let stops = 0
const sampler = new DockerStatsSampler({ openStream: fake.openStream, onStop: () => ++stops })
sampler.sync(['a'])
await tick()
await tick()
sampler.sync(['a', 'b']) // b is being opened
sampler.stop()
sampler.stop()
await tick()
await tick()
assert.equal(stops, 1)
assert.equal(fake.isOpen('a'), false)
assert.equal(fake.isOpen('b'), false)
assert.equal(sampler.size, 0)
})
})
// a hostile daemon behind a real HTTP server on a Unix socket, the streams
// being opened like `DockerConnection#requestStream()` returns them
describe('DockerStatsSampler against a hostile daemon', () => {
let dir: string, socketPath: string, server: Server
let handler: (req: IncomingMessage, res: ServerResponse) => void
before(async () => {
dir = await mkdtemp(join(tmpdir(), 'xo-docker-sampler-'))
socketPath = join(dir, 'docker.sock')
server = createServer((req, res) => handler(req, res))
server.listen(socketPath)
await once(server, 'listening')
})
after(async () => {
server.closeAllConnections()
server.close()
await rm(dir, { recursive: true, force: true })
})
const openStream = (dockerId: string, signal: AbortSignal) =>
new Promise<IncomingMessage>((resolve, reject) => {
const req = httpGet({ socketPath, path: `/containers/${dockerId}/stats?stream=1`, signal }, resolve)
req.on('error', reject)
})
// counts the JSON.parse() calls made while `fn` runs
async function countParses(fn: () => Promise<unknown>) {
const { parse } = JSON
let count = 0
JSON.parse = function (this: JSON, ...args: Parameters<typeof JSON.parse>) {
++count
return parse.apply(this, args)
}
try {
await fn()
} finally {
JSON.parse = parse
}
return count
}
const line = (memory: number) => JSON.stringify(statsObject({ total: 1, system: 1, memory })) + '\n'
it('a flood of objects in one burst is not fully parsed (latest complete line only)', async () => {
handler = (req, res) => {
res.writeHead(200, { 'content-type': 'application/json' })
// ~2.6 MB, split by the socket in chunks: only the last complete line of
// a chunk may be parsed, and at most about once per second
let body = ''
for (let i = 0; i < 10e3; ++i) {
body += line(i)
}
res.write(body)
}
const sampler = new DockerStatsSampler({ openStream })
try {
const parses = await countParses(async () => {
sampler.sync(['a'])
await sleep(300)
})
assert.notEqual(sampler.get('a'), undefined, 'the stream is kept')
assert.ok(sampler.get('a')!.stats !== undefined)
assert.ok(parses <= 2, `${parses} parses`)
} finally {
sampler.stop()
}
})
it('throttles the parsing to about once per second per stream, keeping the latest sample', async () => {
let res: ServerResponse
handler = (_req, _res) => {
res = _res
res.writeHead(200, { 'content-type': 'application/json' })
res.write(line(0))
}
const sampler = new DockerStatsSampler({ openStream, parseInterval: 300 })
try {
let parses = await countParses(async () => {
sampler.sync(['a'])
await sleep(50)
for (let i = 1; i <= 20; ++i) {
res.write(line(i))
await sleep(5)
}
await sleep(50)
})
assert.equal(parses, 1, 'only the first object within the interval')
assert.equal(sampler.get('a')!.stats!.memoryUsage, 0)
parses = await countParses(() => sleep(350))
assert.equal(parses, 1, 'the latest one at the end of the interval')
assert.equal(sampler.get('a')!.stats!.memoryUsage, 20)
} finally {
sampler.stop()
}
})
it('checks the buffer against the cap before scanning it', async () => {
handler = (req, res) => {
res.writeHead(200, { 'content-type': 'application/json' })
// many short lines in one chunk larger than the cap
res.write('{}\n'.repeat(200))
}
const sampler = new DockerStatsSampler({ openStream, maxObjectSize: 100 })
try {
const parses = await countParses(async () => {
sampler.sync(['a'])
await sleep(100)
})
assert.equal(parses, 0)
assert.equal(sampler.get('a'), undefined, 'dropped')
} finally {
sampler.stop()
}
})
it('an object which is not a stats object drops the stream', async () => {
handler = (req, res) => {
res.writeHead(200, { 'content-type': 'application/json' })
res.write('"just a string"\n')
}
const sampler = new DockerStatsSampler({ openStream })
try {
sampler.sync(['a'])
await sleep(100)
assert.equal(sampler.get('a'), undefined)
} finally {
sampler.stop()
}
})
it('hostile values never reach the samples', async () => {
handler = (req, res) => {
res.writeHead(200, { 'content-type': 'application/json' })
const object = statsObject({ total: 1, system: 1 })
object.networks = { eth0: { rx_bytes: '1', tx_bytes: { a: 1 } } }
object.memory_stats!.usage = '1000'
object.cpu_stats!.online_cpus = '4'
res.write(JSON.stringify(object) + '\n')
}
const sampler = new DockerStatsSampler({ openStream })
try {
sampler.sync(['a'])
await sleep(100)
const { stats } = sampler.get('a')!
for (const [key, value] of Object.entries(stats!)) {
assert.ok(value === null || value === undefined || Number.isFinite(value), key)
}
} finally {
sampler.stop()
}
})
})

View File

@@ -1,273 +0,0 @@
// Docker attach/logs stream decoding.
//
// When a container has no TTY, dockerd multiplexes stdout and stderr on the
// same HTTP body (`Content-Type: application/vnd.docker.multiplexed-stream`):
// each frame is an 8-byte header `[streamType, 0, 0, 0, size (uint32 BE)]`
// followed by `size` bytes of payload. With a TTY, the body is the raw output
// (`application/vnd.docker.raw-stream`), stdout and stderr merged.
//
// See https://docs.docker.com/reference/api/engine/version/v1.43/#tag/Container/operation/ContainerAttach
import { StringDecoder } from 'node:string_decoder'
import { Transform, type TransformCallback } from 'node:stream'
import type { XoDockerLogEntry } from '@vates/types'
import { compareApiVersions } from './connection.mjs'
import { DOCKER_API_ERROR, DockerError } from './errors.mjs'
export const MULTIPLEXED_STREAM_CONTENT_TYPE = 'application/vnd.docker.multiplexed-stream'
export const RAW_STREAM_CONTENT_TYPE = 'application/vnd.docker.raw-stream'
const HEADER_SIZE = 8
// stream type (1st byte of a frame header) → stream name
//
// type 3 (`systemErr`) is used by dockerd to report an error in the middle of
// an attach/exec stream, its payload is the error message
const STREAM_NAMES = ['stdin', 'stdout', 'stderr'] as const
const SYSTEM_ERR = 3
// only the beginning of a systemErr payload is kept (it becomes an error
// message), the rest is read and dropped
export const MAX_SYSTEM_ERR_SIZE = 64 * 1024
export type DockerStreamName = (typeof STREAM_NAMES)[number]
/** object emitted by `createStdcopyDemuxer()` */
export type DemuxedChunk = { stream: DockerStreamName; chunk: Buffer }
/** `createStdcopyDemuxer()` */
export type StdcopyDemuxer = Transform & { truncated: boolean }
/**
* Object emitted by `createLogLineParser()`: an `XoDockerLogEntry`, except
* that `stream` may be `stdin` (attach streams), and that `timestamp` is always
* present (`undefined` if the line has none).
*/
export type DockerLogLine = Omit<XoDockerLogEntry, 'stream' | 'timestamp'> & {
stream: DockerStreamName
timestamp: string | undefined
}
/**
* Whether a logs/attach response body is multiplexed (8-byte frames) or raw.
*
* The `Content-Type` is reliable since API 1.42. With older API versions (or
* an unknown one), a `raw-stream` content type is not conclusive and the
* container's `Config.Tty` decides, defaulting to multiplexed, which is what
* containers without TTY (the vast majority) produce.
*
* @param contentType response `Content-Type`
* @param tty `Config.Tty` of the container, if known
* @param apiVersion negotiated API version, e.g. `1.44`
*/
export function isMultiplexedStream(contentType: string | undefined, tty?: boolean, apiVersion?: string): boolean {
const type = contentType?.split(';')[0].trim().toLowerCase()
if (type === MULTIPLEXED_STREAM_CONTENT_TYPE) {
return true
}
if (type === RAW_STREAM_CONTENT_TYPE && apiVersion !== undefined && compareApiVersions(apiVersion, '1.42') >= 0) {
return false
}
return tty !== true
}
/**
* Transform stream: Docker logs/attach body (bytes) → `{ stream, chunk }`
* objects, `stream` being `stdout`, `stderr` or `stdin`, and `chunk` a
* `Buffer`.
*
* Frames can be split across any chunk boundary. Payloads are emitted as soon as
* they arrive, so a big frame is never buffered entirely: consumers must not
* assume one object per frame (see `createLogLineParser()`).
*
* If the input ends in the middle of a frame, the payload received so far has
* already been emitted and `demuxer.truncated` is set to `true`: the stream ends
* normally, so that the complete part of the logs remains usable.
*
* @param opts.tty raw mode: the input is not framed, every chunk is emitted as `stdout`
*/
export function createStdcopyDemuxer({ tty = false }: { tty?: boolean } = {}): StdcopyDemuxer {
if (tty) {
// `truncated` is added right below
const passthrough = new Transform({
readableObjectMode: true,
transform(chunk: Buffer, _encoding, callback) {
callback(null, { stream: 'stdout', chunk } satisfies DemuxedChunk)
},
}) as StdcopyDemuxer
passthrough.truncated = false
return passthrough
}
const header = Buffer.alloc(HEADER_SIZE)
let headerLength = 0
let stream: DockerStreamName | undefined // name of the stream of the current frame
let remaining = 0 // payload bytes still expected for the current frame
let systemErr: Buffer[] | undefined // chunks of a systemErr frame, emitted as an error
let systemErrSize = 0
// `truncated` is added right below
const demuxer = new Transform({
readableObjectMode: true,
transform(chunk: Buffer, _encoding, callback) {
let offset = 0
const { length } = chunk
while (offset < length) {
if (remaining === 0) {
// reading a header
const n = Math.min(HEADER_SIZE - headerLength, length - offset)
chunk.copy(header, headerLength, offset, offset + n)
headerLength += n
offset += n
if (headerLength < HEADER_SIZE) {
break
}
headerLength = 0
const type = header[0]
remaining = header.readUInt32BE(4)
if (type === SYSTEM_ERR) {
systemErr = []
systemErrSize = 0
} else if (type < STREAM_NAMES.length) {
stream = STREAM_NAMES[type]
} else {
callback(
new DockerError(DOCKER_API_ERROR, `invalid Docker stream: unknown stream type ${type}`, {
data: { header: header.toString('hex') },
})
)
return
}
if (remaining === 0 && systemErr !== undefined) {
callback(systemError(systemErr))
return
}
continue
}
// reading a payload
const n = Math.min(remaining, length - offset)
// subarray() does not copy: chunks come from the socket and are not reused
const payload = chunk.subarray(offset, offset + n)
offset += n
remaining -= n
if (systemErr !== undefined) {
if (systemErrSize < MAX_SYSTEM_ERR_SIZE) {
const kept = payload.subarray(0, MAX_SYSTEM_ERR_SIZE - systemErrSize)
systemErr.push(kept)
systemErrSize += kept.length
}
if (remaining === 0) {
callback(systemError(systemErr))
return
}
} else {
// `stream!`: set by the header of this frame
this.push({ stream: stream!, chunk: payload } satisfies DemuxedChunk)
}
}
callback()
},
flush(callback) {
if (headerLength !== 0 || remaining !== 0) {
;(this as StdcopyDemuxer).truncated = true
}
callback()
},
}) as StdcopyDemuxer
demuxer.truncated = false
return demuxer
}
function systemError(chunks: Buffer[]): DockerError {
return new DockerError(DOCKER_API_ERROR, `Docker stream error: ${Buffer.concat(chunks).toString().trim()}`)
}
// RFC3339Nano timestamp as prefixed by dockerd with `timestamps=1`, e.g.
// `2026-09-24T16:54:37.796330221Z` (trailing zeros of the fraction are
// trimmed, the fraction can be missing, the offset is `Z` in practice)
const TIMESTAMP_RE = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,9})?(?:Z|[+-]\d{2}:\d{2})) /
const DEFAULT_MAX_LINE_LENGTH = 64 * 1024
/**
* Transform stream (object mode): `{ stream, chunk }` objects (from
* `createStdcopyDemuxer()`) → `{ stream, timestamp, message }` log entries.
*
* - lines are split on `\n`, a trailing `\r` (TTY output) is removed
* - each stream is buffered separately, so interleaved stdout/stderr chunks do
* not mix partial lines
* - `timestamp` is the RFC3339Nano string prefixed by dockerd with
* `timestamps=1`, kept verbatim (it has a nanosecond precision), or
* `undefined` if the line has none
* - a line longer than `maxLineLength` characters is split, which bounds the
* memory used by an output without new lines
* - the last line is emitted even if it does not end with a new line
*
* The input chunks may also be strings.
*/
export function createLogLineParser({
maxLineLength = DEFAULT_MAX_LINE_LENGTH,
}: { maxLineLength?: number } = {}): Transform {
// stream name → { decoder, pending }
const states = new Map<DockerStreamName, { decoder: StringDecoder; pending: string }>()
const getState = (stream: DockerStreamName) => {
let state = states.get(stream)
if (state === undefined) {
state = { decoder: new StringDecoder('utf8'), pending: '' }
states.set(stream, state)
}
return state
}
const emitLine = (parser: Transform, stream: DockerStreamName, line: string) => {
if (line.endsWith('\r')) {
line = line.slice(0, -1)
}
const match = TIMESTAMP_RE.exec(line)
parser.push(
(match === null
? { stream, timestamp: undefined, message: line }
: { stream, timestamp: match[1], message: line.slice(match[0].length) }) satisfies DockerLogLine
)
}
return new Transform({
objectMode: true,
transform(
{ stream, chunk }: { stream: DockerStreamName; chunk: Buffer | string },
_encoding: BufferEncoding,
callback: TransformCallback
) {
const state = getState(stream)
const text = state.pending + (typeof chunk === 'string' ? chunk : state.decoder.write(chunk))
const lines = text.split('\n')
// `pop()!`: `split()` gives at least one string
let pending = lines.pop()!
for (const line of lines) {
emitLine(this, stream, line)
}
while (pending.length > maxLineLength) {
emitLine(this, stream, pending.slice(0, maxLineLength))
pending = pending.slice(maxLineLength)
}
state.pending = pending
callback()
},
flush(callback) {
for (const [stream, state] of states) {
const last = state.pending + state.decoder.end()
if (last !== '') {
emitLine(this, stream, last)
}
}
states.clear()
callback()
},
})
}

View File

@@ -1,326 +0,0 @@
import assert from 'node:assert/strict'
import { Readable, type Transform } from 'node:stream'
import { pipeline } from 'node:stream/promises'
import test from 'node:test'
import { DOCKER_API_ERROR, type DockerError } from './errors.mjs'
import { LOGS_EXITED, LOGS_NGINX, LOGS_TTY } from './fixtures/logs.fixture.mjs'
import {
createLogLineParser,
createStdcopyDemuxer,
isMultiplexedStream,
MAX_SYSTEM_ERR_SIZE,
MULTIPLEXED_STREAM_CONTENT_TYPE,
RAW_STREAM_CONTENT_TYPE,
type DemuxedChunk,
type DockerLogLine,
} from './stdcopy.mjs'
const { describe, it } = test
const NGINX_BODY = Buffer.from(LOGS_NGINX.body, 'base64')
const EXITED_BODY = Buffer.from(LOGS_EXITED.body, 'base64')
const TTY_BODY = Buffer.from(LOGS_TTY.body, 'base64')
function frame(type: number, payload: string | Buffer) {
const data = Buffer.from(payload)
const header = Buffer.alloc(8)
header[0] = type
header.writeUInt32BE(data.length, 4)
return Buffer.concat([header, data])
}
const bytes = (buffer: Buffer) => Array.from(buffer, byte => Buffer.from([byte]))
// `T`: the objects emitted by the last transform (`DemuxedChunk` or `DockerLogLine` in these tests)
async function run<T = DemuxedChunk>(chunks: unknown[], ...transforms: Transform[]): Promise<T[]> {
const output: T[] = []
// @ts-expect-error @types/node has no overload of pipeline() for a variable number of transforms (rest argument)
await pipeline(Readable.from(chunks), ...transforms, async (source: AsyncIterable<T>) => {
for await (const object of source) {
output.push(object)
}
})
return output
}
// concatenates the emitted chunks of each stream
function byStream(objects: DemuxedChunk[]) {
const result: Record<string, Buffer> = {}
for (const { stream, chunk } of objects) {
result[stream] = Buffer.concat([result[stream] ?? Buffer.alloc(0), chunk])
}
return Object.fromEntries(Object.entries(result).map(([stream, buffer]) => [stream, buffer.toString()]))
}
// splits a multiplexed body into frames, the simple way
function parseFrames(body: Buffer) {
const frames: { type: number; payload: string }[] = []
for (let offset = 0; offset < body.length; ) {
const size = body.readUInt32BE(offset + 4)
frames.push({ type: body[offset], payload: body.subarray(offset + 8, offset + 8 + size).toString() })
offset += 8 + size
}
return frames
}
describe('createStdcopyDemuxer()', () => {
it('demuxes the real logs of a container, fed at once', async () => {
const objects = await run([EXITED_BODY], createStdcopyDemuxer())
assert.deepEqual(
objects.map(({ stream, chunk }) => ({ stream, text: chunk.toString() })),
[{ stream: 'stdout', text: '2026-09-24T16:54:38.377173968Z failing on purpose\n' }]
)
})
it('demuxes real logs fed byte-at-a-time', async () => {
const frames = parseFrames(NGINX_BODY)
const expected = {
stdout: frames
.filter(_ => _.type === 1)
.map(_ => _.payload)
.join(''),
stderr: frames
.filter(_ => _.type === 2)
.map(_ => _.payload)
.join(''),
}
assert.ok(expected.stdout.length > 0 && expected.stderr.length > 0)
const demuxer = createStdcopyDemuxer()
const objects = await run(bytes(NGINX_BODY), demuxer)
assert.deepEqual(byStream(objects), expected)
assert.equal(demuxer.truncated, false)
for (const { chunk } of objects) {
assert.ok(Buffer.isBuffer(chunk))
}
})
it('handles a frame boundary at any position', async () => {
const body = Buffer.concat([
frame(1, 'out 1\n'),
frame(2, 'err 1\n'),
frame(1, ''),
frame(1, 'out 2\n'),
frame(0, 'in\n'),
])
for (let i = 0; i <= body.length; ++i) {
for (let j = i; j <= body.length; j += 3) {
const chunks = [body.subarray(0, i), body.subarray(i, j), body.subarray(j)].filter(_ => _.length !== 0)
assert.deepEqual(byStream(await run(chunks, createStdcopyDemuxer())), {
stdout: 'out 1\nout 2\n',
stderr: 'err 1\n',
stdin: 'in\n',
})
}
}
})
it('keeps the order of interleaved stdout and stderr frames', async () => {
const body = Buffer.concat([frame(1, 'a'), frame(2, 'b'), frame(1, 'c'), frame(2, 'd')])
const objects = await run(bytes(body), createStdcopyDemuxer())
assert.deepEqual(
objects.map(({ stream, chunk }) => stream + ':' + chunk),
['stdout:a', 'stderr:b', 'stdout:c', 'stderr:d']
)
})
it('emits big payloads without waiting for the end of the frame', async () => {
const payload = Buffer.alloc(1024 * 1024, 'x')
const body = frame(1, payload)
const chunks = [body.subarray(0, 1000), body.subarray(1000, 500e3), body.subarray(500e3)]
const objects = await run(chunks, createStdcopyDemuxer())
assert.equal(objects.length, 3)
assert.equal(Buffer.concat(objects.map(_ => _.chunk)).length, payload.length)
})
describe('truncated trailing frame', () => {
const [firstFrameSize] = [8 + NGINX_BODY.readUInt32BE(4)]
it('in the payload: emits what was received and sets `truncated`', async () => {
const cut = firstFrameSize + 8 + 10
const demuxer = createStdcopyDemuxer()
const objects = await run(bytes(NGINX_BODY.subarray(0, cut)), demuxer)
assert.equal(demuxer.truncated, true)
const text = Buffer.concat(objects.map(_ => _.chunk)).toString()
assert.equal(text.length, firstFrameSize - 8 + 10)
assert.ok(text.startsWith(NGINX_BODY.subarray(8, firstFrameSize).toString()))
})
it('in the header: drops the partial header and sets `truncated`', async () => {
const demuxer = createStdcopyDemuxer()
const objects = await run([NGINX_BODY.subarray(0, firstFrameSize + 5)], demuxer)
assert.equal(demuxer.truncated, true)
assert.equal(
Buffer.concat(objects.map(_ => _.chunk)).toString(),
NGINX_BODY.subarray(8, firstFrameSize).toString()
)
})
})
it('fails on an unknown stream type', async () => {
await assert.rejects(run([Buffer.concat([frame(1, 'ok'), frame(7, 'ko')])], createStdcopyDemuxer()), {
code: DOCKER_API_ERROR,
message: /unknown stream type 7/,
})
})
it('fails with the message of a systemErr frame', async () => {
await assert.rejects(run(bytes(Buffer.concat([frame(1, 'ok'), frame(3, 'boom\n')])), createStdcopyDemuxer()), {
code: DOCKER_API_ERROR,
message: 'Docker stream error: boom',
})
})
it('keeps only the first MAX_SYSTEM_ERR_SIZE bytes of a systemErr payload', async () => {
const payload = 'x'.repeat(MAX_SYSTEM_ERR_SIZE) + 'DROPPED'.repeat(1e4)
const big = frame(3, payload)
// split in several chunks: the cap spans chunks
const chunks = []
for (let i = 0; i < big.length; i += 10e3) {
chunks.push(big.subarray(i, i + 10e3))
}
await assert.rejects(run(chunks, createStdcopyDemuxer()), (error: DockerError) => {
assert.equal(error.code, DOCKER_API_ERROR)
assert.equal(error.message, 'Docker stream error: ' + 'x'.repeat(MAX_SYSTEM_ERR_SIZE))
return true
})
})
it('passes raw (TTY) streams through as stdout', async () => {
const demuxer = createStdcopyDemuxer({ tty: true })
const objects = await run(bytes(TTY_BODY), demuxer)
assert.equal(objects.length, TTY_BODY.length)
assert.deepEqual(byStream(objects), { stdout: TTY_BODY.toString() })
assert.equal(demuxer.truncated, false)
})
})
describe('createLogLineParser()', () => {
it('parses real non-TTY logs, fed byte-at-a-time', async () => {
const entries = await run<DockerLogLine>(bytes(NGINX_BODY), createStdcopyDemuxer(), createLogLineParser())
const frames = parseFrames(NGINX_BODY)
// with timestamps=1, dockerd sends one line per frame
assert.equal(entries.length, frames.length)
entries.forEach((entry, i) => {
assert.equal(entry.stream, frames[i].type === 1 ? 'stdout' : 'stderr')
assert.equal(`${entry.timestamp} ${entry.message}\n`, frames[i].payload)
assert.match(entry.timestamp!, /^2026-09-24T16:5\d:\d\d\.\d+Z$/)
})
assert.deepEqual(entries[0], {
stream: 'stdout',
timestamp: '2026-09-24T16:54:37.796330221Z',
message: '/docker-entrypoint.sh: /docker-entrypoint.d/ is not empty, will attempt to perform configuration',
})
assert.ok(entries.some(_ => _.stream === 'stderr' && _.message.includes('[notice]')))
assert.ok(entries.some(_ => _.stream === 'stdout' && _.message.includes('"GET / HTTP/1.1" 200')))
})
it('parses real TTY logs: strips \\r, emits the last line without new line', async () => {
const entries = await run<DockerLogLine>(
bytes(TTY_BODY),
createStdcopyDemuxer({ tty: true }),
createLogLineParser()
)
assert.deepEqual(entries, [
{ stream: 'stdout', timestamp: '2026-09-24T16:56:05.110355030Z', message: 'tty line one' },
// written on stderr by the container, but a TTY merges both
{ stream: 'stdout', timestamp: '2026-09-24T16:56:05.110988999Z', message: 'tty line two' },
{ stream: 'stdout', timestamp: '2026-09-24T16:56:05.170603899Z', message: 'no newline at end' },
])
})
it('buffers partial lines per stream', async () => {
const body = Buffer.concat([
frame(1, 'hel'),
frame(2, 'err '),
frame(1, 'lo\nwor'),
frame(2, 'line\n'),
frame(1, 'ld'),
])
const entries = await run<DockerLogLine>([body], createStdcopyDemuxer(), createLogLineParser())
assert.deepEqual(entries, [
{ stream: 'stdout', timestamp: undefined, message: 'hello' },
{ stream: 'stderr', timestamp: undefined, message: 'err line' },
{ stream: 'stdout', timestamp: undefined, message: 'world' },
])
})
it('extracts the leading RFC3339Nano timestamp', async () => {
const lines = [
'2026-09-24T16:54:37.796330221Z message',
'2026-09-24T16:54:37.7Z trimmed fraction',
'2026-09-24T16:54:37Z no fraction',
'2026-09-24T18:54:37.123+02:00 offset',
'2026-09-24T16:54:37.796330221Z ',
'no timestamp',
'2026-09-24T16:54:37Z',
' 2026-09-24T16:54:37Z leading space',
]
const entries = await run<DockerLogLine>(
[{ stream: 'stdout', chunk: Buffer.from(lines.join('\n')) }],
createLogLineParser()
)
assert.deepEqual(
entries.map(({ timestamp, message }) => [timestamp, message]),
[
['2026-09-24T16:54:37.796330221Z', 'message'],
['2026-09-24T16:54:37.7Z', 'trimmed fraction'],
['2026-09-24T16:54:37Z', 'no fraction'],
['2026-09-24T18:54:37.123+02:00', 'offset'],
['2026-09-24T16:54:37.796330221Z', ''],
[undefined, 'no timestamp'],
[undefined, '2026-09-24T16:54:37Z'],
[undefined, ' 2026-09-24T16:54:37Z leading space'],
]
)
})
it('keeps empty lines', async () => {
const entries = await run<DockerLogLine>(
[{ stream: 'stdout', chunk: Buffer.from('a\n\n\nb\n') }],
createLogLineParser()
)
assert.deepEqual(
entries.map(_ => _.message),
['a', '', '', 'b']
)
})
it('decodes multi-byte UTF-8 characters split across chunks', async () => {
const text = 'héllo wörld 🐳\n'
const chunks = bytes(Buffer.from(text)).map(chunk => ({ stream: 'stdout', chunk }))
const entries = await run<DockerLogLine>(chunks, createLogLineParser())
assert.deepEqual(entries, [{ stream: 'stdout', timestamp: undefined, message: 'héllo wörld 🐳' }])
})
it('splits lines longer than maxLineLength', async () => {
const chunks = [
{ stream: 'stdout', chunk: Buffer.from('x'.repeat(25)) },
{ stream: 'stdout', chunk: 'yy\nz' },
]
const entries = await run<DockerLogLine>(chunks, createLogLineParser({ maxLineLength: 10 }))
assert.deepEqual(
entries.map(_ => _.message),
['x'.repeat(10), 'x'.repeat(10), 'xxxxxyy', 'z']
)
})
})
describe('isMultiplexedStream()', () => {
it('trusts the content type since API 1.42', () => {
assert.equal(isMultiplexedStream(LOGS_NGINX.contentType, undefined, '1.43'), true)
assert.equal(isMultiplexedStream(LOGS_TTY.contentType, undefined, '1.43'), false)
assert.equal(isMultiplexedStream(RAW_STREAM_CONTENT_TYPE, false, '1.42'), false)
assert.equal(isMultiplexedStream(`${MULTIPLEXED_STREAM_CONTENT_TYPE}; charset=utf-8`, true, '1.24'), true)
})
it('falls back to Config.Tty before API 1.42, or when the content type is unknown', () => {
assert.equal(isMultiplexedStream(RAW_STREAM_CONTENT_TYPE, false, '1.41'), true)
assert.equal(isMultiplexedStream(RAW_STREAM_CONTENT_TYPE, true, '1.41'), false)
assert.equal(isMultiplexedStream(undefined, true, '1.43'), false)
assert.equal(isMultiplexedStream('text/plain', false), true)
// defaults to multiplexed, like most containers
assert.equal(isMultiplexedStream(undefined, undefined), true)
})
})

View File

@@ -1,106 +0,0 @@
/**
* Cache of async results with a time to live.
*
* - concurrent `get()` of a missing key share the same pending promise
* - rejections are not cached
* - expired entries are only removed by `sweep()`, `delete()` or
* `deleteByPrefix()`: call `sweep()` periodically
* - a value fetched while its key is deleted is not cached (the caller still
* gets it)
*
* Not `lru-cache` (whose `fetch()` has the rest, with `ignoreFetchAbort`): its
* `keys()` does not list pending fetches, so `deleteByPrefix()` could not drop
* them, and a list fetched with an engine's previous credentials would be
* cached after the credentials change (checked with lru-cache 11.5).
*/
type Entry = { promise: Promise<unknown>; value: unknown; expiresAt: number | undefined }
export class AsyncTtlCache {
// key → { promise, value, expiresAt } (`expiresAt` undefined while pending)
#entries = new Map<string, Entry>()
#expiresIn: number
#now: () => number
/**
* @param opts.expiresIn ms
* @param opts.now for tests
*/
constructor({ expiresIn, now = Date.now }: { expiresIn: number; now?: () => number }) {
this.#expiresIn = expiresIn
this.#now = now
}
get size() {
return this.#entries.size
}
/**
* The type of a cached value is not checked: a key must always be used with
* functions returning the same type.
*
* @param opts.forceRefresh ignore a cached value (a pending one is still shared)
*/
get<T>(key: string, fn: () => Promise<T>, { forceRefresh = false }: { forceRefresh?: boolean } = {}): Promise<T> {
const current = this.#entries.get(key)
if (current !== undefined) {
if (current.expiresAt === undefined) {
return current.promise as Promise<T>
}
if (!forceRefresh && current.expiresAt > this.#now()) {
return current.promise as Promise<T>
}
}
const entry: { expiresAt: number | undefined; promise: Promise<T>; value: T | undefined } = {
expiresAt: undefined,
// replaced right below, `entry` must exist before the callbacks run
promise: undefined as unknown as Promise<T>,
value: undefined,
}
entry.promise = (async () => fn())().then(
value => {
if (this.#entries.get(key) === entry) {
entry.value = value
entry.expiresAt = this.#now() + this.#expiresIn
}
return value
},
error => {
if (this.#entries.get(key) === entry) {
this.#entries.delete(key)
}
throw error
}
)
this.#entries.set(key, entry)
return entry.promise
}
/**
* Value of a key if it is cached and not expired, without fetching it.
*/
peek(key: string): unknown {
const entry = this.#entries.get(key)
if (entry !== undefined && entry.expiresAt !== undefined && entry.expiresAt > this.#now()) {
return entry.value
}
}
deleteByPrefix(prefix: string) {
for (const key of Array.from(this.#entries.keys())) {
if (key.startsWith(prefix)) {
this.#entries.delete(key)
}
}
}
/** Remove expired entries. */
sweep() {
const now = this.#now()
for (const [key, entry] of Array.from(this.#entries)) {
if (entry.expiresAt !== undefined && entry.expiresAt <= now) {
this.#entries.delete(key)
}
}
}
}

View File

@@ -1,68 +0,0 @@
import assert from 'node:assert/strict'
import { describe, it } from 'node:test'
import { AsyncTtlCache } from './ttl-cache.mjs'
const createClock = () => {
const clock = () => clock.time
clock.time = 0
return clock
}
describe('AsyncTtlCache', () => {
it('shares pending fetches and caches values for expiresIn', async () => {
const now = createClock()
const cache = new AsyncTtlCache({ expiresIn: 10, now })
let calls = 0
const fn = async () => ++calls
assert.deepEqual(await Promise.all([cache.get('k', fn), cache.get('k', fn)]), [1, 1])
assert.equal(cache.peek('k'), 1)
now.time = 9
assert.equal(await cache.get('k', fn), 1)
now.time = 10
assert.equal(cache.peek('k'), undefined)
assert.equal(await cache.get('k', fn), 2)
})
it('does not cache rejections', async () => {
const cache = new AsyncTtlCache({ expiresIn: 10 })
await assert.rejects(
cache.get('k', async () => {
throw new Error('boom')
}),
/boom/
)
assert.equal(cache.size, 0)
assert.equal(await cache.get('k', async () => 'ok'), 'ok')
})
it('forceRefresh ignores a cached value', async () => {
const cache = new AsyncTtlCache({ expiresIn: 1e3 })
await cache.get('k', async () => 1)
assert.equal(await cache.get('k', async () => 2, { forceRefresh: true }), 2)
assert.equal(cache.peek('k'), 2)
})
it('deleteByPrefix() and sweep()', async () => {
const now = createClock()
const cache = new AsyncTtlCache({ expiresIn: 10, now })
await cache.get('a:1', async () => 1)
await cache.get('a:2', async () => 2)
await cache.get('b:1', async () => 3)
cache.deleteByPrefix('a:')
assert.equal(cache.size, 1)
now.time = 10
cache.sweep()
assert.equal(cache.size, 0)
})
it('a value fetched before a deletion is not cached', async () => {
const cache = new AsyncTtlCache({ expiresIn: 1e3 })
let resolve: ((value: string) => void) | undefined
const promise = cache.get('k', () => new Promise<string>(_resolve => (resolve = _resolve)))
cache.deleteByPrefix('k')
resolve!('stale')
assert.equal(await promise, 'stale')
assert.equal(cache.peek('k'), undefined)
})
})

View File

@@ -1,161 +0,0 @@
// Docker Engine API wire shapes read by this package. Internal: the XO DTOs are
// in `@vates/types`.
//
// Built from the types generated from Docker's OpenAPI specifications
// (`docker-api.gen.mts`, see `scripts/generate-api-types.mjs`): only the fields
// read by the transport and the normalizers are picked, their types come from
// the spec. The daemon sends more (hence the index signatures), and older API
// versions may omit some of them. Departures from the spec are commented.
//
// These types are what the daemon is expected to send, they are not checked,
// except for the stats: a hostile or buggy daemon controls every value (see
// `normalizeContainerStats()`), which are therefore `unknown`.
import type { definitions as Api } from './docker-api.gen.mjs'
/** the fields `K` of the spec definition `T`, the others being allowed but unknown */
type Wire<T, K extends keyof T> = Pick<T, K> & { [key: string]: unknown }
/**
* `T` with the fields `K` required: sent by every daemon, relied upon by the
* normalizers (an intersection, not `Omit`, which would lose the properties of a
* type with an index signature)
*/
type WithRequired<T, K extends keyof T> = T & { [P in K]-?: NonNullable<T[P]> }
/** `GET /version` */
export type DockerVersion = Wire<
Api['SystemVersion'],
'Version' | 'ApiVersion' | 'MinAPIVersion' | 'Platform' | 'Components'
>
/** `GET /info` */
export type DockerInfo = Wire<
Api['SystemInfo'],
| 'ID'
| 'Name'
| 'ServerVersion'
| 'OperatingSystem'
| 'OSType'
| 'KernelVersion'
| 'Architecture'
| 'NCPU'
| 'MemTotal'
| 'Driver'
| 'LoggingDriver'
| 'CgroupDriver'
| 'CgroupVersion'
| 'Containers'
| 'ContainersRunning'
| 'ContainersPaused'
| 'ContainersStopped'
| 'Images'
> & {
// not in the spec: `null` when empty
SecurityOptions?: Api['SystemInfo']['SecurityOptions'] | null
Warnings?: Api['SystemInfo']['Warnings'] | null
}
export type DockerContainerState = NonNullable<Api['ContainerState']['Status']>
/** entry of `Ports` in `GET /containers/json` */
export type DockerPort = Wire<Api['Port'], 'IP' | 'PrivatePort' | 'PublicPort' | 'Type'>
/**
* `NetworkSettings.Ports` of `GET /containers/{id}/json`, e.g.
* `{ "80/tcp": [{ "HostIp": "0.0.0.0", "HostPort": "8080" }], "443/tcp": null }`
* (not in the spec: `null` for an exposed port which is not published)
*/
export type DockerPortMap = Record<string, WithRequired<Api['PortBinding'], 'HostIp' | 'HostPort'>[] | null>
/** value of `NetworkSettings.Networks` */
export type DockerEndpointSettings = Wire<Api['EndpointSettings'], 'IPAddress' | 'GlobalIPv6Address'>
export type DockerMountPoint = WithRequired<
Wire<Api['MountPoint'], 'Type' | 'Name' | 'Source' | 'Destination' | 'RW'>,
'Type' | 'Source' | 'Destination' | 'RW'
>
/** entry of `GET /containers/json` */
export type DockerContainerSummary = WithRequired<
Wire<
Api['ContainerSummary'],
'Id' | 'Names' | 'Image' | 'ImageID' | 'Command' | 'Created' | 'Status' | 'Ports' | 'Labels' | 'Mounts'
>,
'Id' | 'Image' | 'ImageID' | 'Command' | 'Created'
> & {
// the spec says `string`
State: DockerContainerState
NetworkSettings?: { Networks?: Record<string, DockerEndpointSettings>; [key: string]: unknown }
Mounts?: DockerMountPoint[]
}
/** `Config` of `GET /containers/{id}/json` */
export type DockerContainerConfig = WithRequired<
Wire<Api['ContainerConfig'], 'Image' | 'Labels' | 'Tty' | 'Hostname' | 'WorkingDir' | 'User' | 'Env'>,
'Image'
>
export type DockerHealthCheckResult = Wire<Api['HealthcheckResult'], 'Start' | 'End' | 'ExitCode' | 'Output'>
/** `State` of `GET /containers/{id}/json` */
export type DockerContainerStateInfo = WithRequired<
Wire<Api['ContainerState'], 'Status' | 'ExitCode' | 'OOMKilled' | 'Error' | 'StartedAt' | 'FinishedAt'>,
'Status'
> & {
/** only for a container with a health check */
Health?: WithRequired<Wire<Api['Health'], 'Status' | 'FailingStreak'>, 'FailingStreak'> & {
Log?: DockerHealthCheckResult[]
}
}
/** `GET /containers/{id}/json` */
export type DockerInspect = WithRequired<
Wire<Api['ContainerInspectResponse'], 'Id' | 'Name' | 'Image' | 'Path' | 'Args' | 'Created' | 'RestartCount'>,
'Id' | 'Name' | 'Image' | 'Path'
> & {
Config?: DockerContainerConfig
HostConfig?: { RestartPolicy?: Api['RestartPolicy']; [key: string]: unknown }
NetworkSettings?: {
Ports?: DockerPortMap
Networks?: Record<string, DockerEndpointSettings>
[key: string]: unknown
}
State?: DockerContainerStateInfo
Mounts?: DockerMountPoint[]
}
// === Stats: never trusted
//
// The keys come from the spec (API 1.48, the first one documenting the stats),
// every value is `unknown`: the objects are typed as such so that they can be
// read with optional chaining, which gives `undefined` whatever they really
// are (the keys read are not properties of the prototypes of the primitives).
// No index signature: reading a key which is not in the spec does not compile.
type Untrusted<T> = { [K in keyof T]?: unknown }
/** `cpu_stats` and `precpu_stats` */
export type DockerCpuStats = Omit<Untrusted<Api['ContainerCPUStats']>, 'cpu_usage'> & {
cpu_usage?: Untrusted<Api['ContainerCPUUsage']>
}
/** `memory_stats` (`stats`: cgroup counters, e.g. `inactive_file`; `privateworkingset`: Windows) */
export type DockerMemoryStats = Untrusted<Api['ContainerMemoryStats']>
/** `blkio_stats` (`io_service_bytes_recursive`: `{ op, value }` entries) */
export type DockerBlkioStats = Untrusted<Api['ContainerBlkioStats']>
/** one object of `GET /containers/{id}/stats` */
export type DockerStatsSample = Omit<
Untrusted<Api['ContainerStatsResponse']>,
'cpu_stats' | 'precpu_stats' | 'memory_stats' | 'blkio_stats' | 'pids_stats'
> & {
cpu_stats?: DockerCpuStats
precpu_stats?: DockerCpuStats
memory_stats?: DockerMemoryStats
blkio_stats?: DockerBlkioStats
pids_stats?: Untrusted<Api['ContainerPidsStats']>
/** sent by the daemon (e.g. `windows`), missing from the spec */
os_type?: unknown
}

View File

@@ -1,16 +0,0 @@
{
"compilerOptions": {
"outDir": "./dist",
"rootDir": "./src",
"strict": true,
"module": "ESNext",
"moduleResolution": "bundler",
"target": "es2022",
"skipLibCheck": true,
"types": ["node"], // Only use types from Node.js and packages that are explicitly imported
"declaration": true // Generates `.d.ts` files for type safety
},
"include": ["./src/**/*"],
"exclude": ["./node_modules", "./dist"]
}

View File

@@ -22,7 +22,7 @@
},
"dependencies": {
"@vates/async-each": "^1.0.3",
"@xen-orchestra/backups": "^1.0.0",
"@xen-orchestra/backups": "^1.0.1",
"@xen-orchestra/log": "^1.0.0",
"app-conf": "^3.0.0",
"execa": "^5.0.0",

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

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