Compare commits

..

40 Commits

Author SHA1 Message Date
Olivier Lambert
43e5ed81f5 chore(xo-server-sdn-controller): link the changelog entry to its PR 2026-11-15 10:09:52 +01:00
Olivier Lambert
035a522391 fix(xo-server-sdn-controller): say which host failed a traffic rule with the XAPI plugin
With the XAPI plugin (`useDirectChannel = false`), a traffic rule is
applied by calling `sdncontroller.py` on every host of the network, through
`asyncEach` with `stopOnError: false`. When a host fails, `asyncEach`
rejects with an `AggregateError` that has no message, so the error the user
gets is empty: `{"error": ""}` from the REST API, an empty message in XO 6,
and no useful text in XO 5.

Each host's error is now rethrown with the host's name, keeping the
original as its `cause` (enumerable, so that the XAPI error's code and
params are still serialized, as in the JSON-RPC error's data), and the
`AggregateError` gets these messages, e.g.
`XENAPI_MISSING_PLUGIN(sdncontroller.py) on host-2`; the errors stay in
`errors`. VIF and network rules, added or deleted, share this path.

Test: a rule with the plugin missing on one of two hosts (message, cause,
serialized details), on three hosts with two failing, and a successful one
(the first three fail without the fix).
2026-11-15 10:09:52 +01:00
Joris K
0857694312 fix(web-core): limit modal max width (#10800) 2026-11-13 18:08:46 +01:00
Sylvère
641b13e593 feat(web-core/lite): update UiButtonIcon to v10 (#10799)
feat(web-core/lite): update UiButtonIcon to use counter instead of notification dot
2026-11-13 17:00:57 +01:00
Joris K
9866e0c47c feat(xo6/lite/web-core): replace the Search button with search-as-you-type, like in the treeview (#10797) 2026-11-13 16:34:22 +01:00
ayoub-el-kajji-v
6166c9321f fix(replication): skip orphan snapshots check when VDI is destroyed (#10732)
* fix(replication): skip orphan snapshots check when their VDI is destroyed

* add changelog

* fix after killian's suggestion

* fix after mathieu review

---------

Co-authored-by: Mathieu Piton <mathieu.piton@vates.tech>
2026-11-13 12:58:39 +01:00
Marie Garde
8b4fd15a86 fix(xo6): use new delete modale for backup jobs (#10791) 2026-11-13 11:30:40 +01:00
Marie Garde
3eb48bdbdb feat(xo6): Add filter and actions on backup job (#10772)
* feat(xo6): Add filter and actions on backup job

* add delete

* add duplicate

* add manual run

* add disable enable

* add tests

* refacto for merge

* rafcto for merge

* rebase ok

* refacto post rebase
2026-11-13 10:50:31 +01:00
Joris K
83b1ce297f feat(xo6/vm): select multiple VMs to change their power state, snapshot or delete them (#10780) 2026-11-13 09:48:09 +01:00
amouillard-vates
30d30a66c7 Revert "feat(xo6/vm): add VM tags edition (#10777)" (#10787)
This reverts commit 79219f2e1c.
2026-11-12 19:32:35 +01:00
amouillard-vates
79219f2e1c feat(xo6/vm): add VM tags edition (#10777) 2026-11-12 15:44:42 +01:00
Joris K
67ed8f7eb3 fix(web-core): keep head bar actions next to the title on small screens (#10774) 2026-11-12 14:17:54 +01:00
Killian
2783e60933 feat(fs): lock VM backup folders on S3 and Azure (#10549)
feat(fs): lock VM backup folders on S3 and Azure (#10549)

On S3 and Azure, handler.lock() was a no-op, so two backup jobs, or a job and a
deletion, could write and merge the same VM's backups at the same time. Local, NFS
and SMB repositories have always locked. Both now lock a `<path>.lock` object, with
the contract of LocalHandler#_lock(): ELOCKED at once on contention, and a lost lock
is warned about and taken back.

S3 holds the lock with plain PutObject writes, which every S3-compatible provider
supports, instead of conditional writes that providers handle unevenly. The holder
rewrites the object every 30 seconds, and a lock is stale after 3 minutes without a
rewrite. Its age is read on the provider's clock alone: Last-Modified of the lock
against the Date of the HEAD response. XO's clock takes no part, so a skew of more
than 2.5 minutes no longer takes over a live lock. A provider which omits either
header never lets a lock be taken over. The lock is not atomic: two jobs which find
it free at the same time can both take it.

Azure uses a blob lease, which Azure itself expires: a 60 second lease, renewed every
15 seconds, so there is no clock to compare. A renewal writes nothing, so accounts
with versioning or soft delete do not keep a copy per renewal. Each renewal gives up
after 20 seconds, so a hung request leaves time for the next one before the lease
expires. Releasing deletes the blob only while the lease is still ours
2026-11-12 10:03:18 +01:00
Killian
7679bb0d44 feat(backups): purge the backup journal of a repository (#10703)
feat(backups): purge the backup journal of a repository (#10703)

The journal of a repository (`xo-backup-log/`) is append-only: nothing ever removes its entries,
so it grows with every backup, deletion and merge for as long as the repository lives.

`purgeBackupJournal(handler, before)` removes the day directories before the day of `before`,
whole days at a time, which is what the one-directory-per-day layout was meant for. A day which
cannot be removed (immutable files, a bucket policy refusing deletes) is skipped, so that it does
not keep the later days from being removed, and the next purge tries it again; a purge warns once,
with its first failure and the number of failures. `RemoteAdapter#purgeBackupJournal()` exposes
it, and so does the proxy, as `backup.purgeVmBackupsJournal({ remote, before })`: `before` is
computed by XO, so the horizon is XO's whatever the clock of the proxy.

xo-server purges the journal of every enabled remote when it starts, then once a day, one remote
after another and in the background, of the days older than `backups.journalRetention` (30 days by
default). Whatever that setting says, it keeps what a replay of the listing cache can still read:
the `fullListingInterval` of the remote, plus the clock skew tolerance its cursor is bootstrapped
with. A remote which does not answer within 10 minutes is left to its purge and the next one gets
its turn; a proxy too old to purge fails its remote with a warning.

XO-3039
2026-11-12 09:45:21 +01:00
Joris K
b9f5b0724e feat(xo6/web-core): scroll arrows and keyboard navigation in tab lists (#10759) 2026-11-12 09:37:56 +01:00
Sylvère
7d5c818efb fix(xo6): fix MenuItem display for Pool > Add Network and VM > Add VDI (#10766) 2026-11-12 09:33:19 +01:00
Marie Garde
152365f984 feat(xo6): Add backup log detail page (#10718)
* feat(xo6): Add backup lob detail page

* refacto structure

* refacto for PR

* add tests

* refacto for merge
2026-11-12 09:26:44 +01:00
Florent BEAUCHAMP
83c3e344ba feat(rest-api): expose the endpoint for file level restore (#9941) 2026-11-10 16:59:59 +01:00
Florent BEAUCHAMP
56ffcdba29 feat(rest-api): implement V2V routes (#10597)
implement Rest Api route to do an inventory of a remote esxi/vsphere + the action to import VMs into XCP-ng
2026-11-10 16:59:54 +01:00
Joris K
1d3e1fce39 feat(xo6/web-core): full page menus on mobile and responsive side panel actions (#10745)
* fix(web-core): place menus and tooltips right next to their trigger

- Wrap placement.js in `placeOverlay` which positions the overlay at the top-left corner before measuring, so a temporary scrollbar no longer shifts menus, and compensates when `body` does not cover the whole window
- Submenus open on the same side as their parent menu, unless there is not enough room

* fix(web-core): don't show the side panel for a moment when it is mounted

The panel offset was set through a `v-bind` CSS variable, which Vue only applies once the element is in the page:
the panel was first displayed, then slid out. It is now an inline style, set as soon as the element is created.

* feat(xo6/web-core): open menus in full page on mobile

- New `VtsMobileMenu`: full page menu sliding in like the side panel, with a back button and submenus opening in place
- New `VtsResponsiveMenu`: a `MenuList` on desktop, a `VtsMobileMenu` on mobile
- `VtsActionsMenu` relies on it and gets a `label` prop, it is used by tables, treeview, side panels and the VM and host headers
- Account menu, table bulk actions, "New"/"Add" dropdowns and "Copy all" use `VtsResponsiveMenu`
- On mobile, "Change state" and "Manage in XO-5" move into the "more actions" menu of the VM and host headers and of the VM side panel
- On mobile, an action of a "more actions" menu closes the side panel or the treeview
- New `VmHeaderActions` shared by the VM header and side panel
- Rename "Manage VM lifecycle in XO-5" into "Manage in XO-5"

* feat(xo6/web-core): move side panel actions into "more actions" when space runs out

- `VtsPanel` measures whether its actions fit on one line and moves them one by one, starting from the last one, into its "more actions" menu, created when needed
- New `VtsActionButton`: a button rendered as a menu item when it is inside a menu
- Panel action buttons (connect/disconnect, edit, delete, revert, change state…) use it, and pool, SR and backup repository side panels use the `actions` and `more-actions` slots of `VtsPanel`
- In the VM side panel, "Change state" moves into the "more actions" menu as a submenu

* docs(changelog): add full page menus and side panel actions entries

* refactor(web-core): rename VtsDeleteButton `tooltip` prop into `hint`

Like `VtsActionButton`, it is shown only when the button is disabled.

* fix(web-core): measure again the panel actions when they change

When an action is added, removed or replaced (connect/disconnect), the widths stored to move actions back from the "more actions" menu are no longer valid, so the measure starts over.

* fix(lite): don't show two "more actions" menus in the network side panel

"Copy info JSON" goes into the `more-actions` slot, so the delete button moves into the same menu when the panel is too narrow.

* feat(lite): add stories for VtsMobileMenu, VtsResponsiveMenu and VtsActionButton

The VtsPanel story uses VtsActionButton and MenuItem to show how actions move into the "more actions" menu.

* test(xo6): cover VmHeaderActions and AppHeaderMenu

* feat(web-core): show side panel actions as buttons when there is room

Actions move one by one into the "More actions" menu when they don't fit, and come back out when there is room again.

* feat(web-core): factorize the "Change state" menu and use full page menus on mobile

Add VtsChangeStateMenu and VtsChangeStateMenuItem, rename VmHeaderActions into VmMainActions.

* fix(web-core): don't cut off header actions next to a long name

* feat(xo6,lite): compact PIFs card on narrow side panels

Hosts are links with the master star, and the status is an icon with a tooltip when there is not enough room.

* fix(web-core): keep link icons on the first line and wrap traffic rule cards

* docs(changelog): merge the PR entries
2026-11-10 16:07:58 +01:00
Mathieu
4cd316d23b fix(rest-api): avoid attaching rbac role to admin user (#10694)
introduced by a4b17d5abb
2026-11-10 15:51:37 +01:00
OlivierFL
6e7a6659ab feat(web-core): introduce file uploader components (#10753) 2026-11-10 15:49:03 +01:00
Joris K
2e67209418 feat(xo6): group XO 5 and third party apps links in a mobile header menu (#10744)
* feat(xo6): group XO 5 and third party apps links in a mobile header menu

* docs(changelog): add mobile header menu entry
2026-11-10 10:46:03 +01:00
Enée DI IORIO
03e93498fd feat(web-core): upgrade UiDropdownButton component to v9 (#9850) 2026-11-10 10:05:19 +01:00
Mathieu
50166fe3a4 fix(xo-server): validate authentication token IDs (#10748) 2026-11-10 09:29:37 +01:00
Florent BEAUCHAMP
724402733b feat(rest-api): create backup job routes (#10595)
XO-2189
XO-3282
2026-11-09 17:51:05 +01:00
Thomas Moraine
abbe24631d docs(navbar): make link to vates vms external (#10231)
For legal reasons, the Vates VMS documentation
has to be treated as an external site, relative to
the XCP-ng and Xen Orchestra documentations.

As a result, the link to the Vates VMS doc in the
header of the XO doc has been converted to
an external link.

Clicking the link now opensa new tab instead of
loading the page in the same tab.

Signed-off-by: Thomas Moraine <thomas.moraine@vates.tech>
2026-11-09 16:29:58 +01:00
Elise-F
8e81250ca3 fix(xo6,lite): translate VM and host state tooltips in tree view (#10643) 2026-11-09 16:25:00 +01:00
Joris K
c8c11ae63c feat(xo6/web-core): show a loader in VM and host icons during power state changes (#10720) 2026-11-09 10:49:12 +01:00
Elise-F
8df236a512 feat(xo6): displaying traffic rules by priority within network (#10688)
* feat(xo6): displaying traffic rules by priority within network

* update changelog

* clean code
2026-11-09 09:51:51 +01:00
Joris K
8cc3384850 feat(xo6/network): add dedicated network page (#10704) 2026-11-09 09:39:47 +01:00
Olivier Lambert
e4cc8df323 feat(xo6): compact treeview (#10727) 2026-11-06 19:45:39 +01:00
Joris K
43a7e3d3ac feat(web-core): adapt card rows to their content in side panels (#10733)
* feat(web-core): adapt card rows to their content in side panels

- Key and value stay on one line when they fit, the value moves below the key otherwise
- New `values` prop on `VtsCardRowKeyValue`: one copy button per value, a "Copy all"
  action and an optional "see more" limit for fields with multiple values
- New `VtsCardRowList` component holding the 0.8rem spacing between rows
- `UiInfo` text is small inside side panels (icon stays medium), medium elsewhere
- Side panel links use the small size

* docs: add changelog entries
2026-11-06 18:38:09 +01:00
Joris K
2e586f0369 feat(web-core): make the side panel resizable (#10725)
* feat(web-core): make the side panel resizable

- Resize the side panel like the treeview, with a shared `VtsResizeHandle`
  component and `useResizableWidth` composable
- Default width of the treeview and the side panel is 1/5 of the screen
  (280px minimum), max width is 1/3 of the screen (400px minimum)
- Double-click (or Enter) on the handle restores the default width
- The handle is keyboard accessible (arrows, Home, End) and exposed as an
  ARIA separator

* docs: add changelog entries
2026-11-06 18:27:57 +01:00
Bastien Nollet
93dc079f71 docs: remove british spellings (#10724) 2026-11-06 16:58:11 +01:00
Joris K
9c6a59bb89 feat(web-core): show UiButton loader on the right of the label (#10723) 2026-11-06 12:57:52 +01:00
Thomas Moraine
12aa9576b9 docs: use US spelling for licensing (#10666) 2026-11-06 10:21:31 +01:00
Joris K
85541ce5d7 fix(xo6): Fix some issue in the pool tab (#10714) 2026-11-05 15:42:09 +01:00
Joris K
56a33c1639 fix(xo6): change padding tasks (#10713) 2026-11-05 14:49:03 +01:00
Olivier Lambert
7f6ea616ca feat(docs): add optional email to page feedback (#10697) 2026-11-04 16:58:50 +01:00
585 changed files with 18595 additions and 4635 deletions

View File

@@ -772,6 +772,7 @@ export type RawTrafficRule = {
ipRange: string
direction: TrafficRuleDirection
port?: string
priority?: number
}
type BaseTrafficRule = RawTrafficRule & {

View File

@@ -5,5 +5,7 @@ export * from './xo-app.mjs'
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/complex-matcher.mjs'
export * from './lib/rest-api.mjs'
export * from './lib/xen-orchestra-vmware-explorer.mjs'

View File

@@ -0,0 +1,219 @@
import type { Branded } from '../common.mjs'
import type { XoNetwork, XoSr, XoVmTemplate } from '../xo.mjs'
// Stateless API: requests needing the source carry the connection in a POST body (never in URLs or access logs) and
// xo-server stores nothing it reads from the source.
export const V2V_PLATFORM = {
VMWARE: 'vmware',
} as const
export type V2V_PLATFORM = (typeof V2V_PLATFORM)[keyof typeof V2V_PLATFORM]
// 422 rather than 401 for invalid source credentials: a 401 would open the browser Basic authentication prompt
export const V2V_ERROR_CODE = {
INVALID_CREDENTIALS: 'V2V_INVALID_CREDENTIALS',
} as const
export type V2V_ERROR_CODE = (typeof V2V_ERROR_CODE)[keyof typeof V2V_ERROR_CODE]
// Clones, restores and replicas inherit `other_config`: the imported VM records its own UUID to be told apart from
// them, and the source identity because a moref is only unique within one vCenter. The source identity is the
// inventory `instanceUuid`, or `<lowercased host>:<port>` for a standalone ESXi which has none.
export const V2V_VM_OTHER_CONFIG = {
SOURCE_VM_ID: 'sourceVmId',
SOURCE_SNAPSHOT_ID: 'sourceSnapshotId',
IMPORTED_VM_UUID: 'xo:v2v:importedVmUuid',
SOURCE_ID: 'xo:v2v:sourceId',
SOURCE_VM_INSTANCE_UUID: 'xo:v2v:sourceVmInstanceUuid',
} as const
export type V2V_VM_OTHER_CONFIG = (typeof V2V_VM_OTHER_CONFIG)[keyof typeof V2V_VM_OTHER_CONFIG]
export type XoV2vVmOtherConfig = Partial<Record<V2V_VM_OTHER_CONFIG, string>>
// The disk of the source chain an imported VDI last received, one of the `chainPaths` of its source disk: the CID
// cannot tell a fresh snapshot delta from its parent, the path can
export const V2V_VDI_OTHER_CONFIG = {
DISK_PATH: 'esxi_diskPath',
} as const
export type V2V_VDI_OTHER_CONFIG = (typeof V2V_VDI_OTHER_CONFIG)[keyof typeof V2V_VDI_OTHER_CONFIG]
export const V2V_START_BLOCKED_REASON = 'Esxi migration in progress...'
export const V2V_PARTIAL_IMPORT_TAG = 'xo:no-bak=V2V partial import'
export const V2V_SNAPSHOT_NAME = {
AFTER_PARTIAL_IMPORT: 'after partial import from V2V',
AFTER_COMPLETE_IMPORT: 'after complete import from V2V',
COMPLETE_IMPORT: 'complete import from V2V',
} as const
export type V2V_SNAPSHOT_NAME = (typeof V2V_SNAPSHOT_NAME)[keyof typeof V2V_SNAPSHOT_NAME]
// Set on the task of a start so the front can tell which source VMs are being imported
export const V2V_TASK_PROPERTY = {
SOURCE_VM_IDS: 'sourceVmIds',
} as const
export type XoV2vConnection = {
host: string
port: number
username: string
password: string
skipSslCheck: boolean
}
export type XoV2vStatus = {
vectura: { status: 'success' } | { status: 'error'; error: string }
}
export type XoV2vInventoryPayload = {
platform: V2V_PLATFORM
connection: XoV2vConnection
}
export type XoV2vDatacenter = {
id: Branded<'v2v-datacenter'>
name: string
}
export type XoV2vCluster = {
id: Branded<'v2v-cluster'>
name: string
datacenterId: XoV2vDatacenter['id']
}
export type XoV2vHost = {
id: Branded<'v2v-host'>
name: string
clusterId?: XoV2vCluster['id']
datacenterId: XoV2vDatacenter['id']
}
// Sizes are in bytes, as in the rest of XO, not in the KB/MB VMware returns
export type XoV2vDatastore = {
id: Branded<'v2v-datastore'>
name: string
type: string
capacity: number
free: number
hostIds: XoV2vHost['id'][]
}
export type XoV2vPortGroup = {
id: Branded<'v2v-port-group'>
name: string
vlan?: number
}
export const V2V_DISK_MODE = {
PERSISTENT: 'persistent',
NON_PERSISTENT: 'nonpersistent',
INDEPENDENT_PERSISTENT: 'independent_persistent',
INDEPENDENT_NON_PERSISTENT: 'independent_nonpersistent',
UNDOABLE: 'undoable',
APPEND: 'append',
} as const
export type V2V_DISK_MODE = (typeof V2V_DISK_MODE)[keyof typeof V2V_DISK_MODE]
// `key` is the vmx device node (`scsi0:0`, `ethernet0`…), the identifier the import matches the start maps against
export type XoV2vDisk = {
key: Branded<'v2v-disk'>
label: string
datastoreId: XoV2vDatastore['id']
capacity: number
mode: V2V_DISK_MODE
isRdm: boolean
isEncrypted: boolean
// `dir/disk.vmdk` in its datastore (no `[datastore]` prefix) of the base disk, then of each snapshot delta down to
// the active disk: the chain the import walks for this vmx node
chainPaths: string[]
}
// No port group for opaque (NSX) or missing backings
export type XoV2vNic = {
key: Branded<'v2v-nic'>
label: string
portGroupId?: XoV2vPortGroup['id']
macAddress: string
}
export const V2V_VM_POWER_STATE = {
POWERED_ON: 'poweredOn',
POWERED_OFF: 'poweredOff',
SUSPENDED: 'suspended',
} as const
export type V2V_VM_POWER_STATE = (typeof V2V_VM_POWER_STATE)[keyof typeof V2V_VM_POWER_STATE]
export const V2V_FIRMWARE = {
BIOS: 'bios',
UEFI: 'uefi',
} as const
export type V2V_FIRMWARE = (typeof V2V_FIRMWARE)[keyof typeof V2V_FIRMWARE]
export type XoV2vVm = {
id: Branded<'v2v-vm'>
instanceUuid: string
name: string
description: string
powerState: V2V_VM_POWER_STATE
hostId: XoV2vHost['id']
nCpus: number
memory: number
firmware: V2V_FIRMWARE
secureBoot: boolean
datastoreIds: XoV2vDatastore['id'][]
snapshotCount: number
// Compared with `other_config.sourceSnapshotId` of a partial import: a delta is only possible while they match
currentSnapshotId?: string
disks: XoV2vDisk[]
nics: XoV2vNic[]
}
export type XoV2vInventory = {
product: string
version: string
// Absent on a standalone ESXi, identified by its connection address instead
instanceUuid?: string
datacenters: XoV2vDatacenter[]
clusters: XoV2vCluster[]
hosts: XoV2vHost[]
datastores: XoV2vDatastore[]
portGroups: XoV2vPortGroup[]
vms: XoV2vVm[]
}
export type XoV2vStartOptions = {
stopSource: boolean
startVm: boolean
cleanup: boolean
}
// A resumed import sends no disk or NIC map: the back end reads its mapping from the existing XCP-ng VM
export type XoV2vStartPayloadVm = Partial<XoV2vStartOptions> & {
id: XoV2vVm['id']
disks?: Record<XoV2vDisk['key'], XoSr['id']>
nics?: Record<XoV2vNic['key'], XoNetwork['id']>
template?: XoVmTemplate['id']
tags: string[]
keepMac: boolean
}
// Body of `POST /pools/{id}/actions/import_vms_from_vmware`: the pool is in the path. Checked against the body of the
// route when the REST API is built, which refuses any extra key
export type XoV2vStartPayload = {
connection: XoV2vConnection
defaults: XoV2vStartOptions & {
sr: XoSr['id']
network: XoNetwork['id']
template: XoVmTemplate['id']
}
vms: XoV2vStartPayloadVm[]
stopOnError: boolean
concurrency: number
}

View File

@@ -0,0 +1,103 @@
// shape of `Esxi#getInventory()` in `@xen-orchestra/vmware-explorer`
// the objects reference each other through their VMware managed object references (moref)
export type VmwareDatacenter = {
id: string
name: string
}
export type VmwareCluster = {
id: string
name: string
datacenter?: string
}
export type VmwareHost = {
id: string
name: string
/** a cluster, or the compute resource of a standalone host */
parent?: string
datacenter?: string
}
export type VmwareDatastore = {
id: string
name?: string
type?: string
capacity?: number
freeSpace?: number
/** the hosts which mount the datastore and can reach it */
hosts: string[]
}
export type VmwareVlan = number | { start: number; end: number }[]
export type VmwareStandardNetwork = {
id: string
name: string
distributed: false
}
export type VmwareDistributedPortgroup = {
id: string
name: string
distributed: true
vlan?: VmwareVlan
}
export type VmwareNetwork = VmwareStandardNetwork | VmwareDistributedPortgroup
export type VmwareVmDisk = {
/** node of the disk, as the vmx names it, e.g. `scsi0:0` */
key: string
label: string
capacity: number
datastore?: string
diskMode?: string
rdm: boolean
encrypted: boolean
/** `dir/disk.vmdk` in its datastore of the base disk, then of each snapshot delta down to the active disk */
chainPaths: string[]
}
export type VmwareVmNic = {
/** device key of the card */
key: string
label: string
macAddress?: string
addressType?: string
network?: string
}
export type VmwareVm = {
id: string
name?: string
annotation?: string
instanceUuid?: string
firmware?: string
secureBoot: boolean
isTemplate: boolean
cpus?: number
memory?: number
powerState?: 'poweredOff' | 'poweredOn' | 'suspended'
host?: string
datastores: string[]
currentSnapshot?: string
snapshotCount: number
disks: VmwareVmDisk[]
nics: VmwareVmNic[]
}
export type VmwareInventory = {
/** e.g. `VMware vCenter Server`, `VMware ESXi` */
product?: string
version?: string
/** only set by a vCenter */
instanceUuid?: string
datacenters: VmwareDatacenter[]
clusters: VmwareCluster[]
hosts: VmwareHost[]
datastores: VmwareDatastore[]
networks: VmwareNetwork[]
vms: VmwareVm[]
}

View File

@@ -3,12 +3,16 @@ import type {
AnyXoJob,
AnyXoLog,
NonXapiXoRecord,
XoBackupDiskPartition,
XapiXoRecord,
XoAuthenticationToken,
XoBackupRepository,
XoConfigBackupArchive,
XoGroup,
XoHost,
XoMetadataBackupJob,
XoMirrorBackupJob,
XoNetwork,
XoPlugin,
XoPool,
XoPoolBackupArchive,
@@ -21,9 +25,13 @@ import type {
XoVif,
XoVm,
XoVmBackupArchive,
XoVmBackupJob,
XoVmTemplate,
} from './xo.mjs'
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 { RPU_RECOVERY_STEP_NAME } from './common.mjs'
import {
Xapi,
@@ -202,6 +210,15 @@ type XoStoreRangeOptions = {
reverse?: boolean
}
// `@xen-orchestra/vmware-explorer` is not typed
export type EsxiConnectionParams = {
/** `host` or `host:port` */
host: string
user: string
password: string
sslVerify: boolean
}
export type XoApp = EventEmitter & {
hooks: EventEmitter
_redis: {
@@ -282,6 +299,8 @@ export type XoApp = EventEmitter & {
backupGuard(objectId: XapiXoRecord['id'], opts?: { bypassBackupCheck?: boolean; operation: string }): Promise<void>
/* Throw if no authorization */
checkFeatureAuthorization(featureCode: FeatureCode): Promise<void>
/* whether this machine can run the tools of an import from VMware */
checkEsxiDependencies(): Promise<XoV2vStatus>
/* validate, apply and persist the configuration of a plugin */
configurePlugin(id: string, configuration: unknown, mergeWithExisting?: boolean): Promise<void>
/* connect a server (XCP-ng/XenServer) */
@@ -309,6 +328,17 @@ export type XoApp = EventEmitter & {
set(key: string, value: unknown): void
unset(key: string): void
}
createBackupNgJob<T extends XoVmBackupJob | XoMirrorBackupJob>(
type: T['type'],
props: Omit<T, 'id' | 'type'>,
/** keyed by temporary IDs, which can be used as keys in `props.settings` */
schedules?: Record<string, Pick<XoSchedule, 'cron' | 'enabled' | 'name' | 'timezone'>>
): Promise<T>
createMetadataBackupJob(
props: Omit<XoMetadataBackupJob, 'id' | 'type'>,
/** keyed by temporary IDs, which can be used as keys in `props.settings` */
schedules: Record<string, Pick<XoSchedule, 'cron' | 'enabled' | 'name' | 'timezone'>>
): Promise<XoMetadataBackupJob>
createAuthenticationToken(opts: {
client?: {
id?: string
@@ -324,6 +354,14 @@ export type XoApp = EventEmitter & {
proxy?: XoProxy['id']
url: string
}): Promise<XoBackupRepository>
createSchedule(params: {
cron: XoSchedule['cron']
enabled: XoSchedule['enabled']
jobId: XoSchedule['jobId']
name?: XoSchedule['name']
timezone?: XoSchedule['timezone']
userId?: XoUser['id']
}): Promise<XoSchedule>
createUser(params: {
firstname?: string
lastname?: string
@@ -340,6 +378,7 @@ export type XoApp = EventEmitter & {
deleteAclV2Privilege(privilegeId: XoAclBasePrivilege['id'], options?: { force?: boolean }): Promise<boolean>
deleteAclV2Role(roleId: XoAclRole['id'], options?: { force?: boolean }): Promise<boolean>
deleteGroup(id: XoGroup['id']): Promise<void>
deleteSchedule(id: XoSchedule['id']): Promise<void>
deleteUser(id: XoUser['id']): Promise<void>
detachHostFromPool(hostId: XoHost['id']): Promise<void>
createGroup(params: { name: string; provider?: string; providerGroup?: string }): Promise<XoGroup>
@@ -378,6 +417,8 @@ export type XoApp = EventEmitter & {
getRemote(id: XoBackupRepository['id']): Promise<XoBackupRepository>
getAllRemotes(): Promise<XoBackupRepository[]>
removeRemote(id: XoBackupRepository['id']): Promise<void>
/** Also deletes the schedules of the job */
removeJob(id: AnyXoJob['id']): Promise<void>
getAllRemotesInfo(): Promise<
Record<
XoBackupRepository['id'],
@@ -441,6 +482,7 @@ export type XoApp = EventEmitter & {
}>
getUser: (id: XoUser['id'], opts?: { obfuscatePassword?: boolean }) => Promise<XoUser>
getUserIdentityFields(): string[]
getEsxiInventory(params: EsxiConnectionParams): Promise<VmwareInventory>
getXapi(maybeId: XapiXoRecord['id'] | XapiXoRecord): Xapi
getXapiHostStats: (hostId: XoHost['id'], granularity?: XapiStatsGranularity) => Promise<XapiHostStats>
getXapiObject: <T extends XapiXoRecord>(
@@ -456,6 +498,22 @@ export type XoApp = EventEmitter & {
getXoEventEmitterByType(type: string): EventEmitter
hasFeatureAuthorization(featureCode: string): Promise<boolean>
hasObject<T extends XapiXoRecord>(id: T['id'], type: T['type']): boolean
listBackupNgDiskPartitions(remoteId: XoBackupRepository['id'], diskId: string): Promise<XoBackupDiskPartition[]>
listBackupNgPartitionFiles(
remoteId: XoBackupRepository['id'],
diskId: string,
partitionId: string | undefined,
path: string
// keys ending in "/" are directories; files carry size (bytes) and mtime (epoch ms).
// Values may be empty ({}) for directories or when served by an older proxy.
): Promise<Record<string, { size?: number; mtime?: number }>>
fetchBackupNgPartitionFiles(
remoteId: XoBackupRepository['id'],
diskId: string,
partitionId: string | undefined,
paths: string[],
format: string
): Promise<Readable>
loadPlugin(id: XoPlugin['id']): Promise<void>
listMetadataBackups(backupRepositoryIds: XoBackupRepository['id'][]): Promise<{
xo: Record<XoBackupRepository['id'], XoConfigBackupArchive[]>
@@ -466,6 +524,21 @@ export type XoApp = EventEmitter & {
backupRepositoryIds: XoBackupRepository['id'][],
opts?: { _forceRefresh?: boolean; vmId?: XoVm['id'] }
): Promise<Record<XoBackupRepository['id'], Record<XoVm['id'], XoVmBackupArchive[]> | null>>
/** imports one VM from VMware, resuming a previous partial import when possible, returns the UUID of the XCP-ng VM */
migrationfromEsxi(
params: EsxiConnectionParams & {
sr: XoSr['id']
network: XoNetwork['id']
/** overrides `sr`, by disk node (e.g. `scsi0:0`) */
disks?: Record<string, XoSr['id']>
/** overrides `network`, by NIC device key (e.g. `4000`) */
nics?: Record<string, XoNetwork['id']>
template: XoVmTemplate['id']
stopSource: boolean
/** VMware moref of the VM */
vm: string
}
): Promise<XoVm['uuid']>
/**
* Serve one disk of a backup archive as an iSCSI LUN and attach it to `host`
* as an SR, read-only unless `cacheSrId` is set. Undone by `unmountBackupArchiveDisk`.
@@ -543,6 +616,19 @@ export type XoApp = EventEmitter & {
): Promise<{ vmUuid: string; success: boolean; merge?: boolean; size?: number; error?: string }[]>
/** Remove a server from the DB (XCP-ng/XenServer) */
unregisterXenServer(id: XoServer['id']): Promise<void>
/**
* Shallow merge of the properties into the existing job, a `null` value removes the property.
*/
updateJob(job: { id: AnyXoJob['id']; [key: string]: unknown }, merge?: boolean): Promise<void>
updateSchedule(params: {
id: XoSchedule['id']
cron?: XoSchedule['cron']
enabled?: XoSchedule['enabled']
jobId?: XoSchedule['jobId']
name?: XoSchedule['name']
timezone?: XoSchedule['timezone']
userId?: XoUser['id']
}): Promise<void>
updateUser(
id: XoUser['id'],
updates: {

View File

@@ -180,6 +180,15 @@ export type XoBackupLog = BaseXoLog & {
export type XoRestoreLog = BaseXoLog & {
message: 'restore'
}
export type XoBackupDiskPartition = {
id: Branded<'xo-backup-disk-partition'>
name?: string
size: number
start: number
/** number for MBR, string for GPT partition */
type: string | number
}
export type XoVmBackupArchive = {
id: Branded<'vm-backup-archive'>
type: 'xo-vm-backup'
@@ -530,15 +539,22 @@ type XoBackupJobGeneralSettings = {
[key: string]: unknown
}
/**
* Keeps the last backup of each of the last `retention` days/weeks/months/years, in addition to `exportRetention`.
*
* Requires the `timezone` setting.
*/
export type XoBackupJobLongTermRetention = {
daily?: { retention: number; settings: Record<string, unknown> }
weekly?: { retention: number; settings: Record<string, unknown> }
monthly?: { retention: number; settings: Record<string, unknown> }
yearly?: { retention: number; settings: Record<string, unknown> }
}
export type XoVmBackupJobGeneralSettings = XoBackupJobGeneralSettings & {
cbtDestroySnapshotData?: boolean
concurrency?: number
longTermRetention?: {
daily?: { retention: number; settings: Record<string, unknown> }
weekly?: { retention: number; settings: Record<string, unknown> }
monthly?: { retention: number; settings: Record<string, unknown> }
yearly?: { retention: number; settings: Record<string, unknown> }
}
longTermRetention?: XoBackupJobLongTermRetention
checkpointSnapshot?: boolean
offlineSnapshot?: boolean
maxExportRate?: number
@@ -595,13 +611,12 @@ export type XoMetadataBackupJob = BaseXoJob & {
export type XoMirrorBackupGeneralSettings = XoBackupJobGeneralSettings & {
concurrency?: number
longTermRetention?: XoBackupJobLongTermRetention
nRetriesVmBackupFailures?: number
mergeBackupsSynchronously?: boolean
timeout?: number
timezone?: string
maxExportRate?: number
backupReportTpl?: 'compactMjml'
reportWhen: 'failure'
}
export type XoMirrorBackupScheduleSettings = {
exportRetention?: number

View File

@@ -1,3 +1,5 @@
export default {
read: true,
export: true, // can export the content ( full or file by file )
read: true, // can read the metadata of an archive
mount: true, // can mount the archive for file level restore
}

View File

@@ -27,6 +27,7 @@ import { formatFilenameDate } from './_filenameDate.mjs'
import { isMetadataFile } from './_backupType.mjs'
import {
isKnownJournalEvent,
purgeBackupJournal,
readBackupJournal,
writeBackupJournalEntries,
writeBackupJournalEntry,
@@ -65,6 +66,10 @@ export class RemoteAdapter {
this._handler = handler
this._readCacheListVmBackups = synchronized.withKey()(this._readCacheListVmBackups)
this._useGetDiskLegacy = useGetDiskLegacy
// Cache of the partition list per diskId, populated by listPartitions and evicted by
// getDisk when the disk is unmounted
this._partitionsCache = new Map()
}
get handler() {
@@ -555,6 +560,14 @@ export class RemoteAdapter {
return readBackupJournal(this._handler, cursor, opts)
}
/**
* @param {number} before timestamp in ms, the journal days before its own are removed
* @returns {Promise<void>}
*/
async purgeBackupJournal(before) {
return purgeBackupJournal(this._handler, before)
}
// Same as `readBackupJournal()`, with the current metadata of the added and changed backups
// attached, so that a listing can be brought up to date from the result alone, in a single
// round-trip for a caller which is not on this host.

View File

@@ -393,6 +393,47 @@ describe('readBackupJournal()', { concurrency: 1 }, () => {
})
})
describe('purgeBackupJournal()', { concurrency: 1 }, () => {
const DAY = 24 * 60 * 60 * 1e3
const HOUR = 60 * 60 * 1e3
// midnight of the given number of days ago, so that the tests do not depend on the time they run at
const daysAgo = n => (Math.floor(Date.now() / DAY) - n) * DAY
const writeEntryAt = timestamp =>
writeJournalEntryAt(timestamp, { event: 'add', vmUuid, filename: `/${rootPath}/${timestamp}.json` })
test('removes the days before the one of `before`, and keeps that day whole', async () => {
for (const n of [3, 2]) {
await writeEntryAt(daysAgo(n) + HOUR)
}
// after the entry of its own day: that entry is kept all the same
await adapter.purgeBackupJournal(daysAgo(2) + 2 * HOUR)
assert.deepEqual(await listJournalDays(), [formatJournalDay(daysAgo(2))])
})
test('skips a day which cannot be removed, and removes the next ones', async t => {
for (const n of [3, 2]) {
await writeEntryAt(daysAgo(n))
}
const lockedDay = formatJournalDay(daysAgo(3))
const rmtree = handler.rmtree.bind(handler)
t.mock.method(handler, 'rmtree', async path => {
if (path === `/${BACKUP_JOURNAL_DIR}/${lockedDay}`) {
throw Object.assign(new Error('EPERM: operation not permitted'), { code: 'EPERM' })
}
return rmtree(path)
})
await adapter.purgeBackupJournal(Date.now())
assert.deepEqual(await listJournalDays(), [lockedDay])
})
})
describe('readBackupJournalEvents()', { concurrency: 1 }, () => {
// records the paths whose metadata is read from now on, to check a replay does not re-read the
// same backup once per event

View File

@@ -309,3 +309,47 @@ export async function readBackupJournal(handler, cursor, { mustExist = false } =
return entries
}
/**
* Removes the journal entries of the days before the one of `before`.
*
* Whole days are removed, entries are never removed one by one: the day of `before` is kept entirely,
* whatever the time of its entries.
*
* A day which cannot be removed is skipped, e.g. its files are immutable (`EPERM` on a local
* repository, `AccessDenied` from the policy of a bucket): it must not keep the later days from being
* removed, and the next purge tries it again. Only a failure to list the journal rejects.
*
* A purge warns once, with its first failure and their count: where deletes are refused, every day
* before `before` fails again on each purge, one more each day.
*
* @param {RemoteHandler} handler
* @param {number} before timestamp in ms
* @returns {Promise<void>}
*/
export async function purgeBackupJournal(handler, before) {
const minDay = formatJournalDay(before)
const days = await handler.list(`/${BACKUP_JOURNAL_DIR}`, {
filter: name => isDayName(name) && name < minDay,
ignoreMissing: true,
})
let firstFailure
let nFailures = 0
// one day at a time: this runs in the background, it must not compete with the backups for the
// remote
for (const day of days) {
const path = `/${BACKUP_JOURNAL_DIR}/${day}`
try {
await handler.rmtree(path)
debug('journal day purged', { path })
} catch (error) {
if (firstFailure === undefined) {
firstFailure = { error, path }
}
++nFailures
}
}
if (firstFailure !== undefined) {
warn('failed to purge some journal days', { ...firstFailure, nFailures })
}
}

View File

@@ -1,7 +1,7 @@
import { strict as assert } from 'node:assert'
import test from 'node:test'
import { execFile } from 'node:child_process'
import { copyFile, mkdtemp, rm, writeFile } from 'node:fs/promises'
import { copyFile, mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises'
import { Stream } from 'node:stream'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
@@ -9,6 +9,7 @@ import { promisify } from 'node:util'
import { randomBytes } from 'node:crypto'
import Disposable from 'promise-toolbox/Disposable'
import * as tar from 'tar'
import { RemoteAdapter } from './RemoteAdapter.mjs'
@@ -71,6 +72,83 @@ test('fetchPartitionFiles resolves with a node:stream for every format', async t
}
})
async function readAll(stream) {
const chunks = []
for await (const chunk of stream) {
chunks.push(chunk)
}
return Buffer.concat(chunks)
}
async function listTgzEntries(archive, tmp) {
const file = join(tmp, 'archive.tgz')
await writeFile(file, archive)
const entries = []
await tar.t({ file, onReadEntry: entry => entries.push(entry.path.replace(/\/$/, '')) })
return entries
}
// The partition is mounted on the XOA/proxy: a guest symlink is resolved against the host root,
// so following one would expose host files. Paths through a symlink are refused, and symlinks
// met while walking a directory are skipped.
test('file restore never follows symbolic links', async t => {
const tmp = await mkdtemp(join(tmpdir(), 'xo-flr-symlink-'))
t.after(() => rm(tmp, { recursive: true, force: true }))
// `host` stands for the XOA filesystem, `root` for the mounted guest partition
const host = join(tmp, 'host')
const root = join(tmp, 'root')
await mkdir(host)
await writeFile(join(host, 'secret.txt'), 'host secret')
await mkdir(join(root, 'dir'), { recursive: true })
await writeFile(join(root, 'dir', 'file.txt'), 'guest file')
await symlink(host, join(root, 'absolute')) // like `ln -s / foo` in the guest
await symlink('../../host', join(root, 'dir', 'relative'))
await symlink('file.txt', join(root, 'dir', 'in-tree'))
const adapter = new RemoteAdapter({})
adapter.getPartition = Disposable.factory(async function* () {
yield root
})
const refusedPaths = ['/absolute', '/absolute/secret.txt', '/dir/relative', '/dir/relative/host/secret.txt']
await t.test('listing refuses a path through a symlink', async () => {
for (const path of refusedPaths) {
await assert.rejects(adapter.listPartitionFiles('disk', 'partition', path), { code: 'ELINK_NOT_SUPPORTED' }, path)
}
})
await t.test('listing skips symlinks', async () => {
assert.deepEqual(await adapter.listPartitionFiles('disk', 'partition', '/'), { 'dir/': {} })
assert.deepEqual(await adapter.listPartitionFiles('disk', 'partition', '/dir'), { 'file.txt': {} })
})
for (const format of ['tgz', 'zip']) {
await t.test(`${format}: download refuses a path through a symlink`, async () => {
for (const path of refusedPaths) {
await assert.rejects(
adapter.fetchPartitionFiles('disk', 'partition', ['/dir/file.txt', path], format),
{ code: 'ELINK_NOT_SUPPORTED' },
path
)
}
})
}
await t.test('tgz: symlinks inside a selected directory are skipped', async () => {
const archive = await readAll(await adapter.fetchPartitionFiles('disk', 'partition', ['/dir'], 'tgz'))
assert.deepEqual((await listTgzEntries(archive, tmp)).sort(), ['dir', 'dir/file.txt'])
})
await t.test('zip: symlinks inside a selected directory are skipped', async () => {
const archive = await readAll(await adapter.fetchPartitionFiles('disk', 'partition', ['/dir'], 'zip'))
assert.ok(archive.includes('dir/file.txt'))
assert.equal(archive.includes('dir/relative'), false)
assert.equal(archive.includes('dir/in-tree'), false)
})
})
test('LVM file-restore against real losetup/dmsetup/lvm', { skip }, async t => {
const tmp = await mkdtemp(join(tmpdir(), 'xo-flr-'))
const adapter = new RemoteAdapter({})

View File

@@ -66,7 +66,29 @@ export const toLvPartitions = (partitionId, originalVgName, lvItems) =>
}))
const makeRelative = path => resolve('/', path).slice(1)
const resolveSubpath = (root, path) => resolve(root, makeRelative(path))
// The partition is mounted on the XOA/proxy, so the kernel resolves a guest symlink against the
// host root: following one (e.g. `ln -s / foo` in the VM, then `/foo/etc`) would read host files.
// Symlinks are therefore not supported by file restore: a path going through one is refused,
// checked component by component with lstat. The mount is read-only, so no check/use race.
export async function resolveWithoutSymlinks(rootPath, path) {
const relativePath = makeRelative(path)
let currentPath = rootPath
for (const name of relativePath.split('/')) {
if (name === '') {
continue
}
currentPath = join(currentPath, name)
const stats = await lstat(currentPath)
if (stats.isSymbolicLink()) {
const error = new Error(`symbolic links are not supported by file restore: ${path}`)
error.code = 'ELINK_NOT_SUPPORTED'
error.path = path
throw error
}
}
return relativePath
}
async function addZipEntries(zip, realBasePath, virtualBasePath, relativePaths) {
for (const relativePath of relativePaths) {
@@ -290,6 +312,12 @@ export const fileRestoreMethods = {
const self = this
Disposable.use(async function* () {
const path = yield self.getPartition(diskId, partitionId)
// validated before resolving the promise, so a refused path rejects instead of
// producing a truncated archive
const relativePaths = []
for (const requestedPath of paths) {
relativePaths.push(await resolveWithoutSymlinks(path, requestedPath))
}
let outputStream
if (format === 'tgz') {
@@ -298,7 +326,13 @@ export const fileRestoreMethods = {
// simultaneous reads. Those saturate the libuv threadpool and starve
// the underlying vhd/CIFS reads NTFS-3g depends on (FUSE-on-FUSE
// threadpool deadlock). Serializing keeps a worker free for them.
const pack = tar.c({ cwd: path, gzip: true, jobs: 1 }, paths.map(makeRelative))
//
// symlinks found while walking the selected directories are skipped, like in the zip
// format and the file listing
const pack = tar.c(
{ cwd: path, gzip: true, jobs: 1, filter: (_, stats) => !stats.isSymbolicLink() },
relativePaths
)
// node-tar >= 7 returns a Minipass stream: it has `pipe()` but is not a `node:stream`
// instance. xo-proxy serves this stream through Koa, which pipes only bodies passing
@@ -316,7 +350,7 @@ export const fileRestoreMethods = {
// appear as a freeze with no response sent.
outputStream = zip.outputStream
resolve(zip.outputStream)
await addZipEntries(zip, path, '', paths.map(makeRelative))
await addZipEntries(zip, path, '', relativePaths)
zip.end()
} else {
throw new Error('unsupported format ' + format)
@@ -331,17 +365,23 @@ export const fileRestoreMethods = {
},
async *getDisk(diskId) {
if (this._useGetDiskLegacy) {
yield* getDiskLegacy(this._handler, diskId)
return
try {
if (this._useGetDiskLegacy) {
yield* getDiskLegacy(this._handler, diskId)
return
}
const handler = this._handler
// this is a disposable
const mountDir = yield getTmpDir()
// this is also a disposable
yield mount(handler, diskId, mountDir)
// this will yield disk path to caller
yield `${mountDir}/vhd0`
} finally {
// Disposable.factory disposes by calling gen.return(), which runs this finally before
// the mount/tmpdir disposers — i.e. exactly as the disk is unmounted.
this._partitionsCache.delete(diskId)
}
const handler = this._handler
// this is a disposable
const mountDir = yield getTmpDir()
// this is also a disposable
yield mount(handler, diskId, mountDir)
// this will yield disk path to caller
yield `${mountDir}/vhd0`
},
// partitionId values:
@@ -371,7 +411,7 @@ export const fileRestoreMethods = {
listPartitionFiles(diskId, partitionId, path) {
return Disposable.use(this.getPartition(diskId, partitionId), async rootPath => {
path = resolveSubpath(rootPath, path)
path = join(rootPath, await resolveWithoutSymlinks(rootPath, path))
const entriesMap = {}
await asyncEach(
await readdir(path),
@@ -397,7 +437,13 @@ export const fileRestoreMethods = {
},
listPartitions(diskId) {
return Disposable.use(this.getDisk(diskId), async devicePath => {
const cache = this._partitionsCache
const cached = cache.get(diskId)
if (cached !== undefined) {
return cached
}
const pPartitions = Disposable.use(this.getDisk(diskId), async devicePath => {
// partx may return empty on FUSE-backed files (vhd0); a loop device
// presents proper block-device semantics that partx reads reliably.
// losetup may itself fail if the FUSE mount isn't fully ready yet —
@@ -415,11 +461,14 @@ export const fileRestoreMethods = {
}
}
// direct listing failed, try with lvm listing
if (partitions.length === 0) {
debug('direct listing of the volume partition failed, try to read through LVM')
try {
// handle potential raw LVM physical volume
return await this._listLvmLogicalVolumes(devicePath, undefined, partitions)
} catch (error) {
warn('LVM listing of this volume failed ', error)
return []
}
}
@@ -455,6 +504,16 @@ export const fileRestoreMethods = {
})
return results
})
// The entry is evicted on disk unmount (see getDisk)
// a failed probe is not cached so the next call retries.
cache.set(diskId, pPartitions)
pPartitions.catch(() => {
if (cache.get(diskId) === pPartitions) {
cache.delete(diskId)
}
})
return pPartitions
},
}

View File

@@ -60,7 +60,7 @@ const parsePartxLine = createParser({
export async function listPartitions(devicePath) {
const parts = await fromCallback(execFile, 'partx', [
'--bytes',
'--output=NR,START,SIZE,NAME,UUID,TYPE',
'--output=START,SIZE,NAME,UUID,TYPE',
'--pairs',
devicePath,
]).catch(error => {

View File

@@ -65,6 +65,11 @@ export class IncrementalXapiWriter extends MixinXapiWriter(AbstractIncrementalWr
const snapshotCandidates = new Map()
// skip orphan snapshots (active VDI destroyed): they can't be validated against an active disk
const replicaSnapshots = sr.$VDIs.filter(
vdi => vdi?.managed && vdi?.is_a_snapshot && vdi.$snapshot_of !== undefined
)
for (const [baseUuid, srcVdiuid] of baseUuidToSrcVdi) {
let target
@@ -72,11 +77,9 @@ export class IncrementalXapiWriter extends MixinXapiWriter(AbstractIncrementalWr
if (contentKey !== undefined) {
debug('got one content key, look for a candidate')
target = sr.$VDIs.find(
target = replicaSnapshots.find(
vdi =>
vdi?.managed &&
vdi?.is_a_snapshot &&
vdi.other_config[CONTENT_KEY] === contentKey && // &&
vdi.other_config[CONTENT_KEY] === contentKey &&
// ensure we don't replicate on ourself or any of the vdi in the source chain
vdi.$snapshot_of.uuid !== srcVdiuid
)
@@ -85,13 +88,11 @@ export class IncrementalXapiWriter extends MixinXapiWriter(AbstractIncrementalWr
// fall back for older snapshots
if (target === undefined) {
debug('content key not here or not found , look by jobid ')
target = sr.$VDIs.find(
target = replicaSnapshots.find(
vdi =>
vdi?.managed &&
vdi?.is_a_snapshot &&
vdi.other_config[JOB_ID] === this._job.id &&
vdi.other_config[VM_UUID] === this._vmUuid &&
vdi?.other_config[COPY_OF] === baseUuid
vdi.other_config[COPY_OF] === baseUuid
)
}
if (target !== undefined) {

View File

@@ -1,4 +1,4 @@
import { isExpression, compileExpression } from '@xen-orchestra/backups/_expressionPredicate.mjs'
import { isExpression, compileExpression } from './_expressionPredicate.mjs'
import { invalidParameters } from 'xo-common/api-errors.js'
export function assertValidSettingsExpression(settings, keys) {

View File

@@ -2,7 +2,7 @@ import assert from 'node:assert/strict'
import { describe, it } from 'node:test'
import { invalidParameters } from 'xo-common/api-errors.js'
import { assertValidExpression, assertValidSettingsExpression } from './_backupExpressions.mjs'
import { assertValidExpression, assertValidSettingsExpression } from './backupExpressions.mjs'
const VALID = 'vm:tags:prod'
const INVALID = 'vm:('

View File

@@ -43,7 +43,7 @@ A VM directory holds **both** the full and the incremental backups of that VM: t
Transient entries, not listed in the trees below:
- `xo-vm-backups/<VM UUID>.lock`, held for the duration of a job run on that VM. When listing VMs, entries starting with `.` and entries ending with `.lock` are ignored.
- `xo-vm-backups/<VM UUID>.lock`, held while a job writes to that VM's folder and while `cleanVm` cleans or merges it (after a job, after a deletion, or in the merge worker on local remotes). It is effective on S3 (an object rewritten every 30 seconds) and Azure (blob lease) too. When listing VMs, entries starting with `.` and entries ending with `.lock` are ignored.
- `xo-vm-backups/.queue/clean-vm/<YYYYMMDD>T<HHmmss>-<random>`, the merge worker queue
- `.<VHD file name>.merge.json`, in a VDI directory, interrupted merge states.
@@ -167,6 +167,7 @@ Append-only log of what happened to the VM backup metadata.
- entries are never modified nor overwritten, so it works on an immutable remote
- written unencrypted, so it stays readable without the encryption key
- one directory per day: a reader lists only the days it misses, a purge drops whole directories
- xo-server removes the days older than `backups.journalRetention` from every enabled remote when it starts, then once a day; it always keeps the `fullListingInterval` of the remote, during which it reads the journal back; a day which cannot be removed is skipped, and the next purge tries it again
- the time part has a fixed width, so sorting the names by name sorts them by date
- `event` is `add`, `change` or `del`, and the file content also has a `reason` field
- the name of the file is only there to be read by a human: XO reads every field from the file content

View File

@@ -58,6 +58,7 @@
"value-matcher": "^0.2.0",
"vhd-lib": "^4.17.0",
"xen-api": "^5.1.0",
"xo-common": "^0.11.0",
"xo-remote-parser": "^2.0.0",
"yazl": "^2.5.1"
},

View File

@@ -9,7 +9,7 @@ async function consumeGenerator(source: AsyncGenerator) {
return 'finished'
}
test('Disk class', async t => {
const testRes = await t.test('synchronised fork disk ', async () => {
const testRes = await t.test('synchronized fork disk ', async () => {
const blockSize = 1024
const nbBlocks = 20
const source = new DebugDisk({ nbBlocks, blockSize, fillRate: 100 })

View File

@@ -18,7 +18,7 @@ ee.on('start', async function () {
// listeners have settled
await ee.emitAsync('start')
// by default, it will rejects as soon as one listener reject, you can customise
// by default, it will rejects as soon as one listener reject, you can customize
// error handling though:
await ee.emitAsync(
{

View File

@@ -36,7 +36,7 @@ ee.on('start', async function () {
// listeners have settled
await ee.emitAsync('start')
// by default, it will rejects as soon as one listener reject, you can customise
// by default, it will rejects as soon as one listener reject, you can customize
// error handling though:
await ee.emitAsync(
{

View File

@@ -0,0 +1,4 @@
// the error of proper-lockfile, which LocalHandler uses: callers and the documentation know this one
export default function lockedError(path) {
return Object.assign(new Error('Lock file is already being held'), { code: 'ELOCKED', file: path })
}

View File

@@ -1,9 +1,12 @@
import { BlobServiceClient, StorageSharedKeyCredential } from '@azure/storage-blob'
import { createLogger } from '@xen-orchestra/log'
import { pTimeout } from 'promise-toolbox'
import { parse } from 'xo-remote-parser'
import { join, split } from './path'
import RemoteHandlerAbstract from './abstract'
import copyStreamToBuffer from './_copyStreamToBuffer'
import lockedError from './_lockedError.js'
import { randomUUID } from 'node:crypto'
import { PassThrough, Transform, pipeline } from 'stream'
createLogger('xo:fs:azure')
@@ -11,7 +14,52 @@ const MAX_BLOCK_SIZE = 1024 * 1024 * 4000 // 4000 MiB
const MIN_BLOCK_SIZE = 1024 * 1024 * 4 // 4 MiB, default max block size
const MAX_BLOCK_COUNT = 50000
const AZURE_BATCH_MAX_REQUEST = 256 // BATCH_MAX_REQUEST constant from Azure
const { warn, info } = createLogger('xo:fs:azure')
const { debug, warn, info } = createLogger('xo:fs:azure')
// how long the lease of a lock lasts without being renewed, in seconds: the longest finite lease Azure allows, as an
// infinite one would outlive a holder which crashed, and block the path until someone breaks it by hand
export const LEASE_DURATION = 60
// how often a holder renews the lease of its lock: 4 renewals per lease, so that a holder survives a few slow or
// failed requests without losing its lock
export const RENEW_INTERVAL = 15e3
// how long a renewal, or a reacquisition, waits for its requests: a hung one counts as a failed one, and the next
// renewal must still run before the lease expires, so RENEW_INTERVAL + RENEW_TIMEOUT + RENEW_INTERVAL < LEASE_DURATION
// (15 s + 20 s + 15 s < 60 s)
export const RENEW_TIMEOUT = 20e3
// leases the blob, creating it first, or throws `lockedError(path)`
//
// The holder of the lock deletes the blob when it releases it: when that happens between the upload and the
// acquisition, one more attempt. Losing a second race means another contender got it.
async function takeLease(blobClient, leaseClient, path) {
for (let attempt = 0; attempt < 2; ++attempt) {
try {
await blobClient.upload('', 0, { conditions: { ifNoneMatch: '*' } })
} catch (error) {
// 409: the blob exists; 412: it exists and is leased, and a write without the lease ID is refused
if (error.statusCode !== 409 && error.statusCode !== 412) {
throw error
}
}
try {
await leaseClient.acquireLease(LEASE_DURATION)
return
} catch (error) {
// 409: another lease is active
if (error.statusCode === 409) {
throw lockedError(path)
}
// 404: the blob was deleted since the upload
if (error.statusCode !== 404) {
throw error
}
}
}
throw lockedError(path)
}
export default class AzureHandler extends RemoteHandlerAbstract {
#container
@@ -330,4 +378,89 @@ export default class AzureHandler extends RemoteHandlerAbstract {
await blobBatchClient.submitBatch(batch)
}
}
// Locks with a blob lease, Azure's own lock on a blob: Azure enforces its expiry, so there is no clock to compare,
// and a renewal writes nothing, where rewriting the blob would leave a copy every time on accounts with versioning
// or soft delete. An acquisition does leave one copy per lock taken, as the blob is created then deleted on release:
// a lease needs a blob to hold it.
//
// The requests are sent with the blob client directly, not through the handler's methods: those go through the
// handler's concurrency limit, and a renewal queued behind long uploads would let the lease expire.
//
// As with `LocalHandler#_lock()`, losing the lock while holding it is only logged, and the release function never
// rejects. A renewal which finds the lease gone takes the lock back, and the lock is given up only when another
// holder has it: any other error is a failed request, and the next renewal tries again.
async _lock(path) {
// `<path>.lock`, the name of the local lock directory: the listings skip it already
const blobClient = this.#containerClient.getBlockBlobClient(this.#makeFullPath(`${path}.lock`))
// Azure requires a GUID. Proposing it, rather than letting Azure pick one, makes the retry of the SDK harmless
// when the response of an acquisition is lost: acquiring with the ID of the active lease succeeds
const leaseId = randomUUID()
const leaseClient = blobClient.getBlobLeaseClient(leaseId)
await takeLease(blobClient, leaseClient, path)
let lastRenewal = Date.now()
let lost = false
let released = false
let renewing = Promise.resolve()
let timeout
async function renew() {
try {
await pTimeout.call(leaseClient.renewLease(), RENEW_TIMEOUT)
lastRenewal = Date.now()
return
} catch (error) {
// 404: the blob is gone; 409: it is leased to someone else
if (error.statusCode !== 404 && error.statusCode !== 409) {
// a failed request is not a lost lock: it is lost only if the lease expires and someone takes it, which the
// next successful request finds out; it repeats every interval while Azure fails, hence debug
debug('lock could not be renewed', { error, path, sinceLastRenewal: Date.now() - lastRenewal })
return
}
}
warn('lock compromised', { path })
try {
await pTimeout.call(takeLease(blobClient, leaseClient, path), RENEW_TIMEOUT)
lastRenewal = Date.now()
info('compromised lock was reacquired', { path })
} catch (error) {
lost = error.code === 'ELOCKED'
warn('compromised lock could not be reacquired', { error, path })
}
}
function schedule() {
timeout = setTimeout(() => {
renewing = renew().then(() => {
if (!released && !lost) {
schedule()
}
})
}, RENEW_INTERVAL)
timeout.unref()
}
schedule()
return async () => {
released = true
clearTimeout(timeout)
try {
// a renewal in flight which found the blob deleted would take the lock again
await renewing
// only deletes the blob while the lease is ours: after a lost lock, it is someone else's
await blobClient.delete({ conditions: { leaseId } })
} catch (error) {
// 404: the blob is gone; 412: it is not leased to `leaseId`
if (error.statusCode !== 404 && error.statusCode !== 412) {
warn('lock could not be released', { error, path })
}
}
}
}
}

View File

@@ -0,0 +1,252 @@
import { after, afterEach, before, beforeEach, describe, it, mock } from 'node:test'
import { strict as assert } from 'assert'
import 'dotenv/config'
import sinon from 'sinon'
import { ContainerClient } from '@azure/storage-blob'
import { getHandler } from '.'
import AzureHandler, { LEASE_DURATION, RENEW_INTERVAL, RENEW_TIMEOUT } from './azure.js'
// needs a real container, on Azure or Azurite
//
// xo_fs_azure='azure://<account>:<key>@<host>/<container>/<dir>' yarn workspace @xen-orchestra/fs test
const url = process.env.xo_fs_azure
describe('AzureHandler#lock()', { skip: url === undefined }, () => {
let handler
before(async () => {
handler = getHandler({ url }).addPrefix(`xo-fs-tests-${Date.now()}`)
await handler.sync()
})
after(async () => {
await handler?.forget()
})
it('refuses a held lock until it is released', async () => {
const lock = await handler.lock('vm')
try {
await assert.rejects(handler.lock('vm'), { code: 'ELOCKED' })
} finally {
await lock.dispose()
}
const again = await handler.lock('vm')
await again.dispose()
})
})
// `AzureHandler#_lock()` against a stubbed blob client: each status code it maps is checked through the lock it takes
describe('AzureHandler#_lock with stubbed blob client', () => {
let blob
let leaseClient
let getBlockBlobClientStub
let handler
const httpError = statusCode => Object.assign(new Error(`HTTP ${statusCode}`), { statusCode })
// one renewal, after `RENEW_INTERVAL`
async function renewOnce() {
mock.timers.tick(RENEW_INTERVAL)
await new Promise(resolve => setImmediate(resolve))
}
// a request which hangs until `RENEW_TIMEOUT` gives up on it
async function timeOut() {
mock.timers.tick(RENEW_TIMEOUT)
await new Promise(resolve => setImmediate(resolve))
}
beforeEach(() => {
mock.timers.enable({ apis: ['setTimeout', 'Date'] })
leaseClient = {
acquireLease: sinon.stub().resolves(),
renewLease: sinon.stub().resolves(),
}
blob = {
upload: sinon.stub().resolves(),
delete: sinon.stub().resolves(),
getBlobLeaseClient: sinon.stub().returns(leaseClient),
}
getBlockBlobClientStub = sinon.stub(ContainerClient.prototype, 'getBlockBlobClient').returns(blob)
handler = new AzureHandler({ url: 'azure://account:a2V5@account.blob.core.windows.net/container/dir' })
})
afterEach(() => {
getBlockBlobClientStub.restore()
mock.timers.reset()
})
it('leases the blob next to the path, under the directory of the handler, with a GUID of its own', async () => {
const release = await handler._lock('vm')
assert.deepEqual(getBlockBlobClientStub.firstCall.args, ['dir/vm.lock'])
assert.match(
blob.getBlobLeaseClient.firstCall.args[0],
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
)
assert.deepEqual(leaseClient.acquireLease.firstCall.args, [LEASE_DURATION])
await release()
})
describe('create', () => {
// 409: the blob exists; 412: it exists and is leased
for (const statusCode of [409, 412]) {
it(`goes on to acquire the lease when create fails with ${statusCode}`, async () => {
blob.upload.rejects(httpError(statusCode))
const release = await handler._lock('vm')
assert.deepEqual(blob.upload.firstCall.args, ['', 0, { conditions: { ifNoneMatch: '*' } }])
assert.equal(leaseClient.acquireLease.callCount, 1)
await release()
})
}
it('rethrows an unexpected create error', async () => {
blob.upload.rejects(httpError(500))
await assert.rejects(handler._lock('vm'), { statusCode: 500 })
assert.equal(leaseClient.acquireLease.callCount, 0)
})
})
describe('acquire', () => {
it('reports a lease held by another as ELOCKED', async () => {
leaseClient.acquireLease.rejects(httpError(409))
await assert.rejects(handler._lock('vm'), { code: 'ELOCKED' })
})
it('retries once when the blob is gone, then gives up as ELOCKED', async () => {
leaseClient.acquireLease.rejects(httpError(404))
await assert.rejects(handler._lock('vm'), { code: 'ELOCKED' })
assert.equal(blob.upload.callCount, 2)
assert.equal(leaseClient.acquireLease.callCount, 2)
})
it('takes the lock when the blob is back on the retry', async () => {
leaseClient.acquireLease.onFirstCall().rejects(httpError(404))
const release = await handler._lock('vm')
assert.equal(blob.upload.callCount, 2)
await release()
})
it('rethrows an unexpected acquire error', async () => {
leaseClient.acquireLease.rejects(httpError(500))
await assert.rejects(handler._lock('vm'), { statusCode: 500 })
})
})
describe('renew', () => {
// 404: the blob is gone; 409: it is leased to someone else. Either way the lock is taken again
for (const statusCode of [404, 409]) {
it(`takes the lock again when renewal fails with ${statusCode}`, async () => {
const release = await handler._lock('vm')
leaseClient.renewLease.rejects(httpError(statusCode))
await renewOnce()
assert.equal(leaseClient.renewLease.callCount, 1)
assert.equal(leaseClient.acquireLease.callCount, 2)
await release()
})
}
it('keeps the lock and renews again when renewal fails with another error', async () => {
const release = await handler._lock('vm')
leaseClient.renewLease.rejects(httpError(500))
await renewOnce()
await renewOnce()
assert.equal(leaseClient.renewLease.callCount, 2)
assert.equal(leaseClient.acquireLease.callCount, 1)
await release()
})
it('gives up on a renewal which hangs, and renews again', async () => {
const release = await handler._lock('vm')
leaseClient.renewLease.onFirstCall().returns(new Promise(() => {}))
await renewOnce()
await timeOut()
await renewOnce()
assert.equal(leaseClient.renewLease.callCount, 2)
assert.equal(leaseClient.acquireLease.callCount, 1)
await release()
})
it('gives up on a reacquisition which hangs, and renews again', async () => {
const release = await handler._lock('vm')
leaseClient.renewLease.onFirstCall().rejects(httpError(409))
leaseClient.acquireLease.onSecondCall().returns(new Promise(() => {}))
await renewOnce()
await timeOut()
await renewOnce()
assert.equal(leaseClient.renewLease.callCount, 2)
assert.equal(leaseClient.acquireLease.callCount, 2)
await release()
})
it('stops renewing once released', async () => {
const release = await handler._lock('vm')
await renewOnce()
await release()
await renewOnce()
assert.equal(leaseClient.renewLease.callCount, 1)
})
it('gives up the lock when another holder has the lease', async () => {
const release = await handler._lock('vm')
leaseClient.renewLease.rejects(httpError(409))
leaseClient.acquireLease.rejects(httpError(409))
await renewOnce()
await renewOnce()
assert.equal(leaseClient.renewLease.callCount, 1)
assert.equal(leaseClient.acquireLease.callCount, 2)
await release()
})
it('waits for a renewal in flight before releasing', async () => {
const release = await handler._lock('vm')
let renewed
leaseClient.renewLease.returns(new Promise(resolve => (renewed = resolve)))
await renewOnce()
const releasing = release()
await new Promise(resolve => setImmediate(resolve))
assert.equal(blob.delete.callCount, 0)
renewed()
await releasing
assert.equal(blob.delete.callCount, 1)
})
})
describe('remove', () => {
it('deletes the blob only while the lease is ours', async () => {
const release = await handler._lock('vm')
await release()
const [leaseId] = blob.getBlobLeaseClient.firstCall.args
assert.deepEqual(blob.delete.firstCall.args, [{ conditions: { leaseId } }])
})
// 404: the blob is gone; 412: it is not leased to us. Both are fine, and release never rejects anyway
for (const statusCode of [404, 412, 500]) {
it(`releases without rejecting when delete fails with ${statusCode}`, async () => {
const release = await handler._lock('vm')
blob.delete.rejects(httpError(statusCode))
await release()
assert.equal(blob.delete.callCount, 1)
})
}
})
})

View File

@@ -19,6 +19,7 @@ import { getApplyMd5BodyChecksumPlugin } from '@aws-sdk/middleware-apply-body-ch
import { Agent as HttpAgent } from 'http'
import { Agent as HttpsAgent } from 'https'
import { createLogger } from '@xen-orchestra/log'
import lockedError from './_lockedError.js'
import { PassThrough, Transform, pipeline } from 'stream'
import { parse } from 'xo-remote-parser'
import copyStreamToBuffer from './_copyStreamToBuffer.js'
@@ -36,6 +37,13 @@ const MAX_PART_NUMBER = 10000
const MIN_PART_SIZE = 5 * 1024 * 1024
const { debug, info, warn } = createLogger('xo:fs:s3')
// how often a holder rewrites its lock object
export const REFRESH_INTERVAL = 30e3
// how long a lock object may go without being rewritten before a contender takes it over: a holder survives a few
// failed refreshes, and one which crashed blocks the path for 3 minutes at most
export const STALE_AFTER = 180e3
export default class S3Handler extends RemoteHandlerAbstract {
#bucket
#dir
@@ -43,6 +51,8 @@ export default class S3Handler extends RemoteHandlerAbstract {
#httpAgent
#httpsAgent
#immutable = false
// the S3 user may not read the bucket's Object Lock configuration: whether it is enabled is unknown
#objectLockUnknown = false
#maxPartSize
#maxPartNumber
#minPartSize
@@ -514,6 +524,12 @@ export default class S3Handler extends RemoteHandlerAbstract {
if (error.$metadata.httpStatusCode === 403) {
info(`s3 user doesnt have enough privilege to check for Object Lock, enable content MD5 header`)
this.#s3.middlewareStack.use(getApplyMd5BodyChecksumPlugin(this.#s3.config))
if (!this.#objectLockUnknown) {
warn(
'the S3 user cannot read the Object Lock configuration of the bucket (s3:GetBucketObjectLockConfiguration), nothing is locked on this remote'
)
}
this.#objectLockUnknown = true
} else if (error.Code === 'ObjectLockConfigurationNotFoundError' || error.$metadata.httpStatusCode === 501) {
info(`Object lock is not available or not configured, don't add the content MD5 header`)
} else {
@@ -521,4 +537,77 @@ export default class S3Handler extends RemoteHandlerAbstract {
}
}
}
// Object Lock buckets keep the no-op lock of `RemoteHandlerAbstract`: every write of the lock object would leave
// a version retained for the whole retention period. So do the buckets whose Object Lock configuration the S3
// user cannot read (see `_sync()`).
//
// The lock is an object rewritten with plain writes, which every S3 provider supports: it is held while it is
// fresher than STALE_AFTER. It is not atomic: two contenders which find it free at the same time both take it, and
// a holder whose refreshes failed for STALE_AFTER keeps writing in a folder someone else took over.
//
// Its age is read on the provider's clock alone, `Last-Modified` against the `Date` of the response: XO's clock may
// not agree with the provider's, and one more than 2.5 minutes ahead would take over a lock its holder keeps
// refreshing (the SDK corrects its own clock only from 5 minutes off).
async _lock(path) {
if (this.isImmutable() || this.#objectLockUnknown) {
return super._lock(path)
}
// `<path>.lock`, the name of the local lock directory: the listings skip it already
const params = this.#createParams(`${path}.lock`)
// the requests are sent with the S3 client directly, not through the handler's methods: those go through the
// handler's concurrency limit, and a refresh queued behind long uploads would let the lock go stale
const write = () => this.#s3.send(new PutObjectCommand({ ...params, Body: '' }))
// the output of a HEAD has no `Date`: it is read from the response
let date
const head = new HeadObjectCommand(params)
head.middlewareStack.add(
next => async args => {
const result = await next(args)
date = result.response.headers.date
return result
},
{ step: 'deserialize' }
)
let current
try {
current = await this.#s3.send(head)
} catch (error) {
if (error.name !== 'NotFound') {
throw error
}
}
// a provider which omits `Last-Modified` or `Date` never lets a lock be taken over: it stays held until released
const age = Date.parse(date) - current?.LastModified?.getTime()
if (current !== undefined && (Number.isNaN(age) || age <= STALE_AFTER)) {
throw lockedError(path)
}
await write()
let refreshing = Promise.resolve()
const interval = setInterval(() => {
refreshing = write().then(
() => {},
// a failed refresh is not a lost lock: the next one tries again
error => debug('lock could not be refreshed', { error, path })
)
}, REFRESH_INTERVAL)
interval.unref()
return async () => {
clearInterval(interval)
try {
// a refresh landing after the delete would write the lock again
await refreshing
await this.#s3.send(new DeleteObjectCommand(params))
} catch (error) {
warn('lock could not be released', { error, path })
}
}
}
}

View File

@@ -0,0 +1,216 @@
import { after, before, describe, it, beforeEach, afterEach, mock } from 'node:test'
import { strict as assert } from 'assert'
import 'dotenv/config'
import sinon from 'sinon'
import {
DeleteObjectCommand,
GetObjectLockConfigurationCommand,
HeadObjectCommand,
PutObjectCommand,
S3Client,
} from '@aws-sdk/client-s3'
import { getHandler } from '.'
import S3Handler, { REFRESH_INTERVAL, STALE_AFTER } from './s3.js'
// needs a real bucket without Object Lock: on an Object Lock bucket the lock is the no-op one, the second
// `lock()` succeeds, and this test fails
//
// xo_fs_s3='s3://<key>:<secret>@<host>/<bucket>/<dir>' yarn workspace @xen-orchestra/fs test
const url = process.env.xo_fs_s3
describe('S3Handler#lock()', { skip: url === undefined }, () => {
let handler
before(async () => {
handler = getHandler({ url }).addPrefix(`xo-fs-tests-${Date.now()}`)
await handler.sync()
})
after(async () => {
await handler?.forget()
})
it('refuses a held lock until it is released', async () => {
const lock = await handler.lock('vm')
try {
await assert.rejects(handler.lock('vm'), { code: 'ELOCKED' })
} finally {
await lock.dispose()
}
const again = await handler.lock('vm')
await again.dispose()
})
})
const createHandler = () => new S3Handler({ url: 's3://key:secret@localhost/bucket/dir' })
const s3Error = (name, httpStatusCode) => Object.assign(new Error(name), { name, $metadata: { httpStatusCode } })
// lets the async callback of a timer which just fired run to its end
const flush = () => new Promise(resolve => setImmediate(resolve))
const KEY = 'dir/vm.lock'
// `S3Handler#_lock()` against a stubbed `S3Client#send()`
describe('S3Handler#_lock() with a stubbed S3Client', () => {
// by key
let objects
// what the provider does wrong, which each test sets
let faults
// how far the provider's clock is ahead of XO's
let clockOffset
let send
const providerDate = () => new Date(Date.now() + clockOffset)
beforeEach(() => {
mock.timers.enable({ apis: ['setInterval', 'Date'] })
objects = new Map()
faults = {}
clockOffset = 0
send = sinon.stub(S3Client.prototype, 'send').callsFake(async command => {
const { Key } = command.input
const current = objects.get(Key)
if (command instanceof PutObjectCommand) {
if (faults.putStatus !== undefined) {
throw s3Error('InternalError', faults.putStatus)
}
// resolved by the test
if (faults.pendingPut !== undefined) {
await faults.pendingPut
}
objects.set(Key, { lastModified: providerDate() })
return {}
}
if (command instanceof HeadObjectCommand) {
if (current === undefined) {
throw s3Error('NotFound', 404)
}
// the lock reads the `Date` of the response in a middleware of the command, which this stub bypasses: run it
// on a response of its own
await command.middlewareStack.resolve(
async () => ({ response: { headers: { date: providerDate().toUTCString() } } }),
{}
)({ input: command.input })
return { LastModified: current.lastModified }
}
if (command instanceof DeleteObjectCommand) {
objects.delete(Key)
return {}
}
if (command instanceof GetObjectLockConfigurationCommand) {
if (faults.objectLock) {
return { ObjectLockConfiguration: { ObjectLockEnabled: 'Enabled' } }
}
throw s3Error('AccessDenied', 403)
}
throw new Error(`unexpected ${command.constructor.name}`)
})
})
afterEach(() => {
send.restore()
mock.timers.reset()
})
const writes = () => send.getCalls().filter(call => call.args[0] instanceof PutObjectCommand).length
for (const [what, objectLock] of [
['on an Object Lock bucket', true],
['when the S3 user cannot read the Object Lock configuration', false],
]) {
it(`takes no lock ${what}`, async () => {
faults.objectLock = objectLock
const handler = createHandler()
await handler._sync()
assert.equal(handler.isImmutable(), objectLock)
const release = await handler._lock('vm')
await release()
// the only request read the Object Lock configuration
assert.equal(send.callCount, 1)
})
}
it('takes <path>.lock in the directory of the remote, rewrites it every REFRESH_INTERVAL, and deletes it', async () => {
const release = await createHandler()._lock('vm')
assert.equal(objects.get(KEY).lastModified.getTime(), Date.now())
mock.timers.tick(REFRESH_INTERVAL)
await flush()
assert.equal(writes(), 2)
assert.equal(objects.get(KEY).lastModified.getTime(), Date.now())
await release()
assert.equal(objects.has(KEY), false)
})
it('refuses a held lock, and leaves it untouched', async () => {
const handler = createHandler()
const release = await handler._lock('vm')
try {
await assert.rejects(handler._lock('vm'), { code: 'ELOCKED' })
assert.equal(writes(), 1)
} finally {
await release()
}
})
it("takes over a stale lock, not a fresh one, on the provider's clock", async () => {
// XO's clock 2 minutes ahead: on it, the lock would look stale after 1 minute
clockOffset = -120e3
objects.set(KEY, { lastModified: providerDate() })
mock.timers.tick(STALE_AFTER)
await assert.rejects(createHandler()._lock('vm'), { code: 'ELOCKED' })
// the resolution of `Date`
mock.timers.tick(1e3)
const release = await createHandler()._lock('vm')
assert.equal(objects.get(KEY).lastModified.getTime(), providerDate().getTime())
await release()
})
it('keeps the lock when a refresh fails, and refreshes again', async () => {
const release = await createHandler()._lock('vm')
faults.putStatus = 500
mock.timers.tick(REFRESH_INTERVAL)
await flush()
assert.equal(objects.get(KEY).lastModified.getTime(), Date.now() - REFRESH_INTERVAL)
faults.putStatus = undefined
mock.timers.tick(REFRESH_INTERVAL)
await flush()
assert.equal(objects.get(KEY).lastModified.getTime(), Date.now())
await release()
assert.equal(objects.has(KEY), false)
})
it('waits for a refresh in flight before deleting the lock', async () => {
const release = await createHandler()._lock('vm')
let resolvePut
faults.pendingPut = new Promise(resolve => {
resolvePut = resolve
})
mock.timers.tick(REFRESH_INTERVAL)
const released = release()
await flush()
assert.equal(objects.has(KEY), true)
resolvePut()
await released
assert.equal(objects.has(KEY), false)
})
})

View File

@@ -1,5 +1,15 @@
# ChangeLog
## **next**
- [Web-Core/UiButtonIcon] Update icon buttons design, with a counter replacing the notification dot (PR [#10799](https://github.com/vatesfr/xen-orchestra/pull/10799))
- [Mobile/Side panels] Full-page menus on mobile with "Change state" in "More actions", side panel actions shown as buttons when there is room, and fixes for long names in headers and menu placement (PR [#10745](https://github.com/vatesfr/xen-orchestra/pull/10745))
- [Side panels] Side panels can be resized like the treeview, whose default width now adapts to the screen size (PR [#10725](https://github.com/vatesfr/xen-orchestra/pull/10725))
- [Side panels] Values stay next to their label when they fit and move below it otherwise, fields with several values (IP addresses, bond devices) get a copy button per value and a "Copy all" action, and rows, links and statuses are more evenly spaced and sized (PR [#10733](https://github.com/vatesfr/xen-orchestra/pull/10733))
- [Treeview] Fix translations of the tooltip for VM and host statuses in treeview (PR [#10643](https://github.com/vatesfr/xen-orchestra/pull/10643))
- [Web-Core/UiDropdownButton] Update dropdown buttons design (PR [#9850](https://github.com/vatesfr/xen-orchestra/pull/9850))
- [Tables] Tables are filtered as you type, half a second after the last keystroke, or right away with Enter; the "Search" button is removed (PR [#10797](https://github.com/vatesfr/xen-orchestra/pull/10797))
## **0.27.0** (2026-10-29)
- [New network] Choose between no NBD, secure NBD and insecure NBD (not encrypted) when creating a network (PR [#10540](https://github.com/vatesfr/xen-orchestra/pull/10540))

View File

@@ -1,5 +1,5 @@
<template>
<MenuList placement="bottom-end">
<VtsResponsiveMenu :title="t('account')" :section-title="t('menu')" placement="bottom-end">
<template #trigger="{ open, isOpen }">
<UiAccountMenuButton
v-tooltip="isOpen ? false : { content: t('settings'), placement: 'left' }"
@@ -33,13 +33,13 @@
<MenuItem accent="brand" icon="fa:arrow-right-from-bracket" @click="logout">
{{ t('action:log-out') }}
</MenuItem>
</MenuList>
</VtsResponsiveMenu>
</template>
<script lang="ts" setup>
import { useXenApiStore } from '@/stores/xen-api.store.ts'
import MenuItem from '@core/components/menu/MenuItem.vue'
import MenuList from '@core/components/menu/MenuList.vue'
import VtsResponsiveMenu from '@core/components/menu/VtsResponsiveMenu.vue'
import UiAccountMenuButton from '@core/components/ui/account-menu-button/UiAccountMenuButton.vue'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import { nextTick } from 'vue'

View File

@@ -38,7 +38,7 @@
Ctx
</sup>
</th>
<td>
<td class="type">
<CodeHighlight :code="param.getTypeLabel()" />
</td>
<td class="reset-param">
@@ -161,6 +161,10 @@ function openRawValueModal(code: string) {
}
}
.type :deep(.code-highlight) {
white-space: pre-wrap;
}
.help {
font-style: italic;
color: var(--color-neutral-txt-secondary);

View File

@@ -14,27 +14,12 @@
<VtsIcon v-tooltip="t('master')" name="status:primary-circle" size="medium" />
</template>
<template #actions>
<MenuList placement="bottom-end">
<template #trigger="{ open }">
<UiDropdownButton @click="open($event)">{{ t('action:change-state') }}</UiDropdownButton>
</template>
<VtsChangeStateMenu v-if="!uiStore.isSmall">
<HostPowerStateActions :host />
</MenuList>
<MenuList placement="bottom-end">
<template #trigger="{ open }">
<UiButtonIcon
v-tooltip="{
placement: 'left',
content: t('more-actions'),
}"
icon="action:more-actions"
accent="brand"
size="medium"
@click="open($event)"
/>
</template>
<HostMoreActions :host />
</MenuList>
</VtsChangeStateMenu>
<VtsActionsMenu :label="t('more-actions')" size="medium">
<HostMoreActions :host :show-change-state="uiStore.isSmall" />
</VtsActionsMenu>
</template>
</UiHeadBar>
</template>
@@ -46,12 +31,12 @@ import HostMoreActions from '@/modules/host/components/HostMoreActions.vue'
import { useHostUtils } from '@/modules/host/composables/host-utils.composable.ts'
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
import VtsIcon from '@core/components/icon/VtsIcon.vue'
import MenuList from '@core/components/menu/MenuList.vue'
import VtsActionsMenu from '@core/components/menu/VtsActionsMenu.vue'
import VtsChangeStateMenu from '@core/components/menu/VtsChangeStateMenu.vue'
import VtsObjectIcon from '@core/components/object-icon/VtsObjectIcon.vue'
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
import UiDropdownButton from '@core/components/ui/dropdown-button/UiDropdownButton.vue'
import UiHeadBar from '@core/components/ui/head-bar/UiHeadBar.vue'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import { useUiStore } from '@core/stores/ui.store.ts'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
@@ -61,6 +46,8 @@ const { host } = defineProps<{
const { t } = useI18n()
const uiStore = useUiStore()
const { isMasterHost } = usePoolStore().subscribe()
const isMaster = computed(() => isMasterHost(host.$ref))

View File

@@ -4,7 +4,7 @@
<VtsForgetButton
:busy="isForgettingPifs"
:disabled="!canForgetPifs"
:tooltip="!canForgetPifs && forgetPifsErrorMessage"
:hint="forgetPifsErrorMessage"
@click="forgetPifs()"
/>
</template>
@@ -12,7 +12,7 @@
<!-- PIF -->
<UiPanelCard>
<UiPanelCardTitle :id="pif.uuid" size="medium" :label="isBond ? t('bond') : t('pif')" />
<div class="content">
<VtsCardRowList>
<!-- NETWORK -->
<VtsCardRowKeyValue>
<template #key>
@@ -82,34 +82,15 @@
</UiTagsList>
</template>
</VtsCardRowKeyValue>
</div>
</VtsCardRowList>
</UiPanelCard>
<!-- NETWORK INFORMATION -->
<UiPanelCard>
<UiPanelCardTitle size="medium" :label="t('network-information')" />
<div class="content">
<VtsCardRowList>
<!-- IP ADDRESSES -->
<div v-if="ipAddresses.length">
<VtsCardRowKeyValue v-for="(ip, index) in ipAddresses" :key="ip">
<template #key>
<div v-if="index === 0">{{ t('ip-addresses') }}</div>
</template>
<template #value>
<span v-tooltip class="text-ellipsis">{{ ip }}</span>
</template>
<template #addons>
<VtsCopyButton :value="ip" />
<VtsCopyAllMenuItem v-if="index === 0 && ipAddresses.length > 1" :values="ipAddresses" />
</template>
</VtsCardRowKeyValue>
</div>
<VtsCardRowKeyValue v-else>
<template #key>
{{ t('ip-addresses') }}
</template>
<template #value>
<span class="value" />
</template>
<VtsCardRowKeyValue :values="ipAddresses">
<template #key>{{ t('ip-addresses') }}</template>
</VtsCardRowKeyValue>
<!-- MAC ADDRESSES -->
<VtsCardRowKeyValue>
@@ -173,26 +154,15 @@
</template>
</VtsCardRowKeyValue>
<!-- BOND DEVICES -->
<div>
<VtsCardRowKeyValue v-for="(device, index) in bondDevices" :key="device">
<template #key>
<div v-if="index === 0">{{ t('bond-devices') }}</div>
</template>
<template #value>
<span v-tooltip class="text-ellipsis">{{ device }}</span>
</template>
<template v-if="device" #addons>
<VtsCopyButton :value="device" />
<VtsCopyAllMenuItem v-if="index === 0 && bondDevices.length > 1" :values="bondDevicesFiltered" />
</template>
</VtsCardRowKeyValue>
</div>
</div>
<VtsCardRowKeyValue v-if="bondDevicesFiltered.length > 0" :values="bondDevicesFiltered">
<template #key>{{ t('bond-devices') }}</template>
</VtsCardRowKeyValue>
</VtsCardRowList>
</UiPanelCard>
<!-- PROPERTIES -->
<UiPanelCard>
<UiPanelCardTitle size="medium" :label="t('properties')" />
<div class="content">
<VtsCardRowList>
<!-- MTU -->
<VtsCardRowKeyValue>
<template #key>
@@ -226,7 +196,7 @@
<VtsCopyButton :value="networkPurpose" />
</template>
</VtsCardRowKeyValue>
</div>
</VtsCardRowList>
</UiPanelCard>
</template>
</VtsSidePanel>
@@ -239,7 +209,7 @@ import { useNetworkStore } from '@/stores/xen-api/network.store.ts'
import { usePifMetricsStore } from '@/stores/xen-api/pif-metrics.store.ts'
import { usePifStore } from '@/stores/xen-api/pif.store.ts'
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
import VtsCopyAllMenuItem from '@core/components/copy-all-menu-item/VtsCopyAllMenuItem.vue'
import VtsCardRowList from '@core/components/card/VtsCardRowList.vue'
import VtsCopyButton from '@core/components/copy-button/VtsCopyButton.vue'
import VtsForgetButton from '@core/components/forget-button/VtsForgetButton.vue'
import VtsIcon from '@core/components/icon/VtsIcon.vue'
@@ -331,12 +301,6 @@ const speed = computed(() => {
<style scoped lang="postcss">
.host-pif-side-panel {
.content {
display: flex;
flex-direction: column;
gap: 0.8rem;
}
.network {
display: flex;
gap: 0.8rem;

View File

@@ -7,7 +7,7 @@
</template>
</UiTitle>
<div class="container">
<UiQuerySearchBar @search="(value: string) => (searchQuery = value)" />
<UiQuerySearchBar v-bind="searchBindings" />
<VtsTable :state :pagination-bindings sticky="right">
<thead>
<tr>
@@ -35,11 +35,12 @@ import UiQuerySearchBar from '@core/components/ui/query-search-bar/UiQuerySearch
import UiTitle from '@core/components/ui/title/UiTitle.vue'
import { usePagination } from '@core/composables/pagination.composable.ts'
import { useRouteQuery } from '@core/composables/route-query.composable.ts'
import { useSearchFilter } from '@core/composables/search-filter.composable.ts'
import { useTableState } from '@core/composables/table-state.composable.ts'
import { icon } from '@core/icons'
import { usePifColumns } from '@core/tables/column-sets/pif-columns.ts'
import { logicNot } from '@vueuse/math'
import { computed, ref } from 'vue'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { pifs } = defineProps<{
@@ -75,21 +76,10 @@ const getIpConfigurationMode = (ipMode: string) => {
}
}
const searchQuery = ref('')
const filteredPifs = computed(() => {
const searchTerm = searchQuery.value.trim().toLocaleLowerCase()
if (!searchTerm) {
return pifs
}
return pifs.filter(pif =>
[...Object.values(pif), getNetworkName(pif.network)].some(value =>
String(value).toLocaleLowerCase().includes(searchTerm)
)
)
})
const { items: filteredPifs, searchBindings } = useSearchFilter(
() => pifs,
pif => [...Object.values(pif), getNetworkName(pif.network)]
)
const state = useTableState({
busy: logicNot(isReady),

View File

@@ -1,42 +1,42 @@
<template>
<tr class="pif-row" :class="{ clickable: pifHost }" @click="pifHost?.redirect()">
<td v-tooltip class="typo-body-regular-small text-ellipsis host-container">
<div v-if="pifHost" class="host">
<VtsObjectIcon :state="pifHost.powerState" type="host" size="small" />
<span v-tooltip class="typo-body-regular-small text-ellipsis host-name">
{{ pifHost.label }}
</span>
</div>
<div v-else>
<span>{{ t('host:status:unknown') }}</span>
</div>
<tr class="pif-row" :class="{ compact }">
<td class="typo-body-regular-small host">
<UiLink
v-if="host"
:to="{ name: '/host/[uuid]/network', params: { uuid: host.uuid }, query: { id: pif.uuid } }"
:icon="getHostIcon(host, getHostPowerState(host))"
:is-primary="isMasterHost(host.$ref)"
:primary-tooltip="t('master')"
size="small"
class="host-link"
>
<span v-tooltip class="text-ellipsis">{{ host.name_label }}</span>
</UiLink>
<span v-else>{{ t('host:status:unknown') }}</span>
</td>
<td v-tooltip class="typo-body-regular-small text-ellipsis device">{{ pif.device }}</td>
<td v-tooltip class="typo-body-regular-small status">
<VtsStatus :status />
</td>
<td>
<UiButtonIcon size="small" accent="brand" icon="fa:angle-right" :disabled="!pifHost" />
<td class="typo-body-regular-small status">
<VtsStatus :status :icon-only="compact" />
</td>
</tr>
</template>
<script setup lang="ts">
import type { XenApiPif } from '@/libs/xen-api/xen-api.types.ts'
import { getHostState } from '@/modules/host/utils/host.util.ts'
import { getHostIcon } from '@/modules/host/utils/host.util.ts'
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
import { useHostStore } from '@/stores/xen-api/host.store.ts'
import { usePifStore } from '@/stores/xen-api/pif.store.ts'
import VtsObjectIcon from '@core/components/object-icon/VtsObjectIcon.vue'
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
import VtsStatus from '@core/components/status/VtsStatus.vue'
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
import UiLink from '@core/components/ui/link/UiLink.vue'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRouter } from 'vue-router'
const { pif } = defineProps<{
pif: XenApiPif
compact?: boolean
}>()
const { t } = useI18n()
@@ -44,68 +44,41 @@ const { t } = useI18n()
const { getByOpaqueRef } = useHostStore().subscribe()
const { getHostPowerState } = useHostMetricsStore().subscribe()
const { getPifStatus } = usePifStore().subscribe()
const { isMasterHost } = usePoolStore().subscribe()
const router = useRouter()
const host = computed(() => getByOpaqueRef(pif.host))
const status = computed(() => getPifStatus(pif))
const pifHost = computed(() => {
const host = getByOpaqueRef(pif.host)
if (!host) {
return
}
return {
label: host.name_label,
powerState: getHostState(host, getHostPowerState(host)),
redirect() {
router.push({
name: '/host/[uuid]/network',
params: { uuid: host.uuid },
query: { id: pif.uuid },
})
},
} as const
})
</script>
<style lang="postcss" scoped>
.pif-row {
&.clickable {
cursor: pointer;
&:hover {
background-color: var(--color-brand-background-hover);
}
}
td {
color: var(--color-neutral-txt-primary);
}
.host-container {
max-width: 14rem;
.host-link {
max-width: 100%;
}
&:not(.compact) {
.host {
display: flex;
align-items: center;
gap: 0.8rem;
max-width: 14rem;
}
.host-name {
color: var(--color-brand-txt-base);
.device {
width: 8rem;
max-width: 8rem;
}
.status {
width: 11.5rem;
max-width: 11.5rem;
}
}
.device {
width: 8rem;
max-width: 8rem;
}
.status {
width: 11.5rem;
max-width: 11.5rem;
&.compact .device {
padding-inline-start: 1.6rem;
}
}
</style>

View File

@@ -7,7 +7,7 @@
</template>
</UiTitle>
<div class="container">
<UiQuerySearchBar @search="value => (searchQuery = value)" />
<UiQuerySearchBar v-bind="searchBindings" />
<VtsTable :state :pagination-bindings sticky="right">
<thead>
<tr>
@@ -38,10 +38,10 @@ import UiQuerySearchBar from '@core/components/ui/query-search-bar/UiQuerySearch
import UiTitle from '@core/components/ui/title/UiTitle.vue'
import { usePagination } from '@core/composables/pagination.composable.ts'
import { useRouteQuery } from '@core/composables/route-query.composable.ts'
import { useSearchFilter } from '@core/composables/search-filter.composable.ts'
import { useTableState } from '@core/composables/table-state.composable.ts'
import { useNetworkColumns } from '@core/tables/column-sets/network-columns.ts'
import { logicNot } from '@vueuse/math'
import { computed, ref } from 'vue'
import { useI18n } from 'vue-i18n'
const { networks } = defineProps<{
@@ -60,19 +60,7 @@ const selectedNetworkId = useRouteQuery('id')
const getLockingMode = (lockingMode: string) => (lockingMode === 'disabled' ? t('disabled') : t('unlocked'))
const searchQuery = ref('')
const filteredNetworks = computed(() => {
const searchTerm = searchQuery.value.trim().toLocaleLowerCase()
if (!searchTerm) {
return networks
}
return networks.filter(network =>
Object.values(network).some(value => String(value).toLocaleLowerCase().includes(searchTerm))
)
})
const { items: filteredNetworks, searchBindings } = useSearchFilter(() => networks)
const { pageRecords: paginatedNetworks, paginationBindings } = usePagination('internal-networks', filteredNetworks)

View File

@@ -1,27 +1,15 @@
<template>
<VtsSidePanel :has-selection="!!network" class="pool-network-side-panel" @close="emit('close')">
<template v-if="network" #actions>
<VtsDeleteButton v-if="network.PIFs.length === 0" :busy="isDeletingNetworks" @click="deleteNetworks()" />
<MenuList placement="bottom-end">
<template #trigger="{ open, isOpen }">
<UiButtonIcon
v-tooltip="copied && t('copied')"
accent="brand"
size="small"
:icon="copied ? 'fa:check-circle' : 'action:more-actions'"
:selected="isOpen"
@click="open($event)"
/>
</template>
<MenuItem accent="neutral" icon="action:copy" :disabled="!isClipboardSupported" @click="copy()">
{{ t('action:copy-info-json') }}
</MenuItem>
</MenuList>
<template v-if="network && network.PIFs.length === 0" #actions>
<VtsDeleteButton :busy="isDeletingNetworks" @click="deleteNetworks()" />
</template>
<template v-if="network" #corner-actions>
<VtsCopyButton :value="networkAsJson" :label="t('action:copy-info-json')" />
</template>
<template v-if="network" #default>
<UiPanelCard>
<UiPanelCardTitle :id="network.uuid" size="medium" :label="network.name_label" />
<div class="content">
<VtsCardRowList>
<!-- DESCRIPTION -->
<VtsCardRowKeyValue truncate align-top>
<template #key>{{ t('description') }}</template>
@@ -63,27 +51,30 @@
<template #key>{{ t('locking-mode-default') }}</template>
<template #value>{{ networkDefaultLockingMode }}</template>
</VtsCardRowKeyValue>
</div>
</VtsCardRowList>
</UiPanelCard>
<UiPanelCard v-if="pifsCount && pifsCount > 0">
<UiPanelCard v-if="pifsCount && pifsCount > 0" ref="pifsCard">
<UiPanelCardTitle size="medium" :label="t('pifs')" :counter="pifsCount" />
<table class="simple-table">
<table class="simple-table" :class="{ compact: isPifsCardCompact }">
<thead>
<tr>
<th class="text-left typo-body-regular-small">
<th class="typo-body-regular-small">
{{ t('host') }}
</th>
<th class="text-left typo-body-regular-small">
<th class="typo-body-regular-small device">
{{ t('device') }}
</th>
<th class="text-left typo-body-regular-small">
<th
v-tooltip="isPifsCardCompact"
class="typo-body-regular-small status"
:class="{ 'text-ellipsis': isPifsCardCompact }"
>
{{ t('pifs-status') }}
</th>
<th />
</tr>
</thead>
<tbody>
<PifRow v-for="pif in pifs" :key="pif.uuid" :pif />
<PifRow v-for="pif in pifs" :key="pif.uuid" :pif :compact="isPifsCardCompact" />
</tbody>
</table>
</UiPanelCard>
@@ -97,17 +88,15 @@ import type { XenApiNetwork } from '@/libs/xen-api/xen-api.types.ts'
import { useNetworkDelete } from '@/modules/network/composables/use-network-delete.composable.ts'
import { usePifStore } from '@/stores/xen-api/pif.store.ts'
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
import VtsCardRowList from '@core/components/card/VtsCardRowList.vue'
import VtsCopyButton from '@core/components/copy-button/VtsCopyButton.vue'
import VtsDeleteButton from '@core/components/delete-button/VtsDeleteButton.vue'
import MenuItem from '@core/components/menu/MenuItem.vue'
import MenuList from '@core/components/menu/MenuList.vue'
import VtsSidePanel from '@core/components/panel/VtsSidePanel.vue'
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
import UiPanelCard from '@core/components/ui/panel-card/UiPanelCard.vue'
import UiPanelCardTitle from '@core/components/ui/panel-card-title/UiPanelCardTitle.vue'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import { useClipboard } from '@vueuse/core'
import { computed } from 'vue'
import { useElementSize } from '@vueuse/core'
import { computed, useTemplateRef } from 'vue'
import { useI18n } from 'vue-i18n'
const { network } = defineProps<{
@@ -144,28 +133,37 @@ const pifsCount = computed(() => pifs.value.length)
const networkAsJson = computed(() => JSON.stringify(network))
const { copy, copied, isSupported: isClipboardSupported } = useClipboard({ source: networkAsJson, legacy: true })
const PIFS_CARD_COMPACT_MAX_WIDTH = 400
const { width: pifsCardWidth } = useElementSize(useTemplateRef('pifsCard'))
const isPifsCardCompact = computed(() => pifsCardWidth.value > 0 && pifsCardWidth.value < PIFS_CARD_COMPACT_MAX_WIDTH)
</script>
<style scoped lang="postcss">
.pool-network-side-panel {
.content {
display: flex;
flex-direction: column;
gap: 0.4rem;
}
.text-left {
text-align: left;
}
.simple-table {
border-spacing: 0;
padding: 0.4rem;
thead tr th {
th {
text-align: start;
color: var(--color-neutral-txt-secondary);
}
&.compact {
width: 100%;
table-layout: fixed;
.device {
width: 7.6rem;
padding-inline-start: 1.6rem;
}
.status {
width: 4rem;
}
}
}
.value:empty::before {

View File

@@ -7,7 +7,7 @@
</template>
</UiTitle>
<div class="container">
<UiQuerySearchBar @search="value => (searchQuery = value)" />
<UiQuerySearchBar v-bind="searchBindings" />
<VtsTable :state :pagination-bindings sticky="right">
<thead>
<tr>
@@ -38,9 +38,10 @@ import UiQuerySearchBar from '@core/components/ui/query-search-bar/UiQuerySearch
import UiTitle from '@core/components/ui/title/UiTitle.vue'
import { usePagination } from '@core/composables/pagination.composable.ts'
import { useRouteQuery } from '@core/composables/route-query.composable.ts'
import { useSearchFilter } from '@core/composables/search-filter.composable.ts'
import { useTableState } from '@core/composables/table-state.composable.ts'
import { useNetworkColumns } from '@core/tables/column-sets/network-columns.ts'
import { computed, ref } from 'vue'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { networks, busy, error } = defineProps<{
@@ -70,19 +71,7 @@ const getNetworkVlan = (network: XenApiNetwork) => {
const getLockingMode = (lockingMode: string) => (lockingMode === 'disabled' ? t('disabled') : t('unlocked'))
const searchQuery = ref('')
const filteredNetworks = computed(() => {
const searchTerm = searchQuery.value.trim().toLocaleLowerCase()
if (!searchTerm) {
return networks
}
return networks.filter(network =>
Object.values(network).some(value => String(value).toLocaleLowerCase().includes(searchTerm))
)
})
const { items: filteredNetworks, searchBindings } = useSearchFilter(() => networks)
const { pageRecords: paginatedNetworks, paginationBindings } = usePagination('networks', filteredNetworks)

View File

@@ -11,30 +11,18 @@
/>
</template>
<template #actions>
<MenuList v-if="vm !== undefined" placement="bottom-start">
<template #trigger="{ open }">
<UiDropdownButton @click="open($event)">{{ t('action:change-state') }}</UiDropdownButton>
</template>
<VtsChangeStateMenu v-if="vm !== undefined && !uiStore.isSmall" placement="bottom-start">
<VmActionPowerStateItems :vm-refs="[vm.$ref]" />
</MenuList>
<MenuList v-if="vm !== undefined" placement="bottom-end">
<template #trigger="{ open }">
<UiButtonIcon
v-tooltip="{
placement: 'left',
content: t('more-actions'),
}"
icon="action:more-actions-vertical"
accent="brand"
size="medium"
@click="open($event)"
/>
</template>
</VtsChangeStateMenu>
<VtsActionsMenu v-if="vm !== undefined" :label="t('more-actions')" size="medium">
<VtsChangeStateMenuItem v-if="uiStore.isSmall">
<VmActionPowerStateItems :vm-refs="[vm.$ref]" />
</VtsChangeStateMenuItem>
<VmActionCopyItem :selected-refs="[vm.$ref]" is-single-action />
<VmActionExportItem :vm-refs="[vm.$ref]" is-single-action />
<VmActionSnapshotItem :vm-refs="[vm.$ref]" />
<VmActionMigrateItem :selected-refs="[vm.$ref]" is-single-action />
</MenuList>
</VtsActionsMenu>
</template>
</UiHeadBar>
</template>
@@ -48,12 +36,12 @@ import VmActionSnapshotItem from '@/components/vm/VmActionItems/VmActionSnapshot
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import { useVmOperation } from '@/modules/vm/composables/vm-operation.composable.ts'
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
import MenuList from '@core/components/menu/MenuList.vue'
import VtsActionsMenu from '@core/components/menu/VtsActionsMenu.vue'
import VtsChangeStateMenu from '@core/components/menu/VtsChangeStateMenu.vue'
import VtsChangeStateMenuItem from '@core/components/menu/VtsChangeStateMenuItem.vue'
import VtsObjectIcon from '@core/components/object-icon/VtsObjectIcon.vue'
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
import UiDropdownButton from '@core/components/ui/dropdown-button/UiDropdownButton.vue'
import UiHeadBar from '@core/components/ui/head-bar/UiHeadBar.vue'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import { useUiStore } from '@core/stores/ui.store.ts'
import { toLower } from 'lodash-es'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
@@ -61,6 +49,8 @@ import { useRoute } from 'vue-router'
const { t } = useI18n()
const uiStore = useUiStore()
const { getByUuid: getVmByUuid } = useVmStore().subscribe()
const route = useRoute<'/vm/[uuid]'>()

View File

@@ -1,44 +1,39 @@
<template>
<VtsMobileMenu v-if="uiStore.isSmall" :title="t('actions')">
<template #trigger="{ isOpen, open }">
<UiButtonIcon
accent="brand"
size="small"
:disabled="selectedRefs.length === 0"
:selected="isOpen"
icon="fa:ellipsis"
@click="open()"
/>
</template>
<VmsBulkActionItems :selected-refs />
</VtsMobileMenu>
<MenuList
v-else
:disabled="selectedRefs.length === 0"
:horizontal="!uiStore.isSmall"
:no-border="!uiStore.isSmall"
class="vms-actions-bar"
horizontal
no-border
placement="bottom-end"
>
<template v-if="uiStore.isSmall" #trigger="{ isOpen, open }">
<UiButtonIcon accent="brand" size="small" :selected="isOpen" icon="fa:ellipsis" @click="open" />
</template>
<MenuItem accent="brand" icon="fa:power-off">
{{ t('action:change-state') }}
<template #submenu>
<VmActionPowerStateItems :vm-refs="selectedRefs" />
</template>
</MenuItem>
<VmActionMigrateItem :selected-refs="selectedRefs" />
<VmActionCopyItem :selected-refs="selectedRefs" />
<VmActionSnapshotItem :vm-refs="selectedRefs" />
<VmActionExportItems :vm-refs="selectedRefs" />
<VmActionDeleteItem :vm-refs="selectedRefs" />
<VmsBulkActionItems :selected-refs />
</MenuList>
</template>
<script lang="ts" setup>
import VmActionCopyItem from '@/components/vm/VmActionItems/VmActionCopyItem.vue'
import VmActionDeleteItem from '@/components/vm/VmActionItems/VmActionDeleteItem.vue'
import VmActionExportItems from '@/components/vm/VmActionItems/VmActionExportItems.vue'
import VmActionMigrateItem from '@/components/vm/VmActionItems/VmActionMigrateItem.vue'
import VmActionPowerStateItems from '@/components/vm/VmActionItems/VmActionPowerStateItems.vue'
import VmActionSnapshotItem from '@/components/vm/VmActionItems/VmActionSnapshotItem.vue'
import VmsBulkActionItems from '@/components/vm/VmsBulkActionItems.vue'
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import MenuItem from '@core/components/menu/MenuItem.vue'
import MenuList from '@core/components/menu/MenuList.vue'
import VtsMobileMenu from '@core/components/menu/VtsMobileMenu.vue'
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
import { useUiStore } from '@core/stores/ui.store.ts'
import { useI18n } from 'vue-i18n'
defineProps<{
disabled?: boolean
selectedRefs: XenApiVm['$ref'][]
}>()

View File

@@ -0,0 +1,31 @@
<template>
<MenuItem accent="brand" icon="fa:power-off">
{{ t('action:change-state') }}
<template #submenu>
<VmActionPowerStateItems :vm-refs="selectedRefs" />
</template>
</MenuItem>
<VmActionMigrateItem :selected-refs />
<VmActionCopyItem :selected-refs />
<VmActionSnapshotItem :vm-refs="selectedRefs" />
<VmActionExportItems :vm-refs="selectedRefs" />
<VmActionDeleteItem :vm-refs="selectedRefs" />
</template>
<script lang="ts" setup>
import VmActionCopyItem from '@/components/vm/VmActionItems/VmActionCopyItem.vue'
import VmActionDeleteItem from '@/components/vm/VmActionItems/VmActionDeleteItem.vue'
import VmActionExportItems from '@/components/vm/VmActionItems/VmActionExportItems.vue'
import VmActionMigrateItem from '@/components/vm/VmActionItems/VmActionMigrateItem.vue'
import VmActionPowerStateItems from '@/components/vm/VmActionItems/VmActionPowerStateItems.vue'
import VmActionSnapshotItem from '@/components/vm/VmActionItems/VmActionSnapshotItem.vue'
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import MenuItem from '@core/components/menu/MenuItem.vue'
import { useI18n } from 'vue-i18n'
defineProps<{
selectedRefs: XenApiVm['$ref'][]
}>()
const { t } = useI18n()
</script>

View File

@@ -1,5 +1,5 @@
<template>
<VtsQuickInfoCard class="vm-dashboard-quick-info" :loading="!isReady">
<VtsQuickInfoCard :loading="!isReady" class="vm-dashboard-quick-info">
<VtsKeyValueList>
<VtsKeyValueRow :label="t('state')">
<template #value>
@@ -19,11 +19,11 @@
<template #value>
<UiLink
v-if="host"
:to="`/host/${host.uuid}`"
size="medium"
:icon="hostIcon"
:is-primary="isPoolMaster"
:primary-tooltip="t('master')"
:to="`/host/${host.uuid}`"
size="medium"
>
{{ host.name_label }}
</UiLink>
@@ -54,9 +54,9 @@
</template>
<script lang="ts" setup>
import { VM_POWER_STATE } from '@/libs/xen-api/xen-api.enums.ts'
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 { 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'
@@ -70,7 +70,6 @@ import VtsTag from '@core/components/tag/VtsTag.vue'
import UiLink from '@core/components/ui/link/UiLink.vue'
import UiTagsList from '@core/components/ui/tag/UiTagsList.vue'
import { useTimeAgo } from '@core/composables/locale-time-ago.composable.ts'
import { useMapper } from '@core/packages/mapper'
import { formatSizeRaw } from '@core/utils/size.util.ts'
import { formatDate, parseDateTime } from '@core/utils/time.util.ts'
import { computed } from 'vue'
@@ -98,16 +97,7 @@ const isPoolMaster = computed(() => pool.value?.master === host.value?.$ref)
const hostIcon = computed(() => getHostIcon(host.value, getHostPowerState(host.value)))
const powerState = useMapper(
() => vm.power_state,
{
[VM_POWER_STATE.RUNNING]: { icon: 'status:running-circle', text: t('vm:status:running') },
[VM_POWER_STATE.HALTED]: { icon: 'status:halted-circle', text: t('vm:status:halted') },
[VM_POWER_STATE.PAUSED]: { icon: 'status:paused-circle', text: t('vm:status:paused') },
[VM_POWER_STATE.SUSPENDED]: { icon: 'status:suspended-circle', text: t('vm:status:suspended') },
},
VM_POWER_STATE.RUNNING
)
const { powerState } = useVmUtils(() => vm)
function getValidDateTime(dateTime: string | undefined): string | undefined {
return dateTime === '19700101T00:00:00Z' ? undefined : dateTime

View File

@@ -0,0 +1,16 @@
/**
* Builds a `File` to be used as a stub in stories.
*
* `File.size` is derived from the blob content, so it is overridden here: it lets stories display
* realistic sizes without allocating that many bytes.
*
* The blob is empty and carries no MIME type, so such a stub can never satisfy a `file.type` based
* `accept` filter: it is meant for display only, never to be fed back into an uploader.
*/
export function createStoryFile(name: string, size: number): File {
const file = new File([], name)
Object.defineProperty(file, 'size', { value: size })
return file
}

View File

@@ -1,10 +1,7 @@
<template>
<MenuItem v-if="showChangeStateButton" icon="action:change-state" accent="brand">
{{ t('action:change-state') }}
<template #submenu>
<HostPowerStateActions :host />
</template>
</MenuItem>
<VtsChangeStateMenuItem v-if="showChangeState">
<HostPowerStateActions :host />
</VtsChangeStateMenuItem>
<HostRestartToolstackButton :host />
<HostDisableButton v-if="displayDisableButton" :host />
<HostEnableButton v-else :host />
@@ -25,18 +22,15 @@ import HostPowerStateActions from '@/modules/host/components/actions/HostPowerSt
import HostRestartToolstackButton from '@/modules/host/components/actions/restart-toolstack/HostRestartToolstackButton.vue'
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
import VtsDivider from '@core/components/divider/VtsDivider.vue'
import MenuItem from '@core/components/menu/MenuItem.vue'
import VtsChangeStateMenuItem from '@core/components/menu/VtsChangeStateMenuItem.vue'
import { HOST_POWER_STATE } from '@vates/types'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { host } = defineProps<{
host: XenApiHost
showChangeStateButton?: boolean
showChangeState?: boolean
}>()
const { t } = useI18n()
const { getHostPowerState } = useHostMetricsStore().subscribe()
const isHostHalted = computed(() => getHostPowerState(host) === HOST_POWER_STATE.HALTED)

View File

@@ -3,7 +3,7 @@
<UiTitle>
{{ t('hosts') }}
</UiTitle>
<UiQuerySearchBar @search="(value: string) => (searchQuery = value)" />
<UiQuerySearchBar v-bind="searchBindings" />
<div class="container">
<VtsTable :pagination-bindings :state sticky="right">
<thead>
@@ -34,11 +34,12 @@ import UiQuerySearchBar from '@core/components/ui/query-search-bar/UiQuerySearch
import UiTitle from '@core/components/ui/title/UiTitle.vue'
import { usePagination } from '@core/composables/pagination.composable.ts'
import { useRouteQuery } from '@core/composables/route-query.composable.ts'
import { useSearchFilter } from '@core/composables/search-filter.composable.ts'
import { useTableState } from '@core/composables/table-state.composable.ts'
import { icon } from '@core/icons'
import { useHostColumns } from '@core/tables/column-sets/host-columns.ts'
import { logicAnd, logicNot, logicOr } from '@vueuse/math'
import { computed, ref } from 'vue'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const {
@@ -63,19 +64,7 @@ const hasError = logicOr(() => error, hasPifError)
const selectedHostId = useRouteQuery('id')
const searchQuery = ref('')
const filteredHosts = computed(() => {
const searchTerm = searchQuery.value.trim().toLocaleLowerCase()
if (!searchTerm) {
return rawHosts
}
return rawHosts.filter(host =>
Object.values(host).some(value => String(value).toLocaleLowerCase().includes(searchTerm))
)
})
const { items: filteredHosts, searchBindings } = useSearchFilter(() => rawHosts)
const state = useTableState({
busy: logicNot(isReady),

View File

@@ -1,7 +1,7 @@
<template>
<UiPanelCard class="host-hardware-specifications-card">
<UiPanelCard>
<UiPanelCardTitle size="medium" :label="t('hardware-specifications')" />
<div class="content">
<VtsCardRowList>
<VtsCardRowKeyValue>
<template #key>{{ t('manufacturer-info') }}</template>
<template #value>{{ manufacturerInfo }}</template>
@@ -16,7 +16,7 @@
<VtsCopyButton :value="coreSocketInfo" />
</template>
</VtsCardRowKeyValue>
</div>
</VtsCardRowList>
</UiPanelCard>
</template>
@@ -24,6 +24,7 @@
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import { getHostCoreSocketInfo, getHostManufacturerInfo } from '@/modules/host/utils/host.util.ts'
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
import VtsCardRowList from '@core/components/card/VtsCardRowList.vue'
import VtsCopyButton from '@core/components/copy-button/VtsCopyButton.vue'
import UiPanelCard from '@core/components/ui/panel-card/UiPanelCard.vue'
import UiPanelCardTitle from '@core/components/ui/panel-card-title/UiPanelCardTitle.vue'
@@ -40,13 +41,3 @@ const manufacturerInfo = computed(() => getHostManufacturerInfo(host))
const coreSocketInfo = computed(() => getHostCoreSocketInfo(host))
</script>
<style lang="postcss" scoped>
.host-hardware-specifications-card {
.content {
display: flex;
flex-direction: column;
gap: 0.4rem;
}
}
</style>

View File

@@ -7,7 +7,7 @@
:icon="hostIcon"
:to="{ name: '/host/[uuid]/dashboard', params: { uuid: host.uuid } }"
/>
<div class="content">
<VtsCardRowList class="content">
<VtsCardRowKeyValue>
<template #key>{{ t('state') }}</template>
<template #value>
@@ -98,7 +98,7 @@
<VtsCopyButton :value="noMissingPatches ? t('patches-up-to-date') : t('n-missing', nMissingPatches)" />
</template>
</VtsCardRowKeyValue>
</div>
</VtsCardRowList>
</UiPanelCard>
</template>
@@ -110,6 +110,7 @@ import { getHostIcon } from '@/modules/host/utils/host.util.ts'
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
import VtsCardRowList from '@core/components/card/VtsCardRowList.vue'
import VtsCopyButton from '@core/components/copy-button/VtsCopyButton.vue'
import VtsEnabledState from '@core/components/enabled-state/VtsEnabledState.vue'
import VtsIcon from '@core/components/icon/VtsIcon.vue'
@@ -146,10 +147,6 @@ const noMissingPatches = computed(() => nMissingPatches.value === 0)
<style lang="postcss" scoped>
.host-infos-card {
.content {
display: flex;
flex-direction: column;
gap: 0.4rem;
.value {
display: flex;
align-items: center;

View File

@@ -1,7 +1,7 @@
<template>
<UiPanelCard class="host-network-card">
<UiPanelCard>
<UiPanelCardTitle :label="t('network')" size="medium" />
<div class="content">
<VtsCardRowList>
<VtsCardRowKeyValue>
<template #key>{{ t('management-ip') }}</template>
<template #value>{{ host.address }}</template>
@@ -9,37 +9,13 @@
<VtsCopyButton :value="host.address" />
</template>
</VtsCardRowKeyValue>
<template v-if="ipV4Addresses.length > 0">
<VtsCardRowKeyValue v-for="(ip, index) in ipV4Addresses" :key="ip">
<template #key>
<div v-if="index === 0">{{ t('ipv4-addresses') }}</div>
</template>
<template #value>{{ ip }}</template>
<template #addons>
<VtsCopyButton :value="ip" />
<VtsCopyAllMenuItem v-if="index === 0 && ipV4Addresses.length > 1" :values="ipV4Addresses" />
</template>
</VtsCardRowKeyValue>
</template>
<VtsCardRowKeyValue v-else>
<VtsCardRowKeyValue :values="ipV4Addresses">
<template #key>{{ t('ipv4-addresses') }}</template>
</VtsCardRowKeyValue>
<template v-if="ipV6Addresses.length > 0">
<VtsCardRowKeyValue v-for="(ip, index) in ipV6Addresses" :key="ip">
<template #key>
<div v-if="index === 0">{{ t('ipv6-addresses') }}</div>
</template>
<template #value>{{ ip }}</template>
<template #addons>
<VtsCopyButton :value="ip" />
<VtsCopyAllMenuItem v-if="index === 0 && ipV6Addresses.length > 1" :values="ipV6Addresses" />
</template>
</VtsCardRowKeyValue>
</template>
<VtsCardRowKeyValue v-else>
<VtsCardRowKeyValue :values="ipV6Addresses">
<template #key>{{ t('ipv6-addresses') }}</template>
</VtsCardRowKeyValue>
</div>
</VtsCardRowList>
</UiPanelCard>
</template>
@@ -47,7 +23,7 @@
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import { usePifStore } from '@/stores/xen-api/pif.store.ts'
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
import VtsCopyAllMenuItem from '@core/components/copy-all-menu-item/VtsCopyAllMenuItem.vue'
import VtsCardRowList from '@core/components/card/VtsCardRowList.vue'
import VtsCopyButton from '@core/components/copy-button/VtsCopyButton.vue'
import UiPanelCard from '@core/components/ui/panel-card/UiPanelCard.vue'
import UiPanelCardTitle from '@core/components/ui/panel-card-title/UiPanelCardTitle.vue'
@@ -66,13 +42,3 @@ const pifs = computed(() => pifsByHost.value.get(host.$ref))
const ipV4Addresses = computed(() => pifs.value?.map(pif => pif.IP).filter(ip => ip) ?? [])
const ipV6Addresses = computed(() => pifs.value?.flatMap(pif => pif.IPv6.filter(ip => ip)) ?? [])
</script>
<style lang="postcss" scoped>
.host-network-card {
.content {
display: flex;
flex-direction: column;
gap: 0.4rem;
}
}
</style>

View File

@@ -1,7 +1,7 @@
<template>
<UiPanelCard class="host-software-card">
<UiPanelCard>
<UiPanelCardTitle size="medium" :label="t('software')" />
<div class="content">
<VtsCardRowList>
<VtsCardRowKeyValue>
<template #key>{{ t('version') }}</template>
<template #value>{{ host.software_version.product_version }}</template>
@@ -9,13 +9,14 @@
<VtsCopyButton :value="host.software_version.product_version" />
</template>
</VtsCardRowKeyValue>
</div>
</VtsCardRowList>
</UiPanelCard>
</template>
<script lang="ts" setup>
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
import VtsCardRowList from '@core/components/card/VtsCardRowList.vue'
import VtsCopyButton from '@core/components/copy-button/VtsCopyButton.vue'
import UiPanelCard from '@core/components/ui/panel-card/UiPanelCard.vue'
import UiPanelCardTitle from '@core/components/ui/panel-card-title/UiPanelCardTitle.vue'
@@ -27,13 +28,3 @@ defineProps<{
const { t } = useI18n()
</script>
<style lang="postcss" scoped>
.host-software-card {
.content {
display: flex;
flex-direction: column;
gap: 0.4rem;
}
}
</style>

View File

@@ -5,7 +5,7 @@ import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
import type { IconName } from '@core/icons'
import { useTimeAgo } from '@core/composables/locale-time-ago.composable.ts'
import { useMapper } from '@core/packages/mapper'
import { createMapper, useMapper } from '@core/packages/mapper'
import { parseDateTime } from '@core/utils/time.util.ts'
import { toComputed } from '@core/utils/to-computed.util.ts'
import { HOST_POWER_STATE } from '@vates/types'
@@ -70,20 +70,31 @@ export function useHostUtils(rawHost: MaybeRefOrGetter<XenApiHost | undefined>)
const currentOperation = useMapper<string, string>(
() => pendingStateOperation.value,
{
() => ({
[HOST_OPERATION.ENABLE]: t('operation:enable'),
[HOST_OPERATION.EVACUATE]: t('operation:evacuate'),
[HOST_OPERATION.POWER_ON]: t('operation:start'),
[HOST_OPERATION.REBOOT]: t('operation:clean-reboot'),
[HOST_OPERATION.SHUTDOWN]: t('operation:shutdown'),
unknown: '',
},
}),
'unknown'
)
const getHostStatus = createMapper<HostState, { text: string; icon: IconName | undefined }>(
() => ({
running: { text: t('host:status:running'), icon: 'status:running-circle' },
halted: { text: t('host:status:halted'), icon: 'status:halted-circle' },
disabled: { text: t('host:status:disabled'), icon: 'status:host-disabled-circle' },
unknown: { text: t('host:status:unknown'), icon: undefined },
}),
'unknown'
)
return {
isMaster,
isRunning,
getHostStatus,
hostState,
powerState,
isChangingState,

View File

@@ -1,11 +1,10 @@
<template>
<UiButton
v-tooltip="!canConnectSrs && connectSrsErrorMessage"
size="medium"
<VtsActionButton
:hint="connectSrsErrorMessage"
variant="tertiary"
accent="brand"
:disabled="!canConnectSrs"
left-icon="action:connect"
icon="action:connect"
:busy="isConnectingSrs"
@click="connectSrs()"
>
@@ -17,7 +16,7 @@
variant="secondary"
size="small"
/>
</UiButton>
</VtsActionButton>
</template>
<script lang="ts" setup>
@@ -25,9 +24,8 @@ import type { XenApiSr } from '@/libs/xen-api/xen-api.types.ts'
import { useSrUtils } from '@/modules/storage-repository/composables/sr-utils.composable.ts'
import { useSrConnection } from '@/modules/storage-repository/composables/use-sr-connection.composable.ts'
import type { SrScope } from '@core/types/storage-repository.type.ts'
import UiButton from '@core/components/ui/button/UiButton.vue'
import VtsActionButton from '@core/components/action-button/VtsActionButton.vue'
import UiCounter from '@core/components/ui/counter/UiCounter.vue'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import { useI18n } from 'vue-i18n'
const { sr, scope } = defineProps<{

View File

@@ -1,28 +1,15 @@
<template>
<MenuItem
v-tooltip="!canDeleteSrs && deleteSrsErrorMessage"
accent="danger"
icon="action:delete"
:disabled="!canDeleteSrs"
:busy="isDeletingSrs"
@click="deleteSrs()"
>
{{ t('action:delete') }}
</MenuItem>
<VtsDeleteButton :hint="deleteSrsErrorMessage" :disabled="!canDeleteSrs" :busy="isDeletingSrs" @click="deleteSrs()" />
</template>
<script lang="ts" setup>
import type { XenApiSr } from '@/libs/xen-api/xen-api.types.ts'
import { useSrDelete } from '@/modules/storage-repository/composables/use-sr-delete.composable.ts'
import MenuItem from '@core/components/menu/MenuItem.vue'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import { useI18n } from 'vue-i18n'
import VtsDeleteButton from '@core/components/delete-button/VtsDeleteButton.vue'
const { sr } = defineProps<{
sr: XenApiSr
}>()
const { t } = useI18n()
const { deleteSrs, canDeleteSrs, isDeletingSrs, deleteSrsErrorMessage } = useSrDelete(() => [sr])
</script>

View File

@@ -1,7 +1,8 @@
<template>
<MenuItem
v-tooltip="!canDisconnectSrs && disconnectSrsErrorMessage"
accent="neutral"
<VtsActionButton
:hint="disconnectSrsErrorMessage"
variant="tertiary"
accent="brand"
icon="action:disconnect"
:disabled="!canDisconnectSrs"
:busy="isDisconnectingSrs"
@@ -15,19 +16,16 @@
variant="secondary"
size="small"
/>
<i v-if="hint">{{ hint }}</i>
</MenuItem>
</VtsActionButton>
</template>
<script lang="ts" setup>
import type { XenApiSr } from '@/libs/xen-api/xen-api.types.ts'
import { useSrConnection } from '@/modules/storage-repository/composables/use-sr-connection.composable.ts'
import MenuItem from '@core/components/menu/MenuItem.vue'
import VtsActionButton from '@core/components/action-button/VtsActionButton.vue'
import UiCounter from '@core/components/ui/counter/UiCounter.vue'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import { type SrScope } from '@core/types/storage-repository.type.ts'
import { shouldShowTargetCount } from '@core/utils/sr.utils.ts'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { sr, scope } = defineProps<{
@@ -42,6 +40,4 @@ const { disconnectSrs, canDisconnectSrs, isDisconnectingSrs, disconnectSrsErrorM
srs: () => [sr],
scope: () => scope,
})
const hint = computed(() => (!canDisconnectSrs.value ? disconnectSrsErrorMessage.value : undefined))
</script>

View File

@@ -3,7 +3,7 @@
<UiTitle>
{{ t('storage-repositories') }}
</UiTitle>
<UiQuerySearchBar @search="value => (searchQuery = value)" />
<UiQuerySearchBar v-bind="searchBindings" />
<div class="container">
<VtsTable :state :pagination-bindings sticky="right">
<thead>
@@ -33,12 +33,13 @@ import UiQuerySearchBar from '@core/components/ui/query-search-bar/UiQuerySearch
import UiTitle from '@core/components/ui/title/UiTitle.vue'
import { usePagination } from '@core/composables/pagination.composable.ts'
import { useRouteQuery } from '@core/composables/route-query.composable.ts'
import { useSearchFilter } from '@core/composables/search-filter.composable.ts'
import { useTableState } from '@core/composables/table-state.composable.ts'
import { icon } from '@core/icons'
import { useSrColumns } from '@core/tables/column-sets/sr-columns.ts'
import { type SrScope } from '@core/types/storage-repository.type.ts'
import { shouldShowTargetCount } from '@core/utils/sr.utils.ts'
import { computed, ref } from 'vue'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const {
@@ -61,17 +62,7 @@ const { isReady, hasError, isDefaultSr } = useSrStore().subscribe()
const selectedSrId = useRouteQuery('id')
const searchQuery = ref('')
const filteredSrs = computed(() => {
const searchTerm = searchQuery.value.trim().toLocaleLowerCase()
if (!searchTerm) {
return rawSrs
}
return rawSrs.filter(sr => Object.values(sr).some(value => String(value).toLocaleLowerCase().includes(searchTerm)))
})
const { items: filteredSrs, searchBindings } = useSearchFilter(() => rawSrs)
const state = useTableState({
busy: () => busy ?? !isReady.value,

View File

@@ -2,13 +2,8 @@
<VtsSidePanel :key="panelSignature" :has-selection="!!sr" @close="emit('close')">
<template v-if="sr" #actions>
<SrConnectButton :scope :sr />
<MenuList placement="bottom-end">
<template #trigger="{ open }">
<UiButtonIcon accent="brand" icon="action:more-actions" size="medium" @click="open($event)" />
</template>
<SrDisconnectButton :scope :sr />
<SrDeleteButton :sr />
</MenuList>
<SrDisconnectButton :scope :sr />
<SrDeleteButton :sr />
</template>
<template v-if="sr" #default>
<VtsStateHero v-if="!isReady" format="panel" type="busy" size="medium" />
@@ -40,10 +35,8 @@ import { useHostStore } from '@/stores/xen-api/host.store.ts'
import { usePbdStore } from '@/stores/xen-api/pbd.store.ts'
import { useVdiStore } from '@/stores/xen-api/vdi.store.ts'
import type { SrScope } from '@core/types/storage-repository.type.ts'
import MenuList from '@core/components/menu/MenuList.vue'
import VtsSidePanel from '@core/components/panel/VtsSidePanel.vue'
import VtsStateHero from '@core/components/state-hero/VtsStateHero.vue'
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
import { logicAnd } from '@vueuse/math'
import { computed } from 'vue'

View File

@@ -1,12 +1,12 @@
<template>
<UiPanelCard class="storage-repository-infos-card">
<UiPanelCard>
<UiPanelCardTitle
:id="sr.uuid"
size="medium"
:label="sr.name_label"
:icon="sr.name_label ? srStatusIcon : undefined"
/>
<div class="content">
<VtsCardRowList>
<VtsCardRowKeyValue>
<template #key>{{ t('status') }}</template>
<template #value>
@@ -56,7 +56,7 @@
<template #key>{{ t('high-availability') }}</template>
<template #value><VtsStatus :status="isHaSr" /></template>
</VtsCardRowKeyValue>
</div>
</VtsCardRowList>
</UiPanelCard>
</template>
@@ -66,6 +66,7 @@ import { useSrUtils } from '@/modules/storage-repository/composables/sr-utils.co
import { useSrStore } from '@/stores/xen-api/sr.store.ts'
import type { SrScope } from '@core/types/storage-repository.type.ts'
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
import VtsCardRowList from '@core/components/card/VtsCardRowList.vue'
import VtsCopyButton from '@core/components/copy-button/VtsCopyButton.vue'
import VtsStatus from '@core/components/status/VtsStatus.vue'
import VtsTag from '@core/components/tag/VtsTag.vue'
@@ -96,13 +97,3 @@ const allocationStrategy = computed(() => getAllocationStrategy(sr) ?? t('unknow
const isHaSr = computed(() => isHaSrForPool(sr, pool))
</script>
<style scoped lang="postcss">
.storage-repository-infos-card {
.content {
display: flex;
flex-direction: column;
gap: 0.4rem;
}
}
</style>

View File

@@ -5,10 +5,10 @@
{{ t('no-pbd-attached') }}
</VtsStateHero>
<template v-else>
<div class="content">
<VtsCardRowList class="content">
<VtsStatus :status="srConnectionStatus" />
</div>
<div v-if="areSomePbdsDisconnected" class="content">
</VtsCardRowList>
<VtsCardRowList v-if="areSomePbdsDisconnected" class="content">
<template v-for="(pbd, index) in disconnectedPbds" :key="pbd.uuid">
<VtsDivider v-if="index > 0" class="divider" type="stretch" />
<UiPanelCardTitle size="small" :label="t('disconnected-pbd-number', { n: index + 1 })" class="subtitle" />
@@ -31,7 +31,7 @@
accent="info"
/>
</template>
</div>
</VtsCardRowList>
</template>
</UiPanelCard>
</template>
@@ -43,6 +43,7 @@ import { usePbdUtils } from '@/modules/storage-repository/composables/pbd-utils.
import { useSrUtils } from '@/modules/storage-repository/composables/sr-utils.composable.ts'
import type { SrScope } from '@core/types/storage-repository.type.ts'
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
import VtsCardRowList from '@core/components/card/VtsCardRowList.vue'
import VtsDivider from '@core/components/divider/VtsDivider.vue'
import VtsStateHero from '@core/components/state-hero/VtsStateHero.vue'
import VtsStatus from '@core/components/status/VtsStatus.vue'
@@ -70,10 +71,6 @@ const { areSomePbdsDisconnected, disconnectedPbds } = usePbdUtils(pbdsInScope)
<style scoped lang="postcss">
.storage-repository-pbds-card {
.content {
display: flex;
flex-direction: column;
gap: 0.4rem;
.subtitle {
margin-block-end: 0.4rem;
}

View File

@@ -7,7 +7,7 @@
>
{{ branch.data.name_label || '(Host)' }}
<template #icon>
<VtsObjectIcon v-tooltip="hostState" type="host" size="medium" :state="hostState" />
<VtsObjectIcon v-tooltip="powerState.text" type="host" size="medium" :state="hostState" />
</template>
<template #addons>
<UiLoader v-if="isChangingState" v-tooltip="currentOperation" />
@@ -19,18 +19,9 @@
size="small"
variant="secondary"
/>
<MenuList placement="bottom-start">
<template #trigger="{ open, isOpen }">
<UiButtonIcon
accent="brand"
icon="action:more-actions"
size="small"
:selected="isOpen"
@click="open($event)"
/>
</template>
<HostMoreActions :host="branch.data" show-change-state-button />
</MenuList>
<VtsActionsMenu placement="bottom-start">
<HostMoreActions :host="branch.data" show-change-state />
</VtsActionsMenu>
</template>
</UiTreeItemLabel>
</VtsTreeItem>
@@ -43,10 +34,9 @@ import type { HostBranch } from '@/modules/treeview/types/tree.type.ts'
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
import VtsIcon from '@core/components/icon/VtsIcon.vue'
import MenuList from '@core/components/menu/MenuList.vue'
import VtsActionsMenu from '@core/components/menu/VtsActionsMenu.vue'
import VtsObjectIcon from '@core/components/object-icon/VtsObjectIcon.vue'
import VtsTreeItem from '@core/components/tree/VtsTreeItem.vue'
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
import UiCounter from '@core/components/ui/counter/UiCounter.vue'
import UiLoader from '@core/components/ui/loader/UiLoader.vue'
import UiTreeItemLabel from '@core/components/ui/tree-item-label/UiTreeItemLabel.vue'
@@ -63,7 +53,8 @@ const { t } = useI18n()
const { isMasterHost } = usePoolStore().subscribe()
const { runningVmsCountByHostRef } = useVmStore().subscribe()
const { hostState, isChangingState, currentOperation } = useHostUtils(() => branch.data)
const { getHostStatus, hostState, isChangingState, currentOperation } = useHostUtils(() => branch.data)
const powerState = computed(() => getHostStatus(hostState.value))
const isMaster = computed(() => isMasterHost(branch.data.$ref))

View File

@@ -7,18 +7,9 @@
>
{{ branch.data.name_label || '(Pool)' }}
<template #addons>
<MenuList placement="bottom-start">
<template #trigger="{ open, isOpen }">
<UiButtonIcon
accent="brand"
icon="action:more-actions"
size="small"
:selected="isOpen"
@click="open($event)"
/>
</template>
<VtsActionsMenu placement="bottom-start">
<PoolTreeActions :pool="branch.data" />
</MenuList>
</VtsActionsMenu>
</template>
</UiTreeItemLabel>
</VtsTreeItem>
@@ -27,9 +18,8 @@
<script lang="ts" setup>
import PoolTreeActions from '@/modules/pool/components/actions/PoolTreeActions.vue'
import type { PoolBranch } from '@/modules/treeview/types/tree.type.ts'
import MenuList from '@core/components/menu/MenuList.vue'
import VtsActionsMenu from '@core/components/menu/VtsActionsMenu.vue'
import VtsTreeItem from '@core/components/tree/VtsTreeItem.vue'
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
import UiTreeItemLabel from '@core/components/ui/tree-item-label/UiTreeItemLabel.vue'
defineProps<{

View File

@@ -1,52 +1,40 @@
<template>
<VtsTreeItem expanded :node-id="leaf.dataId">
<VtsTreeItem :node-id="leaf.dataId" expanded>
<UiTreeItemLabel :route="{ name: '/vm/[uuid]', params: { uuid: leaf.data.uuid } }" no-indent>
{{ leaf.data.name_label || '(VM)' }}
<template #icon>
<VtsObjectIcon size="medium" :state="powerState" type="vm" />
<VtsObjectIcon v-tooltip="powerState.text" :state="vmState" size="medium" type="vm" />
</template>
<template #addons>
<UiLoader v-if="isChangingState" v-tooltip="{ placement: 'top', content: currentOperation }" />
<MenuList placement="bottom-start">
<template #trigger="{ open, isOpen }">
<UiButtonIcon
v-tooltip="{ placement: 'top', content: t('quick-actions') }"
icon="action:more-actions"
accent="brand"
size="small"
:selected="isOpen"
@click="open($event)"
/>
</template>
<VtsActionsMenu placement="bottom-start">
<VmTreeActions :vm-opaque-ref="leaf.data.$ref" />
</MenuList>
</VtsActionsMenu>
</template>
</UiTreeItemLabel>
</VtsTreeItem>
</template>
<script lang="ts" setup>
import type { VM_POWER_STATE } from '@/libs/xen-api/xen-api.enums.ts'
import type { VmLeaf } from '@/modules/treeview/types/tree.type.ts'
import VmTreeActions from '@/modules/vm/components/actions/VmTreeActions.vue'
import { useVmOperation } from '@/modules/vm/composables/vm-operation.composable.ts'
import MenuList from '@core/components/menu/MenuList.vue'
import { useVmUtils } from '@/modules/vm/composables/vm-utils.composable.ts'
import VtsActionsMenu from '@core/components/menu/VtsActionsMenu.vue'
import VtsObjectIcon from '@core/components/object-icon/VtsObjectIcon.vue'
import VtsTreeItem from '@core/components/tree/VtsTreeItem.vue'
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
import UiLoader from '@core/components/ui/loader/UiLoader.vue'
import UiTreeItemLabel from '@core/components/ui/tree-item-label/UiTreeItemLabel.vue'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import { toLower } from 'lodash-es'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { leaf } = defineProps<{
leaf: VmLeaf
}>()
const { t } = useI18n()
const { isChangingState, currentOperation } = useVmOperation(() => leaf.data)
const { powerState } = useVmUtils(() => leaf.data)
const powerState = computed(() => leaf.data.power_state.toLowerCase() as Lowercase<VM_POWER_STATE>)
const vmState = computed(() => toLower(leaf.data.power_state))
</script>

View File

@@ -3,7 +3,7 @@
<UiTitle>
{{ t('vdis') }}
</UiTitle>
<UiQuerySearchBar @search="(value: string) => (searchQuery = value)" />
<UiQuerySearchBar v-bind="searchBindings" />
<div class="container">
<VtsTable :state :pagination-bindings sticky="right">
<thead>
@@ -30,10 +30,11 @@ import UiQuerySearchBar from '@core/components/ui/query-search-bar/UiQuerySearch
import UiTitle from '@core/components/ui/title/UiTitle.vue'
import { usePagination } from '@core/composables/pagination.composable.ts'
import { useRouteQuery } from '@core/composables/route-query.composable.ts'
import { useSearchFilter } from '@core/composables/search-filter.composable.ts'
import { useTableState } from '@core/composables/table-state.composable.ts'
import { useVdiColumns } from '@core/tables/column-sets/vdi-columns.ts'
import { formatSizeRaw } from '@core/utils/size.util.ts'
import { computed, ref } from 'vue'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { vdis, vbds, busy, error } = defineProps<{
vdis: XenApiVdi[]
@@ -43,14 +44,7 @@ const { vdis, vbds, busy, error } = defineProps<{
}>()
const { t } = useI18n()
const selectedVdiId = useRouteQuery('id')
const searchQuery = ref('')
const filteredVdis = computed(() => {
const searchTerm = searchQuery.value.trim().toLocaleLowerCase()
if (!searchTerm) {
return vdis
}
return vdis.filter(vdi => Object.values(vdi).some(value => String(value).toLocaleLowerCase().includes(searchTerm)))
})
const { items: filteredVdis, searchBindings } = useSearchFilter(() => vdis)
const state = useTableState({
busy: () => busy,
error: () => error,

View File

@@ -1,7 +1,7 @@
<template>
<UiPanelCard class="card-container">
<UiPanelCardTitle size="medium" :label="t('configuration')" />
<div class="content">
<VtsCardRowList>
<VdiFormatCardItem :format="vdi.sm_config['image-format']" />
<VtsCardRowKeyValue>
<template #key>
@@ -43,7 +43,7 @@
<VtsStatus :status="isBootable" />
</template>
</VtsCardRowKeyValue>
</div>
</VtsCardRowList>
</UiPanelCard>
</template>
@@ -53,6 +53,7 @@ import type { XenApiVbd, XenApiVdi } from '@/libs/xen-api/xen-api.types.ts'
import VdiFormatCardItem from '@/modules/vdi/components/list/panel/card-items/VdiFormatCardItem.vue'
import { useSrStore } from '@/stores/xen-api/sr.store.ts'
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
import VtsCardRowList from '@core/components/card/VtsCardRowList.vue'
import VtsCopyButton from '@core/components/copy-button/VtsCopyButton.vue'
import VtsStatus from '@core/components/status/VtsStatus.vue'
import UiLink from '@core/components/ui/link/UiLink.vue'
@@ -73,11 +74,6 @@ const isBootable = computed(() => vbd?.bootable ?? false)
<style scoped lang="postcss">
.card-container {
.content {
display: flex;
flex-direction: column;
gap: 0.4rem;
}
.storage {
display: flex;
gap: 0.8rem;

View File

@@ -1,7 +1,7 @@
<template>
<UiPanelCard class="card-container">
<UiPanelCard>
<UiPanelCardTitle :id="vdi.uuid" size="medium" :label="vdi.name_label" :icon="vdiIcon" />
<div class="content">
<VtsCardRowList>
<VtsCardRowKeyValue truncate align-top>
<template #key>{{ t('description') }}</template>
<template #value>{{ vdi.name_description }}</template>
@@ -36,7 +36,7 @@
<VtsCopyButton :value="vbd.device" />
</template>
</VtsCardRowKeyValue>
</div>
</VtsCardRowList>
</UiPanelCard>
</template>
@@ -45,6 +45,7 @@ import type { XenApiVbd, XenApiVdi } from '@/libs/xen-api/xen-api.types.ts'
import { useVbdsStatus, type VbdAttachmentStatus } from '@/modules/vbd/composables/use-vbds-status.composable.ts'
import type { IconName } from '@core/icons'
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
import VtsCardRowList from '@core/components/card/VtsCardRowList.vue'
import VtsCopyButton from '@core/components/copy-button/VtsCopyButton.vue'
import VtsStatus from '@core/components/status/VtsStatus.vue'
import VtsTag from '@core/components/tag/VtsTag.vue'
@@ -79,13 +80,3 @@ const vbdsStatus = useMapper<VbdAttachmentStatus, (typeof CONNECTION_STATUS)[key
'noneAttached'
)
</script>
<style scoped lang="postcss">
.card-container {
.content {
display: flex;
flex-direction: column;
gap: 0.4rem;
}
}
</style>

View File

@@ -6,7 +6,7 @@
<slot name="title-actions" />
</template>
</UiTitle>
<UiQuerySearchBar @search="(value: string) => (searchQuery = value)" />
<UiQuerySearchBar v-bind="searchBindings" />
<VtsTable :state :pagination-bindings sticky="right">
<thead>
<tr>
@@ -35,6 +35,7 @@ import UiQuerySearchBar from '@core/components/ui/query-search-bar/UiQuerySearch
import UiTitle from '@core/components/ui/title/UiTitle.vue'
import { usePagination } from '@core/composables/pagination.composable.ts'
import { useRouteQuery } from '@core/composables/route-query.composable.ts'
import { useSearchFilter } from '@core/composables/search-filter.composable.ts'
import { useTableState } from '@core/composables/table-state.composable.ts'
import { useMapper } from '@core/packages/mapper'
import { type ActionItem } from '@core/tables/column-definitions/action-column.ts'
@@ -42,7 +43,7 @@ import { useVifColumns } from '@core/tables/column-sets/vif-columns.ts'
import { CONNECTION_ACTION } from '@core/types/connection.ts'
import { getUniqueIpAddressesForDevice } from '@core/utils/ip-address.utils.ts'
import { logicNot } from '@vueuse/math'
import { computed, ref } from 'vue'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { vifs, vm } = defineProps<{
@@ -72,21 +73,10 @@ const getIpAddresses = (vif: XenApiVif) => {
return getUniqueIpAddressesForDevice(networks, vif.device)
}
const searchQuery = ref('')
const filteredVifs = computed(() => {
const searchTerm = searchQuery.value.trim().toLocaleLowerCase()
if (!searchTerm) {
return vifs
}
return vifs.filter(vif =>
[...Object.values(vif), getNetworkName(vif.network)].some(value =>
String(value).toLocaleLowerCase().includes(searchTerm)
)
)
})
const { items: filteredVifs, searchBindings } = useSearchFilter(
() => vifs,
vif => [...Object.values(vif), getNetworkName(vif.network)]
)
const state = useTableState({
busy: logicNot(isReady),

View File

@@ -1,23 +1,21 @@
<template>
<UiButton
v-tooltip="!connection.canToggle && connection.errorMessage"
size="medium"
<VtsActionButton
:hint="connection.errorMessage"
variant="tertiary"
accent="brand"
:disabled="!connection.canToggle"
:left-icon="connection.icon"
:icon="connection.icon"
:busy="connection.isToggling"
@click="connection.toggle()"
>
{{ connection.label }}
</UiButton>
</VtsActionButton>
</template>
<script lang="ts" setup>
import type { XenApiVif, XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import { useVifConnection } from '@/modules/vif/composables/use-vif-connection.composable.ts'
import UiButton from '@core/components/ui/button/UiButton.vue'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import VtsActionButton from '@core/components/action-button/VtsActionButton.vue'
import { useMapper } from '@core/packages/mapper'
import { CONNECTION_ACTION } from '@core/types/connection.ts'
import { useI18n } from 'vue-i18n'

View File

@@ -1,13 +1,13 @@
<template>
<UiButton size="medium" variant="tertiary" accent="brand" left-icon="action:edit" @click="goToVifEdit(vif)">
<VtsActionButton variant="tertiary" accent="brand" icon="action:edit" @click="goToVifEdit(vif)">
{{ t('action:edit') }}
</UiButton>
</VtsActionButton>
</template>
<script lang="ts" setup>
import type { XenApiVif } from '@/libs/xen-api/xen-api.types.ts'
import { useVifEdit } from '@/modules/vif/composables/use-vif-edit.composable.ts'
import UiButton from '@core/components/ui/button/UiButton.vue'
import VtsActionButton from '@core/components/action-button/VtsActionButton.vue'
import { useI18n } from 'vue-i18n'
const { vif } = defineProps<{

View File

@@ -8,7 +8,7 @@
<!-- VIF -->
<UiPanelCard>
<UiPanelCardTitle :id="vif.uuid" size="medium" :label="t('vif')" />
<div class="content">
<VtsCardRowList>
<!-- NETWORK -->
<VtsCardRowKeyValue>
<template #key>
@@ -79,32 +79,15 @@
{{ isTxChecksummingEnabled(vif) }}
</template>
</VtsCardRowKeyValue>
</div>
</VtsCardRowList>
</UiPanelCard>
<!-- VIF NETWORK INFORMATION -->
<UiPanelCard>
<UiPanelCardTitle size="medium" :label="t('network-information')" />
<div class="content">
<VtsCardRowList>
<!-- IP ADDRESSES -->
<div v-if="ipAddresses.length">
<VtsCardRowKeyValue v-for="(ip, index) in ipAddresses" :key="ip">
<template #key>
<div v-if="index === 0">{{ t('ip-addresses') }}</div>
</template>
<template #value>{{ ip }}</template>
<template #addons>
<VtsCopyButton :value="ip" />
<VtsCopyAllMenuItem v-if="index === 0 && ipAddresses.length > 1" :values="ipAddresses" />
</template>
</VtsCardRowKeyValue>
</div>
<VtsCardRowKeyValue v-else>
<template #key>
{{ t('ip-addresses') }}
</template>
<template #value>
<span class="value" />
</template>
<VtsCardRowKeyValue :values="ipAddresses">
<template #key>{{ t('ip-addresses') }}</template>
</VtsCardRowKeyValue>
<!-- MAC ADDRESSES -->
<VtsCardRowKeyValue>
@@ -118,7 +101,7 @@
<VtsCopyButton :value="vif.MAC" />
</template>
</VtsCardRowKeyValue>
</div>
</VtsCardRowList>
</UiPanelCard>
</template>
</VtsSidePanel>
@@ -133,7 +116,7 @@ import { useNetworkStore } from '@/stores/xen-api/network.store.ts'
import { useVmGuestMetricsStore } from '@/stores/xen-api/vm-guest-metrics.store.ts'
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
import VtsCopyAllMenuItem from '@core/components/copy-all-menu-item/VtsCopyAllMenuItem.vue'
import VtsCardRowList from '@core/components/card/VtsCardRowList.vue'
import VtsCopyButton from '@core/components/copy-button/VtsCopyButton.vue'
import VtsSidePanel from '@core/components/panel/VtsSidePanel.vue'
import VtsStatus from '@core/components/status/VtsStatus.vue'
@@ -187,12 +170,6 @@ const rateLimit = computed(() => {
<style scoped lang="postcss">
.vm-vifs-side-panel {
.content {
display: flex;
flex-direction: column;
gap: 0.8rem;
}
.value:empty::before {
content: '-';
}

View File

@@ -1,10 +1,7 @@
<template>
<MenuItem accent="brand" icon="action:change-state">
{{ t('action:change-state') }}
<template #submenu>
<VmActionPowerStateItems :vm-refs />
</template>
</MenuItem>
<VtsChangeStateMenuItem>
<VmActionPowerStateItems :vm-refs />
</VtsChangeStateMenuItem>
<VmActionSnapshotItem :vm-refs />
<VmActionCopyItem :selected-refs="vmRefs" is-single-action />
<VmActionExportItem :vm-refs is-single-action />
@@ -19,16 +16,13 @@ import VmActionExportItem from '@/components/vm/VmActionItems/VmActionExportItem
import VmActionPowerStateItems from '@/components/vm/VmActionItems/VmActionPowerStateItems.vue'
import VmActionSnapshotItem from '@/components/vm/VmActionItems/VmActionSnapshotItem.vue'
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import MenuItem from '@core/components/menu/MenuItem.vue'
import MenuSeparator from '@core/components/menu/MenuSeparator.vue'
import VtsChangeStateMenuItem from '@core/components/menu/VtsChangeStateMenuItem.vue'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { vmOpaqueRef } = defineProps<{
vmOpaqueRef: XenApiVm['$ref']
}>()
const { t } = useI18n()
const vmRefs = computed(() => [vmOpaqueRef])
</script>

View File

@@ -17,7 +17,7 @@ export function useVmOperation(rawVm: MaybeRefOrGetter<XenApiVm | undefined>) {
const currentOperation = useMapper<string, string>(
() => Object.values(vm.value?.current_operations ?? {})[0],
{
() => ({
start: t('operation:start'),
start_on: t('operation:start-on-host'),
pause: t('operation:pause'),
@@ -36,7 +36,7 @@ export function useVmOperation(rawVm: MaybeRefOrGetter<XenApiVm | undefined>) {
export: t('operation:export'),
import: t('operation:import'),
unknown: '',
},
}),
'unknown'
)

View File

@@ -0,0 +1,28 @@
import { VM_POWER_STATE } from '@/libs/xen-api/xen-api.enums.ts'
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import type { IconName } from '@core/icons'
import { useMapper } from '@core/packages/mapper'
import { toComputed } from '@core/utils/to-computed.util.ts'
import type { MaybeRefOrGetter } from 'vue'
import { useI18n } from 'vue-i18n'
export function useVmUtils(rawVm: MaybeRefOrGetter<XenApiVm>) {
const { t } = useI18n()
const vm = toComputed(rawVm)
const powerState = useMapper<VM_POWER_STATE, { icon: IconName; text: string }>(
() => vm.value.power_state,
() => ({
[VM_POWER_STATE.RUNNING]: { icon: 'status:running-circle', text: t('vm:status:running') },
[VM_POWER_STATE.HALTED]: { icon: 'status:halted-circle', text: t('vm:status:halted') },
[VM_POWER_STATE.PAUSED]: { icon: 'status:paused-circle', text: t('vm:status:paused') },
[VM_POWER_STATE.SUSPENDED]: { icon: 'status:suspended-circle', text: t('vm:status:suspended') },
}),
VM_POWER_STATE.RUNNING
)
return {
powerState,
}
}

View File

@@ -3,9 +3,9 @@
<UiCard class="container">
<PoolNetworksTable :networks="networksWithPifs" :busy="!isReady" :error="hasError">
<template #title-actions>
<MenuList placement="bottom-end">
<VtsResponsiveMenu :title="t('new')" placement="bottom-end">
<template #trigger="{ open }">
<UiDropdownButton @click="open($event)">{{ t('new') }}</UiDropdownButton>
<UiDropdownButton size="medium" variant="primary" @click="open($event)">{{ t('new') }}</UiDropdownButton>
</template>
<MenuItem accent="neutral">
<UiLink class="new-network-link" :to="{ name: '/network/new' }" icon="fa:plus" size="medium">
@@ -17,7 +17,7 @@
{{ t('action:create-bonded-network') }}
</UiLink>
</MenuItem>
</MenuList>
</VtsResponsiveMenu>
</template>
</PoolNetworksTable>
<PoolHostInternalNetworksTable :networks="networksWithoutPifs">
@@ -41,7 +41,7 @@ import { usePageTitleStore } from '@/stores/page-title.store.ts'
import { useNetworkStore } from '@/stores/xen-api/network.store.ts'
import VtsContentSidePanel from '@core/components/layout/VtsContentSidePanel.vue'
import MenuItem from '@core/components/menu/MenuItem.vue'
import MenuList from '@core/components/menu/MenuList.vue'
import VtsResponsiveMenu from '@core/components/menu/VtsResponsiveMenu.vue'
import UiCard from '@core/components/ui/card/UiCard.vue'
import UiDropdownButton from '@core/components/ui/dropdown-button/UiDropdownButton.vue'
import UiLink from '@core/components/ui/link/UiLink.vue'
@@ -70,7 +70,7 @@ const selectedNetwork = useRouteQuery<XenApiNetwork | undefined>('id', {
}
.new-network-link {
height: 100%;
width: 100%;
flex-grow: 1;
padding-block: 1.2rem;
}
</style>

View File

@@ -296,6 +296,13 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/action-button/vts-action-button': RouteRecordInfo<
'/story/web-core/action-button/vts-action-button',
'/story/web-core/action-button/vts-action-button',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/banner/vts-banner': RouteRecordInfo<
'/story/web-core/banner/vts-banner',
'/story/web-core/banner/vts-banner',
@@ -317,6 +324,13 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/card/vts-card-row-list': RouteRecordInfo<
'/story/web-core/card/vts-card-row-list',
'/story/web-core/card/vts-card-row-list',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/cell-object/vts-cell-object': RouteRecordInfo<
'/story/web-core/cell-object/vts-cell-object',
'/story/web-core/cell-object/vts-cell-object',
@@ -366,6 +380,13 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/file-uploader-container/vts-file-uploader-container': RouteRecordInfo<
'/story/web-core/file-uploader-container/vts-file-uploader-container',
'/story/web-core/file-uploader-container/vts-file-uploader-container',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/form-error-summary/vts-form-error-summary': RouteRecordInfo<
'/story/web-core/form-error-summary/vts-form-error-summary',
'/story/web-core/form-error-summary/vts-form-error-summary',
@@ -422,6 +443,34 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/menu/vts-change-state-menu': RouteRecordInfo<
'/story/web-core/menu/vts-change-state-menu',
'/story/web-core/menu/vts-change-state-menu',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/menu/vts-change-state-menu-item': RouteRecordInfo<
'/story/web-core/menu/vts-change-state-menu-item',
'/story/web-core/menu/vts-change-state-menu-item',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/menu/vts-mobile-menu': RouteRecordInfo<
'/story/web-core/menu/vts-mobile-menu',
'/story/web-core/menu/vts-mobile-menu',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/menu/vts-responsive-menu': RouteRecordInfo<
'/story/web-core/menu/vts-responsive-menu',
'/story/web-core/menu/vts-responsive-menu',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/object-icon/vts-object-icon': RouteRecordInfo<
'/story/web-core/object-icon/vts-object-icon',
'/story/web-core/object-icon/vts-object-icon',
@@ -737,6 +786,27 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/ui/file-item/ui-file-item': RouteRecordInfo<
'/story/web-core/ui/file-item/ui-file-item',
'/story/web-core/ui/file-item/ui-file-item',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/ui/file-list/ui-file-list': RouteRecordInfo<
'/story/web-core/ui/file-list/ui-file-list',
'/story/web-core/ui/file-list/ui-file-list',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/ui/file-uploader/ui-file-uploader': RouteRecordInfo<
'/story/web-core/ui/file-uploader/ui-file-uploader',
'/story/web-core/ui/file-uploader/ui-file-uploader',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/ui/head-bar/ui-head-bar': RouteRecordInfo<
'/story/web-core/ui/head-bar/ui-head-bar',
'/story/web-core/ui/head-bar/ui-head-bar',
@@ -1367,6 +1437,12 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/stories/web-core/action-button/vts-action-button.story.vue': {
routes:
| '/story/web-core/action-button/vts-action-button'
views:
| never
}
'src/stories/web-core/banner/vts-banner.story.vue': {
routes:
| '/story/web-core/banner/vts-banner'
@@ -1385,6 +1461,12 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/stories/web-core/card/vts-card-row-list.story.vue': {
routes:
| '/story/web-core/card/vts-card-row-list'
views:
| never
}
'src/stories/web-core/cell-object/vts-cell-object.story.vue': {
routes:
| '/story/web-core/cell-object/vts-cell-object'
@@ -1427,6 +1509,12 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/stories/web-core/file-uploader-container/vts-file-uploader-container.story.vue': {
routes:
| '/story/web-core/file-uploader-container/vts-file-uploader-container'
views:
| never
}
'src/stories/web-core/form-error-summary/vts-form-error-summary.story.vue': {
routes:
| '/story/web-core/form-error-summary/vts-form-error-summary'
@@ -1475,6 +1563,30 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/stories/web-core/menu/vts-change-state-menu.story.vue': {
routes:
| '/story/web-core/menu/vts-change-state-menu'
views:
| never
}
'src/stories/web-core/menu/vts-change-state-menu-item.story.vue': {
routes:
| '/story/web-core/menu/vts-change-state-menu-item'
views:
| never
}
'src/stories/web-core/menu/vts-mobile-menu.story.vue': {
routes:
| '/story/web-core/menu/vts-mobile-menu'
views:
| never
}
'src/stories/web-core/menu/vts-responsive-menu.story.vue': {
routes:
| '/story/web-core/menu/vts-responsive-menu'
views:
| never
}
'src/stories/web-core/object-icon/vts-object-icon.story.vue': {
routes:
| '/story/web-core/object-icon/vts-object-icon'
@@ -1745,6 +1857,24 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/stories/web-core/ui/file-item/ui-file-item.story.vue': {
routes:
| '/story/web-core/ui/file-item/ui-file-item'
views:
| never
}
'src/stories/web-core/ui/file-list/ui-file-list.story.vue': {
routes:
| '/story/web-core/ui/file-list/ui-file-list'
views:
| never
}
'src/stories/web-core/ui/file-uploader/ui-file-uploader.story.vue': {
routes:
| '/story/web-core/ui/file-uploader/ui-file-uploader'
views:
| never
}
'src/stories/web-core/ui/head-bar/ui-head-bar.story.vue': {
routes:
| '/story/web-core/ui/head-bar/ui-head-bar'

View File

@@ -0,0 +1,39 @@
<template>
<ComponentStory
v-slot="{ properties, settings }"
:params="[
prop('variant')
.type('ButtonVariant')
.enum('primary', 'secondary', 'tertiary')
.preset('tertiary')
.required()
.widget(),
prop('accent').type('ButtonAccent').enum('brand', 'warning', 'danger').preset('brand').required().widget(),
iconProp().preset('action:connect'),
prop('disabled').bool().widget(),
prop('busy').bool().widget(),
prop('hint').str().preset('Already connected').widget().help('Shown when disabled'),
event('click'),
slot(),
setting('label').preset('Connect').widget(text()),
setting('inMenu').preset(false).widget(boolean()).help('Render the button inside a menu'),
]"
>
<MenuList v-if="settings.inMenu" placement="bottom-start">
<template #trigger="{ open }">
<UiButtonIcon accent="brand" icon="action:more-actions" size="medium" @click="open($event)" />
</template>
<VtsActionButton v-bind="properties">{{ settings.label }}</VtsActionButton>
</MenuList>
<VtsActionButton v-else v-bind="properties">{{ settings.label }}</VtsActionButton>
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { event, iconProp, prop, setting, slot } from '@/libs/story/story-param.ts'
import { boolean, text } from '@/libs/story/story-widget.ts'
import VtsActionButton from '@core/components/action-button/VtsActionButton.vue'
import MenuList from '@core/components/menu/MenuList.vue'
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
</script>

View File

@@ -3,7 +3,7 @@
v-slot="{ properties, settings }"
:params="[
slot('key').help('Meant to receive a title'),
slot('value').help('Meant to receive text, tags or other value'),
slot('value').help('Meant to receive text, tags or other value. Overrides the value rendered from `values`'),
slot('addons').help('Meant to receive icons or other actions buttons '),
prop('truncate')
.type('boolean | number')
@@ -21,6 +21,16 @@
.help('Whether to align the key on the first line in case of multiline value')
.type('boolean')
.widget(),
prop('values')
.help('Values rendered as text with a copy button each, plus a copy all action when there are several')
.type('string[]')
.widget(object())
.preset(['192.168.1.10', '192.168.1.11', '10.0.0.12', 'fe80::a00:27ff:fe4e:66a1']),
prop('maxVisibleValues')
.help('Number of values shown before a see more button')
.type('number')
.widget()
.preset(3),
setting('valueSlotDescription')
.preset(
'Lorem ipsum dolor sit, amet consectetur adipisicing elit. Velit facilis pariatur maiores officia fugit odit, doloremque obcaecati quisquam distinctio adipisci fugiat incidunt hic rerum? Ullam, natus. Iste eum porro dolorum!'
@@ -29,12 +39,16 @@
]"
>
<UiCard class="card">
<VtsCardRowKeyValue v-bind="properties">
<VtsCardRowKeyValue :values="properties.values" :max-visible-values="properties.maxVisibleValues">
<template #key>IP addresses</template>
</VtsCardRowKeyValue>
<VtsCardRowKeyValue v-bind="{ ...properties, values: undefined }">
<template #key>Description</template>
<template #value>{{ settings.valueSlotDescription }}</template>
</VtsCardRowKeyValue>
<VtsCardRowKeyValue v-bind="properties">
<VtsCardRowKeyValue v-bind="{ ...properties, values: undefined }">
<template #key>Network</template>
<template #value>
<UiObjectLink route="`/vm/test/console`" icon="object:network:connected">
@@ -46,7 +60,7 @@
</template>
</VtsCardRowKeyValue>
<VtsCardRowKeyValue v-bind="properties">
<VtsCardRowKeyValue v-bind="{ ...properties, values: undefined }">
<template #key>Status</template>
<template #value>
<UiInfo accent="success">Connected</UiInfo>
@@ -57,7 +71,7 @@
</template>
</VtsCardRowKeyValue>
<VtsCardRowKeyValue v-bind="{ ...properties, truncate: false }">
<VtsCardRowKeyValue v-bind="{ ...properties, truncate: false, values: undefined }">
<template #key>Tags</template>
<template #value>
<UiTagsList v-if="tags.length > 0">
@@ -75,7 +89,7 @@
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { prop, setting, slot } from '@/libs/story/story-param.ts'
import { choice, text } from '@/libs/story/story-widget.ts'
import { choice, object, text } from '@/libs/story/story-widget.ts'
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
import VtsCopyButton from '@core/components/copy-button/VtsCopyButton.vue'
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'

View File

@@ -0,0 +1,35 @@
<template>
<ComponentStory :params="[slot().help('Meant to receive VtsCardRowKeyValue components')]">
<UiCard class="card">
<VtsCardRowList>
<VtsCardRowKeyValue :values="['10.0.0.12']">
<template #key>IP address</template>
</VtsCardRowKeyValue>
<VtsCardRowKeyValue :values="['1500']">
<template #key>MTU</template>
</VtsCardRowKeyValue>
<VtsCardRowKeyValue>
<template #key>Status</template>
<template #value>
<UiInfo accent="success">Connected</UiInfo>
</template>
</VtsCardRowKeyValue>
</VtsCardRowList>
</UiCard>
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { slot } from '@/libs/story/story-param.ts'
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
import VtsCardRowList from '@core/components/card/VtsCardRowList.vue'
import UiCard from '@core/components/ui/card/UiCard.vue'
import UiInfo from '@core/components/ui/info/UiInfo.vue'
</script>
<style lang="postcss" scoped>
.card {
width: 400px;
}
</style>

View File

@@ -1,7 +1,10 @@
<template>
<ComponentStory
v-slot="{ properties }"
:params="[prop('value').type('string').preset('hello world').required().widget()]"
:params="[
prop('value').type('string').preset('hello world').required().widget(),
prop('label').str().widget().help('Tooltip shown before the copy, also used as the accessible name'),
]"
>
<VtsCopyButton v-bind="properties" />
</ComponentStory>

View File

@@ -0,0 +1,94 @@
<template>
<ComponentStory
v-slot="{ settings }"
:params="[
slot().help('Meant to receive a UiFileUploader component, inside a VtsInputWrapper in a form'),
slot('file-list').help('Meant to receive a UiFileList component'),
setting('multiple')
.widget(boolean())
.preset(true)
.help('When disabled, a new pick replaces the listed files: the replacement is up to the consumer'),
]"
>
<VtsFileUploaderContainer>
<VtsInputWrapper label="Upload images" :message="rejectionMessages">
<UiFileUploader
accent="neutral"
accept="image/*"
accept-label="PNG, JPG or GIF"
:multiple="settings.multiple"
:max-size="MAX_FILE_SIZE"
@select="files => addFiles(files, settings.multiple)"
@reject="rejections => showRejections(rejections)"
/>
</VtsInputWrapper>
<template #file-list>
<UiFileList>
<UiFileItem
v-for="storyFile of storyFiles"
:key="storyFile.file.name"
:file="storyFile.file"
:status="storyFile.status"
:error="storyFile.error"
@delete="deleteFile(storyFile.file)"
/>
</UiFileList>
</template>
</VtsFileUploaderContainer>
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { createStoryFile } from '@/libs/story/story-file.ts'
import { setting, slot } from '@/libs/story/story-param.ts'
import { boolean } from '@/libs/story/story-widget.ts'
import VtsFileUploaderContainer from '@core/components/file-uploader-container/VtsFileUploaderContainer.vue'
import VtsInputWrapper, { type InputWrapperMessage } from '@core/components/input-wrapper/VtsInputWrapper.vue'
import UiFileItem, { type FileUploadStatus } from '@core/components/ui/file-item/UiFileItem.vue'
import UiFileList from '@core/components/ui/file-list/UiFileList.vue'
import UiFileUploader, { type FileRejection } from '@core/components/ui/file-uploader/UiFileUploader.vue'
import { formatSize } from '@core/utils/size.util.ts'
import { ref } from 'vue'
type StoryFile = {
file: File
status: FileUploadStatus
error?: string[]
}
const MAX_FILE_SIZE = 2_000_000
const storyFiles = ref<StoryFile[]>([
{ file: createStoryFile('debian-12-generic-amd64.qcow2', 102_020_102), status: 'uploaded' },
{ file: createStoryFile('xcp-ng-8.3.0.iso', 681_574_400), status: 'uploading' },
{
file: createStoryFile('backup-metadata.json', 4_096),
status: 'error',
error: ['Upload failed: connection lost', 'Retried 3 times'],
},
])
const rejectionMessages = ref<InputWrapperMessage>([])
function addFiles(files: File[], multiple: boolean) {
const pickedFiles = files.map(file => ({ file, status: 'uploaded' }) satisfies StoryFile)
storyFiles.value = multiple ? [...storyFiles.value, ...pickedFiles] : pickedFiles
rejectionMessages.value = []
}
function showRejections(rejections: FileRejection[]) {
rejectionMessages.value = rejections.map(({ file, reason }) => ({
content:
reason === 'type'
? `${file.name}: file type not accepted`
: `${file.name}: file larger than ${formatSize(MAX_FILE_SIZE, 0)}`,
accent: 'danger' as const,
}))
}
function deleteFile(file: File) {
storyFiles.value = storyFiles.value.filter(storyFile => storyFile.file !== file)
}
</script>

View File

@@ -0,0 +1,26 @@
<template>
<ComponentStory :params="[slot().help('Power state actions, shown in the submenu')]">
<MenuList placement="bottom-start">
<template #trigger="{ open }">
<UiButtonIcon accent="brand" icon="action:more-actions" size="medium" @click="open($event)" />
</template>
<VtsChangeStateMenuItem>
<MenuItem accent="neutral" icon="fa:play" :on-click>Start</MenuItem>
<MenuItem accent="neutral" icon="fa:stop" :on-click>Shutdown</MenuItem>
</VtsChangeStateMenuItem>
</MenuList>
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { slot } from '@/libs/story/story-param.ts'
import MenuItem from '@core/components/menu/MenuItem.vue'
import MenuList from '@core/components/menu/MenuList.vue'
import VtsChangeStateMenuItem from '@core/components/menu/VtsChangeStateMenuItem.vue'
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
function onClick() {
return new Promise(resolve => setTimeout(resolve, 500))
}
</script>

View File

@@ -0,0 +1,25 @@
<template>
<ComponentStory
v-slot="{ properties }"
:params="[
prop('placement').str().preset('bottom-end').widget().help('Placement of the dropdown'),
slot().help('Power state actions'),
]"
>
<VtsChangeStateMenu v-bind="properties">
<MenuItem accent="neutral" icon="fa:play" :on-click>Start</MenuItem>
<MenuItem accent="neutral" icon="fa:stop" :on-click>Shutdown</MenuItem>
</VtsChangeStateMenu>
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { prop, slot } from '@/libs/story/story-param.ts'
import MenuItem from '@core/components/menu/MenuItem.vue'
import VtsChangeStateMenu from '@core/components/menu/VtsChangeStateMenu.vue'
function onClick() {
return new Promise(resolve => setTimeout(resolve, 500))
}
</script>

View File

@@ -0,0 +1,39 @@
<template>
<ComponentStory
v-slot="{ properties }"
:params="[
prop('title').str().required().preset('More actions').widget(),
prop('sectionTitle').str().preset('Actions').widget(),
event('action').help('Emitted when a menu item closes the menu after its action'),
slot('trigger').prop('open', '() => void').prop('isOpen', 'boolean'),
slot().help('Menu items, a submenu opens in place'),
]"
>
<VtsMobileMenu v-bind="properties">
<template #trigger="{ open }">
<UiButtonIcon accent="brand" icon="action:more-actions" size="medium" @click="open()" />
</template>
<MenuItem accent="brand" icon="action:change-state">
Change state
<template #submenu>
<MenuItem accent="neutral" icon="fa:play" :on-click>Start</MenuItem>
<MenuItem accent="neutral" icon="fa:stop" :on-click>Shutdown</MenuItem>
</template>
</MenuItem>
<MenuItem accent="neutral" icon="action:copy" :on-click>Copy</MenuItem>
<MenuItem accent="danger" icon="action:delete" :on-click>Delete</MenuItem>
</VtsMobileMenu>
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { event, prop, slot } from '@/libs/story/story-param.ts'
import MenuItem from '@core/components/menu/MenuItem.vue'
import VtsMobileMenu from '@core/components/menu/VtsMobileMenu.vue'
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
function onClick() {
return new Promise(resolve => setTimeout(resolve, 500))
}
</script>

View File

@@ -0,0 +1,36 @@
<template>
<ComponentStory
v-slot="{ properties }"
:params="[
prop('title').str().required().preset('New').widget().help('Title of the full page menu on mobile'),
prop('sectionTitle').str().widget().help('Section title of the full page menu on mobile'),
prop('placement').str().preset('bottom-start').widget().help('Placement of the dropdown on desktop'),
prop('disabled').bool().widget(),
event('action').help('Emitted on mobile when a menu item closes the menu after its action'),
slot('trigger').prop('open', '(event: MouseEvent) => void').prop('isOpen', 'boolean'),
slot().help('Menu items'),
]"
>
<VtsResponsiveMenu v-bind="properties">
<template #trigger="{ open, isOpen }">
<UiDropdownButton variant="primary" size="medium" :selected="isOpen" @click="open($event)">
New
</UiDropdownButton>
</template>
<MenuItem accent="neutral" icon="fa:plus" :on-click>Create network</MenuItem>
<MenuItem accent="neutral" icon="fa:plus" :on-click>Create bonded network</MenuItem>
</VtsResponsiveMenu>
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { event, prop, slot } from '@/libs/story/story-param.ts'
import MenuItem from '@core/components/menu/MenuItem.vue'
import VtsResponsiveMenu from '@core/components/menu/VtsResponsiveMenu.vue'
import UiDropdownButton from '@core/components/ui/dropdown-button/UiDropdownButton.vue'
function onClick() {
return new Promise(resolve => setTimeout(resolve, 500))
}
</script>

View File

@@ -11,7 +11,7 @@
event('close').args({}).help('Emitted when the user clicks the close button'),
slot(),
slot('header').help('Meant to receive text or other information'),
slot('actions').help('For the main action buttons'),
slot('actions').help('For the main action buttons, moved into the more actions menu when they do not fit'),
slot('more-actions').help('For other action buttons, shown in a dropdown menu'),
slot('corner-actions').help('For action icon buttons, like the pin button on VtsSidePanel'),
setting('headerText').widget(text()),
@@ -29,15 +29,15 @@
<span>{{ settings.headerText }}</span>
</template>
<template v-if="settings.showButtons" #actions>
<UiButton variant="tertiary" size="medium" accent="brand" left-icon="action:edit">Edit</UiButton>
<UiButton variant="tertiary" size="medium" accent="danger" left-icon="action:delete">Delete</UiButton>
<VtsActionButton variant="tertiary" accent="brand" icon="action:edit">Edit</VtsActionButton>
<VtsActionButton variant="tertiary" accent="danger" icon="action:delete">Delete</VtsActionButton>
</template>
<template v-if="settings.showMoreButtons" #more-actions>
<UiButton variant="tertiary" size="medium" accent="warning" left-icon="action:disconnect">
<MenuItem accent="warning" icon="action:disconnect">
Disconnect<UiCounter value="3" accent="warning" variant="primary" size="small" />
</UiButton>
<UiButton variant="tertiary" size="medium" accent="brand" left-icon="action:copy">Copy</UiButton>
<UiButton variant="tertiary" size="medium" accent="brand" left-icon="action:download">Download</UiButton>
</MenuItem>
<MenuItem accent="neutral" icon="action:copy">Copy</MenuItem>
<MenuItem accent="neutral" icon="action:download">Download</MenuItem>
</template>
<template #default>
<VtsStateHero v-if="settings.showHero" format="card" :type="settings.heroType" size="medium" />
@@ -53,9 +53,10 @@
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { event, iconProp, prop, setting, slot } from '@/libs/story/story-param.ts'
import { boolean, choice, text } from '@/libs/story/story-widget.ts'
import VtsActionButton from '@core/components/action-button/VtsActionButton.vue'
import MenuItem from '@core/components/menu/MenuItem.vue'
import VtsPanel from '@core/components/panel/VtsPanel.vue'
import VtsStateHero from '@core/components/state-hero/VtsStateHero.vue'
import UiButton from '@core/components/ui/button/UiButton.vue'
import UiCounter from '@core/components/ui/counter/UiCounter.vue'
import UiPanelCard from '@core/components/ui/panel-card/UiPanelCard.vue'
import { STATE_HERO_TYPES } from '@core/types/state-hero.type.ts'

View File

@@ -1,7 +1,11 @@
<template>
<ComponentStory
v-slot="{ properties }"
:params="[prop('disabled').bool().widget(), slot().help('Contains <RouterTab> or <UiTabItem>')]"
:params="[
prop('label').str().widget().preset('Tabs'),
prop('disabled').bool().widget(),
slot().help('Contains <RouterTab> or <UiTabItem>'),
]"
>
<TabList v-bind="properties">
<UiTabItem>Foo</UiTabItem>

View File

@@ -1,5 +1,11 @@
<template>
<ComponentStory v-slot="{ properties }" :params="[iconProp().preset('object:host').required()]">
<ComponentStory
v-slot="{ properties }"
:params="[
iconProp().preset('object:host').required(),
prop('size').enum('small', 'medium').preset('medium').widget(),
]"
>
<VtsTreeList>
<VtsTreeLoadingItem v-bind="properties" />
</VtsTreeList>
@@ -8,7 +14,7 @@
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { iconProp } from '@/libs/story/story-param.ts'
import { iconProp, prop } from '@/libs/story/story-param.ts'
import VtsTreeList from '@core/components/tree/VtsTreeList.vue'
import VtsTreeLoadingItem from '@core/components/tree/VtsTreeLoadingItem.vue'
</script>

View File

@@ -7,7 +7,10 @@
prop('size').required().enum('small', 'medium', 'large').preset('medium').widget(),
prop('disabled').bool().widget(),
prop('selected').bool().widget(),
prop('dot').bool().widget(),
prop('counter')
.type('CounterValue | { value: CounterValue; accent: CounterAccent }')
.widget(object())
.help('Info accent by default'),
prop('targetScale')
.type('number | { x: number; y: number }')
.default(1)
@@ -15,6 +18,32 @@
.help('Meant to increase click target size if needed')
.widget(),
]"
:presets="{
'No counter': {
props: {
icon: 'fa:bars-progress',
counter: undefined,
},
},
'Number counter': {
props: {
icon: 'fa:bars-progress',
counter: 6,
},
},
'Percentage (warning)': {
props: {
icon: 'fa:bars-progress',
counter: { value: '42%', accent: 'warning' },
},
},
'Exclamation mark (danger)': {
props: {
icon: 'fa:bars-progress',
counter: { value: '!', accent: 'danger' },
},
},
}"
>
<UiButtonIcon v-bind="properties" />
</ComponentStory>
@@ -23,5 +52,6 @@
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { iconProp, prop } from '@/libs/story/story-param.ts'
import { object } from '@/libs/story/story-widget.ts'
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
</script>

View File

@@ -5,11 +5,15 @@
iconProp(),
prop('selected').bool().widget(),
prop('disabled').bool().widget().ctx(),
prop('variant').enum('primary', 'secondary').preset('primary').widget().required(),
prop('size').enum('small', 'medium').preset('medium').widget().required(),
slot(),
setting('defaultSlotContent').preset('Dropdown title').widget(text()).help('Content for default slot'),
]"
>
<UiDropdownButton v-bind="properties">{{ settings.defaultSlotContent }}</UiDropdownButton>
<UiDropdownButton v-bind="properties">
{{ settings.defaultSlotContent }}
</UiDropdownButton>
</ComponentStory>
</template>

View File

@@ -0,0 +1,75 @@
<template>
<ComponentStory
v-slot="{ properties, settings }"
:params="[
prop('file').type('File').required().help('Only `name` and `size` are read. Driven by the story settings tab'),
prop('status').enum('uploading', 'uploaded', 'error').required().preset('uploading').widget(),
prop('error')
.type('MaybeArray<string>')
.widget(object())
.help('Displayed below the file as a danger message, one line per message, whatever the status'),
event('retry').help('Emitted when the user clicks the Retry button, only shown when status is `error`'),
event('cancel').help('Emitted when the user clicks the cancel button, only shown when status is `uploading`'),
event('delete').help('Emitted when the user clicks the delete button, only shown when status is `uploaded`'),
setting('fileName')
.widget(text())
.preset('debian-12-generic-amd64.qcow2')
.help('Names too long for the available width are truncated in the middle, keeping the extension visible'),
setting('fileSize')
.widget(number())
.preset(DEFAULT_FILE_SIZE)
.help('File size in bytes. Only displayed when status is `uploaded`'),
]"
:presets
>
<ul>
<UiFileItem v-bind="properties" :file="createStoryFile(settings.fileName, settings.fileSize)" />
</ul>
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { createStoryFile } from '@/libs/story/story-file.ts'
import { event, prop, setting } from '@/libs/story/story-param.ts'
import { number, object, text } from '@/libs/story/story-widget.ts'
import UiFileItem from '@core/components/ui/file-item/UiFileItem.vue'
const DEFAULT_FILE_SIZE = 102_020_102
const presets = {
Uploading: {
props: {
status: 'uploading',
error: undefined,
},
},
Uploaded: {
props: {
status: 'uploaded',
error: undefined,
},
},
'Failed with a message': {
props: {
status: 'error',
error: 'File size exceeds 5 MB',
},
},
'Failed with several messages': {
props: {
status: 'error',
error: ['File size exceeds 5 MB', 'File type not accepted'],
},
},
'Truncated file name': {
props: {
status: 'uploaded',
error: undefined,
},
settings: {
fileName: 'a-very-long-file-name-that-only-gets-truncated-when-the-available-width-is-too-small.qcow2',
},
},
}
</script>

View File

@@ -0,0 +1,37 @@
<template>
<ComponentStory :params="[slot().help('Meant to receive UiFileItem components')]">
<UiFileList>
<UiFileItem
v-for="storyFile of storyFiles"
:key="storyFile.file.name"
:file="storyFile.file"
:status="storyFile.status"
:error="storyFile.error"
/>
</UiFileList>
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { createStoryFile } from '@/libs/story/story-file.ts'
import { slot } from '@/libs/story/story-param.ts'
import UiFileItem, { type FileUploadStatus } from '@core/components/ui/file-item/UiFileItem.vue'
import UiFileList from '@core/components/ui/file-list/UiFileList.vue'
type StoryFile = {
file: File
status: FileUploadStatus
error?: string
}
const storyFiles: StoryFile[] = [
{ file: createStoryFile('debian-12-generic-amd64.qcow2', 102_020_102), status: 'uploaded' },
{ file: createStoryFile('xcp-ng-8.3.0.iso', 681_574_400), status: 'uploading' },
{
file: createStoryFile('backup-metadata.json', 4_096),
status: 'error',
error: 'Upload failed: connection lost',
},
]
</script>

View File

@@ -0,0 +1,94 @@
<template>
<ComponentStory
v-slot="{ properties, settings }"
:params="[
prop('accent')
.enum('neutral', 'warning', 'danger')
.required()
.preset('neutral')
.widget()
.help('Overridden by the accent of the parent VtsInputWrapper when that one is not neutral'),
prop('maxSize').num().widget().help('Maximum file size in bytes. Larger files are rejected'),
prop('accept')
.type('MaybeArray<string>')
.default('*/*')
.widget(
choice(
{ label: 'Any file type', value: '*/*' },
{ label: 'Images', value: 'image/*' },
{ label: 'JSON files', value: '.json' },
{ label: 'Images and JSON files', value: ['image/*', '.json'] }
)
)
.help('A single MIME type or extension, or a list of them. Non-matching files are rejected'),
prop('acceptLabel')
.str()
.widget()
.help(
'Readable list of the accepted types shown in the hint. Falls back to `Any file type` or the raw `accept` list'
),
prop('multiple').bool().widget().help('When disabled, only the first accepted file is emitted'),
prop('required').bool().widget().help('Displayed by the label of the parent VtsInputWrapper'),
prop('disabled').bool().widget().ctx(),
event('select').args({ files: 'File[]' }).help('Emitted with the accepted files picked or dropped'),
event('reject')
.args({ rejections: 'FileRejection[]' })
.help('Emitted with the files rejected because of their type or size, with the reason'),
setting('label').widget(text()).preset('Upload files').help('Label of the parent VtsInputWrapper'),
setting('message')
.widget(object())
.preset([])
.help(
'Message of the parent VtsInputWrapper (InputWrapperMessage). A danger message turns the uploader danger'
),
]"
:presets
>
<VtsInputWrapper :label="settings.label" :message="settings.message">
<UiFileUploader v-bind="properties" />
</VtsInputWrapper>
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { event, prop, setting } from '@/libs/story/story-param.ts'
import { choice, object, text } from '@/libs/story/story-widget.ts'
import VtsInputWrapper from '@core/components/input-wrapper/VtsInputWrapper.vue'
import UiFileUploader from '@core/components/ui/file-uploader/UiFileUploader.vue'
const presets = {
'Multiple images, max 2 MB': {
props: {
accept: 'image/*',
acceptLabel: 'PNG, JPG or GIF',
multiple: true,
maxSize: 2_000_000,
},
settings: {
label: 'Upload images',
},
},
'Single required file': {
props: {
accept: '.json',
acceptLabel: 'JSON',
multiple: false,
required: true,
},
settings: {
label: 'Upload a configuration file',
},
},
'With a danger message': {
settings: {
message: [{ content: 'A file is required', accent: 'danger' }],
},
},
Disabled: {
props: {
disabled: true,
},
},
}
</script>

View File

@@ -4,7 +4,10 @@
:params="[
prop('accent').enum('info', 'success', 'warning', 'danger', 'muted').required().preset('info').widget(),
prop('wrap').bool().help('Choose if the text should wrap if too long').widget(),
prop('size').enum('small', 'medium').preset('medium').widget(),
prop('size')
.enum('small', 'medium')
.help('Text size only, the icon is always medium. Defaults to small inside a VtsSidePanel, medium elsewhere')
.widget(),
slot(),
setting('defaultSlot').widget(text()).preset('message'),
]"

View File

@@ -13,6 +13,7 @@
choice({ label: 'Search', value: 'fa:magnifying-glass' }, { label: 'AngleDown', value: 'fa:angle-down' })
),
prop('clearable').bool().widget(),
prop('busy').bool().widget(),
prop('prefix').str().widget(),
prop('suffix').str().widget(),
prop('disabled').bool().widget(),

View File

@@ -1,6 +1,9 @@
<template>
<ComponentStory v-slot="{ properties }" :params="[event('search').args({ value: 'string' })]">
<UiQuerySearchBar id="search-bar" v-bind="properties" @search="(value: string) => (filter = value)" />
<ComponentStory
v-slot="{ properties }"
:params="[model().type('string').required(), prop('busy').bool().widget(), event('search')]"
>
<UiQuerySearchBar id="search-bar" v-bind="properties" v-model="filter" :busy="properties.busy || isSearching" />
<p class="text">Example data:</p>
<ul class="data-list">
@@ -11,7 +14,7 @@
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { event } from '@/libs/story/story-param.ts'
import { event, model, prop } from '@/libs/story/story-param.ts'
import UiQuerySearchBar from '@core/components/ui/query-search-bar/UiQuerySearchBar.vue'
import { useTreeFilter } from '@core/composables/tree-filter.composable.ts'
import { defineTree } from '@core/packages/tree/define-tree.ts'
@@ -120,7 +123,7 @@ const data = [
},
]
const { filter, predicate } = useTreeFilter()
const { filter, predicate, isSearching } = useTreeFilter()
const definitions = defineTree('vms', data, {
getLabel: 'name_label',

View File

@@ -9,6 +9,7 @@
.preset({ name: '/pool/[uuid]', params: { uuid: '355ee47d-ff4c-4924-3db2-fd86ae629676' } })
.widget(),
prop('active').bool().widget(),
prop('size').enum('small', 'medium').preset('medium').widget(),
prop('no-indent').bool().help('Remove indentation based on component depth in the tree'),
slot('default'),
slot('icon').help('Meant to receive a VtsIcon or another icon component in case the icon prop is not used'),

View File

@@ -423,6 +423,19 @@ export default class Backups {
},
},
],
purgeVmBackupsJournal: [
// `before` is computed by the caller: the horizon is the one of XO, whatever the clock of this proxy
({ remote, before }) =>
Disposable.use(this.getAdapter(remote), adapter => adapter.purgeBackupJournal(before)),
{
description: 'remove the days of the backup journal of a remote before the one of a date',
params: {
remote: { type: 'object' },
// timestamp in ms
before: { type: 'number' },
},
},
],
restoreMetadataBackup: [
({ backupId, remote, xapi: xapiOptions }) =>
Disposable.use(app.remotes.getHandler(remote), xapiOptions && this.getXapi(xapiOptions), (handler, xapi) =>

View File

@@ -53,6 +53,16 @@ The following are required only for mirror backup tests (`qa:mirror`):
| `MIRROR_DESTINATION_REPOSITORY_NAME` | Mirror destination repository name | `Test mirror QA` |
| `MIRROR_DESTINATION_REPOSITORY_URL` | `@xen-orchestra/fs` URL for the mirror destination. Same backend flexibility as `BACKUP_REPOSITORY_URL`. | `file:///tmp/xo-test-mirror` |
The following are optional, for the VM folder lock tests (`qa:backup:lock`), which skip a backend whose URL is unset.
The machine running the suite must reach these repositories as XO does.
| Variable | Description | Example |
| ------------------------------ | --------------------------------------------- | --------------------------------------------------------------------------------- |
| `S3_BACKUP_REPOSITORY_NAME` | S3 backup repository name in XO | `Test backup QA S3` |
| `S3_BACKUP_REPOSITORY_URL` | `@xen-orchestra/fs` URL of an S3 bucket | `s3://<access key>:<secret key>@<host>/<bucket>/<directory>` |
| `AZURE_BACKUP_REPOSITORY_NAME` | Azure backup repository name in XO | `Test backup QA Azure` |
| `AZURE_BACKUP_REPOSITORY_URL` | `@xen-orchestra/fs` URL of an Azure container | `azure://<account>:<key>@<account>.blob.core.windows.net/<container>/<directory>` |
The following are optional, for load tests (disk churn via SSH). Leave `TEST_VM_SSH_KEY` unset
to let `ssh` fall back to its own default identity files / `ssh-agent`:
@@ -86,6 +96,7 @@ Log namespaces follow the pattern `qa:<suite>[:<variant>]`:
| `qa:backup:base` | `tests/backup.test.js` |
| `qa:backup:nbd` | `tests/backup.nbd.test.js` |
| `qa:backup:combined` | `tests/backup-replication-combined.test.js` |
| `qa:backup:lock` | `tests/backup.lock.test.js` |
| `qa:mirror` | `tests/backup-mirror.test.js` |
| `qa:export` | `tests/export.vhd.test.js` |
| `qa:load:backup:delta` | `scripts/backup-load-delta.mjs` |
@@ -106,9 +117,15 @@ yarn workspace @xen-orchestra/qa-test qa:vm # VM lifecycle (clone
yarn workspace @xen-orchestra/qa-test qa:backup # Full and delta backup
yarn workspace @xen-orchestra/qa-test qa:backup:nbd # Backup with NBD protocol
yarn workspace @xen-orchestra/qa-test qa:backup:combined # Advanced scenarios (replication + backup)
yarn workspace @xen-orchestra/qa-test qa:backup:lock # VM backup folder lock (S3 and Azure only)
yarn workspace @xen-orchestra/qa-test qa:export # VHD/XVA export and restoration
```
`qa:backup:lock` locks the backup folder of its test VM itself, from the machine running the suite, and checks that
a backup of the VM fails while the folder is locked, and that XO releases its own lock at the end of a backup. It runs
once per repository set in `S3_BACKUP_REPOSITORY_URL` and `AZURE_BACKUP_REPOSITORY_URL` (see above), and skips on an
S3 bucket which XO does not lock (Object Lock).
### Test subsets
```bash
@@ -163,8 +180,8 @@ yarn workspace @xen-orchestra/qa-test demo
├── backup.config.js # Backup job configuration generator
├── client/
│ ├── dispatchClient.js # Central hub: orchestrates connections and handlers
│ ├── restApiClient.js # HTTP REST API client (reads)
│ ├── xoLibClient.js # WebSocket connection via xo-lib (writes)
│ ├── restApiClient.js # HTTP REST API client
│ ├── xoLibClient.js # WebSocket connection via xo-lib (writes not in REST)
│ ├── cleanupClient.js # Automatic test resource cleanup
│ ├── FilterBuilder.js # REST API filter builder
│ └── requests/ # Specialized handlers per resource
@@ -200,8 +217,8 @@ yarn workspace @xen-orchestra/qa-test demo
The `DispatchClient` is the main entry point. It orchestrates:
- **REST API** (`restApiClient`) for reads (GET)
- **WebSocket** (`xoLibClient` via `xo-lib`) for writes (JSON-RPC calls)
- **REST API** (`restApiClient`) for reads (GET) and the writes it supports, e.g. creating, updating, deleting and running backup jobs and schedules
- **WebSocket** (`xoLibClient` via `xo-lib`) for the writes not yet exposed by the REST API (JSON-RPC calls)
Each handler in `requests/` extends `AbstractRequest` which provides generic CRUD operations with a REST-first approach.

View File

@@ -31,6 +31,19 @@ BACKUP_REPOSITORY_URL="file:///tmp/xo-test-backups"
MIRROR_DESTINATION_REPOSITORY_NAME=Test mirror QA
MIRROR_DESTINATION_REPOSITORY_URL="file:///tmp/xo-test-mirror"
# ===========================================
# S3 AND AZURE BACKUP REPOSITORY CONFIGURATION
# ===========================================
# Optional repositories for the VM folder lock tests (qa:backup:lock), which skip
# a backend whose URL is unset. The suite locks a VM's backup folder itself, so
# the machine running it must reach these repositories as XO does.
# use " around the url to handle # escaping
S3_BACKUP_REPOSITORY_NAME=Test backup QA S3
S3_BACKUP_REPOSITORY_URL= # e.g. "s3://<access key>:<secret key>@<host>/<bucket>/<directory>"
AZURE_BACKUP_REPOSITORY_NAME=Test backup QA Azure
AZURE_BACKUP_REPOSITORY_URL= # e.g. "azure://<account>:<key>@<account>.blob.core.windows.net/<container>/<directory>"
# ===========================================
# REPLICATION TEST CONFIGURATION
# ===========================================
@@ -75,7 +88,7 @@ VHD_EXPORT_PATH=/tmp/xo-test-exports
# The source VM must be RUNNING and have NO SNAPSHOT: the test migrates a live VM and checks
# that XO takes its own snapshot. It leaves the VM halted, with that snapshot — restart is
# automatic, but the snapshot has to be removed by hand before the next run.
# ESXI_VM_ID is the VMware MoRef id (a number, as shown by esxi.listVms), not a UUID.
# ESXI_VM_ID is the VMware MoRef id (as listed by POST /rest/v0/v2v/inventory or esxi.listVms), not a UUID.
ESXI_HOST=
ESXI_USER=root
ESXI_PASSWORD=

View File

@@ -61,6 +61,16 @@ The following are required only for mirror backup tests (`qa:mirror`):
| `MIRROR_DESTINATION_REPOSITORY_NAME` | Mirror destination repository name | `Test mirror QA` |
| `MIRROR_DESTINATION_REPOSITORY_URL` | `@xen-orchestra/fs` URL for the mirror destination. Same backend flexibility as `BACKUP_REPOSITORY_URL`. | `file:///tmp/xo-test-mirror` |
The following are optional, for the VM folder lock tests (`qa:backup:lock`), which skip a backend whose URL is unset.
The machine running the suite must reach these repositories as XO does.
| Variable | Description | Example |
| ------------------------------ | --------------------------------------------- | --------------------------------------------------------------------------------- |
| `S3_BACKUP_REPOSITORY_NAME` | S3 backup repository name in XO | `Test backup QA S3` |
| `S3_BACKUP_REPOSITORY_URL` | `@xen-orchestra/fs` URL of an S3 bucket | `s3://<access key>:<secret key>@<host>/<bucket>/<directory>` |
| `AZURE_BACKUP_REPOSITORY_NAME` | Azure backup repository name in XO | `Test backup QA Azure` |
| `AZURE_BACKUP_REPOSITORY_URL` | `@xen-orchestra/fs` URL of an Azure container | `azure://<account>:<key>@<account>.blob.core.windows.net/<container>/<directory>` |
The following are optional, for load tests (disk churn via SSH). Leave `TEST_VM_SSH_KEY` unset
to let `ssh` fall back to its own default identity files / `ssh-agent`:
@@ -94,6 +104,7 @@ Log namespaces follow the pattern `qa:<suite>[:<variant>]`:
| `qa:backup:base` | `tests/backup.test.js` |
| `qa:backup:nbd` | `tests/backup.nbd.test.js` |
| `qa:backup:combined` | `tests/backup-replication-combined.test.js` |
| `qa:backup:lock` | `tests/backup.lock.test.js` |
| `qa:mirror` | `tests/backup-mirror.test.js` |
| `qa:export` | `tests/export.vhd.test.js` |
| `qa:load:backup:delta` | `scripts/backup-load-delta.mjs` |
@@ -114,9 +125,15 @@ yarn workspace @xen-orchestra/qa-test qa:vm # VM lifecycle (clone
yarn workspace @xen-orchestra/qa-test qa:backup # Full and delta backup
yarn workspace @xen-orchestra/qa-test qa:backup:nbd # Backup with NBD protocol
yarn workspace @xen-orchestra/qa-test qa:backup:combined # Advanced scenarios (replication + backup)
yarn workspace @xen-orchestra/qa-test qa:backup:lock # VM backup folder lock (S3 and Azure only)
yarn workspace @xen-orchestra/qa-test qa:export # VHD/XVA export and restoration
```
`qa:backup:lock` locks the backup folder of its test VM itself, from the machine running the suite, and checks that
a backup of the VM fails while the folder is locked, and that XO releases its own lock at the end of a backup. It runs
once per repository set in `S3_BACKUP_REPOSITORY_URL` and `AZURE_BACKUP_REPOSITORY_URL` (see above), and skips on an
S3 bucket which XO does not lock (Object Lock).
### Test subsets
```bash
@@ -171,8 +188,8 @@ yarn workspace @xen-orchestra/qa-test demo
├── backup.config.js # Backup job configuration generator
├── client/
│ ├── dispatchClient.js # Central hub: orchestrates connections and handlers
│ ├── restApiClient.js # HTTP REST API client (reads)
│ ├── xoLibClient.js # WebSocket connection via xo-lib (writes)
│ ├── restApiClient.js # HTTP REST API client
│ ├── xoLibClient.js # WebSocket connection via xo-lib (writes not in REST)
│ ├── cleanupClient.js # Automatic test resource cleanup
│ ├── FilterBuilder.js # REST API filter builder
│ └── requests/ # Specialized handlers per resource
@@ -208,8 +225,8 @@ yarn workspace @xen-orchestra/qa-test demo
The `DispatchClient` is the main entry point. It orchestrates:
- **REST API** (`restApiClient`) for reads (GET)
- **WebSocket** (`xoLibClient` via `xo-lib`) for writes (JSON-RPC calls)
- **REST API** (`restApiClient`) for reads (GET) and the writes it supports, e.g. creating, updating, deleting and running backup jobs and schedules
- **WebSocket** (`xoLibClient` via `xo-lib`) for the writes not yet exposed by the REST API (JSON-RPC calls)
Each handler in `requests/` extends `AbstractRequest` which provides generic CRUD operations with a REST-first approach.

View File

@@ -303,30 +303,14 @@ export class CleanupClient {
}
}
// Mirror backup jobs require mirrorBackup.deleteJob, standard jobs use backupNg.deleteJob.
// The REST API may not expose the type field for mirror jobs, so fall back when backupNg
// returns "no such job" (error.data.type === 'job').
if (job.type === 'mirrorBackup') {
await this.dispatchClient.backup.deleteMirrorBackupJob(job.id)
} else {
try {
await this.dispatchClient.backup.deleteBackupJob(job.id)
} catch (error) {
if (error?.data?.type !== 'job') {
throw error
}
// backupNg doesn't know this job — may be a mirror backup job; try the mirror method
try {
await this.dispatchClient.backup.deleteMirrorBackupJob(job.id)
} catch (mirrorError) {
if (mirrorError?.data?.type === 'job') {
// Job is unreachable through both RPCs (orphaned from a previous run) — skip silently
log.debug('Backup job not found via any delete method, skipping', { jobId: job.id })
return
}
throw mirrorError
}
// the REST API deletes any type of backup job, along with its schedules
try {
await this.dispatchClient.backup.deleteBackupJob(job.id)
} catch (error) {
if (error.status !== 404) {
throw error
}
log.debug('Backup job already deleted, skipping', { jobId: job.id })
}
}
@@ -355,9 +339,8 @@ export class CleanupClient {
}
const findSchedules = async () => {
const allSchedules = await this.dispatchClient.xoClient.call('schedule.getAll')
const schedulesArray = Array.isArray(allSchedules) ? allSchedules : Object.values(allSchedules)
return schedulesArray.filter(
const allSchedules = await this.dispatchClient.backup.listSchedules()
return allSchedules.filter(
schedule =>
config.includeIds.includes(schedule.id) ||
config.namePatterns.some(pattern => schedule.name?.includes(pattern))
@@ -365,7 +348,7 @@ export class CleanupClient {
}
const deleteSchedule = async schedule => {
await this.dispatchClient.xoClient.call('schedule.delete', { id: schedule.id })
await this.dispatchClient.backup.deleteSchedule(schedule.id)
}
return await this._deleteResourcesBatch('schedule', findSchedules, deleteSchedule, {

View File

@@ -4,83 +4,152 @@ import { AbstractRequest } from './abstract.js'
const log = createLogger('xo:qa-test:backup')
/**
* Converts a caller-friendly `{ [id]: anything }` map to the `{ id }` pattern expected by XO.
*
* @param {Object} [objectsById]
* @returns {Object|undefined} undefined if there is no ID
*/
const toIdPattern = objectsById => {
const ids = objectsById !== null && typeof objectsById === 'object' ? Object.keys(objectsById) : []
return ids.length > 0 ? toSimplePattern(ids) : undefined
}
/**
* Specialized request handler for XenOrchestra backup operations.
*
* Provides comprehensive backup job management with REST API for read operations
* and WebSocket for creation/execution operations. Handles job lifecycle,
* execution monitoring, and log retrieval.
* Backup jobs (VM, mirror and metadata) and their schedules are created, updated, deleted
* and run through the REST API. Backup archive operations that are not exposed by the
* REST API yet still use the WebSocket API.
*
* @class BackupRequest
* @extends AbstractRequest
*/
export class BackupRequest extends AbstractRequest {
/**
* REST API endpoint for backup jobs
* Note: This is primarily used for read operations
* REST API endpoint for backup jobs (all types: backup, mirrorBackup, metadataBackup)
* @type {string}
*/
endpoint = 'backup-jobs'
// ===========================================================================
// Backup jobs and schedules (REST API)
// ===========================================================================
/**
* Creates a new backup job in XenOrchestra.
* Creates a backup job of any type with `POST /rest/v0/backup-jobs`.
*
* Backup job creation is only available via WebSocket API.
* REST API doesn't support backup job creation operations.
* `config.schedules` are keyed by temporary IDs, which can be used as keys in
* `config.settings`: XO replaces them by the IDs of the created schedules.
*
* @param {Object} config - Complete backup job configuration
* @param {'backup'|'mirrorBackup'|'metadataBackup'} type - Backup job type
* @param {Object} config - Job properties, in the XO format
* @returns {Promise<string>} The created backup job ID
* @throws {Error} If backup job creation fails or configuration is invalid
*/
async createBackupJob(config) {
async #createJob(type, config) {
this._ensureConnected()
if (!config || typeof config !== 'object') {
throw new Error('Valid backup configuration object is required')
}
const convertConfig = cfg => {
const { vms, remotes, srs, ...rest } = cfg
const result = { ...rest }
const vmIds = vms && typeof vms === 'object' ? Object.keys(vms) : []
if (vmIds.length > 0) {
result.vms = toSimplePattern(vmIds)
}
const backupRepositoryIds = remotes && typeof remotes === 'object' ? Object.keys(remotes) : []
if (backupRepositoryIds.length > 0) {
result.remotes = toSimplePattern(backupRepositoryIds)
}
const srIds = srs && typeof srs === 'object' ? Object.keys(srs) : []
if (srIds.length > 0) {
result.srs = toSimplePattern(srIds)
}
return result
}
const xoConfig = convertConfig({ ...config, mode: config.mode || 'delta' })
try {
const result = await this.dispatchClient.xoClient.call('backupNg.createJob', xoConfig)
return result
const { id } = await this.dispatchClient.restApiClient.post(`/rest/v0/${this.endpoint}`, { ...config, type })
return id
} catch (error) {
log.warn('Backup job creation failed', { message: error.message, code: error.code, data: error.data })
log.warn('Backup job creation failed', { type, message: error.message, body: error.body })
throw error
}
}
/**
* Deletes an existing backup job.
* Creates a new VM backup job (backup or replication).
*
* Backup job deletion is only available via WebSocket API.
* `vms`, `remotes` and `srs` are maps keyed by IDs, converted to the `{ id }` pattern expected by XO.
*
* @param {Object} config - Complete backup job configuration
* @returns {Promise<string>} The created backup job ID
*/
async createBackupJob(config) {
const { vms, remotes, srs, ...rest } = config ?? {}
return this.#createJob('backup', {
...rest,
mode: rest.mode || 'delta',
vms: toIdPattern(vms),
remotes: toIdPattern(remotes),
srs: toIdPattern(srs),
})
}
/**
* Creates a new mirror backup job, replicating backups from one remote to others.
*
* @param {Object} config - Mirror backup job configuration
* @param {string} config.mode - 'full' or 'delta'
* @param {string} config.sourceRemote - ID of the source remote
* @param {Object} config.remotes - Destination remotes (e.g., { [remoteId]: {} })
* @param {string} [config.name] - Job name
* @param {Object} [config.schedules] - Schedule definitions
* @param {Object} [config.settings] - Job settings
* @returns {Promise<string>} The created mirror backup job ID
*/
async createMirrorBackupJob(config) {
const { remotes, ...rest } = config ?? {}
return this.#createJob('mirrorBackup', {
...rest,
mode: rest.mode || 'full',
remotes: toIdPattern(remotes),
})
}
/**
* Creates a new metadata backup job.
*
* Accepts a caller-friendly shape:
* { name, pools: { [poolId]: true }, remotes: { [remoteId]: true },
* schedules, settings, xoMetadata }
*
* @param {Object} config - Metadata backup job configuration
* @returns {Promise<string>} The created job ID
*/
async createMetadataBackupJob(config) {
const { pools, remotes, ...rest } = config ?? {}
return this.#createJob('metadataBackup', {
...rest,
pools: toIdPattern(pools),
remotes: toIdPattern(remotes),
})
}
/**
* Updates a backup job of any type with `PATCH /rest/v0/backup-jobs/:id`.
*
* Root properties are replaced (`settings` must be passed entirely), a `null` value removes the property.
*
* @param {string} jobId - ID of the backup job to update
* @param {Object} changes - Properties to update, in the XO format
* @returns {Promise<void>}
*/
async updateBackupJob(jobId, changes) {
this._ensureConnected()
if (!jobId || typeof jobId !== 'string') {
throw new Error('Valid backup job ID is required')
}
try {
await this.dispatchClient.restApiClient.patch(`/rest/v0/${this.endpoint}/${jobId}`, changes)
} catch (error) {
log.warn('Backup job update failed', { jobId, message: error.message, body: error.body })
throw error
}
}
/**
* Deletes a backup job of any type, and its schedules, with `DELETE /rest/v0/backup-jobs/:id`.
*
* @param {string} jobId - ID of the backup job to delete
* @returns {Promise<Object>} Deletion result
* @throws {Error} If deletion fails or job ID is invalid
* @returns {Promise<void>}
* @throws {Error} If deletion fails, `error.status` is 404 if the job does not exist
*/
async deleteBackupJob(jobId) {
this._ensureConnected()
@@ -89,19 +158,127 @@ export class BackupRequest extends AbstractRequest {
throw new Error('Valid backup job ID is required')
}
// Backup job deletion is only available via WebSocket API
try {
const result = await this.dispatchClient.xoClient.call('backupNg.deleteJob', { id: jobId })
return result
await this.dispatchClient.restApiClient.delete(`/rest/v0/${this.endpoint}/${jobId}`)
} catch (error) {
// "no such job" means the caller used the wrong delete method (e.g. mirror job) — let it handle the fallback
if (error?.data?.type !== 'job') {
log.warn('Delete backup job failed', { error })
// a missing job is handled by the caller (e.g. cleanup of an already deleted job)
if (error.status !== 404) {
log.warn('Delete backup job failed', { jobId, message: error.message, body: error.body })
}
throw error
}
}
/**
* Lists all schedules (of backup jobs and other jobs).
*
* @returns {Promise<Array<Object>>}
*/
async listSchedules() {
this._ensureConnected()
return this.dispatchClient.restApiClient.getObjects('/rest/v0/schedules')
}
/**
* Gets a schedule by ID.
*
* @param {string} scheduleId
* @returns {Promise<Object>}
*/
async getSchedule(scheduleId) {
this._ensureConnected()
return this.dispatchClient.restApiClient.get(`/rest/v0/schedules/${scheduleId}`)
}
/**
* Updates a schedule with `PATCH /rest/v0/schedules/:id`.
*
* @param {string} scheduleId
* @param {{cron?: string, enabled?: boolean, name?: string, timezone?: string}} changes
* @returns {Promise<void>}
*/
async updateSchedule(scheduleId, changes) {
this._ensureConnected()
await this.dispatchClient.restApiClient.patch(`/rest/v0/schedules/${scheduleId}`, changes)
}
/**
* Deletes a schedule with `DELETE /rest/v0/schedules/:id`, its settings are removed from its job.
*
* @param {string} scheduleId
* @returns {Promise<void>}
*/
async deleteSchedule(scheduleId) {
this._ensureConnected()
await this.dispatchClient.restApiClient.delete(`/rest/v0/schedules/${scheduleId}`)
}
/**
* Runs a backup job of any type through one of its schedules, and waits for its log.
*
* The run is started with `POST /rest/v0/schedules/:id/actions/run`, which returns
* immediately with the ID of the REST API task running the job.
*
* @param {string} jobId - Backup job ID, used to find the backup log
* @param {string} scheduleId - Schedule ID to use for this execution
* @param {Object} [options]
* @param {number} [options.runStartTime] - Only logs started after it are considered,
* defaults to 5 s before now (buffer for clock differences): pass `Date.now()` when runs follow each other closely
* @returns {Promise<Object>} Complete backup log with status and details
* @throws {Error} If the job fails to start or times out
*/
async runJobAndGetLog(jobId, scheduleId, { runStartTime = Date.now() - 5000 } = {}) {
this._ensureConnected()
log.debug('Running backup job', { jobId, scheduleId })
const restApiClient = this.dispatchClient.restApiClient
let taskId
try {
;({ taskId } = await restApiClient.post(`/rest/v0/schedules/${scheduleId}/actions/run`))
} catch (error) {
log.warn('Run backup job failed', { jobId, scheduleId, message: error.message, body: error.body })
throw error
}
// Wait for the backup to complete and get the log
const result = await waitUntil(
async () => {
const latestLog = await this.dispatchClient.backupLog.getLatestForJob(jobId, runStartTime)
if (latestLog !== undefined) {
// Check if the backup is complete (case-insensitive status check)
const status = latestLog.status?.toLowerCase()
return status === 'success' || status === 'failure' || latestLog.end ? { backupLog: latestLog } : false
}
// No log yet: the job may have failed before starting (e.g. feature not authorized)
const task = await restApiClient.get(`/rest/v0/tasks/${taskId}`)
return task.status === 'failure' ? { failedTask: task } : false
},
2000, // Check every 2 seconds
300_000, // 5 minute timeout
{ exponentialBackoff: true, backoffMultiplier: 1.2, maxInterval: 10_000 }
)
if (result.failedTask !== undefined) {
const reason = result.failedTask.result?.message ?? JSON.stringify(result.failedTask.result)
throw new Error(`Backup job ${jobId} failed to start: ${reason}`)
}
log.debug('Backup completed', { status: result.backupLog.status })
return result.backupLog
}
// ===========================================================================
// Backup archives
// ===========================================================================
/**
* Lists VM backups for specified backup repositories.
*
@@ -238,273 +415,9 @@ export class BackupRequest extends AbstractRequest {
}
// ===========================================================================
// Mirror Backup operations (mirrorBackup.* API)
// Metadata backups
// ===========================================================================
/**
* Creates a new mirror backup job in XenOrchestra.
*
* Mirror backup replicates backups from one remote to another.
* Uses `mirrorBackup.createJob` WebSocket API.
*
* @param {Object} config - Mirror backup job configuration
* @param {string} config.mode - 'full' or 'delta'
* @param {string} config.sourceRemote - ID of the source remote
* @param {Object} config.remotes - Destination remotes (e.g., { [remoteId]: {} })
* @param {string} [config.name] - Job name
* @param {Object} [config.schedules] - Schedule definitions
* @param {Object} [config.settings] - Job settings
* @param {Object} [config.filter] - VM filter (by UUID)
* @returns {Promise<string>} The created mirror backup job ID
*/
async createMirrorBackupJob(config) {
this._ensureConnected()
if (!config || typeof config !== 'object') {
throw new Error('Valid mirror backup configuration object is required')
}
const { remotes, ...rest } = config
// Convert destination remotes to a simple pattern (supports one or several)
const remoteIds = remotes && typeof remotes === 'object' ? Object.keys(remotes) : []
const xoConfig = {
...rest,
mode: config.mode || 'full',
}
if (remoteIds.length > 0) {
xoConfig.remotes = toSimplePattern(remoteIds)
}
try {
const result = await this.dispatchClient.xoClient.call('mirrorBackup.createJob', xoConfig)
return result
} catch (error) {
log.warn('Mirror backup job creation failed', { message: error.message, code: error.code, data: error.data })
throw error
}
}
/**
* Deletes a mirror backup job.
*
* @param {string} jobId - ID of the mirror backup job to delete
* @returns {Promise<Object>} Deletion result
*/
async deleteMirrorBackupJob(jobId) {
this._ensureConnected()
if (!jobId || typeof jobId !== 'string') {
throw new Error('Valid mirror backup job ID is required')
}
try {
const result = await this.dispatchClient.xoClient.call('mirrorBackup.deleteJob', { id: jobId })
return result
} catch (error) {
if (error?.data?.type !== 'job') {
log.warn('Delete mirror backup job failed', { error })
}
throw error
}
}
/**
* Executes a mirror backup job and monitors completion.
*
* @param {string} jobId - Mirror backup job ID to execute
* @param {string} scheduleId - Schedule ID to use for this execution
* @returns {Promise<Object>} Complete backup log with status and details
*/
async runMirrorJobAndGetLog(jobId, scheduleId) {
this._ensureConnected()
log.debug('Running mirror backup job', { jobId, scheduleId })
const runStartTime = Date.now() - 5000
try {
await this.dispatchClient.xoClient.call('mirrorBackup.runJob', {
id: jobId,
schedule: scheduleId,
})
} catch (wsError) {
log.warn('Run mirror backup job failed', { error: wsError.message })
throw wsError
}
const backupLog = await waitUntil(
async () => {
try {
const latestLog = await this.dispatchClient.backupLog.getLatestForJob(jobId, runStartTime)
if (!latestLog) {
return false
}
const status = latestLog.status?.toLowerCase()
if (status === 'success' || status === 'failure' || latestLog.end) {
return latestLog
}
return false
} catch (error) {
log.debug('Waiting for mirror backup completion', { error })
return false
}
},
2000,
300_000,
{ exponentialBackoff: true, backoffMultiplier: 1.2, maxInterval: 10_000 }
)
log.debug('Mirror backup completed', { status: backupLog.status })
return backupLog
}
// ===========================================================================
// Metadata Backup operations (metadataBackup.* API)
// ===========================================================================
/**
* Creates a new metadata backup job in XenOrchestra.
*
* Accepts a caller-friendly shape:
* { name, pools: { [poolId]: true }, remotes: { [remoteId]: true },
* schedules, settings, xoMetadata }
* and converts pools/remotes to the { id } pattern expected by the API.
*
* @param {Object} config - Metadata backup job configuration
* @returns {Promise<string>} The created job ID
*/
async createMetadataBackupJob(config) {
this._ensureConnected()
if (!config || typeof config !== 'object') {
throw new Error('Valid metadata backup configuration object is required')
}
const { pools, remotes, ...rest } = config
const poolIds = pools && typeof pools === 'object' ? Object.keys(pools) : []
const remoteIds = remotes && typeof remotes === 'object' ? Object.keys(remotes) : []
const xoConfig = { ...rest }
if (poolIds.length > 0) xoConfig.pools = toSimplePattern(poolIds)
if (remoteIds.length > 0) xoConfig.remotes = toSimplePattern(remoteIds)
try {
const result = await this.dispatchClient.xoClient.call('metadataBackup.createJob', xoConfig)
// metadataBackup.createJob returns the full job object (unlike backupNg.createJob which returns only the ID)
return result?.id ?? result
} catch (error) {
log.warn('Metadata backup job creation failed', { message: error.message, code: error.code, data: error.data })
throw error
}
}
/**
* Gets a metadata backup job by ID.
*
* Uses the WebSocket API because the backup-jobs REST endpoint only covers VM backup jobs.
*
* @param {string} jobId - Metadata backup job ID
* @returns {Promise<Object>} The job object
*/
async getMetadataJob(jobId) {
this._ensureConnected()
if (!jobId || typeof jobId !== 'string') {
throw new Error('Valid job ID is required')
}
try {
return await this.dispatchClient.xoClient.call('metadataBackup.getJob', { id: jobId })
} catch (error) {
log.warn('Get metadata backup job failed', { jobId, error })
throw error
}
}
/**
* Deletes a metadata backup job.
*
* @param {string} jobId - Metadata backup job ID to delete
* @returns {Promise<void>}
*/
async deleteMetadataBackupJob(jobId) {
this._ensureConnected()
if (!jobId || typeof jobId !== 'string') {
throw new Error('Valid job ID is required')
}
try {
return await this.dispatchClient.xoClient.call('metadataBackup.deleteJob', { id: jobId })
} catch (error) {
log.warn('Delete metadata backup job failed', { jobId, error })
throw error
}
}
/**
* Executes a metadata backup job and monitors completion.
*
* Same polling pattern as runJobAndGetLog, but calls metadataBackup.runJob.
*
* @param {string} jobId - Metadata backup job ID to execute
* @param {string} scheduleId - Schedule ID to use for this execution
* @returns {Promise<Object>} Complete backup log with status and details
*/
async runMetadataJobAndGetLog(jobId, scheduleId) {
this._ensureConnected()
log.debug('Running metadata backup job', { jobId, scheduleId })
const runStartTime = Date.now()
try {
await this.dispatchClient.xoClient.call('metadataBackup.runJob', {
id: jobId,
schedule: scheduleId,
})
} catch (wsError) {
// The server has a known bug where a post-job cleanup error of `undefined` causes
// serializeError() to throw, returning a -32000 WS error even though the backup
// already completed. Continue polling for the log rather than failing immediately.
log.debug('metadataBackup.runJob returned a WS error, polling for backup log anyway', {
jobId,
code: wsError.code,
error: wsError.message,
})
}
const backupLog = await waitUntil(
async () => {
try {
const latestLog = await this.dispatchClient.backupLog.getLatestForJob(jobId, runStartTime)
if (!latestLog) return false
const status = latestLog.status?.toLowerCase()
if (status === 'success' || status === 'failure' || latestLog.end) {
return latestLog
}
return false
} catch (error) {
log.debug('Waiting for metadata backup completion', { error })
return false
}
},
2000,
300_000,
{ exponentialBackoff: true, backoffMultiplier: 1.2, maxInterval: 10_000 }
)
log.debug('Metadata backup completed', { status: backupLog.status })
return backupLog
}
/**
* Lists metadata backups for the given backup repositories.
*
@@ -525,74 +438,4 @@ export class BackupRequest extends AbstractRequest {
throw error
}
}
// ===========================================================================
// Standard Backup operations (backupNg.* API)
// ===========================================================================
/**
* Executes a backup job and monitors completion.
*
* Starts the backup job and waits for completion with detailed logging.
* Combines job execution and log monitoring in a single method.
*
* @param {string} jobId - Backup job ID to execute
* @param {string} scheduleId - Schedule ID to use for this execution
* @returns {Promise<Object>} Complete backup log with status and details
* @throws {Error} If job execution fails or times out
*/
async runJobAndGetLog(jobId, scheduleId) {
this._ensureConnected()
log.debug('Running backup job', { jobId, scheduleId })
// Capture timestamp BEFORE starting the job (with small buffer for clock differences)
const runStartTime = Date.now() - 5000 // 5 second buffer before job start
// Backup job execution is only available via WebSocket API
try {
await this.dispatchClient.xoClient.call('backupNg.runJob', {
id: jobId,
schedule: scheduleId,
})
} catch (wsError) {
if (wsError.code === -32000 && wsError.message.includes('task has not started yet')) {
// sometimes we get a task not started error
await new Promise(resolve => setTimeout(resolve, 10_000))
} else {
console.error('❌ Run backup job failed:', wsError.message)
throw wsError
}
}
// Wait for the backup to complete and get the log
const backupLog = await waitUntil(
async () => {
try {
const latestLog = await this.dispatchClient.backupLog.getLatestForJob(jobId, runStartTime)
if (!latestLog) {
return false // Keep waiting
}
// Check if the backup is complete (case-insensitive status check)
const status = latestLog.status?.toLowerCase()
if (status === 'success' || status === 'failure' || latestLog.end) {
return latestLog
}
return false // Still running
} catch (error) {
log.debug('Waiting for backup completion', { error })
return false
}
},
2000, // Check every 2 seconds
300_000, // 5 minute timeout
{ exponentialBackoff: true, backoffMultiplier: 1.2, maxInterval: 10_000 }
)
log.debug('Backup completed', { status: backupLog.status })
return backupLog
}
}

View File

@@ -136,6 +136,21 @@ export class RestApiClient {
return fetchFn()
}
/**
* Builds the error of a failed response, keeping its status and body so callers
* can react to a specific status (e.g. 404) and log the reason sent by XO.
*
* @param {Response} response - Non-ok fetch response
* @returns {Promise<Error & {status: number, body: string}>}
* @private
*/
static async #httpError(response) {
const error = new Error(`HTTP ${response.status}: ${response.statusText}`)
error.status = response.status
error.body = await response.text().catch(() => '')
return error
}
/**
* Basic GET request method.
*
@@ -157,7 +172,7 @@ export class RestApiClient {
const text = await response.text()
return text ? JSON.parse(text) : {}
}
throw new Error(`HTTP ${response.status}: ${response.statusText}`)
throw await RestApiClient.#httpError(response)
} catch (error) {
log.warn('GET request failed on ' + endpoint, { error })
throw error
@@ -190,7 +205,7 @@ export class RestApiClient {
const text = await response.text()
return text ? JSON.parse(text) : {}
}
throw new Error(`HTTP ${response.status}: ${response.statusText}`)
throw await RestApiClient.#httpError(response)
} catch (error) {
log.warn(`${method} request failed`, { error })
throw error
@@ -255,7 +270,7 @@ export class RestApiClient {
const text = await response.text()
return text ? JSON.parse(text) : {}
}
throw new Error(`HTTP ${response.status}: ${response.statusText}`)
throw await RestApiClient.#httpError(response)
} catch (error) {
log.warn('DELETE request failed', { error })
throw error

View File

@@ -39,6 +39,7 @@
"qa:backup:combined": "node --env-file-if-exists=.env --test tests/backup-replication-combined.test.js",
"qa:backup:combined:cycle": "node --env-file-if-exists=.env --test tests/backup-replication-combined.test.js --test-name-pattern='Full Cycle'",
"qa:backup:sync": "node --env-file-if-exists=.env --test tests/backup.synchronized.test.js --test-concurrency=1",
"qa:backup:lock": "node --env-file-if-exists=.env --test tests/backup.lock.test.js",
"qa:mirror:cr": "node --env-file-if-exists=.env --test tests/backup-replication-combined.test.js --test-name-pattern='CR Mode'",
"qa:mirror": "node --env-file-if-exists=.env --test tests/backup-mirror.test.js",
"qa:replication": "node --env-file-if-exists=.env --test --test-concurrency=1 tests/replication.test.js",

View File

@@ -134,7 +134,7 @@ describe('Mirror Backup - Full Remote', () => {
assert.ok(scheduleKey, 'Mirror schedule key is required')
tracker.trackResource('schedule', scheduleKey, { name, backupJobId: jobId })
const result = await dispatchClient.backup.runMirrorJobAndGetLog(jobId, scheduleKey)
const result = await dispatchClient.backup.runJobAndGetLog(jobId, scheduleKey)
assertBackupSuccess(result, `Mirror backup: ${name}`)
return result
}
@@ -258,6 +258,60 @@ describe('Mirror Backup - Full Remote', () => {
})
})
// =========================================================================
// Long-term retention
// =========================================================================
describe('Long-term retention', () => {
after(async () => {
await purgeBackupData(sourceRepository, destRepository)
})
it('should create and run a mirror job with long-term retention', async () => {
const longTermRetention = {
daily: { retention: 3, settings: {} },
weekly: { retention: 2, settings: {} },
}
log.debug('Running full backup to populate source repository')
await runFullBackup()
// a named temporary schedule ID keeps the general settings ('') apart from the schedule ones
const name = generateBackupJobName()
const jobId = await dispatchClient.backup.createMirrorBackupJob({
name,
mode: 'full',
sourceRemote: sourceRepository.id,
remotes: { [destRepository.id]: {} },
schedules: { tmpSchedule: getDefaultSchedule() },
settings: {
// the timezone is required by the long-term retention
'': { timezone: 'Europe/Paris', longTermRetention },
tmpSchedule: { exportRetention: 1 },
},
})
tracker.trackResource('backupJob', jobId, { name, mode: 'full', type: 'mirrorBackup' })
const job = await dispatchClient.backup.details(jobId)
assert.strictEqual(job.type, 'mirrorBackup')
assert.deepStrictEqual(job.settings[''].longTermRetention, longTermRetention, 'LTR should be kept on the job')
assert.strictEqual(job.settings[''].timezone, 'Europe/Paris', 'Timezone should be kept on the job')
const scheduleKey = getScheduleKey(job)
assert.ok(scheduleKey, 'Mirror schedule key is required')
assert.notStrictEqual(scheduleKey, 'tmpSchedule', 'Temporary schedule ID should be replaced')
assert.strictEqual(job.settings[scheduleKey].exportRetention, 1, 'Schedule settings should be kept')
tracker.trackResource('schedule', scheduleKey, { name, backupJobId: jobId })
// the LTR is applied when the destination is cleaned, a misconfiguration fails the run
const result = await dispatchClient.backup.runJobAndGetLog(jobId, scheduleKey)
assertBackupSuccess(result, `Mirror backup with LTR: ${name}`)
const destCount = await countVmBackups(destRepository.id, vm.uuid)
assert.ok(destCount > 0, 'Destination repository should contain backups after mirror')
})
})
// =========================================================================
// Retention — source retention > destination retention
// =========================================================================

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