Compare commits

..

1 Commits

Author SHA1 Message Date
Alexandre Mouillard
b322f12769 feat(xo6/lite): add stats tabs for hosts, VMs and pools
Charts the CPU, RAM, network and load (or disk for VMs) stats 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, as in XO 5.

The stats-to-chart mapping and the toolbar/charts components live in
web-core, shared by XO 6 and XO Lite.
2026-12-01 15:49:42 +01:00
48 changed files with 1869 additions and 238 deletions

View File

@@ -382,9 +382,7 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
const xapi = this._xapi
const vdiCandidates = {}
// 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)
const vdiUuids = this._vm.$VBDs.map(({ VDI }) => VDI)
Object.values(xapi.objects.indexes.type.VDI)
.filter(_ => !!_) // filter nullish
.filter(({ other_config, snapshot_of }) => {
@@ -403,20 +401,21 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
this._jobSnapshotVdis = Object.values(vdiCandidates)
// 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)
)
// 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 = []
}
}
async _removeUnusedSnapshots() {
@@ -452,13 +451,7 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
.pop()
// remove older snapshot schedule per schedule
// 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])
const snapshotsPerSchedule = groupBy(this._jobSnapshotVdis, _ => _.other_config[SCHEDULE_ID])
await asyncMap(Object.entries(snapshotsPerSchedule), async ([scheduleId, snapshots]) => {
const snapshotPerDatetime = groupBy(snapshots, _ => _.other_config[DATETIME])
@@ -481,18 +474,7 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
) {
return
}
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)
const vdis = snapshotPerDatetime[datetime]
let vm
// if there is an attached VM => destroy the VM (Non CBT backups)
for (const vdi of vdis) {
@@ -546,6 +528,34 @@ 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, VM_UUID } from '../../_otherConfig.mjs'
import { DATETIME, EXPORTED_SUCCESSFULLY, JOB_ID, SCHEDULE_ID } from '../../_otherConfig.mjs'
// Build an AbstractXapi instance without running its heavy constructor, then
// assign only the fields the method under test reads.
@@ -735,120 +735,3 @@ 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,6 +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))
## **0.28.0** (2026/12/01)

View File

@@ -0,0 +1,25 @@
<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,6 +6,9 @@
<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

@@ -0,0 +1,50 @@
<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 ?? '-' } }" disabled>
<RouterTab :to="{ name: '/pool/[uuid]/stats', params: { uuid: pool?.uuid ?? '-' } }">
{{ t('stats') }}
</RouterTab>
<RouterTab :to="{ name: '/pool/[uuid]/system', params: { uuid: pool?.uuid ?? '-' } }">

View File

@@ -0,0 +1,25 @@
<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 } }" disabled>
<RouterTab :to="{ name: '/vm/[uuid]/stats', params: { uuid } }">
{{ t('stats') }}
</RouterTab>
<RouterTab :to="{ name: '/vm/[uuid]/system', params: { uuid } }">

View File

@@ -1,13 +1,17 @@
import { type GRANULARITY, RRD_STEP_FROM_STRING, type XapiStatsResponse } from '@/libs/xapi-stats.ts'
import { 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, XapiVmStatsRaw } from '@vates/types/common'
import type { XapiHostStatsRaw, XapiStatsGranularity, XapiVmStatsRaw } from '@vates/types/common'
import { type Pausable, promiseTimeout, useTimeoutPoll } from '@vueuse/core'
import { computed, type ComputedRef, onUnmounted, ref, type Ref } from 'vue'
import { computed, type ComputedRef, markRaw, 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
}
@@ -17,7 +21,7 @@ export type GetStats<
S extends XapiHostStatsRaw | XapiVmStatsRaw = T extends XenApiHost ? XapiHostStatsRaw : XapiVmStatsRaw,
> = (
uuid: T['uuid'],
granularity: GRANULARITY,
granularity: XapiStatsGranularity,
ignoreExpired: boolean,
opts: { abortSignal?: AbortSignal }
) => Promise<XapiStatsResponse<S> | undefined> | undefined
@@ -33,10 +37,13 @@ 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: GRANULARITY): FetchedStats<T, S> {
>(getStats: GetStats<T, S>, granularity: XapiStatsGranularity): FetchedStats<T, S> {
const stats = ref(new Map()) as Ref<Map<string, Stat<S>>>
const timestamp = ref<number[]>([0, 0])
const abortController = new AbortController()
@@ -48,15 +55,36 @@ export default function useFetchStats<
return
}
const ignoreExpired = computed(() => !stats.value.has(mapKey))
let isFirstCall = true
const pausable = useTimeoutPoll(
async () => {
const newStats = (await getStats(object.uuid, granularity, ignoreExpired.value, {
abortSignal: abortController.signal,
})) as XapiStatsResponse<S>
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
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
}
@@ -66,9 +94,16 @@ export default function useFetchStats<
newStats.endTimestamp,
]
stats.value.get(mapKey)!.stats = newStats.stats
stats.value.get(mapKey)!.canBeExpired = newStats.canBeExpired
await promiseTimeout(newStats.interval * 1000)
// 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)
},
0,
{ immediate: true }
@@ -76,8 +111,10 @@ 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

@@ -0,0 +1,20 @@
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,6 +1,7 @@
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'
@@ -32,7 +33,7 @@ export enum GRANULARITY {
Days = 'days',
}
export const RRD_STEP_FROM_STRING: { [key in GRANULARITY]: RRD_STEP } = {
export const RRD_STEP_FROM_STRING: Record<XapiStatsGranularity, RRD_STEP> = {
[GRANULARITY.Seconds]: RRD_STEP.Seconds,
[GRANULARITY.Minutes]: RRD_STEP.Minutes,
[GRANULARITY.Hours]: RRD_STEP.Hours,
@@ -416,7 +417,7 @@ export default class XapiStats {
host: XenApiHost
ignoreExpired?: boolean
uuid: any
granularity: GRANULARITY
granularity: XapiStatsGranularity
}) {
const step = granularity === undefined ? RRD_STEP.Seconds : RRD_STEP_FROM_STRING[granularity]
if (step === undefined) {

View File

@@ -0,0 +1,78 @@
<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,11 +1,33 @@
<template>
<PageUnderConstruction />
<div class="stats">
<VtsStatsToolbar v-model:granularity="granularity" v-model:show-totals="showTotals" />
<PoolStatsCharts :key="granularity" :granularity :show-totals />
</div>
</template>
<script lang="ts" setup>
import PageUnderConstruction from '@/components/PageUnderConstruction.vue'
import PoolStatsCharts from '@/components/pool/PoolStatsCharts.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,11 +1,73 @@
<template>
<PageUnderConstruction />
<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>
</template>
<script lang="ts" setup>
import PageUnderConstruction from '@/components/PageUnderConstruction.vue'
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 { 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'
usePageTitleStore().setTitle(useI18n().t('stats'))
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)
</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,6 +52,7 @@ 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'
@@ -78,6 +79,13 @@ 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',
@@ -590,6 +598,20 @@ 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',
@@ -1349,6 +1371,7 @@ 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'
@@ -1374,6 +1397,12 @@ 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'
@@ -1815,6 +1844,18 @@ 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,60 @@
<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

@@ -0,0 +1,25 @@
<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

@@ -4,7 +4,7 @@
<script lang="ts" setup>
import type { LinearChartData, ValueFormatter } from '@core/types/chart.ts'
import { timeFormat } from 'd3-time-format'
import { timeFormat as createTimeFormatter } from 'd3-time-format'
import type { EChartsOption } from 'echarts'
import { LineChart } from 'echarts/charts'
import { GridComponent, LegendComponent, TooltipComponent } from 'echarts/components'
@@ -17,15 +17,18 @@ 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 = timeFormat('%a\n%H:%M')
const xAxisLabelFormatter = computed(() => createTimeFormatter(timeFormat))
const valueFormatter = computed<ValueFormatter>(() => {
const formatter = rawValueFormatter
@@ -47,6 +50,8 @@ 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: {
@@ -58,9 +63,10 @@ const option = computed<EChartsOption>(() => ({
xAxis: {
type: 'time',
axisLabel: {
formatter: (timestamp: number) => xAxisLabelFormatter(new Date(timestamp)),
formatter: (timestamp: number) => xAxisLabelFormatter.value(new Date(timestamp)),
showMaxLabel: false,
showMinLabel: false,
hideOverlap: true,
},
},
yAxis: {
@@ -74,6 +80,7 @@ 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

@@ -0,0 +1,81 @@
<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

@@ -0,0 +1,48 @@
<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

@@ -0,0 +1,49 @@
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

@@ -0,0 +1,99 @@
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

@@ -0,0 +1,135 @@
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

@@ -0,0 +1,122 @@
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

@@ -0,0 +1,163 @@
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

@@ -0,0 +1,22 @@
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

@@ -0,0 +1,63 @@
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

@@ -0,0 +1,49 @@
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

@@ -404,6 +404,7 @@
"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",
@@ -936,12 +937,15 @@
"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.",
@@ -1449,6 +1453,7 @@
"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",
@@ -1538,11 +1543,16 @@
"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",

View File

@@ -404,6 +404,7 @@
"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",
@@ -936,12 +937,15 @@
"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é.",
@@ -1449,6 +1453,7 @@
"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",
@@ -1538,11 +1543,16 @@
"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",

View File

@@ -1,5 +1,7 @@
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

@@ -0,0 +1,63 @@
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

@@ -0,0 +1,91 @@
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,6 +20,7 @@
"@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

@@ -29,11 +29,11 @@
{{ t('console') }}
</UiTabItem>
</RouterLink>
<UiTabItem>
<UiLink :href="xo5HostStatsHref" size="medium">
<RouterLink v-slot="{ isActive, href }" :to="{ name: '/host/[id]/stats', params: { id: host.id } }" custom>
<UiTabItem :active="isActive" :href tag="a">
{{ t('stats') }}
</UiLink>
</UiTabItem>
</UiTabItem>
</RouterLink>
<RouterLink v-slot="{ isActive, href }" :to="{ name: '/host/[id]/system', params: { id: host.id } }" custom>
<UiTabItem :active="isActive" :href tag="a">
{{ t('system') }}
@@ -67,11 +67,9 @@ import HostHeaderActions from '@/modules/host/components/actions/HostHeaderActio
import { useXoHostUtils } from '@/modules/host/composables/xo-host-utils.composable.ts'
import { type FrontXoHost, useXoHostCollection } from '@/modules/host/remote-resources/use-xo-host-collection.ts'
import { getHostIcon } from '@/modules/host/utils/xo-host.util.ts'
import { useXoRoutes } from '@/shared/remote-resources/use-xo-routes.ts'
import VtsIcon from '@core/components/icon/VtsIcon.vue'
import TabList from '@core/components/tab-list/TabList.vue'
import UiHeadBar from '@core/components/ui/head-bar/UiHeadBar.vue'
import UiLink from '@core/components/ui/link/UiLink.vue'
import UiLoader from '@core/components/ui/loader/UiLoader.vue'
import UiTabItem from '@core/components/ui/tab-item/UiTabItem.vue'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
@@ -86,9 +84,6 @@ const { t } = useI18n()
const { isChangingState, currentOperation, iconTooltip } = useXoHostUtils(() => host)
const { buildXo5Route } = useXoRoutes()
const xo5HostStatsHref = computed(() => buildXo5Route(`/hosts/${host.id}/stats`))
const { isMasterHost } = useXoHostCollection()
const isMaster = computed(() => isMasterHost(host.id))

View File

@@ -14,11 +14,11 @@
{{ t('dashboard') }}
</UiTabItem>
</RouterLink>
<UiTabItem>
<UiLink :href="xo5PoolStatsHref" size="medium">
<RouterLink v-slot="{ isActive, href }" :to="{ name: '/pool/[id]/stats', params: { id: pool.id } }" custom>
<UiTabItem :active="isActive" :href tag="a">
{{ t('stats') }}
</UiLink>
</UiTabItem>
</UiTabItem>
</RouterLink>
<RouterLink v-slot="{ isActive, href }" :to="{ name: '/pool/[id]/system', params: { id: pool.id } }" custom>
<UiTabItem :active="isActive" :href tag="a">
{{ t('system') }}
@@ -60,12 +60,10 @@
<script lang="ts" setup>
import PoolAddHostButton from '@/modules/pool/components/actions/add-host/PoolAddHostButton.vue'
import type { FrontXoPool } from '@/modules/pool/remote-resources/use-xo-pool-collection.ts'
import { useXoRoutes } from '@/shared/remote-resources/use-xo-routes.ts'
import TabList from '@core/components/tab-list/TabList.vue'
import UiHeadBar from '@core/components/ui/head-bar/UiHeadBar.vue'
import UiLink from '@core/components/ui/link/UiLink.vue'
import UiTabItem from '@core/components/ui/tab-item/UiTabItem.vue'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { pool } = defineProps<{
@@ -73,7 +71,4 @@ const { pool } = defineProps<{
}>()
const { t } = useI18n()
const { buildXo5Route } = useXoRoutes()
const xo5PoolStatsHref = computed(() => buildXo5Route(`/pools/${pool.id}/stats`))
</script>

View File

@@ -75,6 +75,7 @@ it('points every in-app tab at the page of that VM', async () => {
'/vm/vm-42/dashboard',
'/vm/vm-42/console',
'/vm/vm-42/backups',
'/vm/vm-42/stats',
'/vm/vm-42/system',
'/vm/vm-42/networks',
'/vm/vm-42/vdis',
@@ -83,15 +84,6 @@ it('points every in-app tab at the page of that VM', async () => {
])
})
it('sends the stats tab to XO 5 rather than to an in-app page', async () => {
const wrapper = await mountHeader()
const statsTab = findTabs(wrapper).find(tab => tab.text() === t('stats'))!
expect(statsTab.element.tagName).not.toBe('A')
expect(statsTab.get('a').attributes('href')).toBe('https://xo5.example.com/#/vms/vm-42/stats')
})
it('marks the tab of the current route as the active one', async () => {
const wrapper = await mountHeader(createVm({ id: 'vm-42' as FrontXoVm['id'] }), '/vm/vm-42/system')

View File

@@ -32,11 +32,11 @@
{{ t('backups') }}
</UiTabItem>
</RouterLink>
<UiTabItem>
<UiLink :href="xo5VmStatsHref" size="medium">
<RouterLink v-slot="{ isActive, href }" :to="{ name: '/vm/[id]/stats', params: { id: vm.id } }" custom>
<UiTabItem :active="isActive" :href tag="a">
{{ t('stats') }}
</UiLink>
</UiTabItem>
</UiTabItem>
</RouterLink>
<RouterLink v-slot="{ isActive, href }" :to="{ name: '/vm/[id]/system', params: { id: vm.id } }" custom>
<UiTabItem :active="isActive" :href tag="a">
{{ t('system') }}
@@ -67,14 +67,12 @@
<script lang="ts" setup>
import VmHeaderActions from '@/modules/vm/components/actions/VmHeaderActions.vue'
import { useXo5VmRoute } from '@/modules/vm/composables/xo-vm-route-xo5.composable.ts'
import { useXoVmUtils } from '@/modules/vm/composables/xo-vm-utils.composable.ts'
import type { FrontXoVm } from '@/modules/vm/remote-resources/use-xo-vm-collection.ts'
import { getVmIcon } from '@/modules/vm/utils/xo-vm.util.ts'
import VtsIcon from '@core/components/icon/VtsIcon.vue'
import TabList from '@core/components/tab-list/TabList.vue'
import UiHeadBar from '@core/components/ui/head-bar/UiHeadBar.vue'
import UiLink from '@core/components/ui/link/UiLink.vue'
import UiLoader from '@core/components/ui/loader/UiLoader.vue'
import UiTabItem from '@core/components/ui/tab-item/UiTabItem.vue'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
@@ -85,8 +83,6 @@ const { vm } = defineProps<{ vm: FrontXoVm }>()
const { t } = useI18n()
const { xo5VmStatsHref } = useXo5VmRoute(() => vm)
const { hasPendingOperation, currentOperation, iconTooltip } = useXoVmUtils(() => vm)
const vmIcon = computed(() => getVmIcon(vm))

View File

@@ -10,9 +10,7 @@ export function useXo5VmRoute(rawVm: MaybeRefOrGetter<FrontXoVm>) {
const xo5VmGeneralHref = computed(() => buildXo5Route(`/vms/${vm.value.id}/general`))
const xo5VmStatsHref = computed(() => buildXo5Route(`/vms/${vm.value.id}/stats`))
const xo5VmAdvancedHref = computed(() => buildXo5Route(`/vms/${vm.value.id}/advanced`))
return { xo5VmGeneralHref, xo5VmStatsHref, xo5VmAdvancedHref }
return { xo5VmGeneralHref, xo5VmAdvancedHref }
}

View File

@@ -6,10 +6,9 @@ import { mountComposable } from '@/test/mount-composable.ts'
mockXoRoutes()
it('builds the XO5 general, stats and advanced routes for the VM id', () => {
it('builds the XO5 general and advanced routes for the VM id', () => {
const { wrapper } = mountComposable(() => useXo5VmRoute(createVm({ id: 'vm-42' as FrontXoVm['id'] })))
expect(wrapper.vm.xo5VmGeneralHref).toBe('https://xo5.example.com/#/vms/vm-42/general')
expect(wrapper.vm.xo5VmStatsHref).toBe('https://xo5.example.com/#/vms/vm-42/stats')
expect(wrapper.vm.xo5VmAdvancedHref).toBe('https://xo5.example.com/#/vms/vm-42/advanced')
})

View File

@@ -0,0 +1,69 @@
<template>
<div class="stats">
<VtsStateHero v-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" />
<VtsStatsCharts :charts :granularity :loading="data === null" :error="!!error" />
</template>
</div>
</template>
<script lang="ts" setup>
import type { FrontXoHost } from '@/modules/host/remote-resources/use-xo-host-collection.ts'
import { useFetchStats } from '@/shared/composables/fetch-stats.composable.ts'
import VtsStateHero from '@core/components/state-hero/VtsStateHero.vue'
import VtsStatsCharts from '@core/components/stats-charts/VtsStatsCharts.vue'
import VtsStatsToolbar from '@core/components/stats-toolbar/VtsStatsToolbar.vue'
import { useHostStatsCharts } from '@core/composables/stats-charts/host-stats-charts.composable.ts'
import { HOST_POWER_STATE } from '@vates/types'
import type { XapiStatsGranularity } from '@vates/types/common'
import { computed, ref } from 'vue'
import { useI18n } from 'vue-i18n'
const { host } = defineProps<{
host: FrontXoHost
}>()
const { t } = useI18n()
const granularity = ref<XapiStatsGranularity>('seconds')
const showTotals = ref(false)
const isHostRunning = computed(() => host.power_state === HOST_POWER_STATE.RUNNING)
// Halted hosts have no stats to fetch
const { data, error } = useFetchStats('host', () => (isHostRunning.value ? host.id : undefined), granularity)
const charts = useHostStatsCharts(() => data.value ?? undefined, showTotals)
</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

@@ -0,0 +1,62 @@
<template>
<div class="stats">
<VtsStatsToolbar v-model:granularity="granularity" v-model:show-totals="showTotals" />
<VtsStatsCharts :charts :granularity :loading="data === null" :error="!!error" />
</div>
</template>
<script lang="ts" setup>
import { useXoHostCollection } from '@/modules/host/remote-resources/use-xo-host-collection.ts'
import type { FrontXoPool } from '@/modules/pool/remote-resources/use-xo-pool-collection.ts'
import { useFetchStats } from '@/shared/composables/fetch-stats.composable.ts'
import VtsStatsCharts from '@core/components/stats-charts/VtsStatsCharts.vue'
import VtsStatsToolbar from '@core/components/stats-toolbar/VtsStatsToolbar.vue'
import { type PoolHostStats, usePoolStatsCharts } from '@core/composables/stats-charts/pool-stats-charts.composable.ts'
import type { XoHost } from '@vates/types'
import type { XapiHostStats, XapiStatsGranularity } from '@vates/types/common'
import { isEqual } from 'lodash-es'
import { computed, ref } from 'vue'
const { pool } = defineProps<{
pool: FrontXoPool
}>()
const granularity = ref<XapiStatsGranularity>('seconds')
const showTotals = ref(false)
const { getHostById } = useXoHostCollection()
const { data, error } = useFetchStats('pool', () => pool.id, granularity)
// The host collection changes with any field of any host: the previous names are kept when they are the same, so that
// the charts are only rebuilt with new stats
const hostNames = computed<Record<XoHost['id'], string>>(previousNames => {
const names = Object.fromEntries(
Object.keys(data.value ?? {}).map(hostId => [hostId, getHostById(hostId as XoHost['id'])?.name_label ?? hostId])
)
return previousNames !== undefined && isEqual(names, previousNames) ? previousNames : names
})
const poolHostsStats = computed<PoolHostStats[]>(() =>
Object.entries(data.value ?? {})
// Halted hosts come with an `error` instead of stats
.filter((entry): entry is [XoHost['id'], XapiHostStats] => !('error' in entry[1]))
.map(([hostId, stats]) => ({ name: hostNames.value[hostId], stats }))
)
const charts = usePoolStatsCharts(poolHostsStats, showTotals)
</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

@@ -0,0 +1,70 @@
<template>
<div class="stats">
<VtsStateHero v-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" />
<VtsStatsCharts :charts :granularity :loading="data === null" :error="!!error" />
</template>
</div>
</template>
<script lang="ts" setup>
import type { FrontXoVm } from '@/modules/vm/remote-resources/use-xo-vm-collection.ts'
import { useFetchStats } from '@/shared/composables/fetch-stats.composable.ts'
import VtsStateHero from '@core/components/state-hero/VtsStateHero.vue'
import VtsStatsCharts from '@core/components/stats-charts/VtsStatsCharts.vue'
import VtsStatsToolbar from '@core/components/stats-toolbar/VtsStatsToolbar.vue'
import { useVmStatsCharts } from '@core/composables/stats-charts/vm-stats-charts.composable.ts'
import { VM_POWER_STATE } from '@vates/types'
import type { XapiStatsGranularity } from '@vates/types/common'
import { computed, ref } from 'vue'
import { useI18n } from 'vue-i18n'
const { vm } = defineProps<{
vm: FrontXoVm
}>()
const { t } = useI18n()
const granularity = ref<XapiStatsGranularity>('seconds')
const showTotals = ref(false)
// A paused VM is still on its host, which keeps recording its stats
const isVmActive = computed(() => vm.power_state === VM_POWER_STATE.RUNNING || vm.power_state === VM_POWER_STATE.PAUSED)
// Halted and suspended VMs have no stats to fetch
const { data, error } = useFetchStats('vm', () => (isVmActive.value ? vm.id : undefined), granularity)
const charts = useVmStatsCharts(() => data.value ?? undefined, showTotals)
</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

@@ -235,6 +235,7 @@ declare module 'vue-router/auto-routes' {
| '/host/[id]/console'
| '/host/[id]/dashboard'
| '/host/[id]/networks'
| '/host/[id]/stats'
| '/host/[id]/storage'
| '/host/[id]/system'
| '/host/[id]/tasks'
@@ -261,6 +262,13 @@ declare module 'vue-router/auto-routes' {
{ id: ParamValue<false> },
| never
>,
'/host/[id]/stats': RouteRecordInfo<
'/host/[id]/stats',
'/host/:id/stats',
{ id: ParamValue<true> },
{ id: ParamValue<false> },
| never
>,
'/host/[id]/storage': RouteRecordInfo<
'/host/[id]/storage',
'/host/:id/storage',
@@ -319,6 +327,7 @@ declare module 'vue-router/auto-routes' {
| '/pool/[id]/dashboard'
| '/pool/[id]/hosts'
| '/pool/[id]/networks'
| '/pool/[id]/stats'
| '/pool/[id]/storage'
| '/pool/[id]/system'
| '/pool/[id]/tasks'
@@ -346,6 +355,13 @@ declare module 'vue-router/auto-routes' {
{ id: ParamValue<false> },
| never
>,
'/pool/[id]/stats': RouteRecordInfo<
'/pool/[id]/stats',
'/pool/:id/stats',
{ id: ParamValue<true> },
{ id: ParamValue<false> },
| never
>,
'/pool/[id]/storage': RouteRecordInfo<
'/pool/[id]/storage',
'/pool/:id/storage',
@@ -456,6 +472,7 @@ declare module 'vue-router/auto-routes' {
| '/vm/[id]/dashboard'
| '/vm/[id]/networks'
| '/vm/[id]/snapshots'
| '/vm/[id]/stats'
| '/vm/[id]/system'
| '/vm/[id]/tasks'
| '/vm/[id]/vdis'
@@ -495,6 +512,13 @@ declare module 'vue-router/auto-routes' {
{ id: ParamValue<false> },
| never
>,
'/vm/[id]/stats': RouteRecordInfo<
'/vm/[id]/stats',
'/vm/:id/stats',
{ id: ParamValue<true> },
{ id: ParamValue<false> },
| never
>,
'/vm/[id]/system': RouteRecordInfo<
'/vm/[id]/system',
'/vm/:id/system',
@@ -717,6 +741,7 @@ declare module 'vue-router/auto-routes' {
| '/host/[id]/console'
| '/host/[id]/dashboard'
| '/host/[id]/networks'
| '/host/[id]/stats'
| '/host/[id]/storage'
| '/host/[id]/system'
| '/host/[id]/tasks'
@@ -742,6 +767,12 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/pages/host/[id]/stats.vue': {
routes:
| '/host/[id]/stats'
views:
| never
}
'src/pages/host/[id]/storage.vue': {
routes:
| '/host/[id]/storage'
@@ -792,6 +823,7 @@ declare module 'vue-router/auto-routes' {
| '/pool/[id]/dashboard'
| '/pool/[id]/hosts'
| '/pool/[id]/networks'
| '/pool/[id]/stats'
| '/pool/[id]/storage'
| '/pool/[id]/system'
| '/pool/[id]/tasks'
@@ -818,6 +850,12 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/pages/pool/[id]/stats.vue': {
routes:
| '/pool/[id]/stats'
views:
| never
}
'src/pages/pool/[id]/storage.vue': {
routes:
| '/pool/[id]/storage'
@@ -915,6 +953,7 @@ declare module 'vue-router/auto-routes' {
| '/vm/[id]/dashboard'
| '/vm/[id]/networks'
| '/vm/[id]/snapshots'
| '/vm/[id]/stats'
| '/vm/[id]/system'
| '/vm/[id]/tasks'
| '/vm/[id]/vdis'
@@ -951,6 +990,12 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/pages/vm/[id]/stats.vue': {
routes:
| '/vm/[id]/stats'
views:
| never
}
'src/pages/vm/[id]/system.vue': {
routes:
| '/vm/[id]/system'

View File

@@ -1,8 +1,11 @@
import { type GRANULARITY, RRD_STEP_FROM_STRING } from '@/shared/utils/rest-api-stats.ts'
import { RRD_STEP_FROM_STRING } from '@/shared/utils/rest-api-stats.ts'
import type { XoHost, XoPool, XoVm } from '@vates/types'
import type { XapiHostStats, XapiPoolStats, XapiVmStats } from '@vates/types/common'
import { useFetch, useIntervalFn } from '@vueuse/core'
import { computed, type MaybeRefOrGetter, type ShallowRef, toValue } from 'vue'
import type { XapiHostStats, XapiPoolStats, XapiStatsGranularity, XapiVmStats } from '@vates/types/common'
import { useFetch, useIntervalFn, useTimeoutFn } from '@vueuse/core'
import { computed, type MaybeRefOrGetter, shallowRef, type ShallowRef, toValue, watch } from 'vue'
// In milliseconds
const RETRY_DELAY = 10_000
type StatsByObjectType = {
host: { stats: XapiHostStats; id: XoHost['id'] }
@@ -10,38 +13,83 @@ type StatsByObjectType = {
pool: { stats: XapiPoolStats; id: XoPool['id'] }
}
/**
* Polls the stats of an object at the pace of the granularity.
*
* An `undefined` ID pauses the polling, e.g. while the object is halted and has no stats.
*
* After a failure, `data` keeps the last fetched stats, and `error` is kept until a request succeeds.
*/
export function useFetchStats<T extends keyof StatsByObjectType>(
objectType: T,
id: MaybeRefOrGetter<StatsByObjectType[T]['id']>,
granularity: MaybeRefOrGetter<GRANULARITY>
id: MaybeRefOrGetter<StatsByObjectType[T]['id'] | undefined>,
granularity: MaybeRefOrGetter<XapiStatsGranularity>
): {
data: ShallowRef<StatsByObjectType[T]['stats']>
data: ShallowRef<StatsByObjectType[T]['stats'] | null>
error: ShallowRef<any>
isFetching: Readonly<ShallowRef<boolean>>
} {
const url = computed(() => `/rest/v0/${objectType}s/${toValue(id)}/stats?granularity=${toValue(granularity)}`)
const result = useFetch(url, {
immediate: false,
// `useFetch` clears its own `data` on a failure and its `error` on each request: both are kept here instead
const data = shallowRef<StatsByObjectType[T]['stats'] | null>(null)
const error = shallowRef<any>(null)
// A failure is retried soon rather than at the next poll, which can be an hour or a day later
const { start: scheduleRetry } = useTimeoutFn(() => refresh(), RETRY_DELAY, { immediate: false })
// `refetch` alone fetches when the URL changes: an immediate interval callback would also fire on a granularity change
const { execute, isFetching } = useFetch(url, {
refetch: true,
beforeFetch({ options }) {
beforeFetch({ options, cancel }) {
if (toValue(id) === undefined) {
cancel()
}
options.credentials = 'include'
return { options }
},
afterFetch(fetchContext) {
// The response for another object or granularity is ignored
if (fetchContext.context.url === url.value) {
data.value = fetchContext.data
error.value = null
}
return fetchContext
},
onFetchError(fetchContext) {
// A URL change cancels the pending request: that cancellation is not a failure
if (fetchContext.error?.name !== 'AbortError' && fetchContext.context.url === url.value) {
error.value = fetchContext.error
scheduleRetry()
}
return fetchContext
},
})
.get()
.json()
useIntervalFn(
() => result.execute(),
() => RRD_STEP_FROM_STRING[toValue(granularity)] * 1000,
{ immediateCallback: true }
)
// A new request would cancel the pending one, so a server slower than the poll would never answer
function refresh() {
if (!isFetching.value) {
execute()
}
}
useIntervalFn(refresh, () => RRD_STEP_FROM_STRING[toValue(granularity)] * 1000)
// The data and error of another object or granularity must not be shown while the new ones are fetched
watch(url, () => {
data.value = null
error.value = null
})
return {
data: result.data,
error: result.error,
isFetching: result.isFetching,
data,
error,
isFetching,
}
}

View File

@@ -1,3 +1,5 @@
import type { XapiStatsGranularity } from '@vates/types/common'
// according to https://xapi-project.github.io/xen-api/metrics.html
// The values are stored at intervals of:
// - 5 seconds for the past 10 minutes
@@ -18,7 +20,7 @@ export enum GRANULARITY {
Days = 'days',
}
export const RRD_STEP_FROM_STRING: { [key in GRANULARITY]: RRD_STEP } = {
export const RRD_STEP_FROM_STRING: Record<XapiStatsGranularity, RRD_STEP> = {
[GRANULARITY.Seconds]: RRD_STEP.Seconds,
[GRANULARITY.Minutes]: RRD_STEP.Minutes,
[GRANULARITY.Hours]: RRD_STEP.Hours,

View File

@@ -11,13 +11,13 @@
- [Backups] A backup job running in the xo-server process (`backups.disableWorkers`) can be aborted from its task (tasks view, REST API, or the "run schedule" action): the reads and writes stop, the partial backups are removed and the VMs are reported as interrupted (PR [#10875](https://github.com/vatesfr/xen-orchestra/pull/10875))
- [@vates/task] With the new `skipSubtasksAfterAbort` option of a root task, a subtask created after the abort fails without running, unless it is created with `cleanup: true`, which is meant for the cleanup steps of an aborted task (PR [#10875](https://github.com/vatesfr/xen-orchestra/pull/10875))
- [XO6/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))
### Bug fixes
> Users must be able to say: "I had this issue, happy to know it's fixed"
- [Backup reports] Aborted or interrupted VMs are no longer counted as failed (PR [#10875](https://github.com/vatesfr/xen-orchestra/pull/10875))
- [Backup] Correctly cleanup the snapshot of a VM without any backed up disk: only a CDROM or only `[NOBAK]` disks (PR [#10789](https://github.com/vatesfr/xen-orchestra/pull/10789))
### Packages to release
@@ -37,6 +37,8 @@
- @vates/task minor
- @xen-orchestra/backups minor
- @xen-orchestra/web minor
- @xen-orchestra/web-core minor
- @xen-orchestra/xapi minor
- xo-server minor
- xo-server-backup-reports minor