Compare commits

..

4 Commits

Author SHA1 Message Date
Simon Pacotte
9b69b339a6 refix 2026-10-05 14:55:35 +02:00
Simon Pacotte
19b1fe1009 fix Florent 2026-10-05 10:53:45 +02:00
Simon Pacotte
86b9686c5c update changelog 2026-10-02 11:23:40 +02:00
Simon Pacotte
0eab596880 fix(backups): fix synchronized backup snapshop showing as vm in task log 2026-10-02 11:15:27 +02:00
607 changed files with 2492 additions and 20022 deletions

View File

@@ -1,19 +1,8 @@
name: Vectura
# only when vectura changes: the rest of the repository does not build it
#
# pull requests rather than every push: GitHub filters a push on the diff with
# the previous push, which after a rebase on `master` (or a merge of it)
# contains the vectura changes of `master`, whereas it filters a pull request
# on the diff with the merge base, i.e. the changes of the branch only
on:
pull_request:
paths:
- '@xen-orchestra/vmware-explorer/vectura/**'
- .github/workflows/vectura.yml
push:
branches:
- master
paths:
- '@xen-orchestra/vmware-explorer/vectura/**'
- .github/workflows/vectura.yml

View File

@@ -54,11 +54,6 @@ export default class AbstractNbdClient {
// publish itself
#connectGeneration = 0
// generation of the attempt which published the current transport, undefined
// when not connected: an error on a transport of another generation is stale
// and must be ignored
#connectedGeneration
#waitBeforeReconnect
#readBlockRetries
#reconnectRetry
@@ -72,6 +67,7 @@ export default class AbstractNbdClient {
#nextCommandQueryId = BigInt(0)
// map of command waiting for a response queryId => { size/*in byte*/, resolve, reject}
#commandQueryBacklog = new Map()
#connected = false
#reconnectingPromise
@@ -112,7 +108,7 @@ export default class AbstractNbdClient {
}
get connected() {
return this.#connectedGeneration !== undefined
return this.#connected
}
/* ---------------------------------------------------------------------------
@@ -206,31 +202,22 @@ export default class AbstractNbdClient {
* connection
* ------------------------------------------------------------------------- */
#onTransportError(generation, error) {
#onTransportError = error => {
// without this listener an error on the transport would be thrown as an
// uncaught exception, and pending reads would only fail on message timeout
//
// an error on a transport which is not the current one is expected (a
// closed transport can be reset late by the other end, after a reconnection)
// and must not reject the reads of the current transport
//
// an error during the handshake is reported by the handshake reads
// themselves, through the connect() rejection
if (generation !== this.#connectedGeneration) {
debug('error on a stale nbd transport', { error })
return
}
warn('error on the nbd transport', { error })
// an error outside of the connected window is expected (the other end can
// be gone already while we're closing), and always reported to the caller
// through the connect()/readBlock() rejection
const log = this.#connected ? warn : debug
log('error on the nbd transport', { error })
this.#rejectAll(error)
}
// the generation is used instead of the transport itself since an attempt can
// own multiple transports (the raw one and the one upgraded to TLS)
#watchTransport(transport, generation) {
const onError = error => this.#onTransportError(generation, error)
transport.readable.on('error', onError)
#watchTransport(transport) {
transport.readable.on('error', this.#onTransportError)
if (transport.writable !== transport.readable) {
transport.writable.on('error', onError)
transport.writable.on('error', this.#onTransportError)
}
}
@@ -240,10 +227,10 @@ export default class AbstractNbdClient {
// not cancel on timeout, so a superseded attempt must not be able to use,
// replace or destroy the transport of the attempt which replaced it
let transport = await this._openTransport()
this.#watchTransport(transport, generation)
this.#watchTransport(transport)
try {
// the transport can be replaced during the handshake (TLS upgrade)
transport = await this.#handshake(transport, generation)
transport = await this.#handshake(transport)
if (generation !== this.#connectGeneration) {
const error = new Error('this connection has been superseded by a newer one')
@@ -257,7 +244,7 @@ export default class AbstractNbdClient {
throw error
}
this.#transport = transport
this.#connectedGeneration = generation
this.#connected = true
// reset internal state if we reconnected a nbd client
this.#commandQueryBacklog = new Map()
this.#waitingForResponse = false
@@ -280,10 +267,10 @@ export default class AbstractNbdClient {
}
async disconnect() {
if (this.#connectedGeneration === undefined) {
if (!this.#connected) {
return
}
this.#connectedGeneration = undefined
this.#connected = false
const transport = this.#transport
this.#transport = undefined
if (transport === undefined) {
@@ -379,10 +366,9 @@ export default class AbstractNbdClient {
//
/**
* @param {NbdTransport} transport
* @param {number} generation - the connection attempt owning the transport
* @returns {Promise<NbdTransport>}
*/
async #handshake(transport, generation) {
async #handshake(transport) {
assert((await this.#read(transport, 8)).equals(INIT_PASSWD))
assert((await this.#read(transport, 8)).equals(OPTS_MAGIC))
const flagsBuffer = await this.#read(transport, 2)
@@ -393,7 +379,7 @@ export default class AbstractNbdClient {
// let the subclass upgrade the transport if it needs to (TLS)
const secured = await this._secureTransport(transport)
if (secured !== transport) {
this.#watchTransport(secured, generation)
this.#watchTransport(secured)
transport = secured
}

View File

@@ -166,28 +166,6 @@ describe('AbstractNbdClient', () => {
}
})
it('does not let an error on a superseded transport disturb the current one', async () => {
const client = new InMemoryNbdClient({}, { readBlockRetries: 1, waitBeforeReconnect: 0 })
await client.connect()
await client.reconnect()
try {
assert.equal(client.transports.length, 2)
const [supersededTransport] = client.transports
// the read is queued synchronously, the in memory server answers later
const promise = client.readBlock(0, BLOCK_SIZE)
// the other end of the closed transport resets it late
supersededTransport.readable.emit('error', Object.assign(new Error('read ECONNRESET'), { code: 'ECONNRESET' }))
const block = await promise
assert.ok(block.equals(DATA.subarray(0, BLOCK_SIZE)))
// no reconnection has been triggered
assert.equal(client.transports.length, 2)
} finally {
await client.disconnect()
}
})
it('does not support getMap()', async () => {
const client = new InMemoryNbdClient()
await assert.rejects(client.getMap(), ({ code }) => code === 'NBD_MAP_UNSUPPORTED')

View File

@@ -25,7 +25,7 @@
"@xen-orchestra/disk-transform": "^1.3.3",
"@xen-orchestra/log": "^0.7.2",
"promise-toolbox": "^0.21.0",
"xen-api": "^5.0.2"
"xen-api": "^5.0.1"
},
"devDependencies": {
"tap": "^18.7.0",

View File

@@ -800,7 +800,3 @@ export const XAPI_TYPES: readonly string[] = [
export const RPU_RECOVERY_STEP_NAMES = ['evacuate', 'update', 'reboot', 'enable', 'restoreVms'] as const
export type RPU_RECOVERY_STEP_NAME = (typeof RPU_RECOVERY_STEP_NAMES)[number]
export const COMMON_TAG = {
NOBAK: 'xo:no-bak',
} as const

View File

@@ -1,4 +1,4 @@
import { EventEmitter, Readable } from 'node:stream'
import { EventEmitter } from 'node:stream'
import type {
AnyXoJob,
AnyXoLog,
@@ -52,7 +52,6 @@ import {
XoGroupRole,
XoUserRole,
} from './index.mjs'
import { IncomingHttpHeaders } from 'node:http'
type FeatureCode =
| 'BACKUP.DELTA'
@@ -234,12 +233,6 @@ export type XoApp = {
}
}
/**
* the VM backup archives of the backup repositories, as a collection: `add`, `update` and
* `remove` events carrying the archive and its previous value
*/
vmBackupArchives: EventEmitter
tasks: EventEmitter & {
abort(id: XoTask['id'], reason?: string): Promise<void>
clearLogs(): Promise<void>
@@ -292,11 +285,7 @@ export type XoApp = {
id: XoAclRole['id'],
params?: { name?: XoAclRole['name']; description?: XoAclRole['description'] }
): Promise<XoAclRole['id']>
createAclV2Role(role: {
name: XoAclRole['name']
description?: XoAclRole['description']
privileges?: Omit<XoAclBasePrivilege, 'id' | 'roleId'>[]
}): Promise<XoAclRole>
createAclV2Role(role: { name: XoAclRole['name']; description?: XoAclRole['description'] }): Promise<XoAclRole>
createAuthenticationToken(opts: {
client?: {
id?: string
@@ -420,20 +409,6 @@ export type XoApp = {
getXoEventEmitterByType(type: string): EventEmitter
hasFeatureAuthorization(featureCode: string): Promise<boolean>
hasObject<T extends XapiXoRecord>(id: T['id'], type: T['type']): boolean
httpRequest(
url: string,
opts: {
auth?: string
body?: string | NodeJS.ArrayBufferView | Readable | null
bypassStatusCheck?: boolean
headers?: IncomingHttpHeaders
method: string
rejectUnauthorized?: boolean
bodyTimeout?: number
headersTimeout?: number
signal?: AbortSignal
}
): Promise<Response>
listMetadataBackups(backupRepositoryIds: XoBackupRepository['id'][]): Promise<{
xo: Record<XoBackupRepository['id'], XoConfigBackupArchive[]>
pool: Record<XoBackupRepository['id'], Record<XoPool['id'], XoPoolBackupArchive[]>>

View File

@@ -628,7 +628,6 @@ export type XoSr = BaseXapiXo & {
current_operations: Record<string, STORAGE_OPERATIONS>
id: Branded<'SR'>
inMaintenanceMode: boolean
is_tools_sr: boolean
name_description: string
name_label: string
other_config: Record<string, string>
@@ -910,7 +909,6 @@ export type NonXapiXoRecord =
| AnyXoBackupArchive
| AnyXoJob
| AnyXoLog
| XoAuthenticationToken
| XoGroup
| XoProxy
| XoJob

View File

@@ -8,8 +8,6 @@ import { default as backupRepository } from './backup-repository.mjs'
import { default as gpuGroup } from './gpuGroup.mjs'
import { default as group } from './group.mjs'
import { default as host } from './host.mjs'
import { default as kubernetesCluster } from './kubernetes-cluster.mjs'
import { default as kubernetesNode } from './kubernetes-node.mjs'
import { default as message } from './message.mjs'
import { default as network } from './network.mjs'
import { default as pbd } from './pbd.mjs'
@@ -52,8 +50,6 @@ export const SUPPORTED_ACTIONS_BY_RESOURCE = {
group,
gpuGroup,
host,
'kubernetes-cluster': kubernetesCluster,
'kubernetes-node': kubernetesNode,
message,
network,
pbd,

View File

@@ -1,6 +0,0 @@
export default {
create: true,
delete: true,
read: true,
'read-config': true,
}

View File

@@ -1,3 +0,0 @@
export default {
read: true,
}

View File

@@ -38,8 +38,8 @@
"build": "yarn run clean && tsc",
"dev": "tsc --watch",
"postversion": "npm publish --access public",
"test": "yarn run clean && tsc && node --test './dist/**/*.test.mjs'",
"test-integration": "tsc && node --test './src/**/*.integ.mjs'",
"test": "yarn run clean && tsc && node --test **/*.test.mjs",
"test-integration": "tsc && node --test **/*.integ.mjs",
"clean": "rimraf dist/"
},
"private": false,

View File

@@ -42,13 +42,12 @@ export class RemoteDiskLineage {
#childOf: Map<string, string> = new Map()
// Disk paths declared active by their owning archives (accumulated across all referencing archives)
#activeDiskPaths: Set<string> = new Set()
// Interrupted merges: normalized parent path { stateFilePath, chain, step }
#interruptedMerges: Map<string, { stateFilePath: string; chain?: string[]; step?: 'mergeBlocks' | 'cleanup' }> =
new Map()
// Interrupted merges: normalized parent path { stateFilePath, chain }
#interruptedMerges: Map<string, { stateFilePath: string; chain?: string[] }> = new Map()
constructor(handler: RemoteHandlerAbstract, vdiDir: string, opts: ResolvedBackupCleanOptions) {
this.#handler = handler
this.#vdiDir = normalize(vdiDir)
this.#vdiDir = vdiDir
this.#opts = opts
}
@@ -267,38 +266,8 @@ export class RemoteDiskLineage {
return undefined
}
// Read-only walk toward the descendants: true if any of them is still referenced by a backup.
// Unlike getUsedChildChainOrDelete, it neither marks disks visited nor schedules deletions.
const hasUsedDescendant = (diskPath: string): boolean => {
// `seen` guards against a cycle in corrupted headers
const seen = new Set<string>()
for (let p: string | undefined = diskPath; p !== undefined && !seen.has(p); p = this.#childOf.get(p)) {
seen.add(p)
if (!orphanDisks.has(p)) {
return true
}
}
return false
}
// Keeps the orphan loop away from a chain that must not be touched this run. Pinned disks are
// differencing: every ancestor they read through must survive too, however deep the lineage is
// (e.g. after a retention change). The ancestors are merged normally once the chain is
// resumed or dropped.
const pin = (paths: readonly string[]): void => {
for (const path of paths) {
// `seen` guards against a cycle in corrupted headers
const seen = new Set<string>()
for (let p: string | undefined = path; p !== undefined && !seen.has(p); p = this.#parentOf.get(p)) {
seen.add(p)
visited.add(p)
toDelete.delete(p)
}
}
}
// Process interrupted merges first so their disks are protected from the orphan loop
for (const [parentPath, { stateFilePath, chain: stateChain, step }] of this.#interruptedMerges) {
for (const [parentPath, { stateFilePath, chain: stateChain }] of this.#interruptedMerges) {
if (!this.#diskPaths.has(parentPath)) {
this.#opts.logWarn('orphan merge state', { stateFilePath, missingDisk: parentPath })
if (remove) {
@@ -310,85 +279,14 @@ export class RemoteDiskLineage {
let chain: string[] | undefined
if (stateChain !== undefined) {
const missing = stateChain.filter(p => !this.#diskPaths.has(p))
// A merge only removes disks during its cleanup step, so outside of it every disk of the
// recorded chain must still be there. Merging what is left would fold the surviving
// children into the parent and then rename it onto the chain tip, silently dropping the
// blocks of the disks that went missing. Never resume such a chain.
if (missing.length > 0 && step !== 'cleanup') {
// Each surviving disk is walked on its own: the missing disk breaks the `childOf` links,
// so a walk from the parent alone would stop at the gap.
const survivors = stateChain.filter(p => this.#diskPaths.has(p))
if (survivors.some(hasUsedDescendant)) {
// A backup still references a disk downstream: pin the chain so the orphan loop
// neither merges it afresh nor deletes it. It is dropped once nothing uses it anymore.
this.#opts.logWarn('merge chain lost disks before its cleanup step, refusing to resume', {
stateFilePath,
parentPath,
step,
missing,
})
pin(survivors)
continue
}
// Nothing uses the chain anymore (descendants of the missing disk are broken, so never
// active): drop the state, the orphan loop below deletes the disks.
this.#opts.logWarn('unmergeable merge chain on a fully orphaned lineage', {
stateFilePath,
parentPath,
step,
missing,
})
if (remove) {
this.#opts.logInfo('deleting merge state of orphaned lineage', { stateFilePath })
await this.#handler.unlink(stateFilePath)
}
continue
}
const existing = stateChain.filter(p => this.#diskPaths.has(p))
if (existing.length >= 2) {
chain = existing
} else {
// fewer than 2 disks of the recorded chain are left, there is nothing to resume and
// the state would otherwise stay on disk forever.
//
// only done when the chain was read successfully: an undefined `stateChain` also
// covers a state file that is merely unreadable right now, which must be kept
this.#opts.logWarn('merge state without a resumable chain', { stateFilePath, parentPath })
if (remove) {
this.#opts.logInfo('deleting unresumable merge state', { stateFilePath })
await this.#handler.unlink(stateFilePath)
}
continue
}
if (existing.length >= 2) chain = existing
}
if (chain === undefined) {
// state file unreadable: leave it alone, the orphan loop below schedules a fresh merge
continue
if (chain !== undefined) {
chain.forEach(p => visited.add(p))
toMerge.push({ chain, isResuming: true })
}
// Nothing downstream of the merge parent is still referenced by a backup: merging would
// write into a lineage nothing points at, and pinning it below would exempt it from the
// orphan loop forever. The walk already marked the whole lineage for deletion, so only
// the state file is left to drop.
//
// It walks the live lineage rather than `stateChain`, which is frozen at the retention
// boundary of the run that created it and can be shorter than the real chain.
if (getUsedChildChainOrDelete(parentPath) === undefined) {
this.#opts.logWarn('merge state on a fully orphaned lineage', { stateFilePath, parentPath })
if (remove) {
this.#opts.logInfo('deleting merge state of orphaned lineage', { stateFilePath })
await this.#handler.unlink(stateFilePath)
}
continue
}
pin(chain)
toMerge.push({ chain, isResuming: true })
}
for (const orphan of orphanDisks) {

View File

@@ -1,279 +0,0 @@
import { test } from 'node:test'
import { strict as assert } from 'node:assert'
import tmp from 'tmp'
import * as uuid from 'uuid'
import { getHandler } from '@xen-orchestra/fs'
import { normalize } from '@xen-orchestra/fs/path'
import { pFromCallback } from 'promise-toolbox'
import { rimraf } from 'rimraf'
import { Constants, VhdAbstract, VhdDirectory } from 'vhd-lib'
import { VHDFOOTER, VHDHEADER } from './tests.fixtures.mjs'
// `RemoteDiskLineage` is a `.mts` module: this is the TS ESM spelling of the sibling import, which
// resolves at runtime because the `test` script runs the built `dist/` copy of this file. It must
// NOT go through `../dist/`, which would make `tsc` pull the emitted declarations back in as
// inputs (TS5055) — the `*.integ.mjs` files can only do that because tsconfig excludes them.
/* eslint-disable n/no-missing-import */
import { RemoteDiskLineage } from './RemoteDiskLineage.mjs'
/* eslint-enable n/no-missing-import */
const { beforeEach, afterEach, describe } = test
let handler, tempDir, vdiDir
beforeEach(async () => {
tempDir = await pFromCallback(cb => tmp.dir(cb))
handler = getHandler({ url: `file://${tempDir}` })
await handler.sync()
// VmIncrementalBackupArchive passes a normalized path, and RemoteDiskLineage compares
// #vdiDir against normalized paths, so the fixture has to match
vdiDir = normalize(`xo-vm-backups/VMUUID/vdis/${uuid.v1()}/${uuid.v1()}`)
await handler.mktree(`${vdiDir}/data`)
})
afterEach(async () => {
await rimraf(tempDir)
await handler.forget()
})
// Creates an aliased VHD directory in `vdiDir`, chained onto `parent` when given.
async function generateDisk(name, { parent } = {}) {
const aliasPath = `${vdiDir}/${name}.alias.vhd`
const dataPath = `${vdiDir}/data/${name}.vhd`
await handler.mkdir(dataPath)
const vhd = new VhdDirectory(handler, dataPath)
vhd.header = { ...VHDHEADER }
vhd.footer = { ...VHDFOOTER, uuid: uuid.v1({}, Buffer.alloc(16)) }
if (parent !== undefined) {
vhd.header.parentUnicodeName = `${parent.name}.alias.vhd`
vhd.header.parentUuid = parent.vhd.footer.uuid
vhd.footer.diskType = Constants.DISK_TYPES.DIFFERENCING
} else {
vhd.footer.diskType = Constants.DISK_TYPES.DYNAMIC
}
await vhd.writeEntireBlock({ id: 0, buffer: Buffer.alloc(2 * 1024 * 1024 + 512, 1) })
await vhd.writeBlockAllocationTable()
await vhd.writeHeader()
await vhd.writeFooter()
await VhdAbstract.createAlias(handler, aliasPath, dataPath)
return { name, aliasPath, dataPath, vhd }
}
// Plants the merge state file a previous interrupted merge would have left on `parent`.
async function writeMergeState(parent, { chain, step = 'mergeBlocks' }) {
const statePath = `${vdiDir}/.${parent.name}.alias.vhd.merge.json`
await handler.writeFile(
statePath,
JSON.stringify({
child: { uuid: uuid.v1() },
parent: { uuid: uuid.v1() },
chain: chain.map(name => `${name}.alias.vhd`),
currentBlock: 0,
mergedDataSize: 0,
step,
diskSize: 0,
})
)
return statePath
}
async function cleanLineage({ activeDisks = [], lineageDir = vdiDir, merge = false } = {}) {
const warnings = []
const infos = []
const lineage = new RemoteDiskLineage(handler, lineageDir, {
remove: true,
merge,
logInfo: (message, data) => infos.push({ message, data }),
logWarn: (message, data) => warnings.push({ message, data }),
})
await lineage.init()
for (const disk of activeDisks) {
lineage.addActiveDiskPath(disk.aliasPath)
}
await lineage.clean({ remove: true, merge })
return { warnings, infos }
}
const exists = path => handler.list(vdiDir).then(files => files.includes(path.slice(vdiDir.length + 1)))
describe('RemoteDiskLineage.clean() interrupted merges', { concurrency: 1 }, () => {
test('drops the merge state and the disks when no descendant is still referenced', async () => {
const base = await generateDisk('base')
const child = await generateDisk('child', { parent: base })
const statePath = await writeMergeState(base, { chain: ['base', 'child'] })
// no active disk: the whole lineage is out of retention
const { warnings } = await cleanLineage()
assert.equal(await exists(statePath), false, 'merge state should be deleted')
assert.equal(await exists(base.aliasPath), false, 'base should be deleted')
assert.equal(await exists(child.aliasPath), false, 'child should be deleted')
assert.ok(
warnings.some(({ message }) => message === 'merge state on a fully orphaned lineage'),
'the dropped chain should be reported'
)
})
test('refuses to resume, and keeps everything, when the chain lost a disk before its cleanup step', async () => {
const base = await generateDisk('base')
const child = await generateDisk('child', { parent: base })
// `missing` was recorded in the chain but is no longer on the remote: merging base + child
// and renaming onto the tip would silently drop its blocks
const statePath = await writeMergeState(base, { chain: ['base', 'missing', 'child'] })
// merge enabled: the orphan loop must not pick the refused chain up and merge it afresh
const { warnings, infos } = await cleanLineage({ activeDisks: [child], merge: true })
assert.equal(
infos.some(({ message }) => message === 'Disk chain needs merging'),
false,
'no merge should be scheduled for a chain that was refused'
)
assert.equal(await exists(statePath), true, 'merge state should be kept while a backup uses the chain')
assert.equal(await exists(base.aliasPath), true, 'base should be kept')
assert.equal(await exists(child.aliasPath), true, 'child should be kept')
const warning = warnings.find(
({ message }) => message === 'merge chain lost disks before its cleanup step, refusing to resume'
)
assert.notEqual(warning, undefined, 'the incomplete chain should be reported')
assert.deepEqual(warning.data.missing, [`${vdiDir}/missing.alias.vhd`])
})
test('keeps every ancestor of a chain it refused to resume', async () => {
// several ancestors fell out of retention after the merge was interrupted (e.g. the retention
// was lowered): deleting any of them would leave `base`, a differencing disk, without a parent
const ggp = await generateDisk('ggp')
const gp = await generateDisk('gp', { parent: ggp })
const base = await generateDisk('base', { parent: gp })
const child = await generateDisk('child', { parent: base })
const statePath = await writeMergeState(base, { chain: ['base', 'missing', 'child'] })
const { warnings, infos } = await cleanLineage({ activeDisks: [child], merge: true })
assert.ok(
warnings.some(({ message }) => message === 'merge chain lost disks before its cleanup step, refusing to resume'),
'the incomplete chain should be reported'
)
assert.equal(
infos.some(({ message }) => message === 'Disk chain needs merging'),
false,
'neither the refused chain nor its ancestors should be merged'
)
assert.equal(await exists(ggp.aliasPath), true, 'ggp should be kept')
assert.equal(await exists(gp.aliasPath), true, 'gp should be kept')
assert.equal(await exists(statePath), true, 'merge state should be kept')
assert.equal(await exists(base.aliasPath), true, 'base should be kept')
assert.equal(await exists(child.aliasPath), true, 'child should be kept')
})
test('keeps every ancestor of a resumed chain, and merges them on the next run', async () => {
const ggp = await generateDisk('ggp')
const gp = await generateDisk('gp', { parent: ggp })
const base = await generateDisk('base', { parent: gp })
const child = await generateDisk('child', { parent: base })
const statePath = await writeMergeState(base, { chain: ['base', 'child'] })
// first run: only the interrupted merge is resumed, its ancestors are left alone
const firstRun = await cleanLineage({ activeDisks: [child], merge: true })
assert.ok(
firstRun.infos.some(({ message, data }) => message === 'merging disk chain' && data.chain.length === 2),
'the interrupted merge should be resumed'
)
assert.equal(await exists(statePath), false, 'merge state should be deleted once the merge completed')
assert.equal(await exists(base.aliasPath), false, 'base should be merged into child')
assert.equal(await exists(ggp.aliasPath), true, 'ggp should be kept')
assert.equal(await exists(gp.aliasPath), true, 'gp should be kept')
assert.equal(await exists(child.aliasPath), true, 'child should be kept')
// second run: the ancestors are merged into child as a regular chain
const secondRun = await cleanLineage({ activeDisks: [child], merge: true })
assert.deepEqual(
secondRun.warnings.filter(({ message }) => message === 'disk broken: parent missing or broken'),
[],
'child should still have its parents'
)
assert.ok(
secondRun.infos.some(({ message, data }) => message === 'merging disk chain' && data.chain.length === 3),
'ggp and gp should be merged into child'
)
assert.equal(await exists(ggp.aliasPath), false, 'ggp should be merged into child')
assert.equal(await exists(gp.aliasPath), false, 'gp should be merged into child')
assert.equal(await exists(child.aliasPath), true, 'child should be kept')
})
test('drops an unmergeable chain, state and disks, once nothing uses it', async () => {
const base = await generateDisk('base')
const missing = await generateDisk('missing', { parent: base })
const child = await generateDisk('child', { parent: missing })
const statePath = await writeMergeState(base, { chain: ['base', 'missing', 'child'] })
// the intermediate disk vanished mid-merge: child is now broken, so its backup is incomplete
// and never declares it active
await handler.unlink(missing.aliasPath)
await handler.rmtree(missing.dataPath)
const { warnings, infos } = await cleanLineage({ merge: true })
assert.equal(
infos.some(({ message }) => message === 'Disk chain needs merging'),
false,
'an unmergeable chain should not be merged'
)
assert.equal(await exists(statePath), false, 'merge state should be deleted')
assert.equal(await exists(base.aliasPath), false, 'base should be deleted')
assert.equal(await exists(child.aliasPath), false, 'child should be deleted')
assert.ok(
warnings.some(({ message }) => message === 'unmergeable merge chain on a fully orphaned lineage'),
'the dropped chain should be reported'
)
})
test('drops a merge state whose chain no longer has two disks to merge, during cleanup', async () => {
const base = await generateDisk('base')
// the cleanup step unlinks the children as it goes, so a gap there is expected
const statePath = await writeMergeState(base, { chain: ['base', 'alreadyUnlinked'], step: 'cleanup' })
const { warnings } = await cleanLineage({ activeDisks: [base] })
assert.equal(await exists(statePath), false, 'merge state should be deleted')
assert.equal(await exists(base.aliasPath), true, 'the active disk should be kept')
assert.ok(
warnings.some(({ message }) => message === 'merge state without a resumable chain'),
'the unresumable state should be reported'
)
})
test('keeps a resumable merge state and its disks', async () => {
const base = await generateDisk('base')
const child = await generateDisk('child', { parent: base })
const statePath = await writeMergeState(base, { chain: ['base', 'child'] })
const { warnings } = await cleanLineage({ activeDisks: [child] })
assert.equal(await exists(statePath), true, 'merge state should be kept')
assert.equal(await exists(base.aliasPath), true, 'base should be kept')
assert.equal(await exists(child.aliasPath), true, 'child should be kept')
assert.deepEqual(warnings, [], 'a resumable merge should not warn')
})
test('behaves the same when built with a non-normalized VDI directory', async () => {
const base = await generateDisk('base')
const child = await generateDisk('child', { parent: base })
const statePath = await writeMergeState(base, { chain: ['base', 'child'] })
// the constructor must normalize: otherwise #cleanOrphanDataFiles fails to exclude the VDI
// directory from the data directories it sweeps and deletes every unclaimed file in it,
// starting with the merge state
const { warnings } = await cleanLineage({ activeDisks: [child], lineageDir: vdiDir.replace(/^\//, '') })
assert.equal(await exists(statePath), true, 'merge state should be kept')
assert.equal(await exists(base.aliasPath), true, 'base should be kept')
assert.equal(await exists(child.aliasPath), true, 'child should be kept')
assert.deepEqual(warnings, [], 'nothing should be reported as orphaned')
})
})

View File

@@ -331,7 +331,7 @@ export class MergeRemoteDisk {
* @param {string[]} files - all file paths in vdiDir (prependDir: true)
* @param {Map<string, string>} uuidToPath - diskUuid: normalized disk path
* @param {Map<string, string>} childOf - parentPath: child path (from disk headers)
* @returns {Promise<Map<string, { stateFilePath: string, chain?: string[], step?: 'mergeBlocks' | 'cleanup' }>>}
* @returns {Promise<Map<string, { stateFilePath: string, chain?: string[] }>>}
*/
static async findInterruptedMerges(handler, vdiDir, files, uuidToPath, childOf) {
const STATE_FILE_RE = /^\.(.+)\.merge\.json$/
@@ -343,12 +343,8 @@ export class MergeRemoteDisk {
const parentPath = normalize(vdiDir + '/' + match[1])
let chain
let step
try {
const state = JSON.parse(await handler.readFile(filePath))
// disks are only removed during the cleanup step, so the caller needs the step to tell
// an expected gap in the chain from a lineage that lost data
step = state?.step ?? 'mergeBlocks'
if (Array.isArray(state?.chain)) {
chain = state.chain.map((/** @type {string} */ relPath) => normalize(resolveFromFile(filePath, relPath)))
} else {
@@ -361,7 +357,7 @@ export class MergeRemoteDisk {
warn("Merge state unreadable, can't restart merging.", error)
}
result.set(parentPath, { stateFilePath: filePath, chain, step })
result.set(parentPath, { stateFilePath: filePath, chain })
}
return result

View File

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

View File

@@ -702,8 +702,7 @@ export class RemoteAdapter {
) {
const container = watchStreamSize(input)
await this._handler.outputStream(path, input, {
// a known checksum is the one of unencrypted data: an encrypted remote stores no checksum
checksum: typeof checksum === 'string' && this._handler.isEncrypted ? false : checksum,
checksum,
dirMode: this._dirMode,
maxStreamLength,
streamLength,
@@ -754,28 +753,6 @@ export class RemoteAdapter {
return this._handler.createReadStream(resolve('/', dirname(metadata._filename), metadata.xva))
}
/**
* @returns {Promise<string | undefined>} the checksum of the XVA as stored, undefined if it is unknown (no checksum
* file, or encrypted remote: the stored data are not the data read)
*/
async readFullVmBackupChecksum(metadata) {
if (this._handler.isEncrypted) {
return
}
try {
const checksum = String(
await this._handler.readFile(resolve('/', dirname(metadata._filename), metadata.xva) + '.checksum')
).trim()
// $<algorithm id>$<salt>$<hash>
return checksum.startsWith('$') ? checksum : undefined
} catch (error) {
if (error.code === 'ENOENT') {
return
}
throw error
}
}
async readVmBackupMetadata(path) {
let json
let isImmutable = false

View File

@@ -141,6 +141,8 @@ export const VmsXapi = class VmsXapiBackupRunner extends Abstract {
await asyncEach(
[...vms].filter(vm => batchIds.has(vm.uuid)),
async vm => {
// The task deliverately includes both the transfer (including the wait) and and backup.
// This is done to have the snapshot reported under the VM.
const { task } = getVmTask(vm.uuid, vm.name_label)
const vmSettings = { ...settings, ...allSettings[vm.uuid] }

View File

@@ -1,5 +1,3 @@
import { createLogger } from '@xen-orchestra/log'
import { AbstractRemote } from './_AbstractRemote.mjs'
import { FullRemoteWriter } from '../_writers/FullRemoteWriter.mjs'
import { forkStreamUnpipe } from '../_forkStreamUnpipe.mjs'
@@ -7,8 +5,6 @@ import { watchStreamSize } from '../../_watchStreamSize.mjs'
import { AggregatedFullRemoteWriter } from '../_writers/AggregatedFullRemoteWriter.mjs'
import { Task } from '@vates/task'
const { warn } = createLogger('xo:backups:FullRemoteVmBackup')
export const FullRemote = class FullRemoteVmBackupRunner extends AbstractRemote {
_getRemoteWriters() {
return [FullRemoteWriter, AggregatedFullRemoteWriter]
@@ -25,23 +21,12 @@ export const FullRemote = class FullRemoteVmBackupRunner extends AbstractRemote
for (const metadata of transferList) {
const stream = this._throttleStream(await this._sourceRemoteAdapter.readFullVmBackup(metadata))
const sizeContainer = watchStreamSize(stream)
let checksum
try {
// the unencrypted destinations store the same data as the source: no need to compute their checksum again
checksum = await this._sourceRemoteAdapter.readFullVmBackupChecksum(metadata)
} catch (error) {
warn('error while copying reading source checksum, recomputing it', error)
}
// a single writer can consume the stream itself: no need to fork it
const isForked = this._writers.size > 1
// @todo shouldn't transfer backup if it will be deleted by retention policy (higher retention on source than destination)
await this._callWriters(
writer =>
writer.run({
checksum,
stream: isForked ? forkStreamUnpipe(stream) : stream,
stream: forkStreamUnpipe(stream),
// stream will be forked and transformed, it's not safe to attach additional properties to it
streamLength: stream.length,
maxStreamLength: stream.maxStreamLength, // for encrypted destination/source without length

View File

@@ -6,14 +6,13 @@ export class AggregatedIncrementalXapiWriter extends AbstractAggregatedXapiWrite
/**
*
* @param {Map<string,string>} baseUuidToSrcVdi
* @param {Map<string,string>} contentKeys
*/
async checkBaseVdis(baseUuidToSrcVdi, contentKeys) {
async checkBaseVdis(baseUuidToSrcVdi) {
debug('checkBaseVdis', { baseUuidToSrcVdi })
let selectedCopy = new Map()
for (const writer of this.writers) {
const copy = new Map(baseUuidToSrcVdi)
await writer.checkBaseVdis(copy, contentKeys)
await writer.checkBaseVdis(copy)
if (copy.size > 0) {
debug('checkBaseVdis found a mainwriter candidate ', writer._sr.name_label)
// there can be multiple candidates
@@ -35,17 +34,17 @@ export class AggregatedIncrementalXapiWriter extends AbstractAggregatedXapiWrite
}
// take the lock on every adapters with this VM
// cleanup if deleteFirst is selected
async beforeBackup() {
await this.setupWriters()
await Promise.all(this.writers.map(writer => writer.beforeBackup()))
this.setOldReplicaList()
if (this.props.settings.deleteFirst) {
await this.deleteOldReplicas()
}
}
async prepare(args) {
const { settings } = this.props
if (settings.deleteFirst) {
await this.deleteOldReplicas({ keepMostRecent: !args.isFull && settings.copyRetention === 1 })
}
if (this.mainWriter === undefined) {
debug('no mainwriter found, fallback to a new SR')
// use the SR with the most empty space for starting a new chain
@@ -63,7 +62,9 @@ export class AggregatedIncrementalXapiWriter extends AbstractAggregatedXapiWrite
// remove the backups and remove the entries
async cleanup() {
debug('cleanup')
await this.deleteOldReplicas()
if (!this.props.settings.deleteFirst) {
await this.deleteOldReplicas()
}
await Promise.all(this.writers.map(writer => writer.cleanup()))
}

View File

@@ -25,11 +25,7 @@ export class FullRemoteWriter extends MixinRemoteWriter(AbstractFullWriter) {
)
}
/**
* @param {object} params
* @param {string} [params.checksum] - checksum of the stream data if known (full mirror of an unencrypted backup)
*/
async _run({ checksum, maxStreamLength, timestamp, sizeContainer, stream, streamLength, vm, vmSnapshot }) {
async _run({ maxStreamLength, timestamp, sizeContainer, stream, streamLength, vm, vmSnapshot }) {
const settings = this._settings
const job = this._job
const scheduleId = this._schedule.id
@@ -71,7 +67,6 @@ export class FullRemoteWriter extends MixinRemoteWriter(AbstractFullWriter) {
await Task.run({ properties: { name: 'transfer' } }, async () => {
await adapter.outputStream(dataFilename, stream, {
checksum,
maxStreamLength,
streamLength,
validator: tmpPath => adapter.isValidXva(tmpPath),

View File

@@ -383,11 +383,11 @@ export class IncrementalXapiWriter extends MixinXapiWriter(AbstractIncrementalWr
retentionEntries.sort(compareReplicatedVmDatetime)
this._oldEntries = getOldEntries(settings.copyRetention - 1, retentionEntries)
if (settings.deleteFirst && !settings.skipDeleteOldEntries) {
if (settings.deleteFirst && settings.skipDeleteOldEntries) {
// we want to keep the baseVM when copying a delta
// even if we want to keep only one after
let mostRecentEntry
if (this._oldEntries.length > 0 && settings.copyRetention === 1 && !isFull) {
if (this._oldEntries.length > 1 && settings.copyRetention === 1 && !isFull) {
mostRecentEntry = this._oldEntries.pop()
}
await this._deleteOldEntries()

View File

@@ -61,7 +61,7 @@ export class AbstractAggregatedXapiWriter {
setOldReplicaList() {
debug(`setOldReplicaList for vm ${this.#props.vmUuid}`)
const scheduleId = this.#props.schedule.id
const scheduleId = this.#props.scheduleId
const vmUuid = this.#props.vmUuid
const settings = this.#props.settings
@@ -80,35 +80,14 @@ export class AbstractAggregatedXapiWriter {
)
}
/**
* Deletes the old replicas computed by `setOldReplicaList`.
*
* @param {Object} [options]
* @param {boolean} [options.keepMostRecent=false] - Keep the most recent old replica, which is the base of the
* next incremental replication (needed when copyRetention is 1 with deleteFirst). The kept replica stays in
* the list, so a later call without `keepMostRecent` (from `cleanup()`) deletes it once the transfer is done.
*/
async deleteOldReplicas({ keepMostRecent = false } = {}) {
let toDelete = this.#oldVmReplicaList
let kept
// the list is sorted by datetime (oldest first), so the last entry is the most recent replica,
// which is the base of the next incremental replication
if (keepMostRecent && toDelete.length > 0) {
kept = toDelete[toDelete.length - 1]
toDelete = toDelete.slice(0, -1)
}
debug(`deleteOldReplicas will delete ${toDelete.length} replicated vms for vm ${this.#props.vmUuid}`)
async deleteOldReplicas() {
debug(`deleteOldReplicas will delete ${this.#oldVmReplicaList.length} replicated vms for vm ${this.#props.vmUuid}`)
// destroy the VM on the right xapi
await asyncMapSettled(toDelete, async vm => {
await asyncMapSettled(this.#oldVmReplicaList, async vm => {
debug('will delete old replica', vm.name_label)
await vm.$xapi.VM_destroy(vm.$ref)
})
debug(`deleteOldReplicas deleted ${toDelete.length} replicated vms for vm ${this.#props.vmUuid}`)
// whatever is left (the kept base, if any) will be deleted by the next call, from cleanup()
this.#oldVmReplicaList = kept !== undefined ? [kept] : []
debug(`deleteOldReplicas deleted ${this.#oldVmReplicaList.length} replicated vms for vm ${this.#props.vmUuid}`)
}
async setupWriters() {

View File

@@ -1,182 +0,0 @@
import assert from 'node:assert/strict'
import { describe, it } from 'node:test'
import { AbstractAggregatedXapiWriter } from './_AbstractAggregatedXapiWriter.mjs'
import { DATETIME, JOB_ID, REPLICATED_TO_SR_UUID, SCHEDULE_ID, VM_UUID } from '../../_otherConfig.mjs'
// This exercises setOldReplicaList()/deleteOldReplicas() through the REAL
// listReplicatedVms() (same fixture style as ./_listReplicatedVms.test.mjs), rather
// than mocking the module. This is deliberate: `node:test`'s module mocking needs
// --experimental-test-module-mocks, which this repo's `test` script (and therefore
// the pre-commit hook) does not pass, so a mocked version of this test would never
// pass CI. Going through the real filtering logic also means this test genuinely
// proves the fix — not just that a particular value gets forwarded to a spy.
const SOURCE_VM_UUID = 'vm-1'
const SR_UUID = 'sr-1'
const SCHEDULE_A = 'schedule-a'
const SCHEDULE_B = 'schedule-b'
const replicaTarget = { uuid: 'replica-target-uuid' } // stand-in for $snapshot_of on new-style replicas
/**
* Builds a fake "new-style" replication snapshot: a snapshot of the replicated
* target VM (not of the source VM), tagged with the schedule/job that produced it.
*/
const makeReplicaSnapshot = ({ id, datetime, scheduleId, srUuid = SR_UUID, vmUuid = SOURCE_VM_UUID }) => ({
$id: id,
$type: 'VM',
blocked_operations: {},
is_a_snapshot: true,
is_a_template: false,
name_label: id,
$snapshot_of: replicaTarget,
other_config: {
[DATETIME]: datetime,
[JOB_ID]: 'job-1',
[SCHEDULE_ID]: scheduleId,
[VM_UUID]: vmUuid,
[REPLICATED_TO_SR_UUID]: srUuid,
},
})
const makeXapi = vms => ({ objects: { indexes: { type: { VM: Object.fromEntries(vms.map(vm => [vm.$id, vm])) } } } })
/** Attaches $xapi/$ref (as deleteOldReplicas expects) and a VM_destroy spy to each vm. */
function wireForDestroy(vms, destroyCalls) {
const xapi = makeXapi(vms)
for (const vm of vms) {
vm.$xapi = { objects: xapi.objects, VM_destroy: ref => destroyCalls.push(ref) }
vm.$ref = vm.$id
}
return xapi
}
function makeSr(xapi, uuid = SR_UUID) {
return {
uuid,
name_label: `sr-${uuid}`,
physical_utilisation: 0,
physical_size: 100,
$xapi: xapi,
}
}
function makeWriter({ srs, vmUuid = SOURCE_VM_UUID, scheduleId, copyRetention }) {
return new AbstractAggregatedXapiWriter({
srs,
ReplicationWriter: class {},
vmUuid,
schedule: { id: scheduleId }, // <-- the real shape passed by the caller
settings: { copyRetention },
job: { settings: {} },
})
}
describe('AbstractAggregatedXapiWriter#setOldReplicaList / deleteOldReplicas', () => {
it('finds and prunes replicas for its own schedule down to copyRetention', async () => {
const replicas = [
makeReplicaSnapshot({ id: 'a-1', datetime: '20260101T000000Z', scheduleId: SCHEDULE_A }),
makeReplicaSnapshot({ id: 'a-2', datetime: '20260102T000000Z', scheduleId: SCHEDULE_A }),
makeReplicaSnapshot({ id: 'a-3', datetime: '20260103T000000Z', scheduleId: SCHEDULE_A }),
makeReplicaSnapshot({ id: 'a-4', datetime: '20260104T000000Z', scheduleId: SCHEDULE_A }),
]
const destroyCalls = []
const xapi = wireForDestroy(replicas, destroyCalls)
const writer = makeWriter({ srs: [makeSr(xapi)], scheduleId: SCHEDULE_A, copyRetention: 2 })
writer.setOldReplicaList()
await writer.deleteOldReplicas()
// copyRetention 2 keeps the running copy + 1 old one => 4 - 1 = 3 old ones pruned.
// (If setOldReplicaList still reads props.scheduleId instead of props.schedule.id,
// scheduleId is undefined, listReplicatedVms matches nothing, and destroyCalls
// stays empty — this assertion catches exactly that regression.)
assert.equal(
destroyCalls.length,
replicas.length - (2 - 1),
`expected ${replicas.length - 1} replicas pruned for retention 2, got ${destroyCalls.length}. ` +
'An empty destroyCalls list means listReplicatedVms was called with an undefined schedule id ' +
'and matched nothing (the scheduleId-vs-schedule.id bug).'
)
})
it('does not touch another schedule’s replicas on the same VM/SR when pruning its own', async () => {
const scheduleAReplicas = [
makeReplicaSnapshot({ id: 'a-1', datetime: '20260101T000000Z', scheduleId: SCHEDULE_A }),
makeReplicaSnapshot({ id: 'a-2', datetime: '20260102T000000Z', scheduleId: SCHEDULE_A }),
makeReplicaSnapshot({ id: 'a-3', datetime: '20260103T000000Z', scheduleId: SCHEDULE_A }),
]
const scheduleBReplicas = [
makeReplicaSnapshot({ id: 'b-1', datetime: '20260101T000000Z', scheduleId: SCHEDULE_B }),
makeReplicaSnapshot({ id: 'b-2', datetime: '20260102T000000Z', scheduleId: SCHEDULE_B }),
makeReplicaSnapshot({ id: 'b-3', datetime: '20260103T000000Z', scheduleId: SCHEDULE_B }),
makeReplicaSnapshot({ id: 'b-4', datetime: '20260104T000000Z', scheduleId: SCHEDULE_B }),
makeReplicaSnapshot({ id: 'b-5', datetime: '20260105T000000Z', scheduleId: SCHEDULE_B }),
]
// Both schedules' replicas coexist in the same xapi, same SR, same source VM —
// exactly the real-world "multiple schedules on one job" case the bug breaks.
const allReplicas = [...scheduleAReplicas, ...scheduleBReplicas]
const destroyCalls = []
const xapi = wireForDestroy(allReplicas, destroyCalls)
// Prune schedule A only (retention 1: keep the running copy, drop the rest).
const writerA = makeWriter({ srs: [makeSr(xapi)], scheduleId: SCHEDULE_A, copyRetention: 1 })
writerA.setOldReplicaList()
await writerA.deleteOldReplicas()
const destroyedIds = destroyCalls.slice().sort()
assert.deepEqual(
destroyedIds,
['a-1', 'a-2', 'a-3'],
'pruning schedule A should only ever destroy schedule A replicas, never schedule B’s — ' +
`got ${JSON.stringify(destroyedIds)}`
)
// Now prune schedule B (retention 2: keep the running copy + 1 old one => drop 4 of 5).
const writerB = makeWriter({ srs: [makeSr(xapi)], scheduleId: SCHEDULE_B, copyRetention: 2 })
writerB.setOldReplicaList()
await writerB.deleteOldReplicas()
const destroyedAfterB = destroyCalls.slice(3).sort() // calls added since writerA's pass
assert.equal(destroyedAfterB.length, scheduleBReplicas.length - (2 - 1))
assert.ok(
destroyedAfterB.every(id => id.startsWith('b-')),
`pruning schedule B should only destroy schedule B replicas — got ${JSON.stringify(destroyedAfterB)}`
)
})
it('calls listReplicatedVms scoped to each storage repository in turn', async () => {
const srAReplicas = [
makeReplicaSnapshot({ id: 'sr-a-1', datetime: '20260101T000000Z', scheduleId: SCHEDULE_A, srUuid: 'sr-a' }),
makeReplicaSnapshot({ id: 'sr-a-2', datetime: '20260102T000000Z', scheduleId: SCHEDULE_A, srUuid: 'sr-a' }),
]
const srBReplicas = [
makeReplicaSnapshot({ id: 'sr-b-1', datetime: '20260101T000000Z', scheduleId: SCHEDULE_A, srUuid: 'sr-b' }),
makeReplicaSnapshot({ id: 'sr-b-2', datetime: '20260102T000000Z', scheduleId: SCHEDULE_A, srUuid: 'sr-b' }),
makeReplicaSnapshot({ id: 'sr-b-3', datetime: '20260103T000000Z', scheduleId: SCHEDULE_A, srUuid: 'sr-b' }),
]
const destroyCalls = []
// Both SRs happen to share the same underlying xapi object index in this fixture
// (as they would if source and destination are on the same pool); what matters is
// that each SR's uuid scopes its own replicas.
const xapi = wireForDestroy([...srAReplicas, ...srBReplicas], destroyCalls)
const writer = makeWriter({
srs: [makeSr(xapi, 'sr-a'), makeSr(xapi, 'sr-b')],
scheduleId: SCHEDULE_A,
copyRetention: 1, // keep only the running copy on each SR
})
writer.setOldReplicaList()
await writer.deleteOldReplicas()
assert.deepEqual(
destroyCalls.slice().sort(),
['sr-a-1', 'sr-a-2', 'sr-b-1', 'sr-b-2', 'sr-b-3'],
'retention 1 should prune every replica on every configured SR down to none kept aside'
)
})
})

View File

@@ -1,18 +1,9 @@
import { AbstractWriter } from './_AbstractWriter.mjs'
export class AbstractFullWriter extends AbstractWriter {
async run({ checksum, maxStreamLength, timestamp, sizeContainer, stream, streamLength, vm, vmSnapshot }) {
async run({ maxStreamLength, timestamp, sizeContainer, stream, streamLength, vm, vmSnapshot }) {
try {
return await this._run({
checksum,
maxStreamLength,
timestamp,
sizeContainer,
stream,
streamLength,
vm,
vmSnapshot,
})
return await this._run({ maxStreamLength, timestamp, sizeContainer, stream, streamLength, vm, vmSnapshot })
} finally {
// ensure stream is properly closed
stream.destroy()

View File

@@ -8,7 +8,7 @@
"type": "git",
"url": "https://github.com/vatesfr/xen-orchestra.git"
},
"version": "0.76.1",
"version": "0.76.0",
"engines": {
"node": ">=14.18"
},
@@ -56,7 +56,7 @@
"uuid": "^9.0.0",
"value-matcher": "^0.2.0",
"vhd-lib": "^4.16.2",
"xen-api": "^5.0.2",
"xen-api": "^5.0.1",
"yazl": "^2.5.1"
},
"devDependencies": {

View File

@@ -18,7 +18,7 @@
"preferGlobal": true,
"dependencies": {
"golike-defer": "^0.5.1",
"xen-api": "^5.0.2"
"xen-api": "^5.0.1"
},
"scripts": {
"postversion": "npm publish"

View File

@@ -20,7 +20,7 @@
},
"dependencies": {
"@vates/async-each": "^1.0.3",
"@xen-orchestra/backups": "^0.76.1",
"@xen-orchestra/backups": "^0.76.0",
"@xen-orchestra/backup-archive": "^1.1.3",
"@xen-orchestra/disk-transform": "^1.3.3",
"@xen-orchestra/fs": "^4.9.5",

View File

@@ -26,10 +26,6 @@ const computeRate = (hrtime, size) => {
const DEFAULT_TIMEOUT = 12e5 // 20 min
const DEFAULT_MAX_PARALLEL_OPERATIONS = 10
// size of the chunks of the file streams, same as the backup streams: with the 64 KiB of Node, each chunk costs a
// round trip to the thread pool, which limits a sequential read to about 1.5 GB/s
const DEFAULT_HIGH_WATER_MARK = 10 * 1024 * 1024
const ENCRYPTION_DESC_FILENAME = 'encryption.json'
const ENCRYPTION_METADATA_FILENAME = 'metadata.json'
@@ -162,7 +158,7 @@ export default class RemoteHandlerAbstract {
}
}
;({
highWaterMark: this._highWaterMark = DEFAULT_HIGH_WATER_MARK,
highWaterMark: this._highWaterMark,
timeout: this._timeout = DEFAULT_TIMEOUT,
withLimit: this._withLimit = WITH_LIMIT,
withTimeout: this._withTimeout = WITH_TIMEOUT,
@@ -293,19 +289,12 @@ export default class RemoteHandlerAbstract {
* @param {string} path
* @param {ReadableStream} input
* @param {object} [options]
* @param {boolean|string} [options.checksum=true] - whether to compute and store the checksum of the stored data,
* or this checksum itself when it is already known (an unencrypted file copied from another remote): it is then
* stored as is, without reading the data
* @param {boolean} [options.checksum]
* @param {number} [options.dirMode]
* @param {(this: RemoteHandlerAbstract, path: string) => Promise<undefined>} [options.validator] Function that will be called before the data is commited to the remote, if it fails, file should not exist
*/
async outputStream(path, input, { checksum = true, dirMode, maxStreamLength, streamLength, validator } = {}) {
path = normalizePath(path)
const knownChecksum = typeof checksum === 'string' ? checksum : undefined
if (knownChecksum !== undefined) {
// the checksum is the one of the stored data, which are different once encrypted
assert.strictEqual(this.isEncrypted, false, `a known checksum can't be used on an encrypted remote for ${path}`)
}
let checksumStream
info('will output stream ', { path, streamLength, maxStreamLength, isEncrypted: this.isEncrypted })
if (this.isEncrypted) {
@@ -316,7 +305,7 @@ export default class RemoteHandlerAbstract {
info('stream is updated ', { path, streamLength, maxStreamLength, overhead })
}
input = this.#encryptor.encryptStream(input)
if (checksum === true) {
if (checksum) {
checksumStream = createChecksumStream()
pipeline(input, checksumStream, noop)
input = checksumStream
@@ -330,10 +319,7 @@ export default class RemoteHandlerAbstract {
if (checksum) {
// using _outputFile means the checksum will NOT be encrypted
// it is by design to allow checking of encrypted files without the key
await this._outputFile(checksumFile(path), knownChecksum ?? (await checksumStream.checksum), {
dirMode,
flags: 'wx',
})
await this._outputFile(checksumFile(path), await checksumStream.checksum, { dirMode, flags: 'wx' })
}
}

View File

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

View File

@@ -1,18 +1,5 @@
# ChangeLog
## **next**
- [VM/System] Fix video RAM displayed in bytes instead of MiB (PR [#10486](https://github.com/vatesfr/xen-orchestra/pull/10486))
- [Treeview] Add a search bar and virtualize the tree (PR [#10414](https://github.com/vatesfr/xen-orchestra/pull/10414))
- [New/VM] Hide guest tools ISO SR in new VM ISO selector (PR [#10430](https://github.com/vatesfr/xen-orchestra/pull/10430))
- [Host] Add possibility to enable/disable a host (PR [#10337](https://github.com/vatesfr/xen-orchestra/pull/10337))
- [Host] Add possibility to restart a host toolstack (PR [#10480](https://github.com/vatesfr/xen-orchestra/pull/10480))
- [Host] Add possibility to detach a host (PR [#10520](https://github.com/vatesfr/xen-orchestra/pull/10520))
- [Side panels] Harmonize card titles across side panels (PR [#10289](https://github.com/vatesfr/xen-orchestra/pull/10289))
- [VM/New] Fix UEFI VMs booting in BIOS mode when created with a network install or without disk (PR [#10521](https://github.com/vatesfr/xen-orchestra/pull/10521))
- [Treeview] Press Ctrl+K (Cmd+K on macOS) to focus the treeview search (PR [#10492](https://github.com/vatesfr/xen-orchestra/pull/10492))
- [Pool] Fix connection, stats and consoles when overriding the pool master with `?master=`: use HTTPS by default instead of the protocol and port of the page (PR [#9955](https://github.com/vatesfr/xen-orchestra/pull/9955))
## **0.26.0** (2026-10-01)
- [Host] Add possibility to reboot a host (PR [#10250](https://github.com/vatesfr/xen-orchestra/pull/10250))

View File

@@ -33,7 +33,7 @@
"@vueuse/core": "^14.0.0",
"@vueuse/math": "^14.0.0",
"@vueuse/shared": "^14.0.0",
"@xen-orchestra/web-core": "^0.63.1",
"@xen-orchestra/web-core": "^0.63.0",
"complex-matcher": "^1.1.1",
"d3-time-format": "^4.1.0",
"decorator-synchronized": "^0.6.0",
@@ -63,7 +63,6 @@
"vue-i18n": "^11.1.2",
"vue-router": "5.0.6",
"vue-tsc": "~2.2.8",
"vue-virtual-scroller": "^2.0.0-beta.8",
"zx": "^7.2.3"
},
"private": true,

View File

@@ -5,9 +5,8 @@
<div v-else class="layout">
<AppHeader v-if="uiStore.hasUi" />
<div class="container">
<VtsBackdrop v-if="uiStore.hasUi && showBackdrop" @click="leftSidebar.toggleExpand(false)" />
<AppNavigation v-if="uiStore.hasUi" />
<main class="main">
<main class="main" :class="{ 'no-ui': !uiStore.hasUi }">
<RouterView />
</main>
</div>
@@ -23,11 +22,9 @@ import AppNavigation from '@/components/AppNavigation.vue'
import { useUnreachableHosts } from '@/composables/unreachable-hosts.composable.ts'
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
import { useXenApiStore } from '@/stores/xen-api.store.ts'
import VtsBackdrop from '@core/components/backdrop/VtsBackdrop.vue'
import VtsOverlayList from '@core/components/overlay/VtsOverlayList.vue'
import VtsTooltipList from '@core/components/tooltip-list/VtsTooltipList.vue'
import { useChartTheme } from '@core/composables/chart-theme.composable.ts'
import { useLeftSidebarStore } from '@core/packages/sidebar'
import { useUiStore } from '@core/stores/ui.store.ts'
import { useActiveElement, useMagicKeys, whenever } from '@vueuse/core'
import { logicAnd } from '@vueuse/math'
@@ -42,10 +39,6 @@ const xenApiStore = useXenApiStore()
const { pool } = usePoolStore().subscribe()
const uiStore = useUiStore()
const leftSidebar = useLeftSidebarStore()
const showBackdrop = computed(() => leftSidebar.isExpanded && !leftSidebar.isLocked)
useChartTheme()
if (import.meta.env.DEV) {
@@ -84,16 +77,17 @@ useUnreachableHosts()
}
.container {
position: relative;
display: flex;
flex: 1;
min-height: 0;
overflow-x: hidden;
}
.main {
flex: 1;
overflow: auto;
flex: 1;
height: calc(100vh - 5.5rem);
background-color: var(--color-neutral-background-secondary);
&.no-ui {
height: 100vh;
}
}
</style>

View File

@@ -2,15 +2,11 @@
<header class="app-header">
<div class="left">
<UiButtonIcon
v-tooltip="{
content: leftSidebar.isExpanded ? t('action:sidebar-close') : t('action:sidebar-open'),
placement: 'right',
}"
ref="navigationTrigger"
:class="{ 'menu-to-right': !uiStore.isSmall }"
accent="brand"
icon="fa:bars"
size="medium"
@click="leftSidebar.toggleExpand()"
/>
<RouterLink :to="logoRoute" class="logo-container">
<img v-if="uiStore.isSmall" alt="XO Lite" src="../assets/logo.svg" />
@@ -30,12 +26,12 @@
import AccountMenu from '@/components/account-menu/AccountMenu.vue'
import PoolOverrideWarning from '@/components/PoolOverrideWarning.vue'
import XoaButton from '@/components/XoaButton.vue'
import { useNavigationStore } from '@/stores/navigation.store.ts'
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
import UiLogoText from '@core/components/ui/logo-text/UiLogoText.vue'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import { useLeftSidebarStore } from '@core/packages/sidebar'
import { useUiStore } from '@core/stores/ui.store.ts'
import { storeToRefs } from 'pinia'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import type { RouteLocationRaw } from 'vue-router'
@@ -44,7 +40,8 @@ const uiStore = useUiStore()
const { pool } = usePoolStore().getContext()
const { t } = useI18n()
const leftSidebar = useLeftSidebarStore()
const navigationStore = useNavigationStore()
const { trigger: navigationTrigger } = storeToRefs(navigationStore)
const logoRoute = computed<RouteLocationRaw>(() =>
pool.value

View File

@@ -1,18 +1,104 @@
<template>
<VtsLayoutSidebar v-if="hasStoryNav">
<StoryMenu />
</VtsLayoutSidebar>
<PoolTreeSidebar v-else />
<Transition name="slide">
<nav v-if="isOpen" ref="navElement" class="app-navigation">
<StoryMenu v-if="route.meta.hasStoryNav" />
<InfraPoolList v-else />
</nav>
</Transition>
</template>
<script lang="ts" setup>
import StoryMenu from '@/components/component-story/StoryMenu.vue'
import PoolTreeSidebar from '@/modules/treeview/components/PoolTreeSidebar.vue'
import VtsLayoutSidebar from '@core/components/layout/VtsLayoutSidebar.vue'
import { computed } from 'vue'
import InfraPoolList from '@/components/infra/InfraPoolList.vue'
import { useNavigationStore } from '@/stores/navigation.store.ts'
import { onClickOutside, tryOnMounted, useTimeoutFn, watchImmediate } from '@vueuse/core'
import { storeToRefs } from 'pinia'
import { ref, watch } from 'vue'
import { useRoute } from 'vue-router'
const route = useRoute()
const hasStoryNav = computed(() => route.meta.hasStoryNav === true)
const navigationStore = useNavigationStore()
const { isOpen } = storeToRefs(navigationStore)
const navElement = ref()
watch(
() => navigationStore.trigger?.value,
triggerElement => {
if (triggerElement && navElement.value) {
onClickOutside(
navElement,
() => {
if (isOpen.value) {
isOpen.value = false
}
},
{
ignore: [triggerElement],
}
)
}
},
{ immediate: true }
)
const getCurrentNodeId = () => {
const name = route.name as string | undefined
const params = route.params as Record<string, any>
if (name?.startsWith('/pool/[uuid]')) {
return `pool:${params.uuid}`
}
if (name?.startsWith('/host/[uuid]')) {
return `host:${params.uuid}`
}
if (name?.startsWith('/vm/[uuid]')) {
return `vm:${params.uuid}`
}
return undefined
}
const scrollToCurrent = async () => {
const id = getCurrentNodeId()
if (!id) {
return
}
const container = navElement.value as HTMLElement | undefined
const target = container?.querySelector<HTMLElement>(`[data-node-id="${CSS.escape(id)}"]`)
const hasChildren = !id.startsWith('vm:')
if (target) {
useTimeoutFn(async () => {
if (hasChildren) {
target.style.scrollMarginTop = '0.8rem'
useTimeoutFn(async () => {
target.style.scrollMarginTop = ''
}, 1000)
}
target.scrollIntoView({ block: hasChildren ? 'start' : 'center', behavior: 'smooth' })
}, 200)
} else {
useTimeoutFn(async () => {
await scrollToCurrent()
}, 200)
}
}
tryOnMounted(scrollToCurrent)
watchImmediate(route, scrollToCurrent)
</script>
<style lang="postcss" scoped>
.app-navigation {
overflow: auto;
width: 37rem;
max-width: 37rem;
height: calc(100vh - 5.5rem);
padding: 0.5rem;
border-right: 1px solid var(--color-neutral-border);
background-color: var(--color-neutral-background-primary);
}
</style>

View File

@@ -307,7 +307,6 @@ const applyPreset = (preset: { props?: Record<string, any>; settings?: Record<st
.tab-content {
flex: 1;
min-width: 0;
height: auto;
}
}

View File

@@ -4,7 +4,7 @@
<VtsObjectIcon
size="medium"
type="host"
:state="hostState"
:state="powerState"
:busy="isChangingState"
:busy-tooltip="currentOperation"
/>
@@ -20,6 +20,7 @@
</template>
<HostPowerStateActions :host />
</MenuList>
<MenuList placement="bottom-end">
<template #trigger="{ open }">
<UiButtonIcon
@@ -44,6 +45,7 @@ import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import HostPowerStateActions from '@/modules/host/components/actions/HostPowerStateActions.vue'
import HostMoreActions from '@/modules/host/components/HostMoreActions.vue'
import { useHostUtils } from '@/modules/host/composables/host-utils.composable.ts'
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
import VtsIcon from '@core/components/icon/VtsIcon.vue'
import MenuList from '@core/components/menu/MenuList.vue'
@@ -61,8 +63,12 @@ const { host } = defineProps<{
const { t } = useI18n()
const { isHostRunning } = useHostMetricsStore().subscribe()
const powerState = computed(() => (isHostRunning(host) ? 'running' : 'halted'))
const { isMasterHost } = usePoolStore().subscribe()
const isMaster = computed(() => isMasterHost(host.$ref))
const { hostState, isChangingState, currentOperation } = useHostUtils(() => host)
const { isChangingState, currentOperation } = useHostUtils(() => host)
</script>

View File

@@ -3,7 +3,7 @@
<template v-if="pif" #default>
<!-- PIF -->
<UiPanelCard>
<UiPanelCardTitle :id="pif.uuid" size="medium" :label="isBond ? t('bond') : t('pif')" />
<VtsCardObjectTitle :id="pif.uuid" :label="isBond ? t('bond') : t('pif')" />
<div class="content">
<!-- NETWORK -->
<VtsCardRowKeyValue>
@@ -78,7 +78,7 @@
</UiPanelCard>
<!-- NETWORK INFORMATION -->
<UiPanelCard>
<UiPanelCardTitle size="medium" :label="t('network-information')" />
<UiCardTitle>{{ t('network-information') }}</UiCardTitle>
<div class="content">
<!-- IP ADDRESSES -->
<div v-if="ipAddresses.length">
@@ -183,7 +183,7 @@
</UiPanelCard>
<!-- PROPERTIES -->
<UiPanelCard>
<UiPanelCardTitle size="medium" :label="t('properties')" />
<UiCardTitle>{{ t('properties') }}</UiCardTitle>
<div class="content">
<!-- MTU -->
<VtsCardRowKeyValue>
@@ -230,14 +230,15 @@ import { useNetworkStore } from '@/stores/xen-api/network.store.ts'
import { usePifMetricsStore } from '@/stores/xen-api/pif-metrics.store.ts'
import { usePifStore } from '@/stores/xen-api/pif.store.ts'
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
import VtsCardObjectTitle from '@core/components/card-object-title/VtsCardObjectTitle.vue'
import VtsCopyAllMenuItem from '@core/components/copy-all-menu-item/VtsCopyAllMenuItem.vue'
import VtsCopyButton from '@core/components/copy-button/VtsCopyButton.vue'
import VtsIcon from '@core/components/icon/VtsIcon.vue'
import VtsSidePanel from '@core/components/panel/VtsSidePanel.vue'
import VtsStatus from '@core/components/status/VtsStatus.vue'
import VtsTag from '@core/components/tag/VtsTag.vue'
import UiCardTitle from '@core/components/ui/card-title/UiCardTitle.vue'
import UiPanelCard from '@core/components/ui/panel-card/UiPanelCard.vue'
import UiPanelCardTitle from '@core/components/ui/panel-card-title/UiPanelCardTitle.vue'
import UiTagsList from '@core/components/ui/tag/UiTagsList.vue'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import humanFormat from 'human-format'

View File

@@ -1,20 +1,24 @@
<template>
<VtsTreeItem :expanded="!branch.isCollapsed" :node-id="branch.dataId" :has-children="branch.hasChildren">
<VtsTreeItem
v-if="host !== undefined"
:expanded="isExpanded"
has-children
class="infra-host-item"
:node-id="`host:${host.uuid}`"
>
<UiTreeItemLabel
:route="{ name: '/host/[uuid]', params: { uuid: branch.data.uuid } }"
:route="{ name: '/host/[uuid]', params: { uuid: host.uuid } }"
icon="object:host"
@toggle="branch.toggleCollapse()"
@toggle="toggle()"
>
{{ branch.data.name_label || '(Host)' }}
<template #icon>
<VtsObjectIcon v-tooltip="hostState" type="host" size="medium" :state="hostState" />
</template>
{{ host.name_label || '(Host)' }}
<template #addons>
<UiLoader v-if="isChangingState" v-tooltip="currentOperation" />
<VtsIcon v-if="isMaster" v-tooltip="t('master')" name="status:primary-circle" size="medium" />
<VtsIcon v-if="isPoolMaster" v-tooltip="t('master')" name="status:primary-circle" size="medium" />
<UiCounter
v-tooltip="t('running-vm', { count: runningVmsCount })"
:value="runningVmsCount"
v-if="isReady"
v-tooltip="t('running-vm', { count: vmCount })"
:value="vmCount"
accent="brand"
size="small"
variant="secondary"
@@ -29,43 +33,56 @@
@click="open($event)"
/>
</template>
<HostMoreActions :host="branch.data" show-change-state-button />
<HostMoreActions :host show-change-state-button />
</MenuList>
</template>
</UiTreeItemLabel>
<template #sublist>
<VtsTreeList>
<InfraVmItems :host-opaque-ref="hostOpaqueRef" />
</VtsTreeList>
</template>
</VtsTreeItem>
</template>
<script lang="ts" setup>
import InfraVmItems from '@/components/infra/InfraVmItems.vue'
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import HostMoreActions from '@/modules/host/components/HostMoreActions.vue'
import { useHostUtils } from '@/modules/host/composables/host-utils.composable.ts'
import type { HostBranch } from '@/modules/treeview/types/tree.type.ts'
import { useHostStore } from '@/stores/xen-api/host.store.ts'
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
import VtsIcon from '@core/components/icon/VtsIcon.vue'
import MenuList from '@core/components/menu/MenuList.vue'
import VtsObjectIcon from '@core/components/object-icon/VtsObjectIcon.vue'
import VtsTreeItem from '@core/components/tree/VtsTreeItem.vue'
import VtsTreeList from '@core/components/tree/VtsTreeList.vue'
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
import UiCounter from '@core/components/ui/counter/UiCounter.vue'
import UiLoader from '@core/components/ui/loader/UiLoader.vue'
import UiTreeItemLabel from '@core/components/ui/tree-item-label/UiTreeItemLabel.vue'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import { useToggle } from '@vueuse/shared'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { branch } = defineProps<{
branch: HostBranch
const { hostOpaqueRef } = defineProps<{
hostOpaqueRef: XenApiHost['$ref']
}>()
const { t } = useI18n()
const { isMasterHost } = usePoolStore().subscribe()
const { runningVmsCountByHostRef } = useVmStore().subscribe()
const { getByOpaqueRef } = useHostStore().subscribe()
const host = computed(() => getByOpaqueRef(hostOpaqueRef))
const { hostState, isChangingState, currentOperation } = useHostUtils(() => branch.data)
const { pool } = usePoolStore().subscribe()
const isPoolMaster = computed(() => pool.value?.master === hostOpaqueRef)
const isMaster = computed(() => isMasterHost(branch.data.$ref))
const { isChangingState, currentOperation } = useHostUtils(host)
const runningVmsCount = computed(() => runningVmsCountByHostRef.value.get(branch.data.$ref) ?? 0)
const { runningVms, isReady } = useVmStore().subscribe()
const vmCount = computed(() => runningVms.value.filter(vm => vm.resident_on === hostOpaqueRef)?.length ?? 0)
const [isExpanded, toggle] = useToggle(true)
</script>

View File

@@ -0,0 +1,19 @@
<template>
<VtsTreeItemError v-if="hasError">
{{ t('error-no-data') }}
</VtsTreeItemError>
<VtsTreeLoadingItem v-else-if="!isReady" icon="object:host">{{ t('loading-hosts') }}</VtsTreeLoadingItem>
<InfraHostItem v-for="host in hosts" :key="host.$ref" :host-opaque-ref="host.$ref" />
</template>
<script lang="ts" setup>
import InfraHostItem from '@/components/infra/InfraHostItem.vue'
import { useHostStore } from '@/stores/xen-api/host.store.ts'
import VtsTreeItemError from '@core/components/tree/VtsTreeItemError.vue'
import VtsTreeLoadingItem from '@core/components/tree/VtsTreeLoadingItem.vue'
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
const { records: hosts, isReady, hasError } = useHostStore().subscribe()
</script>

View File

@@ -0,0 +1,60 @@
<template>
<VtsTreeList class="infra-pool-list">
<VtsTreeItem :expanded="isExpanded" has-children :node-id="`pool:${pool?.uuid}`">
<VtsTreeItemError v-if="hasError">
{{ t('error-no-data') }}
</VtsTreeItemError>
<VtsTreeLoadingItem v-else-if="!isReady || pool === undefined" icon="object:pool" />
<UiTreeItemLabel
v-else
:route="{ name: '/pool/[uuid]', params: { uuid: pool.uuid } }"
icon="object:pool"
@toggle="toggle()"
>
{{ pool.name_label || '(Pool)' }}
<template #addons>
<MenuList placement="bottom-start">
<template #trigger="{ open, isOpen }">
<UiButtonIcon
accent="brand"
icon="action:more-actions"
size="small"
:selected="isOpen"
@click="open($event)"
/>
</template>
<PoolTreeActions :pool />
</MenuList>
</template>
</UiTreeItemLabel>
<template #sublist>
<VtsTreeList>
<InfraHostItems />
<InfraVmItems />
</VtsTreeList>
</template>
</VtsTreeItem>
</VtsTreeList>
</template>
<script lang="ts" setup>
import InfraHostItems from '@/components/infra/InfraHostItems.vue'
import InfraVmItems from '@/components/infra/InfraVmItems.vue'
import PoolTreeActions from '@/modules/pool/components/actions/PoolTreeActions.vue'
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
import MenuList from '@core/components/menu/MenuList.vue'
import VtsTreeItem from '@core/components/tree/VtsTreeItem.vue'
import VtsTreeItemError from '@core/components/tree/VtsTreeItemError.vue'
import VtsTreeList from '@core/components/tree/VtsTreeList.vue'
import VtsTreeLoadingItem from '@core/components/tree/VtsTreeLoadingItem.vue'
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
import UiTreeItemLabel from '@core/components/ui/tree-item-label/UiTreeItemLabel.vue'
import { useToggle } from '@vueuse/shared'
import { useI18n } from 'vue-i18n'
const { t } = useI18n()
const { isReady, hasError, pool } = usePoolStore().subscribe()
const [isExpanded, toggle] = useToggle(true)
</script>

View File

@@ -1,24 +1,26 @@
<template>
<VtsTreeItem expanded :node-id="leaf.dataId">
<UiTreeItemLabel :route="{ name: '/vm/[uuid]', params: { uuid: leaf.data.uuid } }" no-indent>
{{ leaf.data.name_label || '(VM)' }}
<VtsTreeItem v-if="vm !== undefined" ref="rootElement" expanded class="infra-vm-item" :node-id="`vm:${vm.uuid}`">
<UiTreeItemLabel v-if="isVisible" :route="{ name: '/vm/[uuid]', params: { uuid: vm.uuid } }" no-indent>
{{ vm.name_label || '(VM)' }}
<template #icon>
<VtsObjectIcon size="medium" :state="powerState" type="vm" />
<VtsObjectIcon size="medium" :state="vmPowerState!" type="vm" />
</template>
<template #addons>
<UiLoader v-if="isChangingState" v-tooltip="{ placement: 'top', content: currentOperation }" />
<MenuList placement="bottom-start">
<template #trigger="{ open, isOpen }">
<template #trigger="{ open }">
<UiButtonIcon
v-tooltip="{ placement: 'top', content: t('quick-actions') }"
v-tooltip="{
placement: 'top',
content: t('quick-actions'),
}"
icon="action:more-actions"
accent="brand"
size="small"
:selected="isOpen"
@click="open($event)"
/>
</template>
<VmTreeActions :vm-opaque-ref="leaf.data.$ref" />
<VmTreeActions :vm-opaque-ref />
</MenuList>
</template>
</UiTreeItemLabel>
@@ -27,9 +29,10 @@
<script lang="ts" setup>
import type { VM_POWER_STATE } from '@/libs/xen-api/xen-api.enums.ts'
import type { VmLeaf } from '@/modules/treeview/types/tree.type.ts'
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import VmTreeActions from '@/modules/vm/components/actions/VmTreeActions.vue'
import { useVmOperation } from '@/modules/vm/composables/vm-operation.composable.ts'
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
import MenuList from '@core/components/menu/MenuList.vue'
import VtsObjectIcon from '@core/components/object-icon/VtsObjectIcon.vue'
import VtsTreeItem from '@core/components/tree/VtsTreeItem.vue'
@@ -37,16 +40,29 @@ import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
import UiLoader from '@core/components/ui/loader/UiLoader.vue'
import UiTreeItemLabel from '@core/components/ui/tree-item-label/UiTreeItemLabel.vue'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import { computed } from 'vue'
import { useIntersectionObserver } from '@vueuse/core'
import { computed, ref } from 'vue'
import { useI18n } from 'vue-i18n'
const { leaf } = defineProps<{
leaf: VmLeaf
const { vmOpaqueRef } = defineProps<{
vmOpaqueRef: XenApiVm['$ref']
}>()
const { t } = useI18n()
const { isChangingState, currentOperation } = useVmOperation(() => leaf.data)
const { getByOpaqueRef } = useVmStore().subscribe()
const vm = computed(() => getByOpaqueRef(vmOpaqueRef))
const rootElement = ref()
const isVisible = ref(false)
const powerState = computed(() => leaf.data.power_state.toLowerCase() as Lowercase<VM_POWER_STATE>)
const { stop } = useIntersectionObserver(rootElement, ([entry]) => {
if (entry.isIntersecting) {
isVisible.value = true
stop()
}
})
const vmPowerState = computed(() => vm.value?.power_state.toLowerCase() as Lowercase<VM_POWER_STATE> | undefined)
const { isChangingState, currentOperation } = useVmOperation(vm)
</script>

View File

@@ -0,0 +1,27 @@
<template>
<VtsTreeItemError v-if="hasError">{{ t('error-no-data') }}</VtsTreeItemError>
<template v-else-if="!isReady">
<VtsTreeLoadingItem v-for="i in 3" :key="i" icon="object:vm" />
</template>
<InfraVmItem v-for="vm in vms" :key="vm.$ref" :vm-opaque-ref="vm.$ref" />
</template>
<script lang="ts" setup>
import InfraVmItem from '@/components/infra/InfraVmItem.vue'
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
import VtsTreeItemError from '@core/components/tree/VtsTreeItemError.vue'
import VtsTreeLoadingItem from '@core/components/tree/VtsTreeLoadingItem.vue'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const props = defineProps<{
hostOpaqueRef?: XenApiHost['$ref']
}>()
const { t } = useI18n()
const { isReady, recordsByHostRef, hasError } = useVmStore().subscribe()
const vms = computed(() => recordsByHostRef.value.get(props.hostOpaqueRef ?? ('OpaqueRef:NULL' as XenApiHost['$ref'])))
</script>

View File

@@ -1,5 +1,5 @@
<template>
<UiCard>
<UiCard class="pool-dashboard-hosts-patches">
<UiCardTitle>
{{ t('patches') }}
<template v-if="areAllLoaded && count > 0" #info>
@@ -30,6 +30,10 @@ const { count, patches, areAllLoaded, areSomeLoaded } = useHostPatches(hosts)
</script>
<style lang="postcss" scoped>
.pool-dashboard-hosts-patches {
min-width: 43.8rem;
}
.patches-title {
color: var(--color-danger-txt-base);
}

View File

@@ -1,5 +1,5 @@
<template>
<UiCard :has-error>
<UiCard :has-error class="pool-dashboard-status">
<UiCardTitle>{{ t('status') }}</UiCardTitle>
<VtsStateHero v-if="!isReady" format="card" type="busy" size="medium" />
<VtsStateHero v-else-if="hasError" format="card" type="error" size="medium">{{ t('error-no-data') }}</VtsStateHero>
@@ -56,3 +56,9 @@ const totalVmsCount = computed(() => vms.value.length)
const activeVmsCount = computed(() => vms.value.filter(vm => vm.power_state === 'Running').length)
</script>
<style lang="postcss" scoped>
.pool-dashboard-status {
min-width: 32rem;
}
</style>

View File

@@ -20,7 +20,7 @@
</template>
<template v-if="network" #default>
<UiPanelCard>
<UiPanelCardTitle :id="network.uuid" size="medium" :label="network.name_label" />
<VtsCardObjectTitle :id="network.uuid" :label="network.name_label" />
<div class="content">
<!-- DESCRIPTION -->
<VtsCardRowKeyValue truncate align-top>
@@ -66,7 +66,10 @@
</div>
</UiPanelCard>
<UiPanelCard v-if="pifsCount && pifsCount > 0">
<UiPanelCardTitle size="medium" :label="t('pifs')" :counter="pifsCount" />
<div class="typo-body-bold">
{{ t('pifs') }}
<UiCounter :value="pifsCount" variant="primary" size="small" accent="neutral" />
</div>
<table class="simple-table">
<thead>
<tr>
@@ -97,14 +100,15 @@ import type { XenApiNetwork } from '@/libs/xen-api/xen-api.types.ts'
import { useNetworkDelete } from '@/modules/network/composables/use-network-delete.composable.ts'
import { usePifStore } from '@/stores/xen-api/pif.store.ts'
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
import VtsCardObjectTitle from '@core/components/card-object-title/VtsCardObjectTitle.vue'
import VtsCopyButton from '@core/components/copy-button/VtsCopyButton.vue'
import VtsDeleteButton from '@core/components/delete-button/VtsDeleteButton.vue'
import MenuItem from '@core/components/menu/MenuItem.vue'
import MenuList from '@core/components/menu/MenuList.vue'
import VtsSidePanel from '@core/components/panel/VtsSidePanel.vue'
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
import UiCounter from '@core/components/ui/counter/UiCounter.vue'
import UiPanelCard from '@core/components/ui/panel-card/UiPanelCard.vue'
import UiPanelCardTitle from '@core/components/ui/panel-card-title/UiPanelCardTitle.vue'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import { useClipboard } from '@vueuse/core'
import { computed } from 'vue'

View File

@@ -0,0 +1,29 @@
<template>
<div :class="{ vertical }" class="ui-card-group">
<slot />
</div>
</template>
<script lang="ts" setup>
import { IK_CARD_GROUP_VERTICAL } from '@/types/injection-keys.ts'
import { inject, provide } from 'vue'
const vertical = inject(IK_CARD_GROUP_VERTICAL, false)
provide(IK_CARD_GROUP_VERTICAL, !vertical)
</script>
<style lang="postcss" scoped>
.ui-card-group {
display: flex;
gap: 1rem;
flex-direction: column;
flex: 1;
}
@media (min-width: 1500px) {
.ui-card-group:not(.vertical) {
flex-direction: row;
}
}
</style>

View File

@@ -143,7 +143,7 @@ const state = useTableState({
})
const { HeadCells, BodyCells } = useVmColumns({
exclude: ['actions', 'checkbox'],
exclude: ['actions'],
body: (vm: XenApiVm) => {
const guestMetrics = computed(() => getGuestMetrics(vm.guest_metrics))
const vmMetrics = computed(() => getVmMetrics(vm.metrics))

View File

@@ -10,8 +10,8 @@
</template>
</VtsTabularKeyValueRow>
<VtsTabularKeyValueRow :label="t('video-ram')">
<template v-if="vm.platform.videoram" #value>
{{ `${vm.platform.videoram} ${t('bytes:mi')}` }}
<template v-if="videoRamValue?.value" #value>
{{ `${videoRamValue.value} ${videoRamValue.prefix || t('bytes:mi')}` }}
</template>
</VtsTabularKeyValueRow>
</VtsTabularKeyValueList>
@@ -25,9 +25,13 @@ import VtsTabularKeyValueList from '@core/components/tabular-key-value-list/VtsT
import VtsTabularKeyValueRow from '@core/components/tabular-key-value-row/VtsTabularKeyValueRow.vue'
import UiCard from '@core/components/ui/card/UiCard.vue'
import UiTitle from '@core/components/ui/title/UiTitle.vue'
import { formatSizeRaw } from '@core/utils/size.util.ts'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
defineProps<{ vm: XenApiVm }>()
const { vm } = defineProps<{ vm: XenApiVm }>()
const { t } = useI18n()
const videoRamValue = computed(() => (vm.platform.videoram ? formatSizeRaw(Number(vm.platform.videoram), 0) : null))
</script>

View File

@@ -1,6 +1,5 @@
import { ipToHostname } from '@/libs/utils.ts'
import { useHostStore } from '@/stores/xen-api/host.store.ts'
import { useXenApiStore } from '@/stores/xen-api.store.ts'
import { useOverlay } from '@core/packages/overlay/use-overlay.ts'
import { reactiveComputed, whenever } from '@vueuse/core'
import { difference } from 'lodash-es'
@@ -9,12 +8,11 @@ import { ref, watch } from 'vue'
export const useUnreachableHosts = () => {
const { records: hosts } = useHostStore().subscribe()
const unreachableHostsUrls = ref<Set<string>>(new Set())
const { protocol } = new URL(useXenApiStore().getXapi().hostUrl)
watch(hosts, (nextHosts, previousHosts) => {
difference(nextHosts, previousHosts).forEach(host => {
const url = new URL('http://localhost')
url.protocol = protocol
url.protocol = window.location.protocol
url.hostname = ipToHostname(host.address)
fetch(url, { mode: 'no-cors' }).catch(() => unreachableHostsUrls.value.add(url.toString()))
})

View File

@@ -18,8 +18,6 @@ export function createHostOperations(xenApi: XenApi) {
const destroy = (hostRef: HostRef) => xenApi.call('host.destroy', [hostRef])
const restartAgent = (hostRef: HostRef) => xenApi.call('host.restart_agent', [hostRef])
const clearHost = async (hostRef: HostRef, force: boolean) => {
await disable(hostRef)
@@ -36,11 +34,8 @@ export function createHostOperations(xenApi: XenApi) {
}
return {
disable,
enable,
powerOn,
destroy,
restartAgent,
cleanReboot: async (hostRef: HostRef, forceReboot: boolean) => {
await clearHost(hostRef, forceReboot)

View File

@@ -1,12 +0,0 @@
import type XenApi from '@/libs/xen-api/xen-api.ts'
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
export function createPoolOperations(xenApi: XenApi) {
type HostRef = XenApiHost['$ref']
const eject = (hostRef: HostRef) => xenApi.call('pool.eject', [hostRef])
return {
eject,
}
}

View File

@@ -91,7 +91,6 @@ export enum ON_NORMAL_EXIT {
}
export enum HOST_OPERATION {
ENABLE = 'enable',
EVACUATE = 'evacuate',
POWER_ON = 'power_on',
REBOOT = 'reboot',

View File

@@ -3,7 +3,6 @@ import { createHostOperations } from '@/libs/xen-api/operations/host-operations.
import { createNetworkOperations } from '@/libs/xen-api/operations/network-operations.ts'
import { createPbdOperations } from '@/libs/xen-api/operations/pbd-operations.ts'
import { createPifOperations } from '@/libs/xen-api/operations/pif-operations.ts'
import { createPoolOperations } from '@/libs/xen-api/operations/pool-operations.ts'
import { createSrOperations } from '@/libs/xen-api/operations/sr-operations.ts'
import { createVbdOperations } from '@/libs/xen-api/operations/vbd-operations.ts'
import { createVdiOperations } from '@/libs/xen-api/operations/vdi-operations.ts'
@@ -96,7 +95,7 @@ export default class XenApi {
{ abortSignal, host, query }: { abortSignal?: AbortSignal; host: XenApiHost; query: any }
) {
const url = new URL('http://localhost')
url.protocol = new URL(this._hostUrl).protocol
url.protocol = window.location.protocol
url.hostname = ipToHostname(host.address)
url.pathname = pathname
url.search = new URLSearchParams({
@@ -302,8 +301,4 @@ export default class XenApi {
get host() {
return createHostOperations(this)
}
get pool() {
return createPoolOperations(this)
}
}

View File

@@ -44,7 +44,7 @@ import type {
VUSB_OPERATION,
} from '@/libs/xen-api/xen-api.enums.ts'
import type { XEN_API_OBJECT_TYPES } from '@/libs/xen-api/xen-api.utils.ts'
import type { OPAQUE_REF_NULL, POOL_ALLOWED_OPERATIONS } from '@vates/types'
import type { OPAQUE_REF_NULL } from '@vates/types'
type TypeMapping = typeof XEN_API_OBJECT_TYPES
export type ObjectType = keyof TypeMapping
@@ -112,7 +112,6 @@ export interface XenApiPool extends XenApiRecord<'pool'> {
cpu_count: string
}
master: XenApiHost['$ref']
current_operations: Record<string, POOL_ALLOWED_OPERATIONS>
name_label: string
other_config: Record<string, string>
// TODO add | OPAQUE_REF_NULL, warning with newVm
@@ -168,7 +167,6 @@ export interface XenApiHost extends XenApiRecord<'host'> {
export interface XenApiSr extends XenApiRecord<'sr'> {
content_type: string
is_tools_sr: boolean
name_description: string
name_label: string
other_config: Record<string, string>

View File

@@ -9,7 +9,6 @@ import { createApp } from 'vue'
import { createRouter, createWebHashHistory } from 'vue-router'
import { routes } from 'vue-router/auto-routes'
import '@xen-orchestra/web-core/assets/css/base.pcss'
import 'vue-virtual-scroller/dist/vue-virtual-scroller.css'
const router = createRouter({
history: createWebHashHistory(),

View File

@@ -5,10 +5,6 @@
<HostPowerStateActions :host />
</template>
</MenuItem>
<HostRestartToolstackButton :host />
<HostDisableButton v-if="displayDisableButton" :host />
<HostEnableButton v-else :host />
<HostDetachButton :host />
<HostForgetButton :host />
<VtsDivider type="stretch" />
<HostDownloadButton :host-opaque-ref="host.$ref" />
@@ -16,30 +12,17 @@
<script setup lang="ts">
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import HostDetachButton from '@/modules/host/components/actions/detach/HostDetachButton.vue'
import HostDisableButton from '@/modules/host/components/actions/disable/HostDisableButton.vue'
import HostDownloadButton from '@/modules/host/components/actions/download/HostDownloadButton.vue'
import HostEnableButton from '@/modules/host/components/actions/enable/HostEnableButton.vue'
import HostForgetButton from '@/modules/host/components/actions/forget/HostForgetButton.vue'
import HostPowerStateActions from '@/modules/host/components/actions/HostPowerStateActions.vue'
import HostRestartToolstackButton from '@/modules/host/components/actions/restart-toolstack/HostRestartToolstackButton.vue'
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
import VtsDivider from '@core/components/divider/VtsDivider.vue'
import MenuItem from '@core/components/menu/MenuItem.vue'
import { HOST_POWER_STATE } from '@vates/types'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { host } = defineProps<{
defineProps<{
host: XenApiHost
showChangeStateButton?: boolean
}>()
const { t } = useI18n()
const { getHostPowerState } = useHostMetricsStore().subscribe()
const isHostHalted = computed(() => getHostPowerState(host) === HOST_POWER_STATE.HALTED)
const displayDisableButton = computed(() => host.enabled || isHostHalted.value)
</script>

View File

@@ -1,78 +0,0 @@
<template>
<MenuItem
v-tooltip="!canDetachHost && detachHostErrorMessage"
:busy="isDetachingHost"
accent="warning"
:disabled="!canDetachHost"
icon="action:detach"
@click="detachHost()"
>
{{ t('action:detach') }}
</MenuItem>
</template>
<script lang="ts" setup>
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import { useHostDetachJob } from '@/modules/host/jobs/host-detach.job.ts'
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
import MenuItem from '@core/components/menu/MenuItem.vue'
import { useActionModal } from '@core/composables/modals/use-action-modal.ts'
import { useRedirectAfterDelete } from '@core/composables/redirect-after-delete.composable.ts'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import { useI18n } from 'vue-i18n'
import { useRoute } from 'vue-router'
const { host } = defineProps<{
host: XenApiHost
}>()
const { t } = useI18n()
const route = useRoute<'/host/[uuid]'>()
const { pool } = usePoolStore().subscribe()
const { open: openActionModal } = useActionModal()
const {
run,
canRun: canDetachHost,
isRunning: isDetachingHost,
errorMessage: detachHostErrorMessage,
} = useHostDetachJob(() => host)
const { redirect: redirectAfterDetachHost } = useRedirectAfterDelete({
isOnObjectPage: () => route.params.uuid === host.uuid,
redirectTo: () => {
if (pool.value === undefined) {
return { name: '/' }
}
return { name: '/pool/[uuid]/hosts', params: { uuid: pool.value.uuid } }
},
})
function detachHost() {
return openActionModal({
props: {
accent: 'warning',
action: 'detach',
object: 'host',
hostName: host.name_label,
icon: 'status:warning-picto',
},
events: {
onConfirm: async () => {
try {
await run()
} catch (error) {
console.error('Error when detaching host:', error)
return
}
await redirectAfterDetachHost()
},
},
})
}
</script>

View File

@@ -1,53 +0,0 @@
<template>
<MenuItem
v-tooltip="!canDisableHost && disableHostErrorMessage"
accent="neutral"
:busy="isDisablingHost"
:disabled="!canDisableHost"
icon="action:disable"
@click="disableHost()"
>
{{ t('action:disable') }}
</MenuItem>
</template>
<script lang="ts" setup>
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import { useHostDisableJob } from '@/modules/host/jobs/host-disable.job.ts'
import MenuItem from '@core/components/menu/MenuItem.vue'
import { useActionModal } from '@core/composables/modals/use-action-modal.ts'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import { useI18n } from 'vue-i18n'
const { host } = defineProps<{
host: XenApiHost
}>()
const { t } = useI18n()
const { open: openActionModal } = useActionModal()
const {
run,
canRun: canDisableHost,
isRunning: isDisablingHost,
errorMessage: disableHostErrorMessage,
} = useHostDisableJob(() => host)
function disableHost() {
return openActionModal({
props: {
accent: 'info',
action: 'disable',
object: 'host',
hostName: host.name_label,
icon: 'status:info-picto',
},
events: {
onConfirm: async () => {
void run()
},
},
})
}
</script>

View File

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

View File

@@ -14,13 +14,10 @@
<script lang="ts" setup>
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import { useHostForgetJob } from '@/modules/host/jobs/host-forget.job.ts'
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
import MenuItem from '@core/components/menu/MenuItem.vue'
import { useActionModal } from '@core/composables/modals/use-action-modal.ts'
import { useRedirectAfterDelete } from '@core/composables/redirect-after-delete.composable.ts'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import { useI18n } from 'vue-i18n'
import { useRoute } from 'vue-router'
const { host } = defineProps<{
host: XenApiHost
@@ -28,10 +25,6 @@ const { host } = defineProps<{
const { t } = useI18n()
const route = useRoute<'/host/[uuid]'>()
const { pool } = usePoolStore().subscribe()
const { open: openActionModal } = useActionModal()
const {
@@ -41,17 +34,6 @@ const {
errorMessage: forgetHostErrorMessage,
} = useHostForgetJob(() => host)
const { redirect: redirectAfterForgetHost } = useRedirectAfterDelete({
isOnObjectPage: () => route.params.uuid === host.uuid,
redirectTo: () => {
if (pool.value === undefined) {
return { name: '/' }
}
return { name: '/pool/[uuid]/hosts', params: { uuid: pool.value.uuid } }
},
})
function forgetHost() {
return openActionModal({
props: {
@@ -63,14 +45,7 @@ function forgetHost() {
},
events: {
onConfirm: async () => {
try {
await run()
} catch (error) {
console.error('Error when forgetting host:', error)
return
}
await redirectAfterForgetHost()
void run()
},
},
})

View File

@@ -1,53 +0,0 @@
<template>
<MenuItem
v-tooltip="!canRestartToolstack && restartToolstackErrorMessage"
accent="neutral"
:busy="isRestartingToolstack"
:disabled="!canRestartToolstack"
icon="action:reboot"
@click="restartToolstack()"
>
{{ t('action:restart-toolstack') }}
</MenuItem>
</template>
<script lang="ts" setup>
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import { useHostRestartToolstackJob } from '@/modules/host/jobs/host-restart-toolstack.job.ts'
import MenuItem from '@core/components/menu/MenuItem.vue'
import { useActionModal } from '@core/composables/modals/use-action-modal.ts'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import { useI18n } from 'vue-i18n'
const { host } = defineProps<{
host: XenApiHost
}>()
const { t } = useI18n()
const { open: openActionModal } = useActionModal()
const {
run,
canRun: canRestartToolstack,
isRunning: isRestartingToolstack,
errorMessage: restartToolstackErrorMessage,
} = useHostRestartToolstackJob(() => host)
function restartToolstack() {
return openActionModal({
props: {
accent: 'info',
action: 'restart-toolstack',
object: 'host',
hostName: host.name_label,
icon: 'status:info-picto',
},
events: {
onConfirm: async () => {
void run()
},
},
})
}
</script>

View File

@@ -1,6 +1,6 @@
import { HOST_OPERATION } from '@/libs/xen-api/xen-api.enums.ts'
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import { getHostPendingStateOperation, getHostState, type HostState } from '@/modules/host/utils/host.util.ts'
import { getHostPendingStateOperation } from '@/modules/host/utils/host.util.ts'
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
import { useMapper } from '@core/packages/mapper'
import { toComputed } from '@core/utils/to-computed.util.ts'
@@ -12,7 +12,7 @@ export function useHostUtils(rawHost: MaybeRefOrGetter<XenApiHost | undefined>)
const host = toComputed(rawHost)
const { isHostRunning, getHostPowerState } = useHostMetricsStore().subscribe()
const { isHostRunning } = useHostMetricsStore().subscribe()
const pendingStateOperation = computed(() => {
if (host.value === undefined) {
@@ -22,20 +22,11 @@ export function useHostUtils(rawHost: MaybeRefOrGetter<XenApiHost | undefined>)
return getHostPendingStateOperation(host.value, isHostRunning(host.value))
})
const hostState = computed<HostState>(() => {
if (host.value === undefined) {
return 'unknown'
}
return getHostState(host.value, getHostPowerState(host.value))
})
const isChangingState = computed(() => pendingStateOperation.value !== undefined)
const currentOperation = useMapper<string, string>(
() => pendingStateOperation.value,
{
[HOST_OPERATION.ENABLE]: t('operation:enable'),
[HOST_OPERATION.EVACUATE]: t('operation:evacuate'),
[HOST_OPERATION.POWER_ON]: t('operation:start'),
[HOST_OPERATION.REBOOT]: t('operation:clean-reboot'),
@@ -46,7 +37,6 @@ export function useHostUtils(rawHost: MaybeRefOrGetter<XenApiHost | undefined>)
)
return {
hostState,
isChangingState,
currentOperation,
}

View File

@@ -1,37 +0,0 @@
import { hostArg } from '@/modules/host/jobs/host-args.ts'
import { isPoolOperationPending } from '@/modules/pool/utils/pool.util.ts'
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
import { useXenApiStore } from '@/stores/xen-api.store.ts'
import { defineJob, JobError, JobRunningError } from '@core/packages/job'
import { POOL_ALLOWED_OPERATIONS } from '@vates/types'
import { useI18n } from 'vue-i18n'
export const useHostDetachJob = defineJob('host.detach', [hostArg], () => {
const xapi = useXenApiStore().getXapi()
const { t } = useI18n()
const { pool, isMasterHost } = usePoolStore().subscribe()
const { isHostRunning } = useHostMetricsStore().subscribe()
return {
run: host => xapi.pool.eject(host.$ref),
validate: (isRunning, host) => {
if (host === undefined) {
throw new JobError(t('job:host-detach:missing-host'))
}
if (isRunning || (pool.value && isPoolOperationPending(pool.value, POOL_ALLOWED_OPERATIONS.EJECT))) {
throw new JobRunningError(t('job:host-detach:in-progress'))
}
if (isMasterHost(host.$ref)) {
throw new JobError(t('job:host-detach:master-host'))
}
if (!isHostRunning(host)) {
throw new JobError(t('job:host-detach:bad-power-state'))
}
},
}
})

View File

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

View File

@@ -1,29 +0,0 @@
import { HOST_OPERATION } from '@/libs/xen-api/xen-api.enums.ts'
import { hostArg } from '@/modules/host/jobs/host-args.ts'
import { isHostOperationPending } from '@/modules/host/utils/host.util.ts'
import { useXenApiStore } from '@/stores/xen-api.store.ts'
import { defineJob, JobError, JobRunningError } from '@core/packages/job'
import { useI18n } from 'vue-i18n'
export const useHostEnableJob = defineJob('host.enable', [hostArg], () => {
const xapi = useXenApiStore().getXapi()
const { t } = useI18n()
return {
run: host => xapi.host.enable(host.$ref),
validate: (isRunning, host) => {
if (host === undefined) {
throw new JobError(t('job:host-enable:missing-host'))
}
if (isRunning || isHostOperationPending(host, HOST_OPERATION.ENABLE)) {
throw new JobRunningError(t('job:enable:in-progress'))
}
if (isHostOperationPending(host, HOST_OPERATION.EVACUATE)) {
throw new JobRunningError(t('job:host-evacuate:in-progress'))
}
},
}
})

View File

@@ -1,35 +0,0 @@
import { hostArg } from '@/modules/host/jobs/host-args.ts'
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
import { useXenApiStore } from '@/stores/xen-api.store.ts'
import { defineJob, JobError, JobRunningError } from '@core/packages/job'
import { useI18n } from 'vue-i18n'
export const useHostRestartToolstackJob = defineJob('host.restart-toolstack', [hostArg], () => {
const xapi = useXenApiStore().getXapi()
const { t } = useI18n()
const { isHostRunning } = useHostMetricsStore().subscribe()
const { pool } = usePoolStore().subscribe()
return {
run: host => xapi.host.restartAgent(host.$ref),
validate: (isRunning, host) => {
if (host === undefined) {
throw new JobError(t('job:host-restart-toolstack:missing-host'))
}
if (isRunning) {
throw new JobRunningError(t('job:host-restart-toolstack:in-progress'))
}
if (!isHostRunning(host)) {
throw new JobError(t('job:host-restart-toolstack:bad-power-state'))
}
if (pool.value?.ha_enabled) {
throw new JobError(t('job:host-restart-toolstack:ha-enabled'))
}
},
}
})

View File

@@ -1,16 +1,8 @@
import { HOST_OPERATION } from '@/libs/xen-api/xen-api.enums.ts'
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import { HOST_POWER_STATE } from '@vates/types'
import { castArray } from 'lodash-es'
export type HostState = Lowercase<HOST_POWER_STATE> | 'disabled'
const RUNNING_CHANGING_STATE_OPERATIONS = [
HOST_OPERATION.ENABLE,
HOST_OPERATION.EVACUATE,
HOST_OPERATION.REBOOT,
HOST_OPERATION.SHUTDOWN,
]
const RUNNING_CHANGING_STATE_OPERATIONS = [HOST_OPERATION.EVACUATE, HOST_OPERATION.REBOOT, HOST_OPERATION.SHUTDOWN]
const NOT_RUNNING_CHANGING_STATE_OPERATIONS = [HOST_OPERATION.POWER_ON]
@@ -31,15 +23,3 @@ export const getHostPendingStateOperation = (host: XenApiHost, isHostRunning: bo
host,
isHostRunning ? RUNNING_CHANGING_STATE_OPERATIONS : NOT_RUNNING_CHANGING_STATE_OPERATIONS
)
export const getHostState = (host: XenApiHost, powerState: HOST_POWER_STATE): HostState => {
if (powerState === HOST_POWER_STATE.UNKNOWN) {
return 'unknown'
}
if (powerState === HOST_POWER_STATE.HALTED) {
return 'halted'
}
return host.enabled ? 'running' : 'disabled'
}

View File

@@ -1,78 +0,0 @@
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import { useHostStore } from '@/stores/xen-api/host.store.ts'
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
import { useTreeCollapse } from '@core/composables/tree-collapse.composable.ts'
import { useTreeFilter } from '@core/composables/tree-filter.composable.ts'
import { defineTree } from '@core/packages/tree/define-tree.ts'
import { useTree } from '@core/packages/tree/use-tree.ts'
import { logicAnd, logicOr } from '@vueuse/math'
import { computed } from 'vue'
const NO_HOST_REF = 'OpaqueRef:NULL' as XenApiHost['$ref']
export function usePoolTree() {
const { pool, isReady: isPoolReady, hasError: hasPoolError } = usePoolStore().subscribe()
const { records: hosts, isReady: areHostsReady, hasError: hasHostError } = useHostStore().subscribe()
const { recordsByHostRef, isReady: areVmsReady, hasError: hasVmError } = useVmStore().subscribe()
const { filter, predicate, isSearching, hasFilter } = useTreeFilter()
const isReady = logicAnd(isPoolReady, areHostsReady, areVmsReady)
const hasError = logicOr(hasPoolError, hasHostError, hasVmError)
const pools = computed(() => (pool.value === undefined ? [] : [pool.value]))
const definitions = computed(() =>
defineTree(
'pools',
pools.value,
{
getId: pool => `pool:${pool.uuid}`,
getLabel: 'name_label',
predicate,
discriminator: 'pool',
},
() => [
...defineTree(
'hosts',
hosts.value,
{
getId: host => `host:${host.uuid}`,
getLabel: 'name_label',
predicate,
discriminator: 'host',
},
host =>
defineTree('vms', recordsByHostRef.value.get(host.$ref) ?? [], {
getId: vm => `vm:${vm.uuid}`,
getLabel: 'name_label',
predicate,
discriminator: 'vm',
})
),
...defineTree('vms', recordsByHostRef.value.get(NO_HOST_REF) ?? [], {
getId: vm => `vm:${vm.uuid}`,
getLabel: 'name_label',
predicate,
discriminator: 'vm',
}),
]
)
)
const collapsedIds = useTreeCollapse('pool.collapsed', filter, hasFilter)
const { flatNodes, flatNodeIndexById, expandToNode } = useTree(definitions, { collapsedIds })
return {
isReady,
hasError,
treeItems: flatNodes,
treeItemIndexById: flatNodeIndexById,
filter,
isSearching,
expandToNode,
}
}

View File

@@ -1,12 +0,0 @@
import type { XenApiPool } from '@/libs/xen-api/xen-api.types.ts'
import type { POOL_ALLOWED_OPERATIONS } from '@vates/types'
import { castArray } from 'lodash-es'
export const isPoolOperationPending = (
pool: XenApiPool,
operations: POOL_ALLOWED_OPERATIONS[] | POOL_ALLOWED_OPERATIONS
) => {
const currentOperations = Object.values(pool.current_operations)
return castArray(operations).some(operation => currentOperations.includes(operation))
}

View File

@@ -105,7 +105,6 @@ function getPrimaryIcon(sr: XenApiSr) {
}
const { HeadCells, BodyCells } = useSrColumns({
exclude: ['checkbox'],
body: (sr: XenApiSr) => {
const rightIcon = computed(() => getPrimaryIcon(sr))

View File

@@ -1,6 +1,8 @@
<template>
<UiPanelCard class="storage-repository-custom-fields-card">
<UiPanelCardTitle size="medium" :label="t('custom-fields')" />
<UiCardTitle>
{{ t('custom-fields') }}
</UiCardTitle>
<div class="content">
<VtsStateHero
v-if="Object.keys(customFields).length === 0"
@@ -19,8 +21,8 @@
<script lang="ts" setup>
import VtsLabelValueList from '@core/components/label-value-list/VtsLabelValueList.vue'
import VtsStateHero from '@core/components/state-hero/VtsStateHero.vue'
import UiCardTitle from '@core/components/ui/card-title/UiCardTitle.vue'
import UiPanelCard from '@core/components/ui/panel-card/UiPanelCard.vue'
import UiPanelCardTitle from '@core/components/ui/panel-card-title/UiPanelCardTitle.vue'
import { useI18n } from 'vue-i18n'
defineProps<{

View File

@@ -1,6 +1,9 @@
<template>
<UiPanelCard>
<UiPanelCardTitle size="medium" :label="t('hosts')" :counter="hosts.length" />
<UiCardTitle>
{{ t('hosts') }}
<UiCounter :value="hosts.length" accent="neutral" size="small" variant="primary" />
</UiCardTitle>
<UiCollapsibleList v-if="hosts.length > 0" tag="ul" :total-items="hosts.length">
<li v-for="host in hosts" :key="host.uuid" v-tooltip class="text-ellipsis">
<UiLink
@@ -22,10 +25,11 @@
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
import VtsStateHero from '@core/components/state-hero/VtsStateHero.vue'
import UiCardTitle from '@core/components/ui/card-title/UiCardTitle.vue'
import UiCollapsibleList from '@core/components/ui/collapsible-list/UiCollapsibleList.vue'
import UiCounter from '@core/components/ui/counter/UiCounter.vue'
import UiLink from '@core/components/ui/link/UiLink.vue'
import UiPanelCard from '@core/components/ui/panel-card/UiPanelCard.vue'
import UiPanelCardTitle from '@core/components/ui/panel-card-title/UiPanelCardTitle.vue'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import { useI18n } from 'vue-i18n'

View File

@@ -1,12 +1,13 @@
<template>
<UiPanelCard class="storage-repository-infos-card">
<UiPanelCardTitle
:id="sr.uuid"
size="medium"
:label="sr.name_label"
:icon="sr.name_label ? srStatusIcon : undefined"
/>
<UiCardTitle>
<div v-if="sr.name_label" class="title">
<VtsIcon :name="srStatusIcon" size="medium" />
{{ sr.name_label }}
</div>
</UiCardTitle>
<div class="content">
<VtsCodeSnippet :content="sr.uuid" copy />
<VtsCardRowKeyValue>
<template #key>{{ t('status') }}</template>
<template #value>
@@ -66,11 +67,13 @@ import { useSrUtils } from '@/modules/storage-repository/composables/sr-utils.co
import { useSrStore } from '@/stores/xen-api/sr.store.ts'
import type { SrScope } from '@core/types/storage-repository.type.ts'
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
import VtsCodeSnippet from '@core/components/code-snippet/VtsCodeSnippet.vue'
import VtsCopyButton from '@core/components/copy-button/VtsCopyButton.vue'
import VtsIcon from '@core/components/icon/VtsIcon.vue'
import VtsStatus from '@core/components/status/VtsStatus.vue'
import VtsTag from '@core/components/tag/VtsTag.vue'
import UiCardTitle from '@core/components/ui/card-title/UiCardTitle.vue'
import UiPanelCard from '@core/components/ui/panel-card/UiPanelCard.vue'
import UiPanelCardTitle from '@core/components/ui/panel-card-title/UiPanelCardTitle.vue'
import UiTagsList from '@core/components/ui/tag/UiTagsList.vue'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
@@ -99,6 +102,12 @@ const isHaSr = computed(() => isHaSrForPool(sr, pool))
<style scoped lang="postcss">
.storage-repository-infos-card {
.title {
display: flex;
align-items: center;
gap: 0.8rem;
}
.content {
display: flex;
flex-direction: column;

View File

@@ -1,6 +1,8 @@
<template>
<UiPanelCard class="storage-repository-pbds-card">
<UiPanelCardTitle size="medium" :label="t('pbd-details')" />
<UiCardTitle>
{{ t('pbd-details') }}
</UiCardTitle>
<VtsStateHero v-if="pbdsInScope.length === 0" type="no-data" format="card" horizontal size="extra-small">
{{ t('no-pbd-attached') }}
</VtsStateHero>
@@ -11,7 +13,7 @@
<div v-if="areSomePbdsDisconnected" class="content">
<template v-for="(pbd, index) in disconnectedPbds" :key="pbd.uuid">
<VtsDivider v-if="index > 0" class="divider" type="stretch" />
<UiPanelCardTitle size="small" :label="t('disconnected-pbd-number', { n: index + 1 })" class="subtitle" />
<span class="typo-body-bold-small subtitle">{{ t('disconnected-pbd-number', { n: index + 1 }) }}</span>
<StorageRepositoryPbdHost :pbd />
<VtsCardRowKeyValue>
<template #key>
@@ -46,9 +48,9 @@ import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
import VtsDivider from '@core/components/divider/VtsDivider.vue'
import VtsStateHero from '@core/components/state-hero/VtsStateHero.vue'
import VtsStatus from '@core/components/status/VtsStatus.vue'
import UiCardTitle from '@core/components/ui/card-title/UiCardTitle.vue'
import UiLogEntryViewer from '@core/components/ui/log-entry-viewer/UiLogEntryViewer.vue'
import UiPanelCard from '@core/components/ui/panel-card/UiPanelCard.vue'
import UiPanelCardTitle from '@core/components/ui/panel-card-title/UiPanelCardTitle.vue'
import { CONNECTION_STATUS } from '@core/types/connection.ts'
import { useI18n } from 'vue-i18n'

View File

@@ -1,10 +1,18 @@
<template>
<UiPanelCard class="storage-repository-vdis-card">
<UiPanelCardTitle size="medium" :label="t('vdis')" :counter="vdis.length + vdiSnapshots.length" />
<UiCardTitle>
<div class="title">
{{ t('vdis') }}
<UiCounter :value="vdis.length + vdiSnapshots.length" accent="neutral" size="small" variant="primary" />
</div>
</UiCardTitle>
<div v-if="vdis.length > 0 || vdiSnapshots.length > 0" class="content">
<template v-if="vdis.length > 0">
<UiPanelCardTitle size="small" :label="t('vdis')" :counter="vdis.length" />
<div class="subsection">
<span class="subtitle typo-body-bold-small">{{ t('vdis') }}</span>
<UiCounter :value="vdis.length" accent="neutral" size="small" variant="primary" />
</div>
<UiCollapsibleList tag="ul" :total-items="vdis.length">
<li v-for="vdi in vdis" :key="vdi.uuid" v-tooltip class="text-ellipsis">
@@ -18,7 +26,10 @@
<VtsDivider v-if="vdis.length > 0 && vdiSnapshots.length > 0" type="stretch" />
<template v-if="vdiSnapshots.length > 0">
<UiPanelCardTitle size="small" :label="t('snapshot-vdis')" :counter="vdiSnapshots.length" />
<div class="subsection">
<span class="subtitle typo-body-bold-small">{{ t('snapshot-vdis') }}</span>
<UiCounter :value="vdiSnapshots.length" accent="neutral" size="small" variant="primary" />
</div>
<UiCollapsibleList tag="ul" :total-items="vdiSnapshots.length">
<li v-for="vdiSnapshot in vdiSnapshots" :key="vdiSnapshot.uuid" v-tooltip class="text-ellipsis">
@@ -42,10 +53,11 @@ import { getVdiIcon, getVbdsForVdi } from '@/modules/vdi/utils/vdi.util.ts'
import { useVbdStore } from '@/stores/xen-api/vbd.store.ts'
import VtsDivider from '@core/components/divider/VtsDivider.vue'
import VtsStateHero from '@core/components/state-hero/VtsStateHero.vue'
import UiCardTitle from '@core/components/ui/card-title/UiCardTitle.vue'
import UiCollapsibleList from '@core/components/ui/collapsible-list/UiCollapsibleList.vue'
import UiCounter from '@core/components/ui/counter/UiCounter.vue'
import UiLink from '@core/components/ui/link/UiLink.vue'
import UiPanelCard from '@core/components/ui/panel-card/UiPanelCard.vue'
import UiPanelCardTitle from '@core/components/ui/panel-card-title/UiPanelCardTitle.vue'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import { useI18n } from 'vue-i18n'
@@ -61,10 +73,28 @@ const { getByOpaqueRef: getVbdByOpaqueRef } = useVbdStore().subscribe()
<style scoped lang="postcss">
.storage-repository-vdis-card {
.title {
display: flex;
align-items: center;
gap: 0.8rem;
}
.content {
display: flex;
flex-direction: column;
gap: 1.6rem;
.subsection {
display: flex;
align-items: center;
gap: 0.8rem;
.subtitle {
display: flex;
align-items: center;
gap: 0.6rem;
}
}
}
}
</style>

View File

@@ -1,38 +0,0 @@
<template>
<VtsTreeItem :expanded="!branch.isCollapsed" :node-id="branch.dataId" :has-children="branch.hasChildren">
<UiTreeItemLabel
:route="{ name: '/pool/[uuid]', params: { uuid: branch.data.uuid } }"
icon="object:pool"
@toggle="branch.toggleCollapse()"
>
{{ branch.data.name_label || '(Pool)' }}
<template #addons>
<MenuList placement="bottom-start">
<template #trigger="{ open, isOpen }">
<UiButtonIcon
accent="brand"
icon="action:more-actions"
size="small"
:selected="isOpen"
@click="open($event)"
/>
</template>
<PoolTreeActions :pool="branch.data" />
</MenuList>
</template>
</UiTreeItemLabel>
</VtsTreeItem>
</template>
<script lang="ts" setup>
import PoolTreeActions from '@/modules/pool/components/actions/PoolTreeActions.vue'
import type { PoolBranch } from '@/modules/treeview/types/tree.type.ts'
import MenuList from '@core/components/menu/MenuList.vue'
import VtsTreeItem from '@core/components/tree/VtsTreeItem.vue'
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
import UiTreeItemLabel from '@core/components/ui/tree-item-label/UiTreeItemLabel.vue'
defineProps<{
branch: PoolBranch
}>()
</script>

View File

@@ -1,42 +0,0 @@
<template>
<RecycleScroller
ref="scroller"
:items
:item-size="37"
:buffer="600"
key-field="id"
list-tag="ul"
item-tag="li"
class="pool-tree-list"
>
<template #default="{ item }">
<TreeNodeRow :node="item.node" :depth="item.depth" />
</template>
</RecycleScroller>
</template>
<script lang="ts" setup>
import TreeNodeRow from '@/modules/treeview/components/TreeNodeRow.vue'
import type { FlatTreeNode } from '@core/packages/tree/types.ts'
import { useTemplateRef } from 'vue'
import { RecycleScroller, type RecycleScrollerInstance } from 'vue-virtual-scroller'
defineProps<{
items: FlatTreeNode[]
}>()
const scroller = useTemplateRef<RecycleScrollerInstance>('scroller')
defineExpose({
scrollToItem: (index: number) => scroller.value?.scrollToItem(index, { smooth: true, align: 'center' }),
})
</script>
<style lang="postcss" scoped>
.pool-tree-list {
height: 100%;
overflow-y: auto;
padding: 0.8rem;
background-color: var(--color-neutral-background-primary);
}
</style>

View File

@@ -1,108 +0,0 @@
<template>
<VtsLayoutSidebar class="pool-tree-sidebar">
<template #subheader>
<VtsTreeSearch ref="treeSearch" v-model="filter" />
</template>
<VtsTreeList v-if="hasError">
<VtsTreeItemError>{{ t('error-no-data') }}</VtsTreeItemError>
</VtsTreeList>
<VtsTreeList v-else-if="!isReady">
<VtsTreeLoadingItem icon="object:pool" />
</VtsTreeList>
<VtsStateHero v-else-if="isSearching" class="loader" format="card" size="medium" type="busy" />
<VtsStateHero v-else-if="treeItems.length === 0" format="card" size="medium" type="no-result">
{{ t('no-result') }}
</VtsStateHero>
<PoolTreeList v-else ref="poolTreeList" :items="treeItems" />
</VtsLayoutSidebar>
</template>
<script lang="ts" setup>
import { usePoolTree } from '@/modules/pool/composables/pool-tree.composable.ts'
import PoolTreeList from '@/modules/treeview/components/PoolTreeList.vue'
import VtsLayoutSidebar from '@core/components/layout/VtsLayoutSidebar.vue'
import VtsStateHero from '@core/components/state-hero/VtsStateHero.vue'
import VtsTreeItemError from '@core/components/tree/VtsTreeItemError.vue'
import VtsTreeList from '@core/components/tree/VtsTreeList.vue'
import VtsTreeLoadingItem from '@core/components/tree/VtsTreeLoadingItem.vue'
import VtsTreeSearch from '@core/components/tree/VtsTreeSearch.vue'
import { useTreeSearchShortcut } from '@core/composables/tree-search-shortcut.composable.ts'
import { computed, nextTick, useTemplateRef, watch } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute } from 'vue-router'
const { t } = useI18n()
const { treeItems, treeItemIndexById, isReady, hasError, filter, isSearching, expandToNode } = usePoolTree()
const route = useRoute<'/pool/[uuid]' | '/host/[uuid]' | '/vm/[uuid]'>()
const poolTreeList = useTemplateRef('poolTreeList')
const treeSearch = useTemplateRef('treeSearch')
useTreeSearchShortcut(treeSearch)
const currentNodeId = computed(() => {
const uuid = Array.isArray(route.params.uuid) ? route.params.uuid[0] : route.params.uuid
if (uuid === undefined) {
return undefined
}
const prefix = (['pool', 'host', 'vm'] as const).find(type => route.path.startsWith(`/${type}/`))
return prefix === undefined ? undefined : `${prefix}:${uuid}`
})
let scrolledToId: string | undefined
async function scrollToCurrentNode() {
const nodeId = currentNodeId.value
if (nodeId === undefined) {
scrolledToId = undefined
return
}
if (nodeId === scrolledToId) {
return
}
const node = expandToNode(nodeId)
if (node === undefined) {
return
}
const index = treeItemIndexById.value.get(node.id)
if (index === undefined) {
return
}
scrolledToId = nodeId
await nextTick()
poolTreeList.value?.scrollToItem(index)
}
watch(
[currentNodeId, isReady, treeItems],
() => {
if (isReady.value) {
scrollToCurrentNode()
}
},
{ immediate: true }
)
</script>
<style lang="postcss" scoped>
.pool-tree-sidebar {
.loader {
padding-block-start: 4rem;
}
}
</style>

View File

@@ -1,25 +0,0 @@
<template>
<PoolTreeItem v-if="node.discriminator === 'pool'" :branch="node as PoolBranch" />
<HostTreeItem v-else-if="node.discriminator === 'host'" :branch="node as HostBranch" />
<VmTreeItem v-else :leaf="node as VmLeaf" />
</template>
<script lang="ts" setup>
import HostTreeItem from '@/modules/treeview/components/HostTreeItem.vue'
import PoolTreeItem from '@/modules/treeview/components/PoolTreeItem.vue'
import VmTreeItem from '@/modules/treeview/components/VmTreeItem.vue'
import type { HostBranch, PoolBranch, VmLeaf } from '@/modules/treeview/types/tree.type.ts'
import type { TreeNode } from '@core/packages/tree/types.ts'
import { IK_TREE_LIST_DEPTH } from '@core/utils/injection-keys.util.ts'
import { computed, provide } from 'vue'
const { node, depth } = defineProps<{
node: TreeNode
depth: number
}>()
provide(
IK_TREE_LIST_DEPTH,
computed(() => depth + 1)
)
</script>

View File

@@ -1,9 +0,0 @@
import type { XenApiHost, XenApiPool, XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import type { Branch } from '@core/packages/tree/branch.ts'
import type { Leaf } from '@core/packages/tree/leaf.ts'
export type VmLeaf = Leaf<XenApiVm, 'vm'>
export type HostBranch = Branch<XenApiHost, VmLeaf, 'host'>
export type PoolBranch = Branch<XenApiPool, HostBranch | VmLeaf, 'pool'>

View File

@@ -1,6 +1,8 @@
<template>
<UiPanelCard class="card-container">
<UiPanelCardTitle size="medium" :label="t('configuration')" />
<UiCard class="card-container">
<UiCardTitle>
{{ t('configuration') }}
</UiCardTitle>
<div class="content">
<VdiFormatCardItem :format="vdi.sm_config['image-format']" />
<VtsCardRowKeyValue>
@@ -44,7 +46,7 @@
</template>
</VtsCardRowKeyValue>
</div>
</UiPanelCard>
</UiCard>
</template>
<script setup lang="ts">
@@ -55,9 +57,9 @@ import { useSrStore } from '@/stores/xen-api/sr.store.ts'
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
import VtsCopyButton from '@core/components/copy-button/VtsCopyButton.vue'
import VtsStatus from '@core/components/status/VtsStatus.vue'
import UiCard from '@core/components/ui/card/UiCard.vue'
import UiCardTitle from '@core/components/ui/card-title/UiCardTitle.vue'
import UiLink from '@core/components/ui/link/UiLink.vue'
import UiPanelCard from '@core/components/ui/panel-card/UiPanelCard.vue'
import UiPanelCardTitle from '@core/components/ui/panel-card-title/UiPanelCardTitle.vue'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { vdi, vbd } = defineProps<{
@@ -73,6 +75,7 @@ const isBootable = computed(() => vbd?.bootable ?? false)
<style scoped lang="postcss">
.card-container {
gap: 1.6rem;
.content {
display: flex;
flex-direction: column;

View File

@@ -1,6 +1,6 @@
<template>
<UiPanelCard class="card-container">
<UiPanelCardTitle :id="vdi.uuid" size="medium" :label="vdi.name_label" :icon="vdiIcon" />
<UiCard class="card-container">
<VtsCardObjectTitle :id="vdi.uuid" :label="vdi.name_label" :icon="vdiIcon" />
<div class="content">
<VtsCardRowKeyValue truncate align-top>
<template #key>{{ t('description') }}</template>
@@ -37,7 +37,7 @@
</template>
</VtsCardRowKeyValue>
</div>
</UiPanelCard>
</UiCard>
</template>
<script lang="ts" setup>
@@ -45,11 +45,11 @@ import type { XenApiVbd, XenApiVdi } from '@/libs/xen-api/xen-api.types.ts'
import { useVbdsStatus, type VbdAttachmentStatus } from '@/modules/vbd/composables/use-vbds-status.composable.ts'
import type { IconName } from '@core/icons'
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
import VtsCardObjectTitle from '@core/components/card-object-title/VtsCardObjectTitle.vue'
import VtsCopyButton from '@core/components/copy-button/VtsCopyButton.vue'
import VtsStatus from '@core/components/status/VtsStatus.vue'
import VtsTag from '@core/components/tag/VtsTag.vue'
import UiPanelCard from '@core/components/ui/panel-card/UiPanelCard.vue'
import UiPanelCardTitle from '@core/components/ui/panel-card-title/UiPanelCardTitle.vue'
import UiCard from '@core/components/ui/card/UiCard.vue'
import UiTagsList from '@core/components/ui/tag/UiTagsList.vue'
import { useMapper } from '@core/packages/mapper'
import { CONNECTION_STATUS } from '@core/types/connection.ts'
@@ -82,6 +82,7 @@ const vbdsStatus = useMapper<VbdAttachmentStatus, (typeof CONNECTION_STATUS)[key
<style scoped lang="postcss">
.card-container {
gap: 1.6rem;
.content {
display: flex;
flex-direction: column;

View File

@@ -6,7 +6,7 @@
<template v-if="vif" #default>
<!-- VIF -->
<UiPanelCard>
<UiPanelCardTitle :id="vif.uuid" size="medium" :label="t('vif')" />
<VtsCardObjectTitle :id="vif.uuid" :label="t('vif')" />
<div class="content">
<!-- NETWORK -->
<VtsCardRowKeyValue>
@@ -65,7 +65,7 @@
</UiPanelCard>
<!-- VIF NETWORK INFORMATION -->
<UiPanelCard>
<UiPanelCardTitle size="medium" :label="t('network-information')" />
<UiCardTitle>{{ t('network-information') }}</UiCardTitle>
<div class="content">
<!-- IP ADDRESSES -->
<div v-if="ipAddresses.length">
@@ -113,12 +113,13 @@ import { useNetworkStore } from '@/stores/xen-api/network.store.ts'
import { useVmGuestMetricsStore } from '@/stores/xen-api/vm-guest-metrics.store.ts'
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
import VtsCardObjectTitle from '@core/components/card-object-title/VtsCardObjectTitle.vue'
import VtsCopyAllMenuItem from '@core/components/copy-all-menu-item/VtsCopyAllMenuItem.vue'
import VtsCopyButton from '@core/components/copy-button/VtsCopyButton.vue'
import VtsSidePanel from '@core/components/panel/VtsSidePanel.vue'
import VtsStatus from '@core/components/status/VtsStatus.vue'
import UiCardTitle from '@core/components/ui/card-title/UiCardTitle.vue'
import UiPanelCard from '@core/components/ui/panel-card/UiPanelCard.vue'
import UiPanelCardTitle from '@core/components/ui/panel-card-title/UiPanelCardTitle.vue'
import { getUniqueIpAddressesForDevice } from '@core/utils/ip-address.utils.ts'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'

View File

@@ -2,21 +2,20 @@ import { isVmOperationPending } from '@/libs/vm.ts'
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import { CHANGING_STATE_OPERATIONS } from '@/modules/vm/utils/vm.util.ts'
import { useMapper } from '@core/packages/mapper'
import { toComputed } from '@core/utils/to-computed.util.ts'
import { computed, type MaybeRefOrGetter } from 'vue'
import { computed, type MaybeRefOrGetter, toValue } from 'vue'
import { useI18n } from 'vue-i18n'
export function useVmOperation(rawVm: MaybeRefOrGetter<XenApiVm | undefined>) {
const { t } = useI18n()
const vm = toComputed(rawVm)
const vm = toValue(rawVm)
const isChangingState = computed(() => {
return vm.value !== undefined && isVmOperationPending(vm.value, CHANGING_STATE_OPERATIONS)
return vm !== undefined && isVmOperationPending(vm, CHANGING_STATE_OPERATIONS)
})
const currentOperation = useMapper<string, string>(
() => Object.values(vm.value?.current_operations ?? {})[0],
() => Object.values(vm?.current_operations ?? {})[0],
{
start: t('operation:start'),
start_on: t('operation:start-on-host'),

View File

@@ -97,7 +97,7 @@ const url = computed(() => {
}
const _url = new URL(hostConsole.value!.location)
_url.protocol = new URL(xenApiStore.getXapi().hostUrl).protocol === 'https:' ? 'wss:' : 'ws:'
_url.protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
_url.searchParams.set('session_id', xenApiStore.currentSessionId)
return _url

View File

@@ -1,30 +1,28 @@
<template>
<div class="pool-dashboard-view" :class="{ mobile: uiStore.isSmall }">
<div class="row first-row">
<PoolDashboardStatus class="status" />
<div class="pool-dashboard-view">
<UiCardGroup>
<PoolDashboardStatus />
<PoolDashboardAlarms class="alarms" />
<PoolDashboardHostsPatches class="patches" />
</div>
<div class="row second-row">
<div class="column first-column">
<PoolDashboardHostsPatches />
</UiCardGroup>
<UiCardGroup>
<UiCardGroup>
<PoolDashboardStorageUsage />
<PoolDashboardNetworkChart />
</div>
<div class="column second-column">
</UiCardGroup>
<UiCardGroup>
<PoolDashboardRamUsage />
<PoolRamUsageChart />
</div>
<div class="column third-column">
</UiCardGroup>
<UiCardGroup>
<PoolDashboardCpuProvisioning />
<PoolDashboardCpuUsage />
<PoolCpuUsageChart />
</div>
</div>
<div class="row third-row">
</UiCardGroup>
</UiCardGroup>
<UiCardGroup>
<PoolDashboardTasks class="tasks" />
</div>
</UiCardGroup>
</div>
</template>
@@ -40,6 +38,7 @@ import PoolDashboardStatus from '@/components/pool/dashboard/PoolDashboardStatus
import PoolDashboardStorageUsage from '@/components/pool/dashboard/PoolDashboardStorageUsage.vue'
import PoolDashboardTasks from '@/components/pool/dashboard/PoolDashboardTasks.vue'
import PoolRamUsageChart from '@/components/pool/dashboard/ramUsage/PoolRamUsageChart.vue'
import UiCardGroup from '@/components/ui/UiCardGroup.vue'
import useFetchStats from '@/composables/fetch-stats.composable.ts'
import { GRANULARITY } from '@/libs/xapi-stats.ts'
import type { XenApiHost, XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
@@ -47,15 +46,12 @@ import { usePageTitleStore } from '@/stores/page-title.store.ts'
import { useHostStore } from '@/stores/xen-api/host.store.ts'
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
import { IK_HOST_LAST_WEEK_STATS, IK_HOST_STATS, IK_VM_STATS } from '@/types/injection-keys.ts'
import { useUiStore } from '@core/stores/ui.store.ts'
import { differenceBy } from 'lodash-es'
import { provide, watch } from 'vue'
import { useI18n } from 'vue-i18n'
usePageTitleStore().setTitle(useI18n().t('dashboard'))
const uiStore = useUiStore()
const { getStats: getHostStats, runningHosts } = useHostStore().subscribe()
const { getStats: getVmStats, runningVms } = useVmStore().subscribe()
@@ -113,79 +109,26 @@ export const N_ITEMS = 5
<style lang="postcss" scoped>
.pool-dashboard-view {
margin: 0.8rem;
display: flex;
flex-direction: column;
gap: 1rem;
padding: 1rem;
}
/* === DESKTOP === */
.row {
display: grid;
gap: 0.8rem;
}
.row + .row {
margin-top: 0.8rem;
}
.first-row {
grid-template-columns: minmax(10rem, 1fr) minmax(20rem, 2fr) minmax(10rem, 1fr);
grid-template-areas: 'status alarms patches';
}
.status {
grid-area: status;
}
.alarms {
grid-area: alarms;
}
.patches {
grid-area: patches;
}
.second-row {
grid-template-columns: repeat(3, minmax(20rem, 1fr));
grid-template-areas: 'first-column second-column third-column';
}
.column {
display: flex;
flex-direction: column;
gap: 0.8rem;
}
.first-column {
grid-area: first-column;
}
.second-column {
grid-area: second-column;
}
.third-column {
grid-area: third-column;
}
.third-row {
grid-template-columns: minmax(20rem, 1fr);
grid-template-areas: 'tasks';
}
.tasks {
grid-area: tasks;
}
/* === MOBILE === */
&.mobile {
display: flex;
flex-direction: column;
gap: 0.8rem;
}
&.mobile .row {
display: flex;
flex-direction: column;
gap: 0.8rem;
margin-top: 0;
@media (min-width: 768px) {
.pool-dashboard-view {
column-count: 2;
}
}
@media (min-width: 1500px) {
.pool-dashboard-view {
column-count: 3;
}
}
.alarms,
.tasks {
flex: 1;
}
</style>

View File

@@ -50,7 +50,7 @@ const state = useTableState({
})
const { HeadCells, BodyCells } = useHostColumns({
exclude: ['checkbox', 'selectItem', 'srStatus'],
exclude: ['selectItem', 'srStatus'],
body: (host: XenApiHost) => {
const state = isHostRunning(host) ? 'running' : 'halted'

View File

@@ -92,7 +92,7 @@ const url = computed(() => {
return
}
const _url = new URL(vmConsole.value!.location)
_url.protocol = new URL(xenApiStore.getXapi().hostUrl).protocol === 'https:' ? 'wss:' : 'ws:'
_url.protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
_url.searchParams.set('session_id', xenApiStore.currentSessionId)
return _url
})

View File

@@ -631,10 +631,7 @@ const _createVm = defer(async ($defer: Defer) => {
if ((newVdis.length === 0 && existingVdis.length === 0) || installMethod === 'network') {
const { order } = vm.HVM_boot_params
await xapi.call('VM.set_HVM_boot_params', [
vmRefs[0],
{ ...vm.HVM_boot_params, order: order ? 'n' + order.replace('n', '') : 'ncd' },
])
await xapi.call('VM.set_HVM_boot_params', [vmRefs[0], { order: order ? 'n' + order.replace('n', '') : 'ncd' }])
}
} else {
if (vm.PV_bootloader === 'eliloader') {

View File

@@ -541,13 +541,6 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/tree/vts-tree-search': RouteRecordInfo<
'/story/web-core/tree/vts-tree-search',
'/story/web-core/tree/vts-tree-search',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/ui/account-menu-button/ui-account-menu-button': RouteRecordInfo<
'/story/web-core/ui/account-menu-button/ui-account-menu-button',
'/story/web-core/ui/account-menu-button/ui-account-menu-button',
@@ -821,13 +814,6 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/ui/panel-card-title/ui-panel-card-title': RouteRecordInfo<
'/story/web-core/ui/panel-card-title/ui-panel-card-title',
'/story/web-core/ui/panel-card-title/ui-panel-card-title',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/ui/progress-bar/ui-progress-bar': RouteRecordInfo<
'/story/web-core/ui/progress-bar/ui-progress-bar',
'/story/web-core/ui/progress-bar/ui-progress-bar',
@@ -1542,12 +1528,6 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/stories/web-core/tree/vts-tree-search.story.vue': {
routes:
| '/story/web-core/tree/vts-tree-search'
views:
| never
}
'src/stories/web-core/ui/account-menu-button/ui-account-menu-button.story.vue': {
routes:
| '/story/web-core/ui/account-menu-button/ui-account-menu-button'
@@ -1782,12 +1762,6 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/stories/web-core/ui/panel-card-title/ui-panel-card-title.story.vue': {
routes:
| '/story/web-core/ui/panel-card-title/ui-panel-card-title'
views:
| never
}
'src/stories/web-core/ui/progress-bar/ui-progress-bar.story.vue': {
routes:
| '/story/web-core/ui/progress-bar/ui-progress-bar'

View File

@@ -0,0 +1,25 @@
import { useUiStore } from '@core/stores/ui.store.ts'
import { useEventListener, whenever } from '@vueuse/core'
import { defineStore } from 'pinia'
import { ref } from 'vue'
export const useNavigationStore = defineStore('navigation', () => {
const uiStore = useUiStore()
const trigger = ref()
const isOpen = ref(true)
const toggle = () => (isOpen.value = !isOpen.value)
useEventListener(trigger, 'click', toggle)
whenever(
() => !uiStore.isSmall,
() => (isOpen.value = false)
)
return {
trigger,
toggle,
isOpen,
}
})

View File

@@ -7,18 +7,6 @@ import { useRoute, useRouter } from 'vue-router'
const HOST_URL = import.meta.env.PROD ? window.origin : import.meta.env.VITE_XO_HOST
function getHostUrl(master: string | null) {
if (master === null) {
return new URL(HOST_URL)
}
try {
return new URL(master.includes('://') ? master : `https://${master}`)
} catch {
return new URL(HOST_URL)
}
}
enum STATUS {
DISCONNECTED,
CONNECTING,
@@ -40,7 +28,10 @@ export const useXenApiStore = defineStore('xen-api', () => {
}
)
const hostUrl = getHostUrl(masterSessionStorage.value)
const hostUrl = new URL(HOST_URL)
if (masterSessionStorage.value !== null) {
hostUrl.hostname = masterSessionStorage.value
}
const isPoolOverridden = hostUrl.origin !== new URL(HOST_URL).origin
const xenApi = new XenApi(hostUrl.origin)

View File

@@ -21,7 +21,7 @@ export const useSrStore = defineStore('xen-api-sr', () => {
const srs = computed(() => baseContext.records.value)
const isoSrs = computed(() => srs.value.filter(sr => sr.type === 'iso' && !sr.is_tools_sr))
const isoSrs = computed(() => srs.value.filter(sr => sr.type === 'iso'))
const concatVdisArray = computed(() =>
isoSrs.value.reduce((acc, sr) => {

View File

@@ -73,18 +73,6 @@ export const useVmStore = defineStore('xen-api-vm', () => {
return undefined
}
const runningVmsCountByHostRef = computed(() => {
const countByHostRef = new Map<XenApiHost['$ref'], number>()
runningVms.value.forEach(vm => {
if (vm.resident_on) {
countByHostRef.set(vm.resident_on, (countByHostRef.get(vm.resident_on) ?? 0) + 1)
}
})
return countByHostRef
})
const recordsByHostRef = computed(() => {
const vmsByHostOpaqueRef = new Map<XenApiHost['$ref'], XenApiVm[]>()
@@ -158,7 +146,6 @@ export const useVmStore = defineStore('xen-api-vm', () => {
records,
templates,
runningVms,
runningVmsCountByHostRef,
recordsByHostRef,
getStats,
getVmHost,

View File

@@ -35,7 +35,16 @@
<div class="slot-header">Sidebar header</div>
</template>
<template v-if="settings.showSubheader" #subheader>
<VtsTreeSearch v-model="search" />
<div class="sidebar-search">
<UiInput
v-model="search"
:aria-label="t('action:search-treeview')"
right-icon="fa:magnifying-glass"
:placeholder="t('action:search-treeview')"
accent="brand"
clearable
/>
</div>
</template>
<div class="slot-content">
<p>Sidebar content</p>
@@ -88,10 +97,10 @@ import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { prop, setting, slot } from '@/libs/story/story-param.ts'
import { boolean } from '@/libs/story/story-widget.ts'
import VtsLayoutSidebar from '@core/components/layout/VtsLayoutSidebar.vue'
import VtsTreeSearch from '@core/components/tree/VtsTreeSearch.vue'
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
import UiCard from '@core/components/ui/card/UiCard.vue'
import UiCardTitle from '@core/components/ui/card-title/UiCardTitle.vue'
import UiInput from '@core/components/ui/input/UiInput.vue'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import { type SidebarSide, useLeftSidebarStore, useRightSidebarStore } from '@core/packages/sidebar'
import { ref } from 'vue'
@@ -146,6 +155,10 @@ function toggleExpand(side: SidebarSide) {
margin-block: 1.6rem;
}
}
.sidebar-search {
padding: 0.4rem;
}
}
.main {

View File

@@ -1,14 +0,0 @@
Search input to filter a treeview. It is meant to be placed in the `subheader` slot of `VtsLayoutSidebar`.
# Example
```vue-template
<VtsLayoutSidebar>
<template #subheader>
<VtsTreeSearch v-model="filter" />
</template>
<VtsTreeList>
<!-- tree items filtered with `filter` -->
</VtsTreeList>
</VtsLayoutSidebar>
```

View File

@@ -1,14 +0,0 @@
<template>
<ComponentStory
v-slot="{ properties }"
:params="[model().type('string').preset('').help('The search query used to filter the treeview')]"
>
<VtsTreeSearch 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 VtsTreeSearch from '@core/components/tree/VtsTreeSearch.vue'
</script>

View File

@@ -1,66 +0,0 @@
<template>
<ComponentStory
v-slot="{ properties, settings }"
:params="[
prop('size').required().enum('small', 'medium').preset('medium').widget(),
prop('label').str().preset('Label').widget(),
iconProp(),
prop('id')
.str()
.preset('71df26a2-678a-49c7-8232-8ebcac4987ab')
.widget()
.help('Displayed below the label, with a copy button'),
prop('counter')
.num()
.widget()
.help(
'Also accepts `{ value, accent }` to change the counter accent, e.g. `{ value: 3, accent: \'warning\' }`'
),
prop('to').str().widget(),
prop('href').str().widget(),
prop('target').enum('_blank', '_self').widget(),
prop('disabled').bool().widget(),
slot('label').help('Replaces the label text; the icon and the link still come from the props'),
setting('showLabelSlotDemo').widget(boolean()),
slot('action').help('Displayed right after the title and its counter'),
setting('showActionSlotDemo').widget(boolean()),
slot('more-actions').help('Pushed to the end of the line'),
setting('showMoreActionsSlotDemo').widget(boolean()),
]"
>
<UiPanelCardTitle v-bind="properties">
<template v-if="settings.showLabelSlotDemo" #label>
Backup of
<UiLink href="#" size="medium">db-01</UiLink>
</template>
<template v-if="settings.showActionSlotDemo" #action>
<UiLink href="#" size="small">See all</UiLink>
</template>
<template v-if="settings.showMoreActionsSlotDemo" #more-actions>
<UiButtonIcon icon="fa:ellipsis" size="small" accent="brand" />
</template>
</UiPanelCardTitle>
<div v-if="!properties.to && !properties.href" class="info">
<VtsIcon name="status:info-circle" size="medium" />
The label renders as plain text: it becomes a link only when `to` or `href` is provided
</div>
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { iconProp, prop, setting, slot } from '@/libs/story/story-param.ts'
import { boolean } from '@/libs/story/story-widget.ts'
import VtsIcon from '@core/components/icon/VtsIcon.vue'
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
import UiLink from '@core/components/ui/link/UiLink.vue'
import UiPanelCardTitle from '@core/components/ui/panel-card-title/UiPanelCardTitle.vue'
</script>
<style lang="postcss" scoped>
.info {
margin-top: 4rem;
font-style: italic;
}
</style>

View File

@@ -1,76 +0,0 @@
import type { Task } from '@core/components/ui/task-item/UiTaskItem.vue'
export const pendingBackupTask: Task = {
id: '1',
name: 'VM backup',
status: 'pending',
progress: 45,
subtasks: [
{ id: '1-1', name: 'Snapshot', status: 'success', progress: 100, end: Date.now() - 3 * 60_000 },
{ id: '1-2', name: 'Export', status: 'pending', progress: 10 },
],
}
export const completedWithRootLinkTask: Task = {
id: '2',
name: 'Pool metadata sync',
to: '#',
status: 'success',
progress: 100,
end: Date.now() - 15 * 60_000,
}
export const failedWithWarningsTask: Task = {
id: '3',
name: 'VM migration',
status: 'failure',
progress: 100,
warnings: [{ message: 'Partial export failure', data: { file: 'backup.log' } }],
}
export const migrationNamePartsTask: Task = {
id: '4',
status: 'pending',
progress: 30,
nameParts: [
{ text: 'Migrating VM ' },
{ text: 'Production', to: { name: '/vm/[uuid]/dashboard', params: { uuid: 'vm-1' } } },
{ text: ' from ' },
{ text: 'Host-1', to: { name: '/host/[uuid]/dashboard', params: { uuid: 'host-1' } } },
{ text: ' to ' },
{ text: 'Host-2', to: { name: '/host/[uuid]/dashboard', params: { uuid: 'host-2' } } },
],
}
export const deepNestedTask: Task = {
id: '5',
name: 'VM backup',
status: 'pending',
progress: 60,
subtasks: [
{
id: '5-1',
name: 'Export',
status: 'pending',
progress: 20,
subtasks: [
{ id: '5-1-1', name: 'VDI export', status: 'pending', progress: 5 },
{
id: '5-1-2',
name: 'Metadata export',
status: 'success',
progress: 100,
end: Date.now() - 60_000,
},
],
},
],
}
export const allTasks: Task[] = [
pendingBackupTask,
completedWithRootLinkTask,
failedWithWarningsTask,
migrationNamePartsTask,
deepNestedTask,
]

View File

@@ -1,26 +1,14 @@
# Type
```typescript
type TaskStatus = 'failure' | 'interrupted' | 'pending' | 'success'
type TaskObjectSegment = {
text: string
to?: RouteLocationRaw
}
type Task = {
id: string
infos?: { data: unknown; message: string }[]
name?: string
nameParts?: TaskObjectSegment[]
to?: LinkOptions['to']
progress?: number
tag?: string
userName?: string
start?: number
end?: number
status: TaskStatus
subtasks?: Task[]
warnings?: { data: unknown; message: string }[]
status: 'failure' | 'interrupted' | 'pending' | 'success'
tasks?: Task[]
warning?: { data: unknown; message: string }[]
}
```

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