Compare commits

..

15 Commits

Author SHA1 Message Date
KAN-vates
576d0670d5 feat(rest-api): accept the PATCH field names when creating a network
The network create routes take name, description and mtu, while PATCH
/networks/{id} takes the XoNetwork names name_label, name_description and
MTU, so a client had to learn two spellings for one network. The create
routes now accept the XoNetwork names too. normalizeNetworkCreateBody maps
them, in one place, to the names xapi.createNetwork reads. The old names
stay accepted and are marked deprecated, so no client breaks.

A body giving both spellings of one field, or no name at all, is refused
with a 422. The check runs in a middleware before the ACL: a refusal
inside the task would come back as a failed task, not a 422. The ACL then
matches the role's selectors against the normalized body, so a selector
on name still sees the name whichever spelling the client used.
tsoa cannot express "one of", so name and name_label are both optional in
the schema and the check is in the code.
2026-12-03 10:29:42 +01:00
KAN-vates
8eaa4c507a fix(xo-server): roll back network edits when one of their writes fails
editNetwork wrote its fields with a Promise.all, so they ran concurrently. A failure on one
field left the others applied, and the rejection reached the caller before the remaining
writes had ended: a multi-field PATCH /rest/v0/networks/{id}, or network.set, could answer
500 with part of the network already changed.

The writes now run one after the other. Each one that succeeds registers a $defer.onFailure
that restores its previous value: name_label, name_description, the automatic flag, the
default locking mode and the NBD purposes. MTU comes last because changing it replugs every
PIF and VIF, and its rollback replugs them again. On failure the rollbacks run in reverse
order; a rollback that fails itself is logged and the original error is the one rethrown.
2026-12-03 10:29:42 +01:00
KAN-vates
f22c27b863 fix(xo-server): skip the MTU replug when network.editNetwork's MTU is unchanged
editNetwork called network.$setMtu whenever the MTU key was present, even
with the value already set. $setMtu replugs every PIF and VIF, so a client
resending its full state on each update (Terraform) interrupted traffic on
every apply with no change.

editNetwork now calls $setMtu only when the requested MTU differs from the
network's current one. The comparison is numeric (+network.MTU), as in
xapi-object-to-xo. The shared Network.setMtu in @xen-orchestra/xapi is
unchanged.
2026-12-03 10:29:42 +01:00
KAN-vates
3e8658c906 feat(rest-api): add PATCH /rest/v0/networks/{id}
The REST API could read a network but not change it: the network controller had no PATCH
route, so a network's name, description, MTU, NBD purposes, automatic flag and default
locking mode could only be set through JSON-RPC network.set. The route is the REST
counterpart of network.set. It has one ACL action per field, update:name_label,
update:MTU and so on, named after the XoNetwork fields GET returns, so a client can send
back what it read. An action is checked only when its field is in the body. nbd: true also
removes the insecure_nbd purpose, and insecureNbd: true the nbd one, so each also requires
the other's action. A body with none of the fields is refused with a 422 before the ACL
runs, so it neither passes unchecked nor tells an existing network from a missing one.

The body is forwarded to Xapi.editNetwork, which holds the NBD rules shared with
JSON-RPC: copying them into rest-api would let the two drift. Changing the MTU unplugs
and replugs the network's interfaces, so the route is exposed to MCP with confirm.
2026-12-03 10:29:42 +01:00
KAN-vates
7b7fab8366 refactor(xo-server): share network.set's logic as Xapi editNetwork
network.set held the whole edit in the JSON-RPC method, where nothing
else could reach it. The REST route for PATCH /networks/{id} needs the
same edit, so the logic moves into Xapi.editNetwork, next to editVif,
and network.set calls it. JSON-RPC behaviour does not change.

The NBD rules (nbd and insecureNbd are exclusive, and a false value only
removes its own purpose) move with the edit. They must not be copied
into rest-api: they are subtle, and two copies would drift apart. The
mutual-exclusion check runs before any XAPI call, so a refused request
changes nothing.
2026-12-03 10:27:11 +01:00
Sylvère
22bcc37439 feat(web-core): add an optional details log viewer to the error modal (#10536) 2026-12-03 08:28:39 +01:00
Joris K
5ca2958d2a fix(web-core): stop the page sliding sideways to closed side panels (#10973) 2026-12-02 17:55:29 +01:00
Killian
205ae67940 docs(backups): add a procedure to repair a broken incremental chain (#10966)
* docs(backups): add a procedure to repair a broken incremental chain

No page told users what to do when a delta backup chain is broken on the
backup repository (a disk file missing or unreadable).

The new page works from the web interface and the REST API only, so it
applies to an air-gapped XOA. It starts from the job log's Clean VM
directory warnings, then relies on what each run already does since
XO 5.100.0: delete the broken restore points and fall back to a full
when no valid base is left. The manual steps (reclaim-space through the
REST API or Delete backups in XO 5, then a forced full) cover what that
run doesn't: failing runs, and corrupted data the header check misses.

The two new screenshots were taken on a chain broken on purpose. The
troubleshooting page links the procedure from the unexpected full
export section.
2026-12-02 17:33:30 +01:00
Florent BEAUCHAMP
addfdd5475 fix(vmware-explorer): detect secure boot -improve snapshots for esxi6 (#10968)
* fix(vmware-explorer): detect secure boot for esxi6

* changelog

* fix: improve compatibility with automatic snapshot
2026-12-02 15:43:36 +01:00
spacotte-vates
5512fc65a6 feat(acl): resolve selectors on partial objects (#10731)
* feat(complex-matcher): throw when unknown state

* update changelog

* lil fixes

* fix review Killian

* move code from package/complex-matcher to xen-orchestra/acl

* fix review MathieuRA

* improve comment
2026-12-02 12:27:06 +01:00
Marie Garde
1f8f265afc fix(xo5): fix crash on metadata job with all objects (#10933)
* fix(xo5): fix crash on metadata job with all objects

* fix changelog

* rebase ok
2026-12-02 10:59:48 +01:00
Marie Garde
c0e7843274 feat(xo6): fix style backup job form (#10940)
* wip

* fix style on form

* fix checkbox and radio button in DS

* fix pipeline

* fix tests

* remove version DS

* edit style

* fix tests

* fix build

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

* rebase ok

* fix changelog
2026-12-02 09:31:17 +01:00
Sebastien Marie
6f91a90299 fix(xo-server-sdn-controller): set up the SDN controller on network rules too (#10917) 2026-12-01 18:14:57 +01:00
Florent BEAUCHAMP
41b290f166 fix(backups): correctly cleanup snapshot of diskless VM with a CDROM (#10789)
* fix(backups): correctly cleanup snapshot of diskless VM with a CDROM
* fix: correctly cleanup the snapshots even when switching from vm based to vdi based retention
2026-12-01 16:14:07 +01:00
130 changed files with 1946 additions and 2086 deletions

View File

@@ -101,6 +101,21 @@ export interface EditVifProps {
txChecksumming?: boolean
}
/**
* Properties accepted by {@link Xapi.editNetwork}: the fields of `XoNetwork` it can change.
*
* `nbd` and `insecureNbd` cannot both be true: `editNetwork` throws `invalidParameters` when they are.
*/
export interface EditNetworkProps {
automatic?: boolean
defaultIsLocked?: boolean
insecureNbd?: boolean
MTU?: number
name_description?: string
name_label?: string
nbd?: boolean
}
export type XcpPatches = {
changelog?: {
author: string
@@ -335,6 +350,7 @@ export interface Xapi {
checkLimits?: (limits: Record<string, number>, vm: XenApiVmWrapped) => Promise<void>
): Promise<void>
editVif(id: XoVif['id'], props: EditVifProps): Promise<void>
editNetwork(id: XoNetwork['id'], props: EditNetworkProps): Promise<void>
startVm(
id: XoVm['id'],
opts?: {

View File

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

View File

@@ -8,9 +8,28 @@ export type SupportedResource = XoAclSupportedResource<SupportedActionsByResourc
export type SupportedActions<T extends SupportedResource> = XoAclSupportedActions<SupportedActionsByResource, T>
export type TPrivilege<T extends SupportedResource> = XoAclPrivilege<SupportedActionsByResource, T>
export const UNKNOWN = Symbol('UNKNOWN')
/**
* Lists the top-level fields read by a selector.
*/
function getSelectorFields(node: CM.Node): string[] {
if (node instanceof CM.Property || node instanceof CM.TruthyProperty) {
return [node.name]
}
if (node instanceof CM.Not) {
return getSelectorFields(node.child)
}
if (node instanceof CM.And || node instanceof CM.Or) {
return node.children.flatMap(getSelectorFields)
}
return node instanceof CM.Null ? [] : ['*']
}
export class Privilege<T extends SupportedResource> {
#action: TPrivilege<T>['action']
#selector?: (object: object) => boolean
#selectorFields: string[] = []
#resource: TPrivilege<T>['resource']
#effect: TPrivilege<T>['effect']
@@ -28,9 +47,14 @@ export class Privilege<T extends SupportedResource> {
Privilege.checkActionIsValid(resource, action)
this.#action = action
this.#selector = selector !== undefined ? CM.parse(selector).createPredicate() : undefined
this.#resource = resource
this.#effect = effect
if (selector !== undefined) {
const node = CM.parse(selector)
this.#selector = node.createPredicate()
this.#selectorFields = getSelectorFields(node)
}
}
get effect() {
@@ -44,11 +68,20 @@ export class Privilege<T extends SupportedResource> {
return this.#action === '*' || this.#action === action || action.startsWith(`${this.#action}:`)
}
#matchSelector(object: object) {
#matchSelector(object: object, knownFields?: string[]) {
if (this.#selector === undefined) {
return true
}
// `*` is a term not bound to a property (e.g. `foo`), it may match any field, including missing ones
// The `*` check is there to handle the case where a `*` field would exist
if (
knownFields !== undefined &&
this.#selectorFields.some(field => field === '*' || !(field in object || knownFields.includes(field)))
) {
return UNKNOWN
}
return this.#selector(object)
}
@@ -60,11 +93,12 @@ export class Privilege<T extends SupportedResource> {
action: SupportedActions<Resource>
resource: Resource
object: object
}): boolean {
knownFields?: string[]
}): boolean | typeof UNKNOWN {
return (
this.#matchResource(constraint.resource) &&
this.#matchAction(constraint.action) &&
this.#matchSelector(constraint.object)
this.#matchSelector(constraint.object, constraint.knownFields)
)
}

View File

@@ -7,6 +7,7 @@ import {
SupportedActions,
SupportedActionsByResource,
SupportedResource,
UNKNOWN,
} from './class/privilege.mjs'
// Export all types constructed using SUPPORTED_ACTIONS_BY_RESOURCE
@@ -23,6 +24,7 @@ export type AnyPrivilegeOnParam = {
resource: Resource
action: SupportedActions<Resource>
objects: object | object[]
knownFields?: string[]
}
}[SupportedResource]
@@ -32,12 +34,14 @@ export function hasPrivilegeOn<T extends SupportedResource>({
resource,
objects,
userPrivileges,
knownFields,
}: {
user: XoUser
resource: T
action: SupportedActions<T>
objects: object | object[]
userPrivileges: AnyPrivilege[]
knownFields?: string[]
}) {
// Function that will be called outside of the module
// We cannot be sure types are respected
@@ -63,7 +67,7 @@ export function hasPrivilegeOn<T extends SupportedResource>({
return true
}
const effectsByObject = new Map<object, Privilege<T>['effect'][]>()
const effectsByObject = new Map<object, { known: boolean; effect: Privilege<T>['effect'] }[]>()
if (Array.isArray(objects)) {
objects.forEach(obj => effectsByObject.set(obj, []))
} else {
@@ -74,20 +78,49 @@ export function hasPrivilegeOn<T extends SupportedResource>({
const privilege = new CPrivilege(userPrivilege as Privilege<typeof userPrivilege.resource>)
for (const [object, effects] of effectsByObject.entries()) {
if (!privilege.match({ action, resource, object })) {
const result = privilege.match({ action, resource, object, knownFields })
if (!result) {
continue
}
effects.push(privilege.effect)
effects.push({ known: result !== UNKNOWN, effect: privilege.effect })
}
}
if (
Array.from(effectsByObject.values()).some(
effects => effects.length === 0 || effects.some(effect => effect === 'deny')
)
) {
return false
let isUndecidable = false
for (const effects of effectsByObject.values()) {
let hasAllow = false
let hasKnownAllow = false
let hasUnknownDeny = false
for (const { known, effect } of effects) {
if (effect === 'allow') {
hasAllow = true
hasKnownAllow ||= known
} else if (known) {
return false
} else {
hasUnknownDeny = true
}
}
if (!hasAllow) {
return false
}
// do not throw yet: another object may still be known to be denied
if (hasUnknownDeny || !hasKnownAllow) {
isUndecidable = true
}
}
if (isUndecidable) {
const error: Error & { code?: string } = new Error(
`The privilege couldn't be decided because the object is missing fields the selectors need. action: ${action}, resource: ${resource}`
)
error.code = 'RBAC_UNKNOWN_RESULT'
throw error
}
return true
}
@@ -101,6 +134,7 @@ export function getMissingPrivileges(params: AnyPrivilegeOnParam[], userPrivileg
action: param.action as SupportedActions<typeof param.resource>,
objects: param.objects,
userPrivileges,
knownFields: param.knownFields,
})
)
.map(({ action, objects, resource }) => {
@@ -142,6 +176,7 @@ export function filterObjectsWithPrivilege<Resource extends SupportedResource, O
action: SupportedActions<Resource>
objects: Object[]
userPrivileges: AnyPrivilege[]
knownFields?: string[]
}) {
return param.objects.filter(obj => hasPrivilegeOn({ ...param, objects: obj }))
}

View File

@@ -3,7 +3,7 @@ import assert from 'node:assert'
import type { Branded } from '@vates/types/common'
import type { XoUser } from '@vates/types/xo'
import { Privilege } from '../class/privilege.mjs'
import { Privilege, UNKNOWN } from '../class/privilege.mjs'
import type { Privilege as TPrivilege } from '../index.mjs'
import {
filterObjectsWithPrivilege,
@@ -81,6 +81,108 @@ suite('Privilege.match behavior', () => {
const vmImportPrivilege = new Privilege({ action: 'import:vm', resource: 'sr', effect: 'allow' })
assert.strictEqual(vmImportPrivilege.match({ resource: 'sr', action: 'import:vdi:url', object }), false)
})
suite('on a partial object', () => {
const ownVmPrivilege = new Privilege({
action: 'read',
resource: 'vm',
selector: 'creation:creator:2',
effect: 'allow',
})
const partialObject = { id: 'alma' }
test('Should not match a missing property if known fields are not provided', () => {
assert.strictEqual(ownVmPrivilege.match({ resource: 'vm', action: 'read', object: partialObject }), false)
})
test('Should not match a missing property if it is a known field', () => {
assert.strictEqual(
ownVmPrivilege.match({
resource: 'vm',
action: 'read',
object: partialObject,
knownFields: ['id', 'creation'],
}),
false
)
})
test('Should return UNKNOWN if the selector uses an unknown field', () => {
assert.strictEqual(
ownVmPrivilege.match({ resource: 'vm', action: 'read', object: partialObject, knownFields: ['id'] }),
UNKNOWN
)
})
test('Should not match because of the resource even if the selector is unknown', () => {
assert.strictEqual(
ownVmPrivilege.match({ resource: 'host', action: 'read', object: partialObject, knownFields: ['id'] }),
false
)
})
test('Should not match because of the action even if the selector is unknown', () => {
assert.strictEqual(
ownVmPrivilege.match({ resource: 'vm', action: 'start', object: partialObject, knownFields: ['id'] }),
false
)
})
test('Should match without selector', () => {
assert.strictEqual(
privilege.match({ resource: 'vm', action: 'read', object: partialObject, knownFields: [] }),
true
)
})
test('Should resolve a field present on the object even if it is not listed', () => {
assert.strictEqual(
ownVmPrivilege.match({
resource: 'vm',
action: 'read',
object: { creation: { creator: '2' } },
knownFields: [],
}),
true
)
})
test('Should resolve a field provided by a getter', () => {
class Vm {
get creation() {
return { creator: '2' }
}
}
assert.strictEqual(
ownVmPrivilege.match({ resource: 'vm', action: 'read', object: new Vm(), knownFields: [] }),
true
)
})
test('Should return UNKNOWN on a term not bound to a property', () => {
const bareTermPrivilege = new Privilege({ action: 'read', resource: 'vm', selector: 'alma', effect: 'allow' })
assert.strictEqual(
bareTermPrivilege.match({ resource: 'vm', action: 'read', object: partialObject, knownFields: ['id'] }),
UNKNOWN
)
})
test('Should return UNKNOWN if one of the fields is unknown, even if the others decide the result', () => {
const orPrivilege = new Privilege({
action: 'read',
resource: 'vm',
selector: '|(id:alma creation:creator:2)',
effect: 'allow',
})
assert.strictEqual(
orPrivilege.match({ resource: 'vm', action: 'read', object: partialObject, knownFields: ['id'] }),
UNKNOWN
)
})
})
})
suite('ACL V2 behavior', async () => {
@@ -397,6 +499,205 @@ suite('ACL V2 behavior', async () => {
assert.strictEqual(vms.length, 2)
})
})
suite('partial objects behavior', () => {
const UNKNOWN_RESULT = { code: 'RBAC_UNKNOWN_RESULT' }
const vmReadAll = {
id: privilegeId,
action: 'read',
resource: 'vm',
effect: 'allow',
roleId,
} satisfies TPrivilege<'vm'>
const vmReadOwn = {
id: privilegeId,
action: 'read',
resource: 'vm',
selector: `creation:creator:${user.id}`,
effect: 'allow',
roleId,
} satisfies TPrivilege<'vm'>
const vmDenyReadOnPool = {
id: privilegeId,
action: 'read',
resource: 'vm',
selector: '$pool:2',
effect: 'deny',
roleId,
} satisfies TPrivilege<'vm'>
const partialVm = { id: 'partial-vm' }
const partialVmOnDeniedPool = { id: 'partial-vm-denied', $pool: '2' }
suite('hasPrivilegeOn', () => {
test('Should always return true for admin', () => {
assert.strictEqual(
hasPrivilegeOn({
user: admin,
action: 'read',
resource: 'vm',
objects: partialVm,
knownFields: ['id'],
userPrivileges: [vmReadOwn],
}),
true
)
})
test('Should keep the current behavior if known fields are not provided', () => {
assert.strictEqual(
hasPrivilegeOn({ user, action: 'read', resource: 'vm', objects: partialVm, userPrivileges: [vmReadOwn] }),
false
)
})
test('Should throw if the only allow privilege is unknown', () => {
assert.throws(
() =>
hasPrivilegeOn({
user,
action: 'read',
resource: 'vm',
objects: partialVm,
knownFields: ['id'],
userPrivileges: [vmReadOwn],
}),
UNKNOWN_RESULT
)
})
test('Should return false if the unknown field is known to be absent', () => {
assert.strictEqual(
hasPrivilegeOn({
user,
action: 'read',
resource: 'vm',
objects: partialVm,
knownFields: ['id', 'creation'],
userPrivileges: [vmReadOwn],
}),
false
)
})
test('Should return true if an allow privilege is known even if another one is unknown', () => {
assert.strictEqual(
hasPrivilegeOn({
user,
action: 'read',
resource: 'vm',
objects: partialVm,
knownFields: ['id'],
userPrivileges: [vmReadOwn, vmReadAll],
}),
true
)
})
test('Should throw if a deny privilege is unknown, even with a known allow privilege', () => {
assert.throws(
() =>
hasPrivilegeOn({
user,
action: 'read',
resource: 'vm',
objects: partialVm,
knownFields: ['id'],
userPrivileges: [vmReadAll, vmDenyReadOnPool],
}),
UNKNOWN_RESULT
)
})
test('Should return true if a deny privilege is known not to match', () => {
assert.strictEqual(
hasPrivilegeOn({
user,
action: 'read',
resource: 'vm',
objects: partialVm,
knownFields: ['id', '$pool'],
userPrivileges: [vmReadAll, vmDenyReadOnPool],
}),
true
)
})
test('Should return false if a deny privilege is known to match, even with an unknown allow privilege', () => {
assert.strictEqual(
hasPrivilegeOn({
user,
action: 'read',
resource: 'vm',
objects: partialVmOnDeniedPool,
knownFields: ['id', '$pool'],
userPrivileges: [vmReadOwn, vmDenyReadOnPool],
}),
false
)
})
test('Should return false if one of the objects is known to be denied, even if another one is unknown', () => {
assert.strictEqual(
hasPrivilegeOn({
user,
action: 'read',
resource: 'vm',
objects: [partialVm, partialVmOnDeniedPool],
knownFields: ['id'],
userPrivileges: [vmReadAll, vmDenyReadOnPool],
}),
false
)
})
test('Should throw if the other objects are allowed and one is unknown', () => {
assert.throws(
() =>
hasPrivilegeOn({
user,
action: 'read',
resource: 'vm',
objects: [{ id: 'allowed-vm', $pool: '1' }, partialVm],
knownFields: ['id'],
userPrivileges: [vmReadAll, vmDenyReadOnPool],
}),
UNKNOWN_RESULT
)
})
})
suite('getMissingPrivileges', () => {
test('Should throw if a privilege is unknown', () => {
assert.throws(
() =>
getMissingPrivileges(
[{ user, action: 'read', resource: 'vm', objects: partialVm, knownFields: ['id'] }],
[vmReadOwn]
),
UNKNOWN_RESULT
)
})
})
suite('filterObjectsWithPrivilege', () => {
test('Should throw if a privilege is unknown on one of the objects', () => {
assert.throws(
() =>
filterObjectsWithPrivilege({
user,
action: 'read',
resource: 'vm',
objects: [partialVm],
knownFields: ['id'],
userPrivileges: [vmReadOwn],
}),
UNKNOWN_RESULT
)
})
})
})
})
suite('getActionStrings', () => {

View File

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

View File

@@ -5,7 +5,7 @@ import { formatDateTime } from '@xen-orchestra/xapi'
import { Task } from '@vates/task'
import { AbstractXapi } from './_AbstractXapi.mjs'
import { DATETIME, EXPORTED_SUCCESSFULLY, JOB_ID, SCHEDULE_ID } from '../../_otherConfig.mjs'
import { DATETIME, EXPORTED_SUCCESSFULLY, JOB_ID, SCHEDULE_ID, VM_UUID } from '../../_otherConfig.mjs'
// Build an AbstractXapi instance without running its heavy constructor, then
// assign only the fields the method under test reads.
@@ -735,3 +735,120 @@ describe('after an abort', () => {
])
})
})
describe('_fetchJobSnapshots() diskless VM snapshot detection', () => {
const makeFetchRunner = ({ vmVbds, snapshotVbds }) => {
const jobSnapshot = {
$ref: 'snap-ref',
$snapshot_of: {},
$VBDs: snapshotVbds,
other_config: { [JOB_ID]: 'job-1', [VM_UUID]: 'vm-uuid', [DATETIME]: '20240101T00:00:00Z' },
}
return makeRunner({
_jobId: 'job-1',
_vm: { uuid: 'vm-uuid', $VBDs: vmVbds, $snapshots: [jobSnapshot] },
_xapi: { objects: { indexes: { type: { VDI: {} } } } },
})
}
const trackedSnapshotRefs = runner => runner._disklessJobSnapshotVms.map(({ $ref }) => $ref)
it('tracks VM snapshots of a VM with only an empty CD drive', async () => {
const cdDrive = { type: 'CD', VDI: 'OpaqueRef:NULL' }
const runner = makeFetchRunner({ vmVbds: [cdDrive], snapshotVbds: [cdDrive] })
await runner._fetchJobSnapshots()
assert.deepEqual(trackedSnapshotRefs(runner), ['snap-ref'], 'a CD drive must not prevent the diskless retention')
})
it('tracks VM snapshots of a VM whose only disk is [NOBAK]', async () => {
// the ignored disk is on the VM, but not on its snapshot
const runner = makeFetchRunner({ vmVbds: [{ type: 'Disk', VDI: 'nobak-vdi-ref' }], snapshotVbds: [] })
await runner._fetchJobSnapshots()
assert.deepEqual(trackedSnapshotRefs(runner), ['snap-ref'], 'a snapshot without disk must be tracked at VM level')
})
it('does not use the diskless retention for a snapshot with a disk', async () => {
const runner = makeFetchRunner({
vmVbds: [{ type: 'Disk', VDI: 'vdi-ref' }],
snapshotVbds: [{ type: 'Disk', VDI: 'snapshot-vdi-ref' }],
})
await runner._fetchJobSnapshots()
assert.deepEqual(trackedSnapshotRefs(runner), [], 'this snapshot is handled through its VDIs')
})
it('does not use the diskless retention when a VBD of the snapshot is not in the cache', async () => {
const runner = makeFetchRunner({ vmVbds: [{ type: 'Disk', VDI: 'vdi-ref' }], snapshotVbds: [undefined] })
await runner._fetchJobSnapshots()
assert.deepEqual(trackedSnapshotRefs(runner), [], 'an unknown VBD may be a disk')
})
})
describe('_removeUnusedSnapshots() applies one retention across VDI-reached and diskless snapshots', () => {
// A VM that switched between "no backed up disk" and "at least one disk"
// has snapshots of both kinds: the retention must apply to their union, not
// keep `snapshotRetention` snapshots of each kind.
const OLD_DATETIME = '20240101T00:00:00Z'
const NEW_DATETIME = '20240102T00:00:00Z'
const makeSwitchedRunner = ({ oldIsDiskless }) => {
const destroyed = []
const disklessSnapshot = datetime => ({
$ref: 'vm-diskless',
other_config: { [DATETIME]: datetime, [SCHEDULE_ID]: 'schedule-1' },
})
const snapshotVm = { $ref: 'vm-with-disk', is_control_domain: false, $snapshot_of: 'live-vm-ref', other_config: {} }
const vdiSnapshot = datetime => ({
$ref: 'vdi-with-disk',
other_config: { [DATETIME]: datetime, [SCHEDULE_ID]: 'schedule-1' },
$VBDs: [{ $VM: snapshotVm }],
})
const vm = disklessSnapshot(oldIsDiskless ? OLD_DATETIME : NEW_DATETIME)
const vdi = vdiSnapshot(oldIsDiskless ? NEW_DATETIME : OLD_DATETIME)
const registry = { [vm.$ref]: vm, [vdi.$ref]: vdi }
const runner = makeRunner({
_vm: { uuid: 'live-uuid', $snapshots: [] },
_baseSettings: { snapshotRetention: 1 },
_jobSnapshotVdis: [vdi],
_disklessJobSnapshotVms: [vm],
job: { mode: 'full', settings: {} },
_xapi: {
barrier: async () => {},
getObject: ref => registry[ref],
VM_destroy: async ref => {
destroyed.push(ref)
},
VDI_destroy: async ref => {
destroyed.push(ref)
},
},
})
return { runner, destroyed }
}
it('removes the older diskless snapshot once a disk was added', async () => {
const { runner, destroyed } = makeSwitchedRunner({ oldIsDiskless: true })
await runner._removeUnusedSnapshots()
assert.deepEqual(destroyed, ['vm-diskless'], 'only the older, diskless, snapshot should be removed')
})
it('removes the older snapshot with a disk once the VM became diskless', async () => {
const { runner, destroyed } = makeSwitchedRunner({ oldIsDiskless: false })
await runner._removeUnusedSnapshots()
assert.deepEqual(destroyed, ['vm-with-disk'], 'only the older snapshot, reached through its VDI, should be removed')
})
})

View File

@@ -3,7 +3,7 @@
## **next**
- [VM/Network] Add possibility to delete a VIF (PR [#10726](https://github.com/vatesfr/xen-orchestra/pull/10726))
- [Host/VM/Pool] Add a Stats tab showing the CPU, RAM, network and load (or disk for VMs) charts over the last 10 minutes, 2 hours, week or year, with one line per CPU, interface, disk or host and an option to show the totals (PR [#10956](https://github.com/vatesfr/xen-orchestra/pull/10956))
- [Web-Core/VtsErrorModal] Add an optional details log viewer, unified icon (PR [#10536](https://github.com/vatesfr/xen-orchestra/pull/10536))
## **0.28.0** (2026/12/01)

View File

@@ -1,25 +0,0 @@
<template>
<VtsStatsCharts :charts :granularity :loading="hostStats === undefined" :error="hasError || !!lastError" />
</template>
<script lang="ts" setup>
import { useObjectStats } from '@/composables/object-stats.composable.ts'
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import { useHostStore } from '@/stores/xen-api/host.store.ts'
import VtsStatsCharts from '@core/components/stats-charts/VtsStatsCharts.vue'
import { useHostStatsCharts } from '@core/composables/stats-charts/host-stats-charts.composable.ts'
import type { XapiStatsGranularity } from '@vates/types/common'
// The parent re-mounts this component (`key`) when the host or the granularity changes
const { host, granularity, showTotals } = defineProps<{
host: XenApiHost
granularity: XapiStatsGranularity
showTotals: boolean
}>()
const { getStats, lastError } = useHostStore().subscribe()
const { stats: hostStats, hasError } = useObjectStats<XenApiHost>(getStats, host, granularity)
const charts = useHostStatsCharts(hostStats, () => showTotals)
</script>

View File

@@ -6,9 +6,6 @@
<RouterTab :to="{ name: '/host/[uuid]/console', params: { uuid } }">
{{ t('console') }}
</RouterTab>
<RouterTab :to="{ name: '/host/[uuid]/stats', params: { uuid } }">
{{ t('stats') }}
</RouterTab>
<RouterTab :to="{ name: '/host/[uuid]/system', params: { uuid } }">
{{ t('system') }}
</RouterTab>

View File

@@ -1,50 +0,0 @@
<template>
<VtsStatsCharts :charts :granularity :loading :error="hasError || !!lastError" />
</template>
<script lang="ts" setup>
import useFetchStats from '@/composables/fetch-stats.composable.ts'
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
import { useHostStore } from '@/stores/xen-api/host.store.ts'
import VtsStatsCharts from '@core/components/stats-charts/VtsStatsCharts.vue'
import { type PoolHostStats, usePoolStatsCharts } from '@core/composables/stats-charts/pool-stats-charts.composable.ts'
import type { XapiStatsGranularity } from '@vates/types/common'
import { differenceBy } from 'lodash-es'
import { computed, watch } from 'vue'
// The parent re-mounts this component (`key`) when the granularity changes
const { granularity, showTotals } = defineProps<{
granularity: XapiStatsGranularity
showTotals: boolean
}>()
const { getStats, runningHosts, lastError } = useHostStore().subscribe()
// The running hosts are only known once their metrics are loaded
const { isReady: areHostMetricsReady } = useHostMetricsStore().subscribe()
const { stats, register, unregister } = useFetchStats<XenApiHost>(getStats, granularity)
watch(
runningHosts,
(hosts, previousHosts = []) => {
differenceBy(hosts, previousHosts, 'uuid').forEach(host => register(host))
differenceBy(previousHosts, hosts, 'uuid').forEach(host => unregister(host))
},
{ immediate: true }
)
// A host whose stats can't be fetched doesn't hold the others back
const loading = computed(
() => !areHostMetricsReady.value || stats.value.some(stat => stat.stats === undefined && !stat.hasError)
)
const hasError = computed(() => stats.value.length > 0 && stats.value.every(stat => stat.hasError))
const hostsStats = computed<PoolHostStats[]>(() =>
stats.value.flatMap(({ name, response }) => (response === undefined ? [] : [{ name, stats: response }]))
)
const charts = usePoolStatsCharts(hostsStats, () => showTotals)
</script>

View File

@@ -6,7 +6,7 @@
<RouterTab :to="{ name: '/pool/[uuid]/alarms', params: { uuid: pool?.uuid ?? '-' } }" disabled>
{{ t('alarms') }}
</RouterTab>
<RouterTab :to="{ name: '/pool/[uuid]/stats', params: { uuid: pool?.uuid ?? '-' } }">
<RouterTab :to="{ name: '/pool/[uuid]/stats', params: { uuid: pool?.uuid ?? '-' } }" disabled>
{{ t('stats') }}
</RouterTab>
<RouterTab :to="{ name: '/pool/[uuid]/system', params: { uuid: pool?.uuid ?? '-' } }">

View File

@@ -1,25 +0,0 @@
<template>
<VtsStatsCharts :charts :granularity :loading="vmStats === undefined" :error="hasError || !!lastError" />
</template>
<script lang="ts" setup>
import { useObjectStats } from '@/composables/object-stats.composable.ts'
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
import VtsStatsCharts from '@core/components/stats-charts/VtsStatsCharts.vue'
import { useVmStatsCharts } from '@core/composables/stats-charts/vm-stats-charts.composable.ts'
import type { XapiStatsGranularity } from '@vates/types/common'
// The parent re-mounts this component (`key`) when the VM or the granularity changes
const { vm, granularity, showTotals } = defineProps<{
vm: XenApiVm
granularity: XapiStatsGranularity
showTotals: boolean
}>()
const { getStats, lastError } = useVmStore().subscribe()
const { stats: vmStats, hasError } = useObjectStats<XenApiVm>(getStats, vm, granularity)
const charts = useVmStatsCharts(vmStats, () => showTotals)
</script>

View File

@@ -9,7 +9,7 @@
<RouterTab :to="{ name: '/vm/[uuid]/alarms', params: { uuid } }" disabled>
{{ t('alarms') }}
</RouterTab>
<RouterTab :to="{ name: '/vm/[uuid]/stats', params: { uuid } }">
<RouterTab :to="{ name: '/vm/[uuid]/stats', params: { uuid } }" disabled>
{{ t('stats') }}
</RouterTab>
<RouterTab :to="{ name: '/vm/[uuid]/system', params: { uuid } }">

View File

@@ -1,17 +1,13 @@
import { RRD_STEP_FROM_STRING, type XapiStatsResponse } from '@/libs/xapi-stats.ts'
import { type GRANULARITY, RRD_STEP_FROM_STRING, type XapiStatsResponse } from '@/libs/xapi-stats.ts'
import type { XenApiHost, XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import type { XapiHostStatsRaw, XapiStatsGranularity, XapiVmStatsRaw } from '@vates/types/common'
import type { XapiHostStatsRaw, XapiVmStatsRaw } from '@vates/types/common'
import { type Pausable, promiseTimeout, useTimeoutPoll } from '@vueuse/core'
import { computed, type ComputedRef, markRaw, onUnmounted, ref, type Ref } from 'vue'
import { computed, type ComputedRef, onUnmounted, ref, type Ref } from 'vue'
export type Stat<T> = {
canBeExpired: boolean
// The last fetch failed: `stats` holds the previous ones, if any
hasError: boolean
id: string
name: string
// Shaped like the XO REST API stats, which the web-core stats charts expect
response: XapiStatsResponse<T> | undefined
stats: T | undefined
pausable: Pausable
}
@@ -21,7 +17,7 @@ export type GetStats<
S extends XapiHostStatsRaw | XapiVmStatsRaw = T extends XenApiHost ? XapiHostStatsRaw : XapiVmStatsRaw,
> = (
uuid: T['uuid'],
granularity: XapiStatsGranularity,
granularity: GRANULARITY,
ignoreExpired: boolean,
opts: { abortSignal?: AbortSignal }
) => Promise<XapiStatsResponse<S> | undefined> | undefined
@@ -37,13 +33,10 @@ export type FetchedStats<
timestampEnd: ComputedRef<number>
}
// In seconds
const RETRY_DELAY = 10
export default function useFetchStats<
T extends XenApiHost | XenApiVm,
S extends XapiHostStatsRaw | XapiVmStatsRaw = T extends XenApiHost ? XapiHostStatsRaw : XapiVmStatsRaw,
>(getStats: GetStats<T, S>, granularity: XapiStatsGranularity): FetchedStats<T, S> {
>(getStats: GetStats<T, S>, granularity: GRANULARITY): FetchedStats<T, S> {
const stats = ref(new Map()) as Ref<Map<string, Stat<S>>>
const timestamp = ref<number[]>([0, 0])
const abortController = new AbortController()
@@ -55,36 +48,15 @@ export default function useFetchStats<
return
}
let isFirstCall = true
const ignoreExpired = computed(() => !stats.value.has(mapKey))
const pausable = useTimeoutPoll(
async () => {
let newStats: XapiStatsResponse<S> | undefined
let hasError = false
// The first call accepts expired cached stats (e.g. when coming back to a page) to show something right away
const ignoreExpired = isFirstCall
isFirstCall = false
const newStats = (await getStats(object.uuid, granularity, ignoreExpired.value, {
abortSignal: abortController.signal,
})) as XapiStatsResponse<S>
try {
newStats = await getStats(object.uuid, granularity, ignoreExpired, {
abortSignal: abortController.signal,
})
} catch {
hasError = true
}
// The object may have been unregistered while its stats were being fetched
const stat = stats.value.get(mapKey)
if (stat === undefined) {
return
}
stat.hasError = hasError
// Without new stats (failure, disconnected XAPI…), retries soon, but not in a tight loop
if (newStats === undefined) {
await promiseTimeout(Math.min(RRD_STEP_FROM_STRING[granularity], RETRY_DELAY) * 1000)
return
}
@@ -94,16 +66,9 @@ export default function useFetchStats<
newStats.endTimestamp,
]
// Raw: replacing the stats is enough to update the charts, which then read their samples without proxies.
// Unchanged stats (e.g. the cache read again right after the first call) don't redraw the charts
if (stat.response?.endTimestamp !== newStats.endTimestamp) {
stat.stats = markRaw(newStats.stats)
stat.response = markRaw(newStats)
}
stat.canBeExpired = newStats.canBeExpired
// Cached stats (`canBeExpired`), possibly old (e.g. when coming back to a page), are checked again right away:
// the next call skips the cache if it's expired, instead of a full interval later, which can be a day
await promiseTimeout(newStats.canBeExpired ? 0 : newStats.interval * 1000)
stats.value.get(mapKey)!.stats = newStats.stats
stats.value.get(mapKey)!.canBeExpired = newStats.canBeExpired
await promiseTimeout(newStats.interval * 1000)
},
0,
{ immediate: true }
@@ -111,10 +76,8 @@ export default function useFetchStats<
stats.value.set(mapKey, {
canBeExpired: false,
hasError: false,
id: object.uuid,
name: object.name_label,
response: undefined,
stats: undefined,
pausable,
})

View File

@@ -1,20 +0,0 @@
import useFetchStats, { type GetStats } from '@/composables/fetch-stats.composable.ts'
import type { XenApiHost, XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import type { XapiHostStatsRaw, XapiStatsGranularity, XapiVmStatsRaw } from '@vates/types/common'
import { computed } from 'vue'
// Polls the stats of a single host or VM. The object and the granularity are fixed: the caller must be re-mounted to
// change them
export function useObjectStats<
T extends XenApiHost | XenApiVm,
S extends XapiHostStatsRaw | XapiVmStatsRaw = T extends XenApiHost ? XapiHostStatsRaw : XapiVmStatsRaw,
>(getStats: GetStats<T, S>, object: T, granularity: XapiStatsGranularity) {
const { stats, register } = useFetchStats<T, S>(getStats, granularity)
register(object)
return {
stats: computed(() => stats.value[0]?.response),
hasError: computed(() => stats.value[0]?.hasError === true),
}
}

View File

@@ -1,7 +1,6 @@
import type XenApi from '@/libs/xen-api/xen-api.ts'
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import type { XapiHostStatsRaw, XapiVmStatsRaw } from '@vates/types'
import type { XapiStatsGranularity } from '@vates/types/common'
import { synchronized } from 'decorator-synchronized'
// eslint-disable-next-line import/default -- https://github.com/json5/json5/issues/287
import JSON5 from 'json5'
@@ -33,7 +32,7 @@ export enum GRANULARITY {
Days = 'days',
}
export const RRD_STEP_FROM_STRING: Record<XapiStatsGranularity, RRD_STEP> = {
export const RRD_STEP_FROM_STRING: { [key in GRANULARITY]: RRD_STEP } = {
[GRANULARITY.Seconds]: RRD_STEP.Seconds,
[GRANULARITY.Minutes]: RRD_STEP.Minutes,
[GRANULARITY.Hours]: RRD_STEP.Hours,
@@ -417,7 +416,7 @@ export default class XapiStats {
host: XenApiHost
ignoreExpired?: boolean
uuid: any
granularity: XapiStatsGranularity
granularity: GRANULARITY
}) {
const step = granularity === undefined ? RRD_STEP.Seconds : RRD_STEP_FROM_STRING[granularity]
if (step === undefined) {

View File

@@ -1,8 +1,8 @@
import type { XenApiNetwork } from '@/libs/xen-api/xen-api.types.ts'
import { useNetworkDeleteJob } from '@/modules/network/jobs/network-delete.job.ts'
import { useDeleteModal } from '@core/composables/modals/use-delete-modal.ts'
import { useErrorModal } from '@core/composables/modals/use-error-modal.ts'
import { useRouteQuery } from '@core/composables/route-query.composable.ts'
import { useOverlay } from '@core/packages/overlay/use-overlay.ts'
import { toComputed } from '@core/utils/to-computed.util.ts'
import type { MaybeRefOrGetter } from 'vue'
import { useI18n } from 'vue-i18n'
@@ -23,12 +23,7 @@ export function useNetworkDelete(rawNetworks: MaybeRefOrGetter<XenApiNetwork[]>)
const { open: openNetworkDeleteModal } = useDeleteModal()
const { open: openNetworkDeleteErrorModal } = useOverlay({
component: () => import('@core/components/modal/VtsErrorModal.vue'),
events: {
onClose: true,
},
})
const { open: openNetworkDeleteErrorModal } = useErrorModal()
function deleteNetworks() {
if (!canDeleteNetworks.value) {

View File

@@ -1,78 +0,0 @@
<template>
<div class="stats">
<VtsStateHero v-if="host === undefined" format="page" type="not-found" size="large">
{{ t('object-not-found', { id: route.params.uuid }) }}
</VtsStateHero>
<!-- The power state is unknown until the host metrics are loaded -->
<VtsStateHero v-else-if="!areHostMetricsReady" format="page" type="busy" size="large" />
<VtsStateHero v-else-if="!isHostRunning" format="page" type="offline" size="large" horizontal>
<span>{{ t('engines-off') }}</span>
<span class="title typo-h1">{{ t('host-off') }}</span>
<div class="description typo-body-bold">
<span>{{ t('host-currently-shutdown') }}</span>
<span>{{ t('start-host') }}</span>
</div>
</VtsStateHero>
<template v-else>
<VtsStatsToolbar v-model:granularity="granularity" v-model:show-totals="showTotals" />
<HostStatsCharts :key="`${host.uuid}-${granularity}`" :host :granularity :show-totals />
</template>
</div>
</template>
<script lang="ts" setup>
import HostStatsCharts from '@/components/host/HostStatsCharts.vue'
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import { usePageTitleStore } from '@/stores/page-title.store.ts'
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
import { useHostStore } from '@/stores/xen-api/host.store.ts'
import VtsStateHero from '@core/components/state-hero/VtsStateHero.vue'
import VtsStatsToolbar from '@core/components/stats-toolbar/VtsStatsToolbar.vue'
import { HOST_POWER_STATE } from '@vates/types'
import type { XapiStatsGranularity } from '@vates/types/common'
import { computed, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute } from 'vue-router'
const { t } = useI18n()
usePageTitleStore().setTitle(t('stats'))
const route = useRoute<'/host/[uuid]/stats'>()
const { getByUuid } = useHostStore().subscribe()
const host = computed(() => getByUuid(route.params.uuid as XenApiHost['uuid']))
const { getHostPowerState, isReady: areHostMetricsReady } = useHostMetricsStore().subscribe()
// As in XO 6, a host whose state is unknown (e.g. disconnected) is shown as off: it has no stats to show
const isHostRunning = computed(() => getHostPowerState(host.value) === HOST_POWER_STATE.RUNNING)
const granularity = ref<XapiStatsGranularity>('seconds')
const showTotals = ref(false)
</script>
<style lang="postcss" scoped>
.stats {
display: flex;
flex: 1;
flex-direction: column;
gap: 0.8rem;
min-height: 0;
padding: 0.8rem;
overflow-y: auto;
.title {
color: var(--color-neutral-txt-primary);
}
.description {
display: flex;
flex-direction: column;
gap: 1.4rem;
color: var(--color-neutral-txt-secondary);
}
}
</style>

View File

@@ -1,33 +1,11 @@
<template>
<div class="stats">
<VtsStatsToolbar v-model:granularity="granularity" v-model:show-totals="showTotals" />
<PoolStatsCharts :key="granularity" :granularity :show-totals />
</div>
<PageUnderConstruction />
</template>
<script lang="ts" setup>
import PoolStatsCharts from '@/components/pool/PoolStatsCharts.vue'
import PageUnderConstruction from '@/components/PageUnderConstruction.vue'
import { usePageTitleStore } from '@/stores/page-title.store.ts'
import VtsStatsToolbar from '@core/components/stats-toolbar/VtsStatsToolbar.vue'
import type { XapiStatsGranularity } from '@vates/types/common'
import { ref } from 'vue'
import { useI18n } from 'vue-i18n'
usePageTitleStore().setTitle(useI18n().t('stats'))
const granularity = ref<XapiStatsGranularity>('seconds')
const showTotals = ref(false)
</script>
<style lang="postcss" scoped>
.stats {
display: flex;
flex: 1;
flex-direction: column;
gap: 0.8rem;
min-height: 0;
padding: 0.8rem;
overflow-y: auto;
}
</style>

View File

@@ -1,73 +1,11 @@
<template>
<div class="stats">
<VtsStateHero v-if="vm === undefined" format="page" type="not-found" size="large">
{{ t('object-not-found', { id: route.params.uuid }) }}
</VtsStateHero>
<VtsStateHero v-else-if="!isVmActive" format="page" type="offline" size="large" horizontal>
<span>{{ t('all-quiet-launchpad') }}</span>
<span class="title typo-h1">{{ t('vm-shutdown') }}</span>
<div class="description typo-body-bold">
<span>{{ t('vm-off') }}</span>
<span>{{ t('start-vm') }}</span>
</div>
</VtsStateHero>
<template v-else>
<VtsStatsToolbar v-model:granularity="granularity" v-model:show-totals="showTotals" />
<VmStatsCharts :key="`${vm.uuid}-${granularity}`" :vm :granularity :show-totals />
</template>
</div>
<PageUnderConstruction />
</template>
<script lang="ts" setup>
import VmStatsCharts from '@/components/vm/VmStatsCharts.vue'
import { ACTIVE_STATES } from '@/libs/utils.ts'
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import PageUnderConstruction from '@/components/PageUnderConstruction.vue'
import { usePageTitleStore } from '@/stores/page-title.store.ts'
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
import VtsStateHero from '@core/components/state-hero/VtsStateHero.vue'
import VtsStatsToolbar from '@core/components/stats-toolbar/VtsStatsToolbar.vue'
import type { XapiStatsGranularity } from '@vates/types/common'
import { computed, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute } from 'vue-router'
const { t } = useI18n()
usePageTitleStore().setTitle(t('stats'))
const route = useRoute<'/vm/[uuid]/stats'>()
const { getByUuid } = useVmStore().subscribe()
const vm = computed(() => getByUuid(route.params.uuid as XenApiVm['uuid']))
// A paused VM is still on its host, which keeps recording its stats
const isVmActive = computed(() => vm.value !== undefined && ACTIVE_STATES.has(vm.value.power_state))
const granularity = ref<XapiStatsGranularity>('seconds')
const showTotals = ref(false)
usePageTitleStore().setTitle(useI18n().t('stats'))
</script>
<style lang="postcss" scoped>
.stats {
display: flex;
flex: 1;
flex-direction: column;
gap: 0.8rem;
min-height: 0;
padding: 0.8rem;
overflow-y: auto;
.title {
color: var(--color-neutral-txt-primary);
}
.description {
display: flex;
flex-direction: column;
gap: 1.4rem;
color: var(--color-neutral-txt-secondary);
}
}
</style>

View File

@@ -52,7 +52,6 @@ declare module 'vue-router/auto-routes' {
| '/host/[uuid]/console'
| '/host/[uuid]/dashboard'
| '/host/[uuid]/network'
| '/host/[uuid]/stats'
| '/host/[uuid]/storage'
| '/host/[uuid]/system'
| '/host/[uuid]/tasks'
@@ -79,13 +78,6 @@ declare module 'vue-router/auto-routes' {
{ uuid: ParamValue<false> },
| never
>,
'/host/[uuid]/stats': RouteRecordInfo<
'/host/[uuid]/stats',
'/host/:uuid/stats',
{ uuid: ParamValue<true> },
{ uuid: ParamValue<false> },
| never
>,
'/host/[uuid]/storage': RouteRecordInfo<
'/host/[uuid]/storage',
'/host/:uuid/storage',
@@ -507,6 +499,13 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/modal/vts-error-modal': RouteRecordInfo<
'/story/web-core/modal/vts-error-modal',
'/story/web-core/modal/vts-error-modal',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/number-input/vts-number-input': RouteRecordInfo<
'/story/web-core/number-input/vts-number-input',
'/story/web-core/number-input/vts-number-input',
@@ -598,20 +597,6 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/stats-charts/vts-stats-charts': RouteRecordInfo<
'/story/web-core/stats-charts/vts-stats-charts',
'/story/web-core/stats-charts/vts-stats-charts',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/stats-toolbar/vts-stats-toolbar': RouteRecordInfo<
'/story/web-core/stats-toolbar/vts-stats-toolbar',
'/story/web-core/stats-toolbar/vts-stats-toolbar',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/status/vts-status': RouteRecordInfo<
'/story/web-core/status/vts-status',
'/story/web-core/status/vts-status',
@@ -1371,7 +1356,6 @@ declare module 'vue-router/auto-routes' {
| '/host/[uuid]/console'
| '/host/[uuid]/dashboard'
| '/host/[uuid]/network'
| '/host/[uuid]/stats'
| '/host/[uuid]/storage'
| '/host/[uuid]/system'
| '/host/[uuid]/tasks'
@@ -1397,12 +1381,6 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/pages/host/[uuid]/stats.vue': {
routes:
| '/host/[uuid]/stats'
views:
| never
}
'src/pages/host/[uuid]/storage.vue': {
routes:
| '/host/[uuid]/storage'
@@ -1766,6 +1744,12 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/stories/web-core/modal/vts-error-modal.story.vue': {
routes:
| '/story/web-core/modal/vts-error-modal'
views:
| never
}
'src/stories/web-core/number-input/vts-number-input.story.vue': {
routes:
| '/story/web-core/number-input/vts-number-input'
@@ -1844,18 +1828,6 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/stories/web-core/stats-charts/vts-stats-charts.story.vue': {
routes:
| '/story/web-core/stats-charts/vts-stats-charts'
views:
| never
}
'src/stories/web-core/stats-toolbar/vts-stats-toolbar.story.vue': {
routes:
| '/story/web-core/stats-toolbar/vts-stats-toolbar'
views:
| never
}
'src/stories/web-core/status/vts-status.story.vue': {
routes:
| '/story/web-core/status/vts-status'

View File

@@ -0,0 +1,29 @@
# Usage
Open the modal with `useErrorModal`.
```vue-script
import { useErrorModal } from '@core/composables/modals/use-error-modal.ts'
const { open: openErrorModal } = useErrorModal()
try {
// ...
} catch (error) {
void openErrorModal({
props: {
title: 'Unable to create cluster',
error: 'An error occurred',
details: error,
},
})
}
```
The `details` prop is displayed below the message, even when the `content` slot is overridden:
```vue-template
<VtsErrorModal title="Unable to delete network" :details @close="close()">
<template #content>Custom error message</template>
</VtsErrorModal>
```

View File

@@ -0,0 +1,60 @@
<template>
<ComponentStory
v-slot="{ properties, settings }"
:params="[
prop('title').str().required().preset('Unable to create cluster').widget(),
prop('error').str().preset('An error occurred').widget(),
prop('details')
.type('string | object')
.preset(details1)
.widget(object())
.help('When set, displayed in a log entry viewer below the error message'),
event('close'),
slot('content').help('Replaces the error message. The details are still displayed below it'),
setting('contentSlotContent').widget(text()).help('Leave empty to use the error prop'),
]"
:presets
>
<VtsErrorModal class="story" v-bind="properties">
<template v-if="settings.contentSlotContent" #content>{{ settings.contentSlotContent }}</template>
</VtsErrorModal>
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { event, prop, setting, slot } from '@/libs/story/story-param.ts'
import { object, text } from '@/libs/story/story-widget.ts'
import VtsErrorModal from '@core/components/modal/VtsErrorModal.vue'
const details1 = {
code: 'HOST_NOT_ENOUGH_FREE_MEMORY',
params: ['8589934592', '2147483648'],
call: {
method: 'VM.start',
params: ['OpaqueRef:3f2a9c1e-7b4d-4e8a-9f6c-2d1b5a8e7c90', false, false],
},
}
const details2 =
'TypeError: Failed to fetch\n at fetchApi (rest-api.ts:42:11)\n at async createCluster (cluster-create.job.ts:88:5)'
const presets = {
'Without details': {
props: { details: undefined },
},
'With details object': {
props: { details: details1 },
},
'With details string': {
props: { details: details2 },
},
}
</script>
<style lang="postcss" scoped>
.story {
position: relative;
height: 100%;
}
</style>

View File

@@ -1,60 +0,0 @@
<template>
<ComponentStory
v-slot="{ properties }"
:params="[
prop('charts').type('StatsChart[]').preset(charts).required().widget(),
prop('granularity')
.type('XapiStatsGranularity')
.enum('seconds', 'minutes', 'hours', 'days')
.preset('seconds')
.required()
.widget(),
prop('loading').bool().required().widget(),
prop('error').bool().widget(),
]"
>
<VtsStatsCharts v-bind="properties" />
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { prop } from '@/libs/story/story-param.ts'
import type { StatsChart } from '@core/composables/stats-charts/stats-chart-builders.composable.ts'
import VtsStatsCharts from '@core/components/stats-charts/VtsStatsCharts.vue'
const SAMPLE_COUNT = 60
const now = Date.now()
function buildSeries(label: string, getValue: (index: number) => number) {
return {
label,
data: Array.from({ length: SAMPLE_COUNT }, (_, index) => ({
timestamp: now - (SAMPLE_COUNT - index) * 5000,
value: getValue(index),
})),
}
}
const charts: StatsChart[] = [
{
id: 'cpu',
title: 'CPU usage',
data: [
buildSeries('CPU 0', index => 20 + 10 * Math.sin(index / 5)),
buildSeries('CPU 1', index => 40 + 15 * Math.cos(index / 7)),
],
maxValue: 100,
valueFormatter: value => (value === null ? '' : `${value.toFixed(0)}%`),
},
{
id: 'ram',
title: 'RAM usage',
data: [],
maxValue: 100,
valueFormatter: value => String(value ?? ''),
noDataMessage: 'Guest tools are required to show the RAM usage',
},
]
</script>

View File

@@ -1,25 +0,0 @@
<template>
<ComponentStory
v-slot="{ properties }"
:params="[
model('granularity')
.preset('seconds')
.prop(p => p.type('XapiStatsGranularity').enum('seconds', 'minutes', 'hours', 'days'))
.required()
.help('Period covered by the stats'),
model('showTotals')
.preset(false)
.prop(p => p.bool())
.required()
.help('Whether the charts add a total line'),
]"
>
<VtsStatsToolbar v-bind="properties" />
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { model } from '@/libs/story/story-param.ts'
import VtsStatsToolbar from '@core/components/stats-toolbar/VtsStatsToolbar.vue'
</script>

View File

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

View File

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

View File

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

View File

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

View File

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

View File

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

View File

@@ -89,7 +89,7 @@ const CONTROLLER_PREFIXES = {
* 'config.annotation'?: string,
* 'config.instanceUuid'?: string,
* 'config.firmware'?: string,
* 'config.bootOptions.efiSecureBootEnabled'?: unknown,
* 'config.bootOptions'?: { efiSecureBootEnabled?: unknown },
* 'config.template'?: unknown,
* 'config.hardware.numCPU'?: unknown,
* 'config.hardware.memoryMB'?: unknown,
@@ -379,7 +379,7 @@ export function buildInventory({
annotation: properties['config.annotation'],
instanceUuid: properties['config.instanceUuid'],
firmware: firmware === 'efi' ? 'uefi' : firmware,
secureBoot: isTrue(properties['config.bootOptions.efiSecureBootEnabled']),
secureBoot: isTrue(properties['config.bootOptions']?.efiSecureBootEnabled),
isTemplate: isTrue(properties['config.template']),
cpus: toNumber(properties['config.hardware.numCPU']),
memory: memoryMb === undefined ? undefined : memoryMb * 1024 * 1024,

View File

@@ -1,7 +1,14 @@
import assert from 'node:assert/strict'
import { describe, it } from 'node:test'
import { countSnapshots, findDatacenter, parseDevices, parseGuestNics, parseVlan } from './_inventory.mjs'
import {
buildInventory,
countSnapshots,
findDatacenter,
parseDevices,
parseGuestNics,
parseVlan,
} from './_inventory.mjs'
// shaped as the SOAP library returns them: the nested references and types are not normalized
const typed = (type, value) => ({ attributes: { 'xsi:type': type }, ...value })
@@ -202,3 +209,37 @@ describe('findDatacenter', function () {
assert.equal(findDatacenter('group-a', loop, datacenterIds), undefined)
})
})
describe('buildInventory', function () {
const EMPTY = {
about: {},
datacenters: {},
clusters: {},
hosts: {},
datastores: {},
networks: {},
portgroups: {},
folders: {},
computeResources: {},
}
it('reads secure boot from the boot options, absent before vSphere 6.5', function () {
const { vms } = buildInventory({
...EMPTY,
vms: {
'vm-65': { 'config.bootOptions': { efiSecureBootEnabled: 'true' } },
// ESXi 6.0: the boot options have no `efiSecureBootEnabled`
'vm-60': { 'config.bootOptions': { bootDelay: '0' } },
'vm-none': {},
},
})
assert.deepEqual(
vms.map(({ id, secureBoot }) => ({ id, secureBoot })),
[
{ id: 'vm-65', secureBoot: true },
{ id: 'vm-60', secureBoot: false },
{ id: 'vm-none', secureBoot: false },
]
)
})
})

View File

@@ -623,7 +623,9 @@ export default class Esxi extends EventEmitter {
'config.annotation',
'config.instanceUuid',
'config.firmware',
'config.bootOptions.efiSecureBootEnabled',
// the whole object rather than `config.bootOptions.efiSecureBootEnabled`: that property only
// exists since vSphere 6.5, and an unknown path fails the whole request (InvalidProperty)
'config.bootOptions',
'config.template',
'config.hardware.numCPU',
'config.hardware.memoryMB',
@@ -1134,9 +1136,11 @@ export default class Esxi extends EventEmitter {
* @returns {Promise<object>} the `info` of the successful task
*/
async snapshot(vmId, name, description, { signal, timeout = 30 * 60e3 } = {}) {
// not `CreateSnapshotEx_Task`: it only exists since vSphere 8 (absent from the WSDL of older
// hosts), and its only addition, the quiesce spec, is not used
return this.#runTask(
'CreateSnapshotEx_Task',
{ _this: vmId, name, description, memory: false },
'CreateSnapshot_Task',
{ _this: vmId, name, description, memory: false, quiesce: false },
{ signal, timeout }
)
}

View File

@@ -696,7 +696,7 @@ describe('tasks', function () {
const controller = new AbortController()
const { esxi, vimClient } = await connectedEsxi({
responses: {
CreateSnapshotEx_Task: () => startedTask(),
CreateSnapshot_Task: () => startedTask(),
RetrievePropertiesEx: () => {
controller.abort()
return taskInfo('running')

View File

@@ -59,6 +59,7 @@ Testing uses **Vitest 5** with a single `unit` project (see `vitest.config.ts`):
| `test/expect-loader.ts` | `hasLoader(wrapper)`: whether a `UiLoader` is rendered; `expectLoaderInsteadOf(wrapper, findContent)`: a `UiLoader` shown and the content it stands for empty (also used by XO 6) |
| `test/select.ts` | `openSelect`, `findShownSelections`, `findSelectOptionLabels`, `pickSelectOption(wrapper, label, { detailed? })`: opens a `VtsSelect`, reads the selection it shows, reads or picks its options (`detailed`: the option shows details after its label); `chooseSelectOption(wrapper, label, { container?, detailed? })`: opens the select inside `container`, then picks the option (also used by XO 6) |
| `test/is-placeholder-shown.ts` | `isPlaceholderShown(field)`: whether a readonly input shows its placeholder in place of its value |
| `test/can-focus-input.ts` | `canFocusInput(wrapper)`: whether the first input of a wrapper attached to the document takes the focus, which an `inert` ancestor prevents |
| `test/inject-or-throw.ts` | `injectOrThrow(key)`: `inject(key)`, throwing when nothing provides it |
| `test/mount-with-setup.ts` | `mountWithSetup(setup, { global?, attachTo? })`: mounts a component whose `setup` sets up what its render needs below it (a select, a provided context) and returns that render (XO 6 wraps it with its config); `mountWithSetupResult(setup, options)`: the same, keeping what `setup` builds (a form, a composable's return), `setup` returning `{ result, render }`, returns `{ wrapper, result }`; `mountComposableUnderSetup(setup, composable, options)`: runs `composable` (given what `setup` returned) in a child of the component whose `setup` provides what it injects, returns `{ provided, result }` |
| `test/mount-with-select.ts` | `renderSelect(id, { accent?, ref? }, slots?)`: renders the `VtsSelect` of a select id, `neutral` accent by default; `mountSelect`: a `VtsSelect` of string sources, its config, accent, wrapper message, option slot and a callback receiving the mounted select |

View File

@@ -46,7 +46,7 @@ const columnTransition = `grid-template-columns ${PANEL_TRANSITION_DURATION}ms`
display: grid;
grid-template-columns: minmax(0, 1fr) 0;
grid-template-rows: minmax(0, 1fr);
overflow: hidden;
overflow: clip;
.content {
overflow-y: auto;

View File

@@ -0,0 +1,38 @@
import VtsLayoutSidebar from '@core/components/layout/VtsLayoutSidebar.vue'
import { useRightSidebarStore } from '@core/packages/sidebar'
import { canFocusInput } from '@core-test/can-focus-input.ts'
import { createGlobalTestConfig } from '@core-test/create-global-test-config.ts'
import { mount } from '@vue/test-utils'
import { h, nextTick } from 'vue'
beforeEach(() => {
localStorage.clear()
})
function mountSidebar({ isExpanded }: { isExpanded: boolean }) {
localStorage.setItem('sidebar.right.expanded', String(isExpanded))
return mount(VtsLayoutSidebar, {
props: { side: 'right' },
slots: { default: () => h('input') },
global: createGlobalTestConfig(),
attachTo: document.body,
})
}
it('lets the focus into an expanded sidebar', () => {
expect(canFocusInput(mountSidebar({ isExpanded: true }))).toBe(true)
})
it('keeps the focus out of a collapsed sidebar', () => {
expect(canFocusInput(mountSidebar({ isExpanded: false }))).toBe(false)
})
it('lets the focus in once the sidebar expands', async () => {
const wrapper = mountSidebar({ isExpanded: false })
useRightSidebarStore().toggleExpand(true)
await nextTick()
expect(canFocusInput(wrapper)).toBe(true)
})

View File

@@ -1,5 +1,5 @@
<template>
<div :class="className" class="vts-layout-sidebar">
<div :class="className" class="vts-layout-sidebar" :inert="!sidebar.isExpanded">
<VtsResizeHandle v-if="showResizeHandle" :position="resizeHandlePosition" :resizable="sidebar" />
<div v-if="slots.header || (showLock && !ui.isSmall)" class="header">
<div v-if="slots.header" class="start">

View File

@@ -4,7 +4,7 @@
<script lang="ts" setup>
import type { LinearChartData, ValueFormatter } from '@core/types/chart.ts'
import { timeFormat as createTimeFormatter } from 'd3-time-format'
import { timeFormat } from 'd3-time-format'
import type { EChartsOption } from 'echarts'
import { LineChart } from 'echarts/charts'
import { GridComponent, LegendComponent, TooltipComponent } from 'echarts/components'
@@ -17,18 +17,15 @@ const {
data,
valueFormatter: rawValueFormatter,
maxValue,
timeFormat = '%a\n%H:%M',
} = defineProps<{
data: LinearChartData
valueFormatter?: ValueFormatter
maxValue?: number
// d3-time-format specifier for the X axis labels
timeFormat?: string
}>()
const Y_AXIS_MAX_VALUE = 200
const xAxisLabelFormatter = computed(() => createTimeFormatter(timeFormat))
const xAxisLabelFormatter = timeFormat('%a\n%H:%M')
const valueFormatter = computed<ValueFormatter>(() => {
const formatter = rawValueFormatter
@@ -50,8 +47,6 @@ use([CanvasRenderer, LineChart, GridComponent, TooltipComponent, LegendComponent
const option = computed<EChartsOption>(() => ({
legend: {
// A single scrollable row, so that many series (e.g. one per CPU) don't overflow onto the chart
type: 'scroll',
data: data.map(series => series.label),
},
tooltip: {
@@ -63,10 +58,9 @@ const option = computed<EChartsOption>(() => ({
xAxis: {
type: 'time',
axisLabel: {
formatter: (timestamp: number) => xAxisLabelFormatter.value(new Date(timestamp)),
formatter: (timestamp: number) => xAxisLabelFormatter(new Date(timestamp)),
showMaxLabel: false,
showMinLabel: false,
hideOverlap: true,
},
},
yAxis: {
@@ -80,7 +74,6 @@ const option = computed<EChartsOption>(() => ({
type: 'line',
name: series.label,
zlevel: index + 1,
lineStyle: series.dashed ? { type: 'dashed' } : undefined,
data: series.data.map(item => [item.timestamp, isNaN(item.value ?? NaN) ? null : item.value]),
})),
}))

View File

@@ -1,13 +1,29 @@
<template>
<UiModal accent="danger" icon="status:danger-picto" @dismiss="emit('close')" @confirm="emit('close')">
<UiModal
class="vts-error-modal"
accent="danger"
icon="status:info-picto"
@dismiss="emit('close')"
@confirm="emit('close')"
>
<template #title>
{{ title }}
</template>
<template #content>
<slot name="content">
{{ error }}
</slot>
<div class="content">
<slot name="content">
{{ error }}
</slot>
<UiLogEntryViewer
v-if="details !== undefined"
:label="t('see-details')"
:content="details"
accent="danger"
size="small"
class="details"
/>
</div>
</template>
<template #buttons>
@@ -20,12 +36,14 @@
<script lang="ts" setup>
import VtsOverlayConfirmButton from '@core/components/overlay/VtsOverlayConfirmButton.vue'
import UiLogEntryViewer from '@core/components/ui/log-entry-viewer/UiLogEntryViewer.vue'
import UiModal from '@core/components/ui/modal/UiModal.vue'
import { useI18n } from 'vue-i18n'
defineProps<{
title: string
error?: string
details?: string | object
}>()
const emit = defineEmits<{
@@ -38,3 +56,19 @@ defineSlots<{
const { t } = useI18n()
</script>
<style lang="postcss" scoped>
.vts-error-modal {
.content {
display: flex;
flex-direction: column;
gap: 0.8rem;
}
.details {
text-align: start;
/* The small action buttons must not overflow the scrollable modal content */
overflow-x: clip;
}
}
</style>

View File

@@ -0,0 +1,36 @@
import VtsSidePanel from '@core/components/panel/VtsSidePanel.vue'
import { canFocusInput } from '@core-test/can-focus-input.ts'
import { createGlobalTestConfig } from '@core-test/create-global-test-config.ts'
import { mount } from '@vue/test-utils'
import { h } from 'vue'
beforeEach(() => {
localStorage.clear()
})
function mountPanel({ hasSelection }: { hasSelection: boolean }) {
localStorage.setItem('panel.locked', 'false')
return mount(VtsSidePanel, {
props: { hasSelection, persistent: true },
slots: { default: () => h('input') },
global: createGlobalTestConfig(),
attachTo: document.body,
})
}
it('lets the focus into a panel that a selection expands', () => {
expect(canFocusInput(mountPanel({ hasSelection: true }))).toBe(true)
})
it('keeps the focus out of a collapsed panel', () => {
expect(canFocusInput(mountPanel({ hasSelection: false }))).toBe(false)
})
it('lets the focus in once a selection expands the panel', async () => {
const wrapper = mountPanel({ hasSelection: false })
await wrapper.setProps({ hasSelection: true })
expect(canFocusInput(wrapper)).toBe(true)
})

View File

@@ -1,6 +1,6 @@
<!-- v5 -->
<template>
<div class="vts-side-panel" :class="{ mobile: uiStore.isSmall }">
<div class="vts-side-panel" :class="{ mobile: uiStore.isSmall }" :inert="!panelStore.isExpanded">
<VtsResizeHandle v-if="showResizeHandle" position="start" :resizable="panelStore" />
<VtsPanel
:closable="isClosable"

View File

@@ -1,81 +0,0 @@
<template>
<!-- After a failed refresh, the charts of the previous stats are kept rather than replaced by the error -->
<VtsStateHero v-if="error && charts.length === 0" format="page" type="error" size="large">
{{ t('error-no-data') }}
</VtsStateHero>
<VtsStateHero v-else-if="loading" format="page" type="busy" size="large" />
<VtsStateHero v-else-if="charts.length === 0" format="page" type="no-data" size="large">
{{ t('no-data-to-calculate') }}
</VtsStateHero>
<div v-else :class="className" class="vts-stats-charts">
<UiCard v-for="chart in charts" :key="chart.id" :has-error="error">
<UiCardTitle>
{{ chart.title }}
<template #description>{{ periodLabel }}</template>
</UiCardTitle>
<VtsStateHero v-if="chart.data.length === 0" format="card" type="no-data" size="medium">
{{ chart.noDataMessage ?? t('no-data-to-calculate') }}
</VtsStateHero>
<VtsLinearChart
v-else
:data="chart.data"
:max-value="chart.maxValue"
:value-formatter="chart.valueFormatter"
:time-format
/>
</UiCard>
</div>
</template>
<script lang="ts" setup>
import VtsStateHero from '@core/components/state-hero/VtsStateHero.vue'
import UiCard from '@core/components/ui/card/UiCard.vue'
import UiCardTitle from '@core/components/ui/card-title/UiCardTitle.vue'
import type { StatsChart } from '@core/composables/stats-charts/stats-chart-builders.composable.ts'
import { useStatsGranularityLabel } from '@core/composables/stats-charts/stats-granularity.composable.ts'
import { useUiStore } from '@core/stores/ui.store.ts'
import type { XapiStatsGranularity } from '@vates/types/common'
import { computed, defineAsyncComponent } from 'vue'
import { useI18n } from 'vue-i18n'
const { granularity } = defineProps<{
charts: StatsChart[]
granularity: XapiStatsGranularity
loading: boolean
error?: boolean
}>()
// d3-time-format specifiers suited to the time span covered by each granularity
const STATS_TIME_FORMATS: Record<XapiStatsGranularity, string> = {
seconds: '%H:%M',
minutes: '%H:%M',
hours: '%a\n%H:%M',
days: '%d %b',
}
const VtsLinearChart = defineAsyncComponent(() => import('@core/components/linear-chart/VtsLinearChart.vue'))
const { t } = useI18n()
const uiStore = useUiStore()
const getGranularityLabel = useStatsGranularityLabel()
const periodLabel = computed(() => getGranularityLabel(granularity))
const timeFormat = computed(() => STATS_TIME_FORMATS[granularity])
const className = computed(() => ({ mobile: uiStore.isSmall }))
</script>
<style lang="postcss" scoped>
.vts-stats-charts {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 0.8rem;
&.mobile {
grid-template-columns: minmax(0, 1fr);
}
}
</style>

View File

@@ -1,48 +0,0 @@
<template>
<UiCard horizontal class="vts-stats-toolbar">
<UiToggle v-model="showTotals">{{ t('show-totals') }}</UiToggle>
<VtsSelect :id accent="neutral" class="granularity" />
</UiCard>
</template>
<script lang="ts" setup>
import VtsSelect from '@core/components/select/VtsSelect.vue'
import UiCard from '@core/components/ui/card/UiCard.vue'
import UiToggle from '@core/components/ui/toggle/UiToggle.vue'
import {
STATS_GRANULARITIES,
useStatsGranularityLabel,
} from '@core/composables/stats-charts/stats-granularity.composable.ts'
import { useFormSelect } from '@core/packages/form-select'
import type { XapiStatsGranularity } from '@vates/types/common'
import { useI18n } from 'vue-i18n'
const granularity = defineModel<XapiStatsGranularity>('granularity', { required: true })
const showTotals = defineModel<boolean>('showTotals', { required: true })
const { t } = useI18n()
const getGranularityLabel = useStatsGranularityLabel()
const { id } = useFormSelect(STATS_GRANULARITIES, {
model: granularity,
required: true,
option: {
label: getGranularityLabel,
},
})
</script>
<style lang="postcss" scoped>
.vts-stats-toolbar {
flex-wrap: wrap;
gap: 1.6rem;
align-items: center;
justify-content: space-between;
.granularity {
min-width: 20rem;
}
}
</style>

View File

@@ -1,6 +1,7 @@
<template>
<UiInfo
v-tooltip="iconOnly ? currentStatus.text : false"
class="vts-status"
:accent="currentStatus.accent"
:role="iconOnly ? 'img' : undefined"
:aria-label="iconOnly ? currentStatus.text : undefined"
@@ -73,3 +74,13 @@ const currentStatus = useMapper<Status, { text: string; accent: InfoAccent }>(
false
)
</script>
<style lang="postcss" scoped>
.ui-info.vts-status {
align-items: center;
:deep(.icon) {
transform: none;
}
}
</style>

View File

@@ -1,7 +1,7 @@
<!-- v9 -->
<template>
<div class="ui-checkbox">
<label :class="classNames" class="checkbox-label" v-bind="wrapperAttrs">
<label :class="[classNames, { 'has-label': slots.default }]" class="checkbox-label" v-bind="wrapperAttrs">
<input
v-model="checkboxModel"
:disabled="isDisabled"
@@ -79,6 +79,14 @@ const attrs = useAttrs()
align-items: center;
gap: 0.4rem;
&.has-label {
align-items: flex-start;
.fake-checkbox {
margin-block-start: 0.4rem;
}
}
.fake-checkbox {
--checkbox-mark-color: var(--color-neutral-background-primary);
position: relative;

View File

@@ -36,13 +36,14 @@ const isDisabled = useDisabled(() => disabled)
.ui-radio-button {
--radio-dot-color: var(--color-neutral-background-primary);
display: inline-flex;
align-items: center;
align-items: flex-start;
gap: 0.8rem;
.radio {
position: relative;
display: inline-flex;
flex-shrink: 0;
margin-block-start: 0.4rem;
border-radius: 50%;
color: var(--radio-color);
transition:

View File

@@ -0,0 +1,10 @@
import { useOverlay } from '@core/packages/overlay/use-overlay.ts'
export function useErrorModal() {
return useOverlay({
component: () => import('@core/components/modal/VtsErrorModal.vue'),
events: {
onClose: true,
},
})
}

View File

@@ -1,49 +0,0 @@
import {
type StatsChart,
toNamedSamples,
useStatsChartBuilders,
} from '@core/composables/stats-charts/stats-chart-builders.composable.ts'
import { getMaxSample } from '@core/utils/linear-chart-series.util.ts'
import type { XapiHostStats } from '@vates/types/common'
import { computed, type ComputedRef, type MaybeRefOrGetter, toValue } from 'vue'
import { useI18n } from 'vue-i18n'
// XAPI names host network metrics after the PIF device (pif_eth0_rx → key `0`)
const getPifName = (key: string) => `eth${key}`
export function useHostStatsCharts(
stats: MaybeRefOrGetter<XapiHostStats | undefined>,
showTotals: MaybeRefOrGetter<boolean>
): ComputedRef<StatsChart[]> {
const { t } = useI18n()
const { buildCpuChart, buildRamChart, buildThroughputChart, buildLoadChart, getCpuSamples, getUsedRamSamples } =
useStatsChartBuilders()
return computed(() => {
const hostStats = toValue(stats)
if (hostStats === undefined) {
return []
}
const withTotal = toValue(showTotals)
const { cpus, memory, memoryFree, pifs, load } = hostStats.stats
return [
buildCpuChart(hostStats, getCpuSamples(cpus), { withTotal }),
buildRamChart(hostStats, getUsedRamSamples(memory, memoryFree), { maxValue: getMaxSample(memory) }),
buildThroughputChart(
'network',
hostStats,
[
{ direction: 'upload', samples: toNamedSamples(pifs?.tx, getPifName) },
{ direction: 'download', samples: toNamedSamples(pifs?.rx, getPifName) },
],
{ withTotal }
),
buildLoadChart(hostStats, load ? [{ name: t('load-average'), values: load }] : []),
]
})
}

View File

@@ -1,99 +0,0 @@
import { useHostStatsCharts } from '@core/composables/stats-charts/host-stats-charts.composable.ts'
import { t } from '@core-test/i18n.ts'
import { mountComposable } from '@core-test/mount-composable.ts'
import type { XapiHostStats } from '@vates/types/common'
import { ref } from 'vue'
const hostStats: XapiHostStats = {
endTimestamp: 1000,
interval: 5,
stats: {
cpus: { 0: [10, 20], 1: [30, 40] },
memory: [100, 100],
memoryFree: [60, 40],
pifs: { rx: { 0: [1, 2], 1: [3, 4] }, tx: { 0: [5, 6] } },
load: [0.5, 0.75],
},
}
function mountCharts(stats: XapiHostStats | undefined, showTotals = false) {
const totals = ref(showTotals)
const { wrapper } = mountComposable(() => ({ charts: useHostStatsCharts(stats, totals) }))
return { charts: () => wrapper.vm.charts, totals }
}
function getLabels(charts: ReturnType<typeof mountCharts>['charts'], id: string) {
return charts()
.find(chart => chart.id === id)
?.data.map(series => series.label)
}
it('has no chart until the stats are fetched', () => {
expect(mountCharts(undefined).charts()).toEqual([])
})
it('shows the CPU, RAM, network and load charts', () => {
expect(
mountCharts(hostStats)
.charts()
.map(chart => chart.id)
).toEqual(['cpu', 'ram', 'network', 'load'])
})
it('draws one line per CPU and per PIF direction', () => {
const { charts } = mountCharts(hostStats)
expect(getLabels(charts, 'cpu')).toEqual([t('cpu-n', { n: 0 }), t('cpu-n', { n: 1 })])
expect(getLabels(charts, 'network')).toEqual([
t('series-upload', { name: 'eth0' }),
t('series-download', { name: 'eth0' }),
t('series-download', { name: 'eth1' }),
])
})
it('draws the used RAM against the total memory', () => {
const ramChart = mountCharts(hostStats)
.charts()
.find(chart => chart.id === 'ram')
expect(ramChart?.data[0].data.map(point => point.value)).toEqual([40, 60])
expect(ramChart?.maxValue).toBe(100)
})
it('scales the CPU chart to a single CPU without the totals', () => {
const { charts } = mountCharts(hostStats)
expect(charts().find(chart => chart.id === 'cpu')?.maxValue).toBe(100)
})
it('adds the totals when asked: the summed CPUs, scaled to every CPU, and the summed throughput', () => {
const { charts } = mountCharts(hostStats, true)
const cpuChart = charts().find(chart => chart.id === 'cpu')
const cpuTotal = cpuChart?.data.at(-1)
expect(cpuTotal?.label).toBe(t('all'))
expect(cpuTotal?.dashed).toBe(true)
expect(cpuTotal?.data.map(point => point.value)).toEqual([40, 60])
expect(cpuChart?.maxValue).toBe(200)
expect(getLabels(charts, 'network')).toContain(t('series-download', { name: t('all') }))
})
it('removes the totals when they are turned off', () => {
const { charts, totals } = mountCharts(hostStats, true)
totals.value = false
expect(getLabels(charts, 'cpu')).not.toContain(t('all'))
})
it('formats the load with 3 significant digits', () => {
const loadChart = mountCharts(hostStats)
.charts()
.find(chart => chart.id === 'load')
expect([0.5, 1.254, 12].map(value => loadChart?.valueFormatter(value))).toEqual(['0.500', '1.25', '12.0'])
})

View File

@@ -1,135 +0,0 @@
import {
type NamedSamples,
type StatsChart,
useStatsChartBuilders,
} from '@core/composables/stats-charts/stats-chart-builders.composable.ts'
import { compareStrings } from '@core/utils/compare-strings.util.ts'
import {
getMaxSample,
type SampleValues,
type SamplesWindow,
subtractSamples,
sumSamples,
} from '@core/utils/linear-chart-series.util.ts'
import type { XapiHostStats } from '@vates/types/common'
import { sum } from 'lodash-es'
import { computed, type ComputedRef, type MaybeRefOrGetter, toValue } from 'vue'
import { useI18n } from 'vue-i18n'
export type PoolHostStats = { name: string; stats: XapiHostStats }
// A host whose last sample is older than this is lagging (stopped polling, clock behind…) and doesn't shrink the window
const MAX_LAG_INTERVALS = 2
// Hosts are not polled at the same instant: the window ends with the oldest last sample of the up-to-date hosts, so that
// they all have a sample at each point and the totals don't drop at the end
function getCommonWindow(hosts: PoolHostStats[]): SamplesWindow {
const interval = hosts[0].stats.interval
const endTimestamps = hosts.map(({ stats }) => stats.endTimestamp)
const newestEndTimestamp = Math.max(...endTimestamps)
return {
endTimestamp: Math.min(
...endTimestamps.filter(endTimestamp => newestEndTimestamp - endTimestamp <= MAX_LAG_INTERVALS * interval)
),
interval,
}
}
// Shifts the samples of a host onto the window, keeping their count: samples past its end are dropped, and a lagging
// host gets `null` samples where it has none yet
function alignToWindow(values: SampleValues, hostStats: XapiHostStats, window: SamplesWindow): SampleValues {
const offset = Math.round((hostStats.endTimestamp - window.endTimestamp) / window.interval)
if (offset > 0) {
return values.slice(0, -offset)
}
if (offset < 0) {
return [...values.slice(-offset), ...Array.from({ length: Math.min(-offset, values.length) }, () => null)]
}
return values
}
function toHostSamples(
hosts: PoolHostStats[],
window: SamplesWindow,
getValues: (stats: XapiHostStats['stats']) => SampleValues | undefined
): NamedSamples[] {
return hosts.flatMap(({ name, stats }) => {
const values = getValues(stats.stats)
return values === undefined ? [] : [{ name, values: alignToWindow(values, stats, window) }]
})
}
function sumRecords(records: Record<string, SampleValues> | undefined): SampleValues | undefined {
return records === undefined ? undefined : sumSamples(Object.values(records))
}
export function usePoolStatsCharts(
hostsStats: MaybeRefOrGetter<PoolHostStats[]>,
showTotals: MaybeRefOrGetter<boolean>
): ComputedRef<StatsChart[]> {
const { t } = useI18n()
const { buildCpuChart, buildRamChart, buildThroughputChart, buildLoadChart } = useStatsChartBuilders()
return computed(() => {
// Sorted so that each host keeps its line color from one refresh to the next
const hosts = [...toValue(hostsStats)].sort((host1, host2) => compareStrings(host1.name, host2.name))
if (hosts.length === 0) {
return []
}
const window = getCommonWindow(hosts)
const withTotal = toValue(showTotals)
// With the totals, the scale covers the whole pool, otherwise the biggest host
const scaleTo = (values: number[]) => (withTotal ? sum(values) : Math.max(0, ...values))
// As in XO 5, the line of a host is the sum of its CPUs
const cpuSamples = toHostSamples(hosts, window, ({ cpus }) => sumRecords(cpus))
const cpuCounts = hosts.map(({ stats }) => Object.keys(stats.stats.cpus ?? {}).length)
const ramSamples = toHostSamples(hosts, window, ({ memory, memoryFree }) =>
memory && memoryFree ? subtractSamples(memory, memoryFree) : undefined
)
const totalMemories = hosts.map(({ stats }) => getMaxSample(stats.stats.memory))
// As in XO 5, the network totals replace the lines of the hosts instead of being added to them
const getPifSamples = (getValues: (stats: XapiHostStats['stats']) => SampleValues | undefined) => {
const samples = toHostSamples(hosts, window, getValues)
return withTotal && samples.length > 0
? [{ name: t('all'), values: sumSamples(samples.map(({ values }) => values)) }]
: samples
}
return [
buildCpuChart(window, cpuSamples, { withTotal, maxValue: 100 * scaleTo(cpuCounts) }),
buildRamChart(window, ramSamples, { withTotal, maxValue: scaleTo(totalMemories) }),
buildThroughputChart(
'network',
window,
[
{ direction: 'upload', samples: getPifSamples(({ pifs }) => sumRecords(pifs?.tx)) },
{ direction: 'download', samples: getPifSamples(({ pifs }) => sumRecords(pifs?.rx)) },
],
{ withTotal: false }
),
buildLoadChart(
window,
toHostSamples(hosts, window, ({ load }) => load),
{ withTotal }
),
]
})
}

View File

@@ -1,122 +0,0 @@
import { type PoolHostStats, usePoolStatsCharts } from '@core/composables/stats-charts/pool-stats-charts.composable.ts'
import { t } from '@core-test/i18n.ts'
import { mountComposable } from '@core-test/mount-composable.ts'
import type { XapiHostStats } from '@vates/types/common'
function createHostStats(endTimestamp: number, stats: XapiHostStats['stats']): XapiHostStats {
return { endTimestamp, interval: 5, stats }
}
function mountCharts(hostsStats: PoolHostStats[], showTotals = false) {
const { wrapper } = mountComposable(() => ({ charts: usePoolStatsCharts(hostsStats, showTotals) }))
return wrapper.vm.charts
}
function getChart(charts: ReturnType<typeof mountCharts>, id: string) {
return charts.find(chart => chart.id === id)
}
it('has no chart without any running host', () => {
expect(mountCharts([])).toEqual([])
})
it('draws one line per host, sorted by name', () => {
const charts = mountCharts([
{ name: 'Host B', stats: createHostStats(1000, { load: [1] }) },
{ name: 'Host A', stats: createHostStats(1000, { load: [2] }) },
])
expect(getChart(charts, 'load')?.data.map(series => series.label)).toEqual(['Host A', 'Host B'])
})
it('sums the CPUs of each host, scaled to the host with the most CPUs', () => {
const charts = mountCharts([
{ name: 'Small host', stats: createHostStats(1000, { cpus: { 0: [100] } }) },
{ name: 'Big host', stats: createHostStats(1000, { cpus: { 0: [10], 1: [30], 2: [0] } }) },
])
const cpuChart = getChart(charts, 'cpu')
expect(cpuChart?.data.find(series => series.label === 'Big host')?.data[0].value).toBe(40)
expect(cpuChart?.maxValue).toBe(300)
})
it('sums the CPUs of every host for the pool total, scaled to every CPU of the pool', () => {
const charts = mountCharts(
[
{ name: 'Small host', stats: createHostStats(1000, { cpus: { 0: [100] } }) },
{ name: 'Big host', stats: createHostStats(1000, { cpus: { 0: [10], 1: [30], 2: [0] } }) },
],
true
)
const cpuChart = getChart(charts, 'cpu')
const cpuTotal = cpuChart?.data.at(-1)
expect(cpuTotal?.label).toBe(t('all'))
expect(cpuTotal?.data[0].value).toBe(140)
expect(cpuChart?.maxValue).toBe(400)
})
it('drops the samples a host has past the others, so that the totals cover every host', () => {
const charts = mountCharts(
[
{ name: 'Late host', stats: createHostStats(1000, { load: [1, 1] }) },
{ name: 'Early host', stats: createHostStats(1005, { load: [2, 2, 2] }) },
],
true
)
const loadTotal = getChart(charts, 'load')?.data.at(-1)
expect(loadTotal?.data).toEqual([
{ timestamp: 995_000, value: 3 },
{ timestamp: 1_000_000, value: 3 },
])
})
it('keeps the newest samples when a host lags behind, and shifts that host onto its own timestamps', () => {
const charts = mountCharts([
{ name: 'Up-to-date host', stats: createHostStats(1000, { load: [1, 1, 1] }) },
{ name: 'Lagging host', stats: createHostStats(600, { load: [2, 2, 2] }) },
])
const [laggingHostLoad, upToDateHostLoad] = getChart(charts, 'load')?.data ?? []
expect(upToDateHostLoad.data.map(point => point.value)).toEqual([1, 1, 1])
expect(upToDateHostLoad.data.at(-1)?.timestamp).toBe(1_000_000)
expect(laggingHostLoad.data.map(point => point.value)).toEqual([null, null, null])
})
it('scales the RAM chart to the biggest host, or to the whole pool with the totals', () => {
const hostsStats = [
{ name: 'Host A', stats: createHostStats(1000, { memory: [100], memoryFree: [50] }) },
{ name: 'Host B', stats: createHostStats(1000, { memory: [300], memoryFree: [100] }) },
]
expect(getChart(mountCharts(hostsStats), 'ram')?.maxValue).toBe(300)
expect(getChart(mountCharts(hostsStats, true), 'ram')?.maxValue).toBe(400)
})
it('draws the network of each host, or only the pool totals with the totals', () => {
const hostsStats = [
{ name: 'Host A', stats: createHostStats(1000, { pifs: { rx: { 0: [1], 1: [2] }, tx: { 0: [10] } } }) },
{ name: 'Host B', stats: createHostStats(1000, { pifs: { rx: { 0: [4] }, tx: { 0: [20] } } }) },
]
expect(getChart(mountCharts(hostsStats), 'network')?.data.map(series => series.label)).toEqual([
t('series-upload', { name: 'Host A' }),
t('series-upload', { name: 'Host B' }),
t('series-download', { name: 'Host A' }),
t('series-download', { name: 'Host B' }),
])
expect(
getChart(mountCharts(hostsStats, true), 'network')?.data.map(({ label, data }) => ({ label, value: data[0].value }))
).toEqual([
{ label: t('series-upload', { name: t('all') }), value: 30 },
{ label: t('series-download', { name: t('all') }), value: 7 },
])
})

View File

@@ -1,163 +0,0 @@
import type { LinearChartData, ValueFormatter } from '@core/types/chart.ts'
import {
getMaxSample,
roundUpToMagnitude,
type SampleValues,
type SamplesWindow,
subtractSamples,
sumSamples,
toLinearChartSeries,
} from '@core/utils/linear-chart-series.util.ts'
import { formatSize } from '@core/utils/size.util.ts'
import { useI18n } from 'vue-i18n'
export type StatsChart = {
id: 'cpu' | 'ram' | 'network' | 'disk' | 'load'
title: string
data: LinearChartData
maxValue: number
valueFormatter: ValueFormatter
noDataMessage?: string
}
// One line of a chart: a CPU, a network interface, a host…
export type NamedSamples = { name: string; values: SampleValues }
type ThroughputDirection = 'download' | 'upload' | 'read' | 'write'
type ChartOptions = { withTotal?: boolean; maxValue?: number }
const ONE_GIB = 1024 ** 3
const ONE_KIB = 1024
export function toNamedSamples(
records: Record<string, SampleValues> | undefined,
getName: (key: string) => string
): NamedSamples[] {
return Object.entries(records ?? {}).map(([key, values]) => ({ name: getName(key), values }))
}
function getDataMax(data: LinearChartData): number {
return getMaxSample(data.flatMap(series => series.data.map(point => point.value)))
}
export function useStatsChartBuilders() {
const { t, n } = useI18n()
const formatPercent: ValueFormatter = value => (value === null ? '' : n(value / 100, 'percent'))
// As in XO 5, 3 significant digits (0.500, 1.25, 12.0)
const formatLoad: ValueFormatter = value =>
value === null ? '' : n(value, { minimumSignificantDigits: 3, maximumSignificantDigits: 3 })
const formatBytes: ValueFormatter = value => (value === null ? '' : formatSize(value, 1))
const directionLabels: Record<ThroughputDirection, (name: string) => string> = {
download: name => t('series-download', { name }),
upload: name => t('series-upload', { name }),
read: name => t('series-read', { name }),
write: name => t('series-write', { name }),
}
// As in XO 5, the total is dashed to set it apart from the lines it sums
function toChartData(
window: SamplesWindow,
samples: NamedSamples[],
withTotal = false,
totalLabel = t('all')
): LinearChartData {
const data = samples.map(({ name, values }) => toLinearChartSeries(window, name, values))
if (withTotal && samples.length > 0) {
data.push({
...toLinearChartSeries(window, totalLabel, sumSamples(samples.map(({ values }) => values))),
dashed: true,
})
}
return data
}
// As in XO 5, the CPU total is a sum, so the scale goes up to 100% per CPU when it's shown
function buildCpuChart(
window: SamplesWindow,
samples: NamedSamples[],
{ withTotal, maxValue = withTotal ? samples.length * 100 : 100 }: ChartOptions
): StatsChart {
return {
id: 'cpu',
title: t('cpu-usage'),
data: toChartData(window, samples, withTotal),
maxValue: maxValue || 100,
valueFormatter: formatPercent,
}
}
function buildRamChart(
window: SamplesWindow,
samples: NamedSamples[],
{ withTotal, maxValue, noDataMessage }: ChartOptions & { noDataMessage?: string }
): StatsChart {
return {
id: 'ram',
title: t('ram-usage'),
data: toChartData(window, samples, withTotal),
maxValue: maxValue || ONE_GIB,
valueFormatter: formatBytes,
noDataMessage,
}
}
function buildThroughputChart(
id: 'network' | 'disk',
window: SamplesWindow,
groups: { direction: ThroughputDirection; samples: NamedSamples[] }[],
{ withTotal }: ChartOptions
): StatsChart {
const data = groups.flatMap(({ direction, samples }) => {
const getLabel = directionLabels[direction]
return toChartData(
window,
samples.map(({ name, values }) => ({ name: getLabel(name), values })),
withTotal,
getLabel(t('all'))
)
})
return {
id,
title: id === 'network' ? t('network-throughput') : t('vdi-throughput'),
data,
maxValue: roundUpToMagnitude(getDataMax(data)) || ONE_KIB,
valueFormatter: formatBytes,
}
}
function buildLoadChart(
window: SamplesWindow,
samples: NamedSamples[],
{ withTotal }: ChartOptions = {}
): StatsChart {
const data = toChartData(window, samples, withTotal)
return {
id: 'load',
title: t('load-average'),
data,
maxValue: roundUpToMagnitude(getDataMax(data)) || 1,
valueFormatter: formatLoad,
}
}
function getCpuSamples(cpus: Record<string, SampleValues> | undefined): NamedSamples[] {
return toNamedSamples(cpus, key => t('cpu-n', { n: key }))
}
function getUsedRamSamples(memory: SampleValues | undefined, memoryFree: SampleValues | undefined): NamedSamples[] {
return memory && memoryFree ? [{ name: t('used'), values: subtractSamples(memory, memoryFree) }] : []
}
return { buildCpuChart, buildRamChart, buildThroughputChart, buildLoadChart, getCpuSamples, getUsedRamSamples }
}

View File

@@ -1,22 +0,0 @@
import type { XapiStatsGranularity } from '@vates/types/common'
import { useI18n } from 'vue-i18n'
export const STATS_GRANULARITIES = ['seconds', 'minutes', 'hours', 'days'] as const satisfies XapiStatsGranularity[]
export function useStatsGranularityLabel() {
const { t } = useI18n()
// XAPI keeps 10 minutes of 5-second samples, 2 hours of 1-minute samples, 1 week of hourly and 1 year of daily samples
return (granularity: XapiStatsGranularity): string => {
switch (granularity) {
case 'seconds':
return t('last-n-minutes', 10)
case 'minutes':
return t('last-n-hours', 2)
case 'hours':
return t('last-week')
case 'days':
return t('last-year')
}
}
}

View File

@@ -1,63 +0,0 @@
import {
type StatsChart,
toNamedSamples,
useStatsChartBuilders,
} from '@core/composables/stats-charts/stats-chart-builders.composable.ts'
import { getMaxSample } from '@core/utils/linear-chart-series.util.ts'
import type { XapiVmStats } from '@vates/types/common'
import { computed, type ComputedRef, type MaybeRefOrGetter, toValue } from 'vue'
import { useI18n } from 'vue-i18n'
// XAPI names VM disk metrics after the device letter (vbd_xvda_read → key `a`)
const getDiskName = (key: string) => `xvd${key}`
export function useVmStatsCharts(
stats: MaybeRefOrGetter<XapiVmStats | undefined>,
showTotals: MaybeRefOrGetter<boolean>
): ComputedRef<StatsChart[]> {
const { t } = useI18n()
const { buildCpuChart, buildRamChart, buildThroughputChart, getCpuSamples, getUsedRamSamples } =
useStatsChartBuilders()
const getVifName = (key: string) => t('vif-device', { device: key })
return computed(() => {
const vmStats = toValue(stats)
if (vmStats === undefined) {
return []
}
const withTotal = toValue(showTotals)
const { cpus, memory, memoryFree, vifs, xvds } = vmStats.stats
return [
buildCpuChart(vmStats, getCpuSamples(cpus), { withTotal }),
buildRamChart(vmStats, getUsedRamSamples(memory, memoryFree), {
maxValue: getMaxSample(memory),
// Free memory is reported by the guest tools only
noDataMessage: memory && !memoryFree ? t('ram-usage-requires-guest-tools') : undefined,
}),
buildThroughputChart(
'network',
vmStats,
[
{ direction: 'upload', samples: toNamedSamples(vifs?.tx, getVifName) },
{ direction: 'download', samples: toNamedSamples(vifs?.rx, getVifName) },
],
{ withTotal }
),
buildThroughputChart(
'disk',
vmStats,
[
{ direction: 'read', samples: toNamedSamples(xvds?.r, getDiskName) },
{ direction: 'write', samples: toNamedSamples(xvds?.w, getDiskName) },
],
{ withTotal }
),
]
})
}

View File

@@ -1,49 +0,0 @@
import { useVmStatsCharts } from '@core/composables/stats-charts/vm-stats-charts.composable.ts'
import { t } from '@core-test/i18n.ts'
import { mountComposable } from '@core-test/mount-composable.ts'
import type { XapiVmStats } from '@vates/types/common'
function createVmStats(stats: XapiVmStats['stats']): XapiVmStats {
return { endTimestamp: 1000, interval: 5, stats }
}
function mountCharts(stats: XapiVmStats) {
const { wrapper } = mountComposable(() => ({ charts: useVmStatsCharts(stats, false) }))
return wrapper.vm.charts
}
it('shows the CPU, RAM, network and disk charts', () => {
expect(mountCharts(createVmStats({})).map(chart => chart.id)).toEqual(['cpu', 'ram', 'network', 'disk'])
})
it('names the VIFs after their device and the disks after their XVD letter', () => {
const charts = mountCharts(
createVmStats({
vifs: { rx: { 0: [1] }, tx: {} },
xvds: { r: { a: [1] }, w: { b: [2] } },
})
)
expect(charts.find(chart => chart.id === 'network')?.data.map(series => series.label)).toEqual([
t('series-download', { name: t('vif-device', { device: 0 }) }),
])
expect(charts.find(chart => chart.id === 'disk')?.data.map(series => series.label)).toEqual([
t('series-read', { name: 'xvda' }),
t('series-write', { name: 'xvdb' }),
])
})
it('explains that the RAM usage needs the guest tools when the VM does not report its free memory', () => {
const ramChart = mountCharts(createVmStats({ memory: [100] })).find(chart => chart.id === 'ram')
expect(ramChart?.data).toEqual([])
expect(ramChart?.noDataMessage).toBe(t('ram-usage-requires-guest-tools'))
})
it('draws the used RAM when the guest tools report the free memory', () => {
const ramChart = mountCharts(createVmStats({ memory: [100], memoryFree: [25] })).find(chart => chart.id === 'ram')
expect(ramChart?.data[0].data[0].value).toBe(75)
expect(ramChart?.noDataMessage).toBeUndefined()
})

View File

@@ -95,7 +95,7 @@ function handleBackdropClick() {
display: flex;
flex: 1;
min-height: 0;
overflow-x: hidden;
overflow-x: clip;
}
.header {

View File

@@ -1049,7 +1049,6 @@
"s3-endpoint-sample": "مثال: s3.us-west-1.amazonaws.com",
"scan-pifs": "فحص PIF",
"schedule": "الجدول الزمني",
"schedules": "الجداول الزمنية",
"secret": "السر",
"secure-boot": "الإقلاع الآمن",
"see-details": "عرض التفاصيل",

View File

@@ -1190,7 +1190,6 @@
"s3-endpoint-sample": "Příklad: s3.us-west-1.amazonaws.com",
"scan-pifs": "Skenovat fyzická rozhraní",
"schedule": "Plán",
"schedules": "Plány",
"secret": "Tajemství",
"secure-boot": "Secure boot",
"see-details": "Viz podrobnosti",

View File

@@ -1117,7 +1117,6 @@
"s3-endpoint-sample": "Eksempel: s3.us-west-1.amazonaws.com",
"scan-pifs": "Skan PIF'er",
"schedule": "Tidsplan",
"schedules": "Tidsplaner",
"secret": "Hemmelighed",
"secure-boot": "Secure boot",
"see-details": "Se detaljer",

View File

@@ -745,7 +745,6 @@
"s3-backup-repository": "S3-Backupdepot",
"scan-pifs": "PIFs scannen",
"schedule": "Zeitplan",
"schedules": "Zeitpläne",
"secure-boot": "Secure Boot",
"see-details": "Details anzeigen",
"select-compression": "Kompression auswählen",

View File

@@ -404,7 +404,6 @@
"cpu-cap": "CPU cap",
"cpu-mask": "CPU mask",
"cpu-model": "CPU model",
"cpu-n": "CPU {n}",
"cpu-provisioning": "CPU provisioning",
"cpu-provisioning-warning": "The number of vCPUs allocated exceeds the number of physical CPUs available. System performance could be affected",
"cpu-usage": "CPU usage",
@@ -937,15 +936,12 @@
"last-n-backup-archives": "Last backup archive | Last {n} backup archives",
"last-n-backup-runs": "Last backup run | Last {n} backup runs",
"last-n-days": "Last day | Last {n} days",
"last-n-hours": "Last hour | Last {n} hours",
"last-n-minutes": "Last minute | Last {n} minutes",
"last-n-runs": "Last run | Last {n} runs",
"last-revert": "Last revert",
"last-run-number": "Last run #{n}",
"last-snapshot": "Last snapshot",
"last-sync": "Last sync",
"last-week": "Last week",
"last-year": "Last year",
"ldap-auth-providers": "LDAP/Auth providers",
"learn-more": "Learn more",
"leave-page-safely": "You can safely leave this page.",
@@ -1069,6 +1065,7 @@
"multi-pathing": "Multi-pathing",
"multiple-schedules": "Multiple schedules",
"multiple-schedules-advice": "We advise splitting a backup job with multiple schedules into multiple backup jobs with one schedule each.",
"multiple-schedules-split-in-xo5": "Multiple schedules: split into one job per schedule in XO 5",
"must-be-at-least-n": "Must be at least {n}.",
"n-blocking": "1 blocking | {n} blocking",
"n-bonded-networks": "1 bonded network | {n} bonded networks",
@@ -1453,7 +1450,6 @@
"ram": "RAM",
"ram-provisioning": "RAM provisioning",
"ram-usage": "RAM usage",
"ram-usage-requires-guest-tools": "Guest tools are required to show the RAM usage",
"rate-limit": "Rate limit",
"read": "Read",
"read-only": "Read-only",
@@ -1512,7 +1508,6 @@
"save-xo-config": "Save XO config",
"scan-pifs": "Scan PIFs",
"schedule": "Schedule",
"schedules": "Schedules",
"scope": "Scope",
"scope-preview": "Scope preview",
"scope-type": "Scope type",
@@ -1543,16 +1538,11 @@
"selector": "Selector",
"self-signed-certificates": "Self-signed certificates",
"send-us-feedback": "Send us feedback",
"series-download": "{name} (download)",
"series-read": "{name} (read)",
"series-upload": "{name} (upload)",
"series-write": "{name} (write)",
"server": "Server",
"settings": "Settings",
"shared": "Shared",
"shorter-backup-reports": "Shorter backup reports",
"show-by": "Show by",
"show-totals": "Show totals",
"shutdown-blocked": "Shutdown Blocked",
"size": "Size",
"size-and-speed": "@:size & @.lower:speed",
@@ -1576,6 +1566,7 @@
"snapshot-mode:with-memory-description": "Includes the VM's memory state. The VM will be briefly suspended during the snapshot.",
"snapshot-revert-snapshot-before": "Take a snapshot of the VM before reverting",
"snapshot-revert-warning": "This will restore the VM to the selected snapshot state. Any changes made since then (data, configuration, and disk state) will be lost. This action cannot be undone.",
"snapshot-settings-disabled-offline-backup": "Snapshot settings are disabled because offline backup shuts down the VMs instead of taking a snapshot.",
"snapshot-synchronisation": "Snapshot synchronisation",
"snapshot-vdis": "Snapshot VDIs",
"snapshots": "Snapshots",

View File

@@ -817,7 +817,6 @@
"s3-backup-repository": "Repositorio S3 de salvaguardas",
"scan-pifs": "Escanear PIFs",
"schedule": "Planificación",
"schedules": "Planificaciones",
"secure-boot": "Arranque seguro",
"see-details": "Ver detalles",
"select-compression": "Elige modo de compression",

View File

@@ -1049,7 +1049,6 @@
"s3-endpoint-sample": "مثال: s3.us-west-1.amazonaws.com",
"scan-pifs": "اسکن PIFها",
"schedule": "زمان‌بندی",
"schedules": "زمان‌بندی‌ها",
"secret": "رمز",
"secure-boot": "بوت امن",
"see-details": "مشاهده جزئیات",

View File

@@ -1049,7 +1049,6 @@
"s3-endpoint-sample": "Esimerkki: s3.us-west-1.amazonaws.com",
"scan-pifs": "Skannaa PIF:t",
"schedule": "Aikataulu",
"schedules": "Aikataulut",
"secret": "Salaisuus",
"secure-boot": "Suojattu käynnistys",
"see-details": "Katso tiedot",

View File

@@ -404,7 +404,6 @@
"cpu-cap": "Limite CPU",
"cpu-mask": "Masque CPU",
"cpu-model": "Modèle du CPU",
"cpu-n": "CPU {n}",
"cpu-provisioning": "Provisionnement CPU",
"cpu-provisioning-warning": "Le nombre de vCPU alloués dépasse le nombre de CPU physique disponible. Les performances du système pourraient être affectées",
"cpu-usage": "Utilisation CPU",
@@ -937,15 +936,12 @@
"last-n-backup-archives": "Dernier run d'archivage | {n} derniers archivages",
"last-n-backup-runs": "Dernier run de sauvegarde | {n} dernières sauvegardes",
"last-n-days": "Dernier jour | {n} derniers jours",
"last-n-hours": "Dernière heure | {n} dernières heures",
"last-n-minutes": "Dernière minute | {n} dernières minutes",
"last-n-runs": "Dernier run | {n} derniers runs",
"last-revert": "Dernière restauration",
"last-run-number": "Dernier run #{n}",
"last-snapshot": "Dernier instantané",
"last-sync": "Dernière synchronisation",
"last-week": "Semaine dernière",
"last-year": "12 derniers mois",
"ldap-auth-providers": "LDAP/Fournisseurs d'authentification",
"learn-more": "En savoir plus",
"leave-page-safely": "Vous pouvez quitter la page en toute sécurité.",
@@ -1069,6 +1065,7 @@
"multi-pathing": "Multi-pathing",
"multiple-schedules": "Plusieurs planifications",
"multiple-schedules-advice": "Nous vous conseillons de diviser un job de sauvegarde à plusieurs planifications en plusieurs jobs ayant chacun une seule planification.",
"multiple-schedules-split-in-xo5": "Plusieurs planifications : diviser en un job par planification dans XO 5",
"must-be-at-least-n": "Doit être au moins {n}.",
"n-blocking": "0 bloquante | 1 bloquante | {n} bloquantes",
"n-bonded-networks": "1 réseau lié | {n} réseaux liés",
@@ -1453,7 +1450,6 @@
"ram": "RAM",
"ram-provisioning": "Provisionnement RAM",
"ram-usage": "Utilisation de la RAM",
"ram-usage-requires-guest-tools": "Les guest tools sont nécessaires pour afficher l'utilisation de la RAM",
"rate-limit": "Limite de débit",
"read": "Lecture",
"read-only": "Lecture seule",
@@ -1512,7 +1508,6 @@
"save-xo-config": "Sauvegarder la config XO",
"scan-pifs": "Scan PIFs",
"schedule": "Planification",
"schedules": "Planifications",
"scope": "Périmètre",
"scope-preview": "Aperçu du périmètre",
"scope-type": "Type de périmètre",
@@ -1543,16 +1538,11 @@
"selector": "Sélecteur",
"self-signed-certificates": "Certificats auto-signés",
"send-us-feedback": "Envoyez-nous vos commentaires",
"series-download": "{name} (descendant)",
"series-read": "{name} (lecture)",
"series-upload": "{name} (montant)",
"series-write": "{name} (écriture)",
"server": "Serveur",
"settings": "Paramètres",
"shared": "Partagé",
"shorter-backup-reports": "Rapports de sauvegarde plus courts",
"show-by": "Afficher par",
"show-totals": "Afficher les totaux",
"shutdown-blocked": "Arrêt bloqué",
"size": "Taille",
"size-and-speed": "@:size et @.lower:speed",
@@ -1576,6 +1566,7 @@
"snapshot-mode:with-memory-description": "Inclut l'état de la mémoire de la VM. La VM sera brièvement suspendue pendant le snapshot.",
"snapshot-revert-snapshot-before": "Créer un instantané de la VM avant la restauration",
"snapshot-revert-warning": "La VM sera restaurée à l'état de l'instantané sélectionné. Tous les changements effectués depuis (données, configuration et état des disques) seront perdus. Cette action est irréversible.",
"snapshot-settings-disabled-offline-backup": "Les paramètres de snapshot sont désactivés car la sauvegarde hors ligne éteint les VMs au lieu de faire un snapshot.",
"snapshot-synchronisation": "Synchronisation des snapshots",
"snapshot-vdis": "VDIs snapshot",
"snapshots": "Instantanés",

View File

@@ -1049,7 +1049,6 @@
"s3-endpoint-sample": "Esempio: s3.us-west-1.amazonaws.com",
"scan-pifs": "Scansiona PIF",
"schedule": "Pianificazione",
"schedules": "Pianificazioni",
"secret": "Segreto",
"secure-boot": "Secure boot",
"see-details": "Vedi i dettagli",

View File

@@ -1049,7 +1049,6 @@
"s3-endpoint-sample": "例: s3.us-west-1.amazonaws.com",
"scan-pifs": "PIF をスキャン",
"schedule": "スケジュール",
"schedules": "スケジュール",
"secret": "シークレット",
"secure-boot": "セキュアブート",
"see-details": "詳細を表示",

View File

@@ -1049,7 +1049,6 @@
"s3-endpoint-sample": "예: s3.us-west-1.amazonaws.com",
"scan-pifs": "PIF 검색",
"schedule": "일정",
"schedules": "일정",
"secret": "시크릿",
"secure-boot": "보안 부팅",
"see-details": "상세 보기",

View File

@@ -1049,7 +1049,6 @@
"s3-endpoint-sample": "Eksempel: s3.us-west-1.amazonaws.com",
"scan-pifs": "Skann PIF-er",
"schedule": "Tidsplan",
"schedules": "Tidsplaner",
"secret": "Hemmelighet",
"secure-boot": "Sikker oppstart",
"see-details": "Se detaljer",

View File

@@ -1190,7 +1190,6 @@
"s3-endpoint-sample": "Voorbeeld: s3.us-west-1.amazonaws.com",
"scan-pifs": "Scan PIF's",
"schedule": "Planning",
"schedules": "Schema's",
"secret": "Secret",
"secure-boot": "Beveiligd opstarten",
"see-details": "Zie details",

View File

@@ -1049,7 +1049,6 @@
"s3-endpoint-sample": "Przykład: s3.us-west-1.amazonaws.com",
"scan-pifs": "Skanuj PIF",
"schedule": "Harmonogram",
"schedules": "Harmonogramy",
"secret": "Sekret",
"secure-boot": "Secure boot",
"see-details": "Zobacz szczegóły",

View File

@@ -1049,7 +1049,6 @@
"s3-endpoint-sample": "Exemplo: s3.us-west-1.amazonaws.com",
"scan-pifs": "Escanear PIFs",
"schedule": "Agendamento",
"schedules": "Agendamentos",
"secret": "Segredo",
"secure-boot": "Secure boot",
"see-details": "Veja os detalhes",

View File

@@ -726,7 +726,6 @@
"s3-backup-repository": "Repositório de cópias de segurança do S3",
"scan-pifs": "Digitalizar PIFs",
"schedule": "Calendário",
"schedules": "Calendários",
"secure-boot": "Arranque seguro",
"see-details": "Veja os detalhes",
"select-compression": "Selecione um tipo de compressão",

View File

@@ -1049,7 +1049,6 @@
"s3-endpoint-sample": "Пример: s3.us-west-1.amazonaws.com",
"scan-pifs": "Сканировать PIFs",
"schedule": "Расписание",
"schedules": "Расписания",
"secret": "Секрет",
"secure-boot": "Безопасная загрузка",
"see-details": "Подробнее",

View File

@@ -1017,7 +1017,6 @@
"s3-backup-repository": "S3 repozitár záloh",
"scan-pifs": "Skenovať PIFs",
"schedule": "Plán",
"schedules": "Plány",
"secret": "Tajomstvo",
"secure-boot": "Secure boot",
"see-details": "Zobraziť podrobnosti",

View File

@@ -940,7 +940,6 @@
"s3-backup-repository": "S3 säkerhetskopieringsförvar",
"scan-pifs": "Skanna PIF",
"schedule": "Schema",
"schedules": "Schema",
"secure-boot": "Säker boot",
"see-details": "Se detaljer",
"select-compression": "Välj komprimering",

View File

@@ -984,7 +984,6 @@
"s3-backup-repository": "S3 yedek deposu",
"scan-pifs": "PIF'leri tara",
"schedule": "Zamanlama",
"schedules": "Zamanlamalar",
"secure-boot": "Güvenli önyükleme",
"see-details": "Ayrıntıları gör",
"select-compression": "Sıkıştırma seçin",

View File

@@ -1049,7 +1049,6 @@
"s3-endpoint-sample": "Приклад: s3.us-west-1.amazonaws.com",
"scan-pifs": "Сканувати PIFs",
"schedule": "Розклад",
"schedules": "Розклади",
"secret": "Секрет",
"secure-boot": "Безпечне завантаження",
"see-details": "Переглянути деталі",

View File

@@ -987,7 +987,6 @@
"s3-backup-repository": "S3备份仓库",
"scan-pifs": "扫描PIF",
"schedule": "计划",
"schedules": "计划",
"secure-boot": "安全启动",
"see-details": "查看详情",
"select-compression": "选择压缩方式",

View File

@@ -1,7 +1,5 @@
export type LinearChartData = {
label: string
// e.g. to set a total apart from the series it sums
dashed?: boolean
data: {
timestamp: number
value: number | null

View File

@@ -1,63 +0,0 @@
import type { LinearChartData } from '@core/types/chart.ts'
export type SampleValues = (number | null)[]
export type SamplesWindow = { endTimestamp: number; interval: number }
export function toLinearChartSeries(
{ endTimestamp, interval }: SamplesWindow,
label: string,
values: SampleValues
): LinearChartData[number] {
const startTimestamp = endTimestamp - interval * (values.length - 1)
return {
label,
data: values.map((value, index) => ({ timestamp: (startTimestamp + index * interval) * 1000, value })),
}
}
// Index-wise sum of several sample lists ending at the same time, so aligned on their last sample.
// An index without any sample stays `null` instead of `0`
export function sumSamples(valuesList: SampleValues[]): SampleValues {
const length = Math.max(0, ...valuesList.map(values => values.length))
const sums = new Float64Array(length)
const counts = new Uint32Array(length)
for (const values of valuesList) {
const offset = length - values.length
values.forEach((value, index) => {
if (value !== null) {
sums[offset + index] += value
counts[offset + index]++
}
})
}
return Array.from({ length }, (_, index) => (counts[index] === 0 ? null : sums[index]))
}
export function subtractSamples(minuends: SampleValues, subtrahends: SampleValues): SampleValues {
return minuends.map((minuend, index) => {
const subtrahend = subtrahends[index]
return minuend === null || subtrahend === null || subtrahend === undefined ? null : minuend - subtrahend
})
}
export function getMaxSample(values: SampleValues | undefined): number {
return (values ?? []).reduce<number>((max, value) => Math.max(max, value ?? 0), 0)
}
// Rounds up to the first digit of the value's order of magnitude (e.g. 1234 → 2000, 0.37 → 0.4)
export function roundUpToMagnitude(value: number): number {
if (value <= 0) {
return 0
}
const magnitude = 10 ** Math.floor(Math.log10(value))
// `toPrecision` drops floating point noise (0.4000000000000001 → 0.4)
return Number((Math.ceil(value / magnitude) * magnitude).toPrecision(12))
}

View File

@@ -1,91 +0,0 @@
import {
getMaxSample,
roundUpToMagnitude,
subtractSamples,
sumSamples,
toLinearChartSeries,
} from '@core/utils/linear-chart-series.util.ts'
const window = { endTimestamp: 1000, interval: 5 }
describe('toLinearChartSeries', () => {
it('ends with the window end and steps by its interval, in milliseconds', () => {
expect(toLinearChartSeries(window, 'CPU 0', [1, 2, 3]).data.map(point => point.timestamp)).toEqual([
990_000, 995_000, 1_000_000,
])
})
it('pairs each sample with its timestamp and keeps missing samples as null', () => {
expect(toLinearChartSeries(window, 'CPU 0', [1, null])).toEqual({
label: 'CPU 0',
data: [
{ timestamp: 995_000, value: 1 },
{ timestamp: 1_000_000, value: null },
],
})
})
})
describe('sumSamples', () => {
it('sums the samples index by index', () => {
expect(
sumSamples([
[1, 2],
[10, 20],
])
).toEqual([11, 22])
})
it('aligns the lists on their last sample, as they end at the same time', () => {
expect(
sumSamples([
[1, 2, 3],
[20, 30],
])
).toEqual([1, 22, 33])
})
it('ignores missing samples, and is null where every sample is missing', () => {
expect(
sumSamples([
[1, null],
[2, null],
])
).toEqual([3, null])
expect(
sumSamples([
[1, null],
[null, 4],
])
).toEqual([1, 4])
})
it('is empty without lists', () => {
expect(sumSamples([])).toEqual([])
})
})
describe('subtractSamples', () => {
it('subtracts index by index, and is null where a sample is missing', () => {
expect(subtractSamples([10, 20, null], [1, null, 3])).toEqual([9, null, null])
})
})
describe('getMaxSample', () => {
it('is the highest sample, or 0 without samples', () => {
expect(getMaxSample([3, null, 7])).toBe(7)
expect(getMaxSample(undefined)).toBe(0)
})
})
describe('roundUpToMagnitude', () => {
it.each([
[1234, 2000],
[2000, 2000],
[0.37, 0.4],
[7, 7],
[0, 0],
])('rounds %d up to %d', (value, expected) => {
expect(roundUpToMagnitude(value)).toBe(expected)
})
})

View File

@@ -20,7 +20,6 @@
"@regle/rules": "^1.26.0",
"@regle/schemas": "^1.20.2",
"@types/d3-time-format": "^4.0.3",
"@vates/types": "^3.0.0",
"@vueuse/core": "^14.0.0",
"@vueuse/math": "^14.0.0",
"@vueuse/router": "^14.0.0",

View File

@@ -0,0 +1,10 @@
import type { VueWrapper } from '@vue/test-utils'
// Whether the first input of a wrapper attached to the document takes the focus, which an `inert` ancestor prevents
export function canFocusInput(wrapper: Pick<VueWrapper, 'get'>) {
const input = wrapper.get('input').element
input.focus()
return document.activeElement === input
}

View File

@@ -24,13 +24,14 @@ it('shows no message without info nor error', () => {
expect(findMessages(mountCheckbox())).toEqual([])
})
it('shows the info, then the error', () => {
it('shows the info as its description, then the error', () => {
const wrapper = mountCheckbox({
info: 'The VMs will be shut down',
error: { content: 'Select at least one option', accent: 'danger' },
})
expect(findMessages(wrapper)).toEqual(['The VMs will be shut down', 'Select at least one option'])
expect(wrapper.get('.ui-rich-checkbox .description').text()).toBe('The VMs will be shut down')
expect(findMessages(wrapper)).toEqual(['Select at least one option'])
})
it('is checked according to its model', () => {

View File

@@ -1,11 +1,11 @@
<template>
<div class="backup-job-form-checkbox">
<UiCheckbox v-model="model" accent="brand">
<UiRichCheckbox v-if="info" v-model="model" accent="brand" :description="info">
{{ label }}
</UiRichCheckbox>
<UiCheckbox v-else v-model="model" accent="brand">
{{ label }}
</UiCheckbox>
<UiInfo v-if="info" accent="info" wrap>
{{ info }}
</UiInfo>
<UiInfo v-if="errorMessage !== undefined" accent="danger" wrap>
{{ errorMessage }}
</UiInfo>
@@ -17,6 +17,7 @@ import { formatErrorMessage } from '@/modules/backup-job/utils/backup-job-error-
import type { InputWrapperMessage } from '@core/components/input-wrapper/VtsInputWrapper.vue'
import UiCheckbox from '@core/components/ui/checkbox/UiCheckbox.vue'
import UiInfo from '@core/components/ui/info/UiInfo.vue'
import UiRichCheckbox from '@core/components/ui/rich-checkbox/UiRichCheckbox.vue'
import { computed } from 'vue'
const { error } = defineProps<{

View File

@@ -8,7 +8,7 @@
</span>
</template>
<template #period>
<span class="typo-body-bold">{{ period }}</span>
<span class="period typo-body-bold">{{ period }}</span>
</template>
<template #keep>
<span class="keep">
@@ -62,6 +62,10 @@ const errorMessage = computed(() => formatErrorMessage(error))
width: 10rem;
}
.period {
margin-inline-end: -1.2rem;
}
.keep {
flex: 0 0 18rem;
width: 18rem;

View File

@@ -1,5 +1,30 @@
<template>
<UiRichRadioButtonGroup
v-if="hasDescription"
class="backup-job-form-radio"
accent="brand"
:vertical="vertical || uiStore.isSmall"
>
<template #label>
<UiLabel accent="neutral" required>{{ label }}</UiLabel>
</template>
<UiRichRadioButton
v-for="option of options"
:key="option.value"
v-model="model"
accent="brand"
:value="option.value"
:description="option.description"
:disabled
>
{{ option.label }}
</UiRichRadioButton>
<template v-if="slots.info" #info>
<slot name="info" />
</template>
</UiRichRadioButtonGroup>
<UiRadioButtonGroup
v-else
class="backup-job-form-radio"
accent="brand"
:gap="vertical || uiStore.isSmall ? 'narrow' : 'wide'"
@@ -8,12 +33,17 @@
<template #label>
<UiLabel accent="neutral" required>{{ label }}</UiLabel>
</template>
<div v-for="option of options" :key="option.value" class="option">
<UiRadioButton v-model="model" accent="brand" :value="option.value">
{{ option.label }}
</UiRadioButton>
<UiInfo v-if="option.description" accent="info" wrap>{{ option.description }}</UiInfo>
</div>
<UiRadioButton
v-for="option of options"
:key="option.value"
v-model="model"
class="radio-button"
accent="brand"
:value="option.value"
:disabled
>
{{ option.label }}
</UiRadioButton>
<template v-if="slots.info" #info>
<slot name="info" />
</template>
@@ -22,16 +52,19 @@
<script setup lang="ts" generic="TValue extends string">
import type { BackupJobFormOption } from '@/modules/backup-job/types/backup-job-form.type.ts'
import UiInfo from '@core/components/ui/info/UiInfo.vue'
import UiLabel from '@core/components/ui/label/UiLabel.vue'
import UiRadioButton from '@core/components/ui/radio-button/UiRadioButton.vue'
import UiRadioButtonGroup from '@core/components/ui/radio-button-group/UiRadioButtonGroup.vue'
import UiRichRadioButton from '@core/components/ui/rich-radio-button/UiRichRadioButton.vue'
import UiRichRadioButtonGroup from '@core/components/ui/rich-radio-button-group/UiRichRadioButtonGroup.vue'
import { useUiStore } from '@core/stores/ui.store.ts'
import { computed } from 'vue'
defineProps<{
const { options } = defineProps<{
label: string
options: BackupJobFormOption<TValue>[]
vertical?: boolean
disabled?: boolean
}>()
const model = defineModel<TValue>({ required: true })
@@ -41,14 +74,19 @@ const slots = defineSlots<{
}>()
const uiStore = useUiStore()
const hasDescription = computed(() => options.some(option => option.description !== undefined))
</script>
<style lang="postcss" scoped>
.backup-job-form-radio {
.option {
display: flex;
flex-direction: column;
gap: 0.4rem;
:deep(.group.gap--wide) {
flex-wrap: wrap;
row-gap: 0.8rem;
}
.radio-button {
white-space: nowrap;
}
}
</style>

View File

@@ -3,13 +3,13 @@
<BackupJobFormRow>
<div class="field">
<UiLabel :accent="hasError ? 'danger' : 'neutral'" required>{{ label }}</UiLabel>
<UiInput v-model.number="model" :accent="hasError ? 'danger' : 'neutral'" type="number" required />
<UiInput v-model.number="model" :accent="hasError ? 'danger' : 'neutral'" type="number" required :disabled />
</div>
</BackupJobFormRow>
<div class="messages">
<UiInfo accent="info" wrap>{{ t('value-by-default', { value: 1 }) }}</UiInfo>
<div class="ephemeral typo-body-regular-small">
<div class="ephemeral typo-body-regular">
<span>{{ t('ephemeral-snapshot-mode:title') }}</span>
<ul>
<li>{{ t('ephemeral-snapshot-mode:incremental') }}</li>
@@ -34,6 +34,7 @@ import { useI18n } from 'vue-i18n'
const { error } = defineProps<{
label: string
error?: InputWrapperMessage
disabled?: boolean
}>()
const model = defineModel<number | undefined>({ required: true })
@@ -66,7 +67,6 @@ const hasError = computed(() => errorMessage.value !== undefined)
.ephemeral {
padding-inline-start: 2.4rem;
color: var(--color-neutral-txt-secondary);
ul {
padding-inline-start: 2rem;

View File

@@ -37,5 +37,14 @@ const { t } = useI18n()
display: flex;
flex-direction: column;
gap: 1.6rem;
:deep(.ui-subtitle) {
margin-block-start: 1.6rem;
}
:deep(.vts-tabular-key-value-list) {
grid-template-columns: minmax(min-content, 28rem) 1fr;
row-gap: 0.8rem;
}
}
</style>

View File

@@ -8,6 +8,11 @@
:label="t('compression-type')"
:value="compressionLabel"
/>
<VtsTabularKeyValueRow v-if="!isMirror" :label="t('offline-backup')">
<template #value>
<VtsStatus :status="form.formData.offlineBackup" />
</template>
</VtsTabularKeyValueRow>
</VtsTabularKeyValueList>
<template v-if="isIncremental && !isMirror">
@@ -33,22 +38,15 @@
</VtsTabularKeyValueList>
</template>
<template v-if="!isMirror">
<template v-if="!isMirror && !form.formData.offlineBackup">
<UiSubtitle>{{ t('snapshot') }}</UiSubtitle>
<VtsTabularKeyValueList>
<VtsTabularKeyValueRow :label="t('offline-backup')">
<template #value>
<VtsStatus :status="form.formData.offlineBackup" />
</template>
</VtsTabularKeyValueRow>
<template v-if="!form.formData.offlineBackup">
<VtsTabularKeyValueRow :label="t('snapshot-mode')" :value="snapshotModeLabel" />
<VtsTabularKeyValueRow :label="t('snapshot-synchronisation')" :value="snapshotSyncLabel" />
<VtsTabularKeyValueRow
:label="t('minimum-snapshots-to-retain')"
:value="form.formData.snapshotRetention?.toString()"
/>
</template>
<VtsTabularKeyValueRow :label="t('snapshot-mode')" :value="snapshotModeLabel" />
<VtsTabularKeyValueRow :label="t('snapshot-synchronisation')" :value="snapshotSyncLabel" />
<VtsTabularKeyValueRow
:label="t('minimum-snapshots-to-retain')"
:value="form.formData.snapshotRetention?.toString()"
/>
</VtsTabularKeyValueList>
</template>
</template>

View File

@@ -119,27 +119,39 @@ function findMessages(wrapper: VueWrapper) {
return wrapper.findAll('.ui-info').map(message => message.text())
}
function getEnableToggle(wrapper: VueWrapper) {
return wrapper.get('.general .ui-toggle')
function findStatusRadios(wrapper: VueWrapper) {
return wrapper.findAll('.general .ui-radio-button')
}
function findCheckedStatus(wrapper: VueWrapper) {
return findStatusRadios(wrapper)
.filter(radio => radio.get<HTMLInputElement>('input').element.checked)
.map(radio => radio.text())
}
it('enables the job by default', () => {
const toggle = getEnableToggle(mountSourceStep())
const wrapper = mountSourceStep()
expect(toggle.text()).toBe(t('action:enable'))
expect(toggle.get<HTMLInputElement>('input').element.checked).toBe(true)
expect(findStatusRadios(wrapper).map(radio => radio.text())).toEqual([t('action:enable'), t('action:disable')])
expect(findCheckedStatus(wrapper)).toEqual([t('action:enable')])
})
it('shows a disabled job as disabled', () => {
expect(getEnableToggle(mountSourceStep({ enabled: false })).get<HTMLInputElement>('input').element.checked).toBe(
false
)
expect(findCheckedStatus(mountSourceStep({ enabled: false }))).toEqual([t('action:disable')])
})
it('disables the job', async () => {
const wrapper = mountSourceStep()
await findStatusRadios(wrapper)[1].get('input').setValue(true)
expect(findCheckedStatus(wrapper)).toEqual([t('action:disable')])
})
it('offers the data source, the backup mode and the scope of a VM backup', () => {
const wrapper = mountSourceStep()
expect(findRadioLabels(wrapper)).toEqual([t('data-source'), t('backup-mode'), t('scope-type')])
expect(findRadioLabels(wrapper)).toEqual([t('status'), t('data-source'), t('backup-mode'), t('scope-type')])
expect(findLabels(wrapper, BackupJobFormSelect)).toEqual([])
expect(findLabels(wrapper, BackupJobFormCheckbox)).toEqual([])
})
@@ -153,14 +165,14 @@ it('selects the source proxy and backup repository of a mirror backup', () => {
it('offers the options of a metadata backup, without backup mode', () => {
const wrapper = mountSourceStep({ dataSource: 'metadata' })
expect(findRadioLabels(wrapper)).toEqual([t('data-source'), t('scope-type')])
expect(findRadioLabels(wrapper)).toEqual([t('status'), t('data-source'), t('scope-type')])
expect(findLabels(wrapper, BackupJobFormCheckbox)).toEqual([t('save-xo-config'), t('save-pools-metadata')])
})
it('selects no scope for a metadata backup saving the XO config only', () => {
const wrapper = mountSourceStep({ dataSource: 'metadata', saveXoConfig: true, savePoolsMetadata: false })
expect(findRadioLabels(wrapper)).toEqual([t('data-source')])
expect(findRadioLabels(wrapper)).toEqual([t('status'), t('data-source')])
})
it('tells that the replications are excluded from the VM selection', () => {

View File

@@ -1,15 +1,15 @@
<template>
<div class="backup-job-source-step">
<div class="general">
<BackupJobFormRow>
<BackupJobFormRow class="name-status">
<BackupJobFormTextInput v-bind="bindings.name" />
<BackupJobFormRadio
:label="bindings.enabled.label"
:options="bindings.enabled.options"
:model-value="bindings.enabled.modelValue ? 'enabled' : 'disabled'"
@update:model-value="value => bindings.enabled['onUpdate:modelValue'](value === 'enabled')"
/>
</BackupJobFormRow>
<UiToggle
:model-value="bindings.enabled.modelValue"
@update:model-value="value => bindings.enabled['onUpdate:modelValue'](value ?? false)"
>
{{ t('action:enable') }}
</UiToggle>
</div>
<BackupJobFormRadio v-bind="bindings.dataSource" />
<div v-if="!isMetadata" class="mode">
@@ -95,7 +95,6 @@ import VtsIcon from '@core/components/icon/VtsIcon.vue'
import VtsOption from '@core/components/select/VtsOption.vue'
import UiInfo from '@core/components/ui/info/UiInfo.vue'
import UiLabel from '@core/components/ui/label/UiLabel.vue'
import UiToggle from '@core/components/ui/toggle/UiToggle.vue'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
@@ -142,6 +141,10 @@ const isSourceBackupRepositoryMissing = computed(
gap: 2.4rem;
}
.name-status {
column-gap: 8rem;
}
.mode {
display: flex;
flex-direction: column;

View File

@@ -7,6 +7,7 @@ import {
useBackupJobTransferForm,
} from '@/modules/backup-job/form/use-backup-job-transfer-form.ts'
import type { useXoVmCollection } from '@/modules/vm/remote-resources/use-xo-vm-collection.ts'
import { findAllGenericComponents } from '@/test/find-generic-components.ts'
import { createGlobalTestConfig } from '@/test/global-test-config.ts'
import { t } from '@/test/i18n.ts'
import { mockModule } from '@/test/spy-on-module.ts'
@@ -106,9 +107,14 @@ it('offers the snapshot mode, its synchronisation and its retention', () => {
expect(wrapper.findComponent(BackupJobFormSnapshotRetention).exists()).toBe(true)
})
it('takes no snapshot for an offline backup', () => {
it('disables the snapshot settings of an offline backup', () => {
const wrapper = mountTransferStep({ offlineBackup: true })
expect(findRadioLabels(wrapper)).not.toContain(t('snapshot-mode'))
expect(wrapper.findComponent(BackupJobFormSnapshotRetention).exists()).toBe(false)
const disabledRadioLabels = findAllGenericComponents(wrapper, 'BackupJobFormRadio')
.filter(radio => radio.props('disabled'))
.map(radio => radio.props('label'))
expect(wrapper.text()).toContain(t('snapshot-settings-disabled-offline-backup'))
expect(disabledRadioLabels).toEqual([t('snapshot-mode'), t('snapshot-synchronisation')])
expect(wrapper.findComponent(BackupJobFormSnapshotRetention).props('disabled')).toBe(true)
})

View File

@@ -9,6 +9,8 @@
</BackupJobFormRow>
<BackupJobFormRadio v-if="!isIncremental && !isMirror" v-bind="bindings.compression" />
<BackupJobFormCheckbox v-if="!isMirror" v-bind="bindings.offlineBackup" />
</div>
<div v-if="isIncremental && !isMirror" class="section">
@@ -40,19 +42,22 @@
<div v-if="!isMirror" class="section">
<UiTitle>{{ t('snapshot') }}</UiTitle>
<BackupJobFormCheckbox v-bind="bindings.offlineBackup" />
<UiInfo v-if="bindings.offlineBackup.modelValue" accent="warning" wrap>
{{ t('snapshot-settings-disabled-offline-backup') }}
</UiInfo>
<template v-if="!bindings.offlineBackup.modelValue">
<BackupJobFormRadio v-bind="bindings.snapshotMode" vertical />
<BackupJobFormRadio v-bind="bindings.snapshotMode" vertical :disabled="bindings.offlineBackup.modelValue" />
<BackupJobFormRadio v-bind="bindings.snapshotSync" />
<BackupJobFormRadio v-bind="bindings.snapshotSync" :disabled="bindings.offlineBackup.modelValue" />
<BackupJobFormRow v-if="bindings.snapshotSync.modelValue === 'smart'">
<BackupJobFormSelect v-bind="bindings.snapshotSyncTag" />
</BackupJobFormRow>
<BackupJobFormRow v-if="bindings.snapshotSync.modelValue === 'smart'">
<BackupJobFormSelect v-bind="bindings.snapshotSyncTag" />
</BackupJobFormRow>
<BackupJobFormSnapshotRetention v-bind="bindings.snapshotRetention" />
</template>
<BackupJobFormSnapshotRetention
v-bind="bindings.snapshotRetention"
:disabled="bindings.offlineBackup.modelValue"
/>
</div>
</div>
</template>

View File

@@ -40,6 +40,7 @@ import { useXoBackupJobTypeLabels } from '@/modules/backup-job/composables/use-x
import type { FrontAnyXoBackupJob } from '@/modules/backup-job/remote-resources/use-xo-backup-job-collection.ts'
import { getBackupJobHealthCheckStatus } from '@/modules/backup-job/utils/xo-backup-job.util.ts'
import { useXoBackupLogCollection } from '@/modules/backup-log/remote-resources/use-xo-backup-log-collection.ts'
import { useXoScheduleCollection } from '@/modules/schedule/remote-resources/use-xo-schedule-collection.ts'
import { useXoRoutes } from '@/shared/remote-resources/use-xo-routes.ts'
import VtsQueryBuilder from '@core/components/query-builder/VtsQueryBuilder.vue'
import VtsRow from '@core/components/table/VtsRow.vue'
@@ -73,6 +74,8 @@ const { buildXo5Route } = useXoRoutes()
const { areBackupLogsReady } = useXoBackupLogCollection()
const { schedulesByJobId } = useXoScheduleCollection()
const { items: queryFilteredBackupJobs, searchBindings } = useQueryBuilderFilter('backup-jobs', () => backupJobs)
const { filteredBackupJobs, statusSelectId, lastRunsStatusSelectId, lastDaysStatusSelectId } =
@@ -122,6 +125,7 @@ const { HeadCells, BodyCells } = useBackupJobColumns({
const modeLabel = useXoBackupJobModeLabel(() => backupJob)
const lastRuns = useXoBackupJobLastRuns(() => backupJob)
const healthCheckStatus = computed(() => getBackupJobHealthCheckStatus(backupJob))
const hasMultipleSchedules = computed(() => (schedulesByJobId.value.get(backupJob.id)?.length ?? 0) > 1)
const { isEnabled, moreActions, deleteAction } = useXoBackupJobActions(() => backupJob)
@@ -136,6 +140,9 @@ const { HeadCells, BodyCells } = useBackupJobColumns({
label: backupJob.name ?? t('untitled'),
href: jobOverviewHref.value,
icon: 'object:backup-job',
rightIcon: hasMultipleSchedules.value
? { icon: 'status:warning-circle', tooltip: t('multiple-schedules-split-in-xo5') }
: undefined,
}),
type: r => r(typeLabels.value[0] ?? '', { extraCount: typeLabels.value.length - 1 }),
mode: r => r(modeLabel.value),

View File

@@ -9,7 +9,6 @@ import { mockXoRoutes } from '@/test/mock-xo-routes.ts'
import VtsDivider from '@core/components/divider/VtsDivider.vue'
import VtsStatus from '@core/components/status/VtsStatus.vue'
import UiLink from '@core/components/ui/link/UiLink.vue'
import UiPanelCardTitle from '@core/components/ui/panel-card-title/UiPanelCardTitle.vue'
import { formatDateTime } from '@core/utils/time.util.ts'
import { mount, type VueWrapper } from '@vue/test-utils'
@@ -72,12 +71,11 @@ it('shows the status of each schedule when there are several', () => {
expect(statuses.map(status => status.props('status'))).toEqual([true, false])
})
it('counts the schedules and separates them', () => {
it('separates the schedules', () => {
const wrapper = mountSchedulesCard([
createSchedule({ id: 'schedule-1' as FrontXoSchedule['id'] }),
createSchedule({ id: 'schedule-2' as FrontXoSchedule['id'] }),
])
expect(wrapper.getComponent(UiPanelCardTitle).props('counter')).toBe(2)
expect(wrapper.findAllComponents(VtsDivider)).toHaveLength(1)
})

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