mirror of
https://github.com/vatesfr/xen-orchestra.git
synced 2026-11-16 20:11:12 -06:00
Compare commits
31 Commits
feat_check
...
debug_time
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
9829eb58f3 | ||
|
|
2e5ec8c9e2 | ||
|
|
8054d88a88 | ||
|
|
20bedca539 | ||
|
|
f61019b960 | ||
|
|
be960b36b9 | ||
|
|
40dede9e11 | ||
|
|
e9548959c6 | ||
|
|
be94d0d083 | ||
|
|
9c6d10327f | ||
|
|
a94eba4dd1 | ||
|
|
a6970b0150 | ||
|
|
26cd23179d | ||
|
|
03d2af39ad | ||
|
|
be868a307b | ||
|
|
01c00b110e | ||
|
|
65c32014d6 | ||
|
|
69dfeeaaf6 | ||
|
|
4a1269b898 | ||
|
|
498cc7509f | ||
|
|
f98b4c9e4a | ||
|
|
cc7ba53b29 | ||
|
|
1a795970f9 | ||
|
|
59306dce8f | ||
|
|
6ba465be04 | ||
|
|
068c4cdc86 | ||
|
|
93a7c3b509 | ||
|
|
07c42bbd1e | ||
|
|
ada3cf745c | ||
|
|
6a0332a784 | ||
|
|
09bd5c3425 |
@@ -19,7 +19,7 @@
|
||||
},
|
||||
"main": "./index.mjs",
|
||||
"dependencies": {
|
||||
"@xen-orchestra/fs": "^4.9.2",
|
||||
"@xen-orchestra/fs": "^4.9.3",
|
||||
"@xen-orchestra/log": "^0.7.2",
|
||||
"fuse-native": "^2.2.6",
|
||||
"lru-cache": "^7.14.0",
|
||||
|
||||
@@ -19,6 +19,12 @@ export class NbdDisk extends RandomAccessDisk {
|
||||
/** @type {number} */
|
||||
#blockSize
|
||||
|
||||
/** @type {number | undefined} */
|
||||
#hasBlockCursor
|
||||
|
||||
/** @type {number | undefined} */
|
||||
#hasBlockPreviousIndex
|
||||
|
||||
constructor(nbdInfos, blockSize, { dataMap } = {}) {
|
||||
super()
|
||||
this.#blockSize = blockSize
|
||||
@@ -27,11 +33,38 @@ export class NbdDisk extends RandomAccessDisk {
|
||||
}
|
||||
|
||||
#processDatamap(rawDataMap) {
|
||||
return rawDataMap
|
||||
.filter(({ type }) => type === 0)
|
||||
const ranges = rawDataMap
|
||||
.filter(({ type, length }) => type === 0 && length > 0)
|
||||
.map(({ offset, length }) => ({ offset, length }))
|
||||
.sort(({ offset: offset1 }, { offset: offset2 }) => offset1 - offset2)
|
||||
|
||||
// hasBlock()'s forward-only cursor is only correct if the extents are
|
||||
// sorted AND disjoint: an earlier extent must never reach into a block
|
||||
// after a later one, otherwise the cursor could skip it and wrongly report
|
||||
// a block as empty, dropping data and corrupting the output.
|
||||
// Touching extents (cur.offset === prevEnd) are merged
|
||||
const merged = []
|
||||
for (const range of ranges) {
|
||||
const last = merged[merged.length - 1]
|
||||
if (last !== undefined) {
|
||||
const lastEnd = last.offset + last.length
|
||||
if (range.offset < lastEnd) {
|
||||
throw new Error(
|
||||
`overlapping ranges in data map: [${last.offset}, ${lastEnd}) and [${range.offset}, ${range.offset + range.length})`
|
||||
)
|
||||
}
|
||||
if (range.offset === lastEnd) {
|
||||
// touching: extend the previous extent
|
||||
last.length += range.length
|
||||
continue
|
||||
}
|
||||
}
|
||||
// gap (or first range): new extent
|
||||
merged.push(range)
|
||||
}
|
||||
return merged
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} index
|
||||
* @returns {Promise<DiskBlock>}
|
||||
@@ -117,6 +150,34 @@ export class NbdDisk extends RandomAccessDisk {
|
||||
return [...indexes].sort((a, b) => a - b)
|
||||
}
|
||||
|
||||
/**
|
||||
* Counts the allocated blocks without materializing the index list.
|
||||
*
|
||||
* @returns {number}
|
||||
*/
|
||||
getBlockIndexesCount() {
|
||||
if (!this.#dataMap) {
|
||||
throw new Error("can't getBlockIndexesCount before init")
|
||||
}
|
||||
|
||||
const blockSize = this.getBlockSize()
|
||||
|
||||
let count = 0
|
||||
let lastCountedBlock = -1
|
||||
for (const { offset, length } of this.#dataMap) {
|
||||
const firstBlockIndex = Math.floor(offset / blockSize)
|
||||
const lastBlockIndex = Math.floor((offset + length - 1) / blockSize)
|
||||
const from = Math.max(firstBlockIndex, lastCountedBlock + 1)
|
||||
|
||||
if (lastBlockIndex >= from) {
|
||||
count += lastBlockIndex - from + 1
|
||||
lastCountedBlock = lastBlockIndex
|
||||
}
|
||||
}
|
||||
|
||||
return count
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} index
|
||||
* @returns {boolean}
|
||||
@@ -125,8 +186,32 @@ export class NbdDisk extends RandomAccessDisk {
|
||||
if (!this.#dataMap) {
|
||||
throw new Error("can't hasBlock before init")
|
||||
}
|
||||
const blockStart = index * this.getBlockSize()
|
||||
const blockEnd = (index + 1) * this.getBlockSize()
|
||||
return this.#dataMap.some(({ offset, length }) => offset + length > blockStart && offset < blockEnd)
|
||||
|
||||
const blockSize = this.getBlockSize()
|
||||
const blockStart = index * blockSize
|
||||
const blockEnd = blockStart + blockSize
|
||||
|
||||
let startExtentIndex = 0
|
||||
if (this.#hasBlockCursor !== undefined && index >= this.#hasBlockPreviousIndex) {
|
||||
startExtentIndex = this.#hasBlockCursor
|
||||
} else {
|
||||
this.#hasBlockCursor = undefined
|
||||
}
|
||||
this.#hasBlockPreviousIndex = index
|
||||
|
||||
const dataMap = this.#dataMap
|
||||
const l = dataMap.length
|
||||
for (let i = startExtentIndex; i < l; i++) {
|
||||
const { offset, length } = dataMap[i]
|
||||
if (offset >= blockEnd) {
|
||||
// extents are sorted: nothing from here on can overlap this block
|
||||
break
|
||||
}
|
||||
if (offset + length > blockStart) {
|
||||
this.#hasBlockCursor = i
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
127
@vates/nbd-client/NbdDisk.test.mjs
Normal file
127
@vates/nbd-client/NbdDisk.test.mjs
Normal file
@@ -0,0 +1,127 @@
|
||||
import { describe, it } from 'node:test'
|
||||
import assert from 'node:assert'
|
||||
|
||||
import { NbdDisk } from './NbdDisk.mjs'
|
||||
|
||||
const KiB = 1024
|
||||
const MiB = 1024 * KiB
|
||||
const TiB = 1024 * 1024 * MiB
|
||||
|
||||
const SOURCE_BLOCK_SIZE = 2 * MiB // VHD_BLOCK_SIZE, the block size used when importing from VMware
|
||||
const CLUSTER_SIZE = 64 * KiB // qcow2 cluster size
|
||||
|
||||
// hasBlock() only needs the dataMap (passed through the constructor) and the
|
||||
// block size, so we can exercise it without a live NBD connection.
|
||||
describe('NbdDisk.hasBlock', () => {
|
||||
it('reports allocated and unallocated blocks correctly', () => {
|
||||
const dataMap = [
|
||||
{ type: 0, offset: 0, length: SOURCE_BLOCK_SIZE }, // block 0
|
||||
{ type: 0, offset: 5 * SOURCE_BLOCK_SIZE, length: SOURCE_BLOCK_SIZE }, // block 5
|
||||
]
|
||||
const disk = new NbdDisk({}, SOURCE_BLOCK_SIZE, { dataMap })
|
||||
|
||||
assert.strictEqual(disk.hasBlock(0), true)
|
||||
assert.strictEqual(disk.hasBlock(1), false)
|
||||
assert.strictEqual(disk.hasBlock(4), false)
|
||||
assert.strictEqual(disk.hasBlock(5), true)
|
||||
assert.strictEqual(disk.hasBlock(6), false)
|
||||
})
|
||||
|
||||
it('handles repeated and out-of-order queries with the resume cursor', () => {
|
||||
const dataMap = [
|
||||
{ type: 0, offset: 0, length: SOURCE_BLOCK_SIZE }, // block 0
|
||||
{ type: 0, offset: 5 * SOURCE_BLOCK_SIZE, length: SOURCE_BLOCK_SIZE }, // block 5
|
||||
]
|
||||
const disk = new NbdDisk({}, SOURCE_BLOCK_SIZE, { dataMap })
|
||||
|
||||
// repeated indexes (the qcow2 path queries each 2MB block ~32 times as it
|
||||
// walks 64KB clusters) must return a stable answer
|
||||
assert.strictEqual(disk.hasBlock(5), true)
|
||||
assert.strictEqual(disk.hasBlock(5), true)
|
||||
assert.strictEqual(disk.hasBlock(6), false)
|
||||
assert.strictEqual(disk.hasBlock(6), false)
|
||||
|
||||
// querying backwards must still be correct (falls back to a full scan)
|
||||
assert.strictEqual(disk.hasBlock(0), true)
|
||||
assert.strictEqual(disk.hasBlock(5), true)
|
||||
})
|
||||
|
||||
it('invalidates the cursor on a backward miss (no stale skip)', () => {
|
||||
const dataMap = [
|
||||
{ type: 0, offset: 3 * SOURCE_BLOCK_SIZE, length: SOURCE_BLOCK_SIZE }, // block 3
|
||||
{ type: 0, offset: 10 * SOURCE_BLOCK_SIZE, length: SOURCE_BLOCK_SIZE }, // block 10
|
||||
]
|
||||
const disk = new NbdDisk({}, SOURCE_BLOCK_SIZE, { dataMap })
|
||||
|
||||
assert.strictEqual(disk.hasBlock(10), true) // forward hit: cursor parks on the high extent
|
||||
assert.strictEqual(disk.hasBlock(1), false) // backward miss: must invalidate the cursor
|
||||
assert.strictEqual(disk.hasBlock(3), true) // lower extent must not be skipped
|
||||
})
|
||||
|
||||
it('throws on overlapping ranges (would break the resume cursor)', () => {
|
||||
const dataMap = [
|
||||
{ type: 0, offset: 0, length: SOURCE_BLOCK_SIZE },
|
||||
{ type: 0, offset: SOURCE_BLOCK_SIZE / 2, length: SOURCE_BLOCK_SIZE }, // overlaps the previous range
|
||||
]
|
||||
assert.throws(() => new NbdDisk({}, SOURCE_BLOCK_SIZE, { dataMap }), /overlapping ranges/)
|
||||
})
|
||||
|
||||
it('merges touching ranges and drops zero-length / non type-0 entries', () => {
|
||||
const dataMap = [
|
||||
{ type: 0, offset: 2 * SOURCE_BLOCK_SIZE, length: SOURCE_BLOCK_SIZE }, // [2, 3)
|
||||
{ type: 0, offset: 0, length: SOURCE_BLOCK_SIZE / 2 }, // [0, .5)
|
||||
{ type: 0, offset: SOURCE_BLOCK_SIZE, length: SOURCE_BLOCK_SIZE }, // [1, 2)
|
||||
{ type: 0, offset: SOURCE_BLOCK_SIZE / 2, length: SOURCE_BLOCK_SIZE / 2 }, // [.5, 1), touches [0, .5)
|
||||
{ type: 1, offset: 10 * SOURCE_BLOCK_SIZE, length: SOURCE_BLOCK_SIZE }, // wrong type: ignored
|
||||
{ type: 0, offset: 7 * SOURCE_BLOCK_SIZE, length: 0 }, // zero length: ignored
|
||||
]
|
||||
const disk = new NbdDisk({}, SOURCE_BLOCK_SIZE, { dataMap })
|
||||
|
||||
assert.strictEqual(disk.hasBlock(0), true)
|
||||
assert.strictEqual(disk.hasBlock(1), true)
|
||||
assert.strictEqual(disk.hasBlock(2), true)
|
||||
assert.strictEqual(disk.hasBlock(3), false)
|
||||
assert.strictEqual(disk.hasBlock(7), false) // zero-length range dropped
|
||||
assert.strictEqual(disk.hasBlock(10), false) // non type-0 range dropped
|
||||
})
|
||||
})
|
||||
|
||||
describe('NbdDisk.getBlockIndexesCount', () => {
|
||||
const cases = {
|
||||
'aligned, disjoint blocks': [
|
||||
{ type: 0, offset: 0, length: SOURCE_BLOCK_SIZE }, // block 0
|
||||
{ type: 0, offset: 5 * SOURCE_BLOCK_SIZE, length: SOURCE_BLOCK_SIZE }, // block 5
|
||||
],
|
||||
'a range spanning several blocks': [
|
||||
{ type: 0, offset: SOURCE_BLOCK_SIZE / 2, length: 3 * SOURCE_BLOCK_SIZE }, // blocks 0,1,2,3
|
||||
],
|
||||
'two disjoint extents sharing block 0 (needs dedup)': [
|
||||
{ type: 0, offset: 0, length: SOURCE_BLOCK_SIZE / 2 }, // [0, .5) => block 0
|
||||
{ type: 0, offset: 3 * (SOURCE_BLOCK_SIZE / 4), length: SOURCE_BLOCK_SIZE }, // [.75, 1.75) => blocks 0,1
|
||||
],
|
||||
'touching sub-block fragments': [
|
||||
{ type: 0, offset: 0, length: SOURCE_BLOCK_SIZE / 2 },
|
||||
{ type: 0, offset: SOURCE_BLOCK_SIZE / 2, length: SOURCE_BLOCK_SIZE / 2 },
|
||||
{ type: 0, offset: SOURCE_BLOCK_SIZE, length: SOURCE_BLOCK_SIZE },
|
||||
],
|
||||
empty: [],
|
||||
}
|
||||
|
||||
for (const [name, dataMap] of Object.entries(cases)) {
|
||||
it(`matches getBlockIndexes().length: ${name}`, () => {
|
||||
const disk = new NbdDisk({}, SOURCE_BLOCK_SIZE, { dataMap })
|
||||
assert.strictEqual(disk.getBlockIndexesCount(), disk.getBlockIndexes().length)
|
||||
})
|
||||
}
|
||||
|
||||
it('matches getBlockIndexes().length on the large sparse map', () => {
|
||||
const virtualSize = Math.floor(3.5 * TiB)
|
||||
const NB_RANGES = 113528
|
||||
const dataMap = []
|
||||
for (let i = 0; i < NB_RANGES; i++) {
|
||||
dataMap.push({ type: 0, offset: Math.floor((i / NB_RANGES) * virtualSize), length: CLUSTER_SIZE })
|
||||
}
|
||||
const disk = new NbdDisk({}, SOURCE_BLOCK_SIZE, { dataMap })
|
||||
assert.strictEqual(disk.getBlockIndexesCount(), disk.getBlockIndexes().length)
|
||||
})
|
||||
})
|
||||
@@ -13,7 +13,7 @@
|
||||
"url": "https://vates.fr"
|
||||
},
|
||||
"license": "ISC",
|
||||
"version": "3.4.0",
|
||||
"version": "3.5.0",
|
||||
"engines": {
|
||||
"node": ">=14.0"
|
||||
},
|
||||
@@ -22,7 +22,7 @@
|
||||
"@vates/async-each": "^1.0.3",
|
||||
"@vates/read-chunk": "^1.2.1",
|
||||
"@xen-orchestra/async-map": "^0.1.3",
|
||||
"@xen-orchestra/disk-transform": "^1.3.2",
|
||||
"@xen-orchestra/disk-transform": "^1.3.3",
|
||||
"@xen-orchestra/log": "^0.7.2",
|
||||
"promise-toolbox": "^0.21.0",
|
||||
"xen-api": "^4.8.0"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@vates/types",
|
||||
"private": false,
|
||||
"version": "1.29.0",
|
||||
"version": "1.30.1",
|
||||
"main": "./dist/index.mjs",
|
||||
"exports": {
|
||||
".": {
|
||||
|
||||
@@ -411,7 +411,7 @@ export interface Xapi {
|
||||
): Promise<Readable & { length?: number }>
|
||||
VDI_importContent(
|
||||
vdiRef: XenApiVdi['$ref'],
|
||||
stream: Readable,
|
||||
stream: Readable | Buffer,
|
||||
opts: { cancelToken?: unknown; format: SUPPORTED_VDI_FORMAT }
|
||||
): Promise<void>
|
||||
VIF_create(
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.19.0",
|
||||
"@vates/types": "^1.29.0",
|
||||
"@vates/types": "^1.30.1",
|
||||
"rimraf": "^6.0.1",
|
||||
"typescript": "~5.6",
|
||||
"typescript-eslint": "^8.61.0"
|
||||
|
||||
@@ -16,6 +16,7 @@ export default {
|
||||
smart: true,
|
||||
},
|
||||
'restart-toolstack': true,
|
||||
'scan-pifs': true,
|
||||
shutdown: {
|
||||
clean: true,
|
||||
emergency: true,
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@xen-orchestra/backup-archive",
|
||||
"version": "1.1.0",
|
||||
"version": "1.1.1",
|
||||
"description": "Helper to handle generic backup archives",
|
||||
"license": "ISC",
|
||||
"author": "",
|
||||
@@ -21,12 +21,12 @@
|
||||
"tar-stream": "^3.1.8",
|
||||
"@types/tar-stream": "^3.1.4",
|
||||
"tmp": "^0.2.1",
|
||||
"@vates/types": "^1.29.0"
|
||||
"@vates/types": "^1.30.1"
|
||||
},
|
||||
"dependencies": {
|
||||
"@xen-orchestra/log": "^0.7.1",
|
||||
"@xen-orchestra/fs": "^4.9.2",
|
||||
"@xen-orchestra/disk-transform": "^1.3.2",
|
||||
"@xen-orchestra/fs": "^4.9.3",
|
||||
"@xen-orchestra/disk-transform": "^1.3.3",
|
||||
"@vates/task": "0.7.0",
|
||||
"golike-defer": "0.5.1",
|
||||
"uuid": "^9.0.0",
|
||||
|
||||
@@ -44,9 +44,6 @@ export class RemoteDiskLineage {
|
||||
#activeDiskPaths: Set<string> = new Set()
|
||||
// Interrupted merges: normalized parent path { stateFilePath, chain }
|
||||
#interruptedMerges: Map<string, { stateFilePath: string; chain?: string[] }> = new Map()
|
||||
// Disks whose parent link is contradicted by the uuids: any merge chain containing one of them
|
||||
// crosses that link and is left alone
|
||||
#inconsistentParentLinks: Set<string> = new Set()
|
||||
|
||||
constructor(handler: RemoteHandlerAbstract, vdiDir: string, opts: ResolvedBackupCleanOptions) {
|
||||
this.#handler = handler
|
||||
@@ -97,11 +94,6 @@ export class RemoteDiskLineage {
|
||||
}
|
||||
|
||||
const uuidToPath = new Map<string, string>()
|
||||
// disk path: its own uuid / the uuid of the parent it claims, to check the chain links once
|
||||
// every disk has been read — a disk is closed as soon as it is scanned, and a parent may be
|
||||
// scanned after its child
|
||||
const uuidOf = new Map<string, string>()
|
||||
const claimedParentUuidOf = new Map<string, string>()
|
||||
for (const diskPath of this.#diskPaths) {
|
||||
let disk: RemoteDisk | undefined
|
||||
try {
|
||||
@@ -147,11 +139,9 @@ export class RemoteDiskLineage {
|
||||
}
|
||||
}
|
||||
uuidToPath.set(uuid, diskPath)
|
||||
uuidOf.set(diskPath, uuid)
|
||||
|
||||
if (disk.isDifferencing()) {
|
||||
const parentPath = disk.getParentPath()
|
||||
claimedParentUuidOf.set(diskPath, disk.getParentUuid())
|
||||
this.#parentOf.set(diskPath, parentPath)
|
||||
if (this.#childOf.has(parentPath)) {
|
||||
const error = new Error('this script does not support multiple children', {
|
||||
@@ -194,35 +184,6 @@ export class RemoteDiskLineage {
|
||||
if (!this.#diskPaths.has(parent) || this.#brokenDiskPaths.has(parent)) {
|
||||
this.#opts.logWarn('disk broken: parent missing or broken', { child, parent })
|
||||
propagateBroken(child)
|
||||
continue
|
||||
}
|
||||
|
||||
// A disk records the uuid of the parent it was chained onto, so a link whose uuids disagree
|
||||
// means the file at that path is not the parent this disk was built from — a rename or a
|
||||
// restore mixed up the directory. Detect it here rather than when the chain is opened: the
|
||||
// merge would fail with NOT_SUPPORTED, and that error aborts the whole clean of this VM
|
||||
// (asyncEach stops on the first error), so every other lineage would stop being merged and
|
||||
// cleaned as well, at every run.
|
||||
//
|
||||
// The link is only reported: the disks are readable and the backups referencing them are
|
||||
// still restorable, and since the parent links do not describe the real topology, deleting
|
||||
// anything here would be a guess. It needs a human to repair it, so the warning names both
|
||||
// disks and both uuids.
|
||||
//
|
||||
// Skipped for a parent under an interrupted merge: its footer already carries the uuid of the
|
||||
// child being merged into it, so the mismatch is expected and that merge must be resumed.
|
||||
if (!mergeParentPaths.has(parent)) {
|
||||
const claimedParentUuid = claimedParentUuidOf.get(child)
|
||||
const parentUuid = uuidOf.get(parent)
|
||||
if (claimedParentUuid !== undefined && parentUuid !== undefined && claimedParentUuid !== parentUuid) {
|
||||
this.#opts.logWarn('inconsistent chain, it will not be merged until repaired', {
|
||||
child,
|
||||
parent,
|
||||
parentUuidExpectedByChild: claimedParentUuid,
|
||||
parentUuid,
|
||||
})
|
||||
this.#inconsistentParentLinks.add(child)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -370,12 +331,7 @@ export class RemoteDiskLineage {
|
||||
await asyncEach(
|
||||
toMerge,
|
||||
async ({ chain, isResuming }) => {
|
||||
const merged = await limitedMergeChain([...chain], isResuming)
|
||||
if (merged === undefined) {
|
||||
// chain left untouched, its disks are still there
|
||||
return
|
||||
}
|
||||
const { finalDiskSize, mergeTargetPath } = merged
|
||||
const { finalDiskSize, mergeTargetPath } = await limitedMergeChain([...chain], isResuming)
|
||||
mergedSizes.set(mergeTargetPath, (mergedSizes.get(mergeTargetPath) ?? 0) + finalDiskSize)
|
||||
// parentPath alias deleted by parentDisk.rename(mergeTargetPath)
|
||||
// intermediates deleted by childDisk.unlink() when removeUnused=true
|
||||
@@ -405,27 +361,11 @@ export class RemoteDiskLineage {
|
||||
|
||||
/**
|
||||
* Merges ancestors into the active child at the end of the chain.
|
||||
* Returns the final size of the merge target and its path, or undefined when the chain was left
|
||||
* untouched.
|
||||
* Returns the final size of the merge target and its path.
|
||||
*/
|
||||
async #mergeChain(
|
||||
chain: string[],
|
||||
isResuming: boolean
|
||||
): Promise<{ finalDiskSize: number; mergeTargetPath: string } | undefined> {
|
||||
async #mergeChain(chain: string[], isResuming: boolean): Promise<{ finalDiskSize: number; mergeTargetPath: string }> {
|
||||
assert.ok(chain.length >= 2, `look to merge a chain shorter than 2 ${JSON.stringify(chain)}`)
|
||||
const parentPath = chain[0]
|
||||
|
||||
// A chain crossing a contradicted parent link cannot be merged: openDiskChain below refuses it,
|
||||
// and that error would abort the clean of the whole VM. Leave this chain as it is until someone
|
||||
// repairs it — every other chain of this directory is still merged and cleaned.
|
||||
//
|
||||
// An interrupted merge is exempt: the parent it was merging into already carries the uuid of its
|
||||
// child, so a mismatch is expected there and resuming is the way out of it.
|
||||
if (!isResuming && chain.some(path => this.#inconsistentParentLinks.has(path))) {
|
||||
this.#opts.logWarn('not merging an inconsistent disk chain', { chain: [...chain] })
|
||||
return undefined
|
||||
}
|
||||
|
||||
this.#opts.logInfo('merging disk chain', { chain: [...chain] }) // need a copy here to log full chain
|
||||
// The last disk in the chain is the active one that everything gets merged into
|
||||
const mergeTargetPath = chain.pop()!
|
||||
|
||||
@@ -7,9 +7,9 @@ import * as uuid from 'uuid'
|
||||
import { getHandler } from '@xen-orchestra/fs'
|
||||
import { pFromCallback } from 'promise-toolbox'
|
||||
// eslint-disable-next-line n/no-missing-import
|
||||
import { VmBackupDirectory } from './VmBackupDirectory.mjs'
|
||||
import { RemoteVhdDisk } from './disks/RemoteVhdDisk.mjs'
|
||||
import { MergeRemoteDisk } from './disks/MergeRemoteDisk.mjs'
|
||||
import { VmBackupDirectory } from '../dist/VmBackupDirectory.mjs'
|
||||
import { RemoteVhdDisk } from '../dist/disks/RemoteVhdDisk.mjs'
|
||||
import { MergeRemoteDisk } from '../dist/disks/MergeRemoteDisk.mjs'
|
||||
import { VHDFOOTER, VHDHEADER } from './tests.fixtures.mjs'
|
||||
import { VhdFile, Constants, VhdDirectory, VhdAbstract } from 'vhd-lib'
|
||||
import { dirname, basename } from 'node:path'
|
||||
@@ -609,92 +609,6 @@ test('it resumes an interrupted merge without chain field', async () => {
|
||||
assert.equal(remainingVhds.includes('child.vhd'), true)
|
||||
})
|
||||
|
||||
test('it still resumes an interrupted merge, whose parent already carries the uuid of its child', async () => {
|
||||
// mergeMetadata() copies the child's uuid onto the parent before the cleanup step, so an
|
||||
// interrupted merge legitimately leaves a parent whose uuid contradicts what its child claims.
|
||||
// That must not be mistaken for a corrupted chain: resuming is the way out of it.
|
||||
const ancestor = await generateVhd(`${basePath}/ancestor.vhd`, { blocks: [0, 1] })
|
||||
await generateVhd(`${basePath}/child.vhd`, {
|
||||
header: { parentUnicodeName: 'ancestor.vhd', parentUuid: ancestor.footer.uuid },
|
||||
blocks: [2, 3],
|
||||
})
|
||||
await handler.writeFile(
|
||||
`${rootPath}/metadata.json`,
|
||||
JSON.stringify({ mode: 'delta', size: 12000, vhds: [`${relativePath}/child.vhd`] })
|
||||
)
|
||||
|
||||
// Interrupt the merge in its cleanup step, after mergeMetadata() rewrote the ancestor's footer
|
||||
// with the child's uuid and before the child is removed.
|
||||
const parent = new RemoteVhdDisk({ handler, path: `${basePath}/ancestor.vhd` })
|
||||
const child = new RemoteVhdDisk({ handler, path: `${basePath}/child.vhd` })
|
||||
await parent.init({ force: false })
|
||||
await child.init({ force: false })
|
||||
child.unlink = async () => {
|
||||
throw new Error('simulated interruption')
|
||||
}
|
||||
const merger = new MergeRemoteDisk(handler, { removeUnused: true, writeStateDelay: 0 })
|
||||
await assert.rejects(merger.merge(parent, child), /simulated interruption/)
|
||||
|
||||
const afterCrash = await handler.list(basePath)
|
||||
assert.ok(afterCrash.includes('.ancestor.vhd.merge.json'), 'an interrupted-merge state file should remain')
|
||||
assert.ok(afterCrash.includes('child.vhd'), 'the child should still be there')
|
||||
|
||||
const logged = []
|
||||
await VmBackupDirectory.cleanVm(handler, rootPath, {
|
||||
remove: true,
|
||||
merge: true,
|
||||
logInfo: () => {},
|
||||
logWarn: message => logged.push(message),
|
||||
})
|
||||
|
||||
assert.equal(logged.includes('not merging an inconsistent disk chain'), false, 'the resume must not be declined')
|
||||
const remaining = await handler.list(basePath)
|
||||
assert.equal(remaining.includes('.ancestor.vhd.merge.json'), false, 'state file removed after successful resume')
|
||||
assert.equal(remaining.includes('ancestor.vhd'), false, 'ancestor consolidated into the merge target')
|
||||
assert.equal(remaining.includes('child.vhd'), true, 'merge target remains')
|
||||
})
|
||||
|
||||
test('it does not merge a chain whose parent uuid is contradicted, and still cleans the rest', async () => {
|
||||
// orphan <- child, but the child claims a parent uuid that is not the orphan's: the file at that
|
||||
// path is not the disk it was built from, so the chain cannot be opened, let alone merged.
|
||||
const orphan = await generateVhd(`${basePath}/orphan.vhd`, { blocks: [0, 1] })
|
||||
await generateVhd(`${basePath}/child.vhd`, {
|
||||
header: {
|
||||
parentUnicodeName: 'orphan.vhd',
|
||||
parentUuid: uniqueIdBuffer(), // NOT orphan.footer.uuid
|
||||
},
|
||||
blocks: [2],
|
||||
})
|
||||
|
||||
// an unrelated VDI directory, with one active disk and one plain orphan to collect
|
||||
await generateVhd(`${basePath2}/keep.vhd`)
|
||||
await generateVhd(`${basePath2}/collectme.vhd`)
|
||||
|
||||
await handler.writeFile(
|
||||
`${rootPath}/metadata.json`,
|
||||
JSON.stringify({
|
||||
mode: 'delta',
|
||||
size: 12000,
|
||||
vhds: [`${relativePath}/child.vhd`, `${relativePath2}/keep.vhd`],
|
||||
})
|
||||
)
|
||||
|
||||
const logged = []
|
||||
const logWarn = message => logged.push(message)
|
||||
await VmBackupDirectory.cleanVm(handler, rootPath, { remove: true, merge: true, logInfo: () => {}, logWarn })
|
||||
|
||||
assert.equal(logged.includes('inconsistent chain, it will not be merged until repaired'), true)
|
||||
assert.equal(logged.includes('not merging an inconsistent disk chain'), true)
|
||||
|
||||
// nothing of the inconsistent chain was merged nor deleted: repairing it is a human decision
|
||||
const remainingVhds = await handler.list(basePath)
|
||||
assert.deepEqual(remainingVhds.sort(), ['child.vhd', 'orphan.vhd'])
|
||||
assert.notEqual(orphan.footer.uuid, undefined)
|
||||
|
||||
// the rest of the VM was still cleaned: the unreferenced disk of the other VDI is gone
|
||||
assert.deepEqual(await handler.list(basePath2), ['keep.vhd'])
|
||||
})
|
||||
|
||||
// each of the vhd can be a file, a directory, an alias to a file or an alias to a directory
|
||||
// the message and resulting files should be identical to the output with vhd files which is tested independently
|
||||
describe('tests multiple combination ', { concurrency: 1 }, () => {
|
||||
|
||||
@@ -8,8 +8,8 @@
|
||||
"dependencies": {
|
||||
"@vates/async-each": "^1.0.3",
|
||||
"@xen-orchestra/async-map": "^0.1.3",
|
||||
"@xen-orchestra/backups": "^0.73.8",
|
||||
"@xen-orchestra/fs": "^4.9.2",
|
||||
"@xen-orchestra/backups": "^0.73.10",
|
||||
"@xen-orchestra/fs": "^4.9.3",
|
||||
"filenamify": "^6.0.0",
|
||||
"getopts": "^2.2.5",
|
||||
"lodash": "^4.18.0",
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { strict as assert } from 'node:assert'
|
||||
import test from 'node:test'
|
||||
import { execFile } from 'node:child_process'
|
||||
import { copyFile, mkdtemp, rm } from 'node:fs/promises'
|
||||
import { copyFile, mkdtemp, rm, writeFile } from 'node:fs/promises'
|
||||
import { Stream } from 'node:stream'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { promisify } from 'node:util'
|
||||
@@ -39,6 +40,37 @@ async function createLvmImage(imagePath, vgName, lvName) {
|
||||
})
|
||||
}
|
||||
|
||||
// xo-proxy answers this stream through Koa, which pipes only bodies passing `instanceof Stream`
|
||||
// and JSON-serializes anything else: node-tar >= 7 returns a duck-typed (Minipass) stream, which
|
||||
// silently turned a proxied file restore into a JSON dump of the tar object. Every format must
|
||||
// resolve with a real node stream.
|
||||
test('fetchPartitionFiles resolves with a node:stream for every format', async t => {
|
||||
const tmp = await mkdtemp(join(tmpdir(), 'xo-flr-fetch-'))
|
||||
t.after(() => rm(tmp, { recursive: true, force: true }))
|
||||
await writeFile(join(tmp, 'file.txt'), 'hello')
|
||||
|
||||
const adapter = new RemoteAdapter({})
|
||||
// at this point of a real restore the partition is already mounted
|
||||
adapter.getPartition = Disposable.factory(async function* () {
|
||||
yield tmp
|
||||
})
|
||||
|
||||
for (const [format, magic] of [
|
||||
['tgz', Buffer.from([0x1f, 0x8b])],
|
||||
['zip', Buffer.from('PK')],
|
||||
]) {
|
||||
const stream = await adapter.fetchPartitionFiles('disk', 'partition', ['/file.txt'], format)
|
||||
assert.ok(stream instanceof Stream, `${format}: expected a node:stream instance`)
|
||||
|
||||
const chunks = []
|
||||
for await (const chunk of stream) {
|
||||
chunks.push(chunk)
|
||||
}
|
||||
const archive = Buffer.concat(chunks)
|
||||
assert.deepEqual(archive.subarray(0, magic.length), magic, `${format}: unexpected archive header`)
|
||||
}
|
||||
})
|
||||
|
||||
test('LVM file-restore against real losetup/dmsetup/lvm', { skip }, async t => {
|
||||
const tmp = await mkdtemp(join(tmpdir(), 'xo-flr-'))
|
||||
const adapter = new RemoteAdapter({})
|
||||
|
||||
@@ -12,6 +12,7 @@ import { compose } from '@vates/compose'
|
||||
import { createLogger } from '@xen-orchestra/log'
|
||||
import { deduped } from '@vates/disposable/deduped.js'
|
||||
import { randomBytes } from 'node:crypto'
|
||||
import { Readable } from 'node:stream'
|
||||
import { join, resolve } from 'node:path'
|
||||
import { execFile } from 'child_process'
|
||||
import { finished } from 'node:stream/promises'
|
||||
@@ -297,7 +298,15 @@ export const fileRestoreMethods = {
|
||||
// simultaneous reads. Those saturate the libuv threadpool and starve
|
||||
// the underlying vhd/CIFS reads NTFS-3g depends on (FUSE-on-FUSE
|
||||
// threadpool deadlock). Serializing keeps a worker free for them.
|
||||
outputStream = tar.c({ cwd: path, gzip: true, jobs: 1 }, paths.map(makeRelative))
|
||||
const pack = tar.c({ cwd: path, gzip: true, jobs: 1 }, paths.map(makeRelative))
|
||||
|
||||
// node-tar >= 7 returns a Minipass stream: it has `pipe()` but is not a `node:stream`
|
||||
// instance. xo-proxy serves this stream through Koa, which pipes only bodies passing
|
||||
// `instanceof Stream` and JSON-serializes anything else — so a file restore through a
|
||||
// proxy answered a JSON dump of the tar object instead of the archive. Wrapping it in a
|
||||
// real node stream also propagates tar errors to the consumer and aborts the tar job
|
||||
// when the client disconnects.
|
||||
outputStream = Readable.from(pack, { objectMode: false })
|
||||
resolve(outputStream)
|
||||
} else if (format === 'zip') {
|
||||
const zip = new ZipFile()
|
||||
|
||||
@@ -1,10 +1,13 @@
|
||||
import { asyncMap } from '@xen-orchestra/async-map'
|
||||
import { createLogger } from '@xen-orchestra/log'
|
||||
import { Task } from '@vates/task'
|
||||
|
||||
import { DIR_XO_POOL_METADATA_BACKUPS } from '../RemoteAdapter.mjs'
|
||||
import { forkStreamUnpipe } from './_forkStreamUnpipe.mjs'
|
||||
import { formatFilenameDate } from '../_filenameDate.mjs'
|
||||
|
||||
const { debug } = createLogger('xo:backups:PoolMetadataBackup')
|
||||
|
||||
export const PATH_DB_DUMP = '/pool/xmldbdump'
|
||||
|
||||
export class PoolMetadataBackup {
|
||||
@@ -31,7 +34,22 @@ export class PoolMetadataBackup {
|
||||
const poolDir = `${DIR_XO_POOL_METADATA_BACKUPS}/${schedule.id}/${pool.$id}`
|
||||
const dir = `${poolDir}/${formatFilenameDate(timestamp)}`
|
||||
|
||||
const tasks = Object.values(pool.$xapi.objects.indexes.type.task ?? {})
|
||||
const pendingTasks = tasks.filter(task => task.status === 'pending')
|
||||
debug('pool tasks before export', {
|
||||
total: tasks.length,
|
||||
pending: pendingTasks.length,
|
||||
oldestPendingCreated: pendingTasks.map(task => task.created).sort()[0],
|
||||
})
|
||||
|
||||
const stream = (await this._exportPoolMetadata()).body
|
||||
const startedAt = Date.now()
|
||||
let bytes = 0
|
||||
stream.once('data', () => debug('first byte received', { afterMs: Date.now() - startedAt }))
|
||||
stream.on('data', chunk => (bytes += chunk.length))
|
||||
stream.once('end', () => debug('stream ended', { bytes, durationMs: Date.now() - startedAt }))
|
||||
stream.once('error', error => debug('stream errored', { error, bytes, durationMs: Date.now() - startedAt }))
|
||||
|
||||
const fileName = `${dir}/data`
|
||||
|
||||
const metadata = JSON.stringify(
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
"type": "git",
|
||||
"url": "https://github.com/vatesfr/xen-orchestra.git"
|
||||
},
|
||||
"version": "0.73.8",
|
||||
"version": "0.73.10",
|
||||
"engines": {
|
||||
"node": ">=14.18"
|
||||
},
|
||||
@@ -27,17 +27,17 @@
|
||||
"@vates/disposable": "^0.1.6",
|
||||
"@vates/fuse-vhd": "^2.1.3",
|
||||
"@vates/generator-toolbox": "^1.1.3",
|
||||
"@vates/nbd-client": "^3.4.0",
|
||||
"@vates/nbd-client": "^3.5.0",
|
||||
"@vates/parse-duration": "^0.1.1",
|
||||
"@vates/task": "^0.7.0",
|
||||
"@vates/types": "^1.29.0",
|
||||
"@vates/types": "^1.30.1",
|
||||
"@xen-orchestra/async-map": "^0.1.3",
|
||||
"@xen-orchestra/disk-transform": "^1.3.2",
|
||||
"@xen-orchestra/fs": "^4.9.2",
|
||||
"@xen-orchestra/disk-transform": "^1.3.3",
|
||||
"@xen-orchestra/fs": "^4.9.3",
|
||||
"@xen-orchestra/log": "^0.7.2",
|
||||
"@xen-orchestra/qcow2": "^1.3.1",
|
||||
"@xen-orchestra/template": "^0.1.1",
|
||||
"@xen-orchestra/backup-archive": "^1.1.0",
|
||||
"@xen-orchestra/backup-archive": "^1.1.1",
|
||||
"app-conf": "^3.0.0",
|
||||
"compare-versions": "^6.0.0",
|
||||
"d3-time-format": "^4.1.0",
|
||||
@@ -67,7 +67,7 @@
|
||||
"typescript": "^5.9.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@xen-orchestra/xapi": "^8.10.0"
|
||||
"@xen-orchestra/xapi": "^8.10.2"
|
||||
},
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"author": {
|
||||
|
||||
@@ -20,10 +20,10 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@vates/async-each": "^1.0.3",
|
||||
"@xen-orchestra/backups": "^0.73.8",
|
||||
"@xen-orchestra/backup-archive": "^1.1.0",
|
||||
"@xen-orchestra/disk-transform": "^1.3.2",
|
||||
"@xen-orchestra/fs": "^4.9.2",
|
||||
"@xen-orchestra/backups": "^0.73.10",
|
||||
"@xen-orchestra/backup-archive": "^1.1.1",
|
||||
"@xen-orchestra/disk-transform": "^1.3.3",
|
||||
"@xen-orchestra/fs": "^4.9.3",
|
||||
"@xen-orchestra/qcow2": "^1.3.1",
|
||||
"promise-toolbox": "^0.21.0",
|
||||
"vhd-lib": "^4.16.1"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@xen-orchestra/disk-transform",
|
||||
"version": "1.3.2",
|
||||
"version": "1.3.3",
|
||||
"main": "./dist/index.mjs",
|
||||
"license": "MIT",
|
||||
"private": false,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"private": false,
|
||||
"name": "@xen-orchestra/fs",
|
||||
"version": "4.9.2",
|
||||
"version": "4.9.3",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"description": "The File System for Xen Orchestra backups.",
|
||||
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/@xen-orchestra/fs",
|
||||
|
||||
@@ -441,7 +441,11 @@ export default class S3Handler extends RemoteHandlerAbstract {
|
||||
new DeleteObjectsCommand({
|
||||
Bucket: this.#bucket,
|
||||
Delete: {
|
||||
Objects: result.Contents ?? [],
|
||||
// only keep the key: `ETag` and `Size` are also part of `ObjectIdentifier`, where they
|
||||
// mean "delete only if it still matches", and passing the whole listed object would
|
||||
// serialize them in the request. Beyond making the deletion conditional, some
|
||||
// providers reject these elements with a `MalformedXML` error.
|
||||
Objects: (result.Contents ?? []).map(({ Key }) => ({ Key })),
|
||||
},
|
||||
})
|
||||
)
|
||||
|
||||
@@ -38,8 +38,7 @@ immutabilityDuration = "7d"
|
||||
|
||||
## CLI commands
|
||||
|
||||
- **`xo-immutable-remote`**: Start the watching daemon. Must be kept running to protect new backups reliably.
|
||||
- **`xo-lift-remote-immutability`**: Manually trigger a lifting pass. If `liftEvery` is set in the config, the process continues running and repeats the check on that interval.
|
||||
- **`xo-immutable-remote`**: Start the watching daemon. Must be kept running to protect new backups reliably. It lifts expired immutability on startup, then every `liftEvery`.
|
||||
|
||||
## How protection works
|
||||
|
||||
@@ -86,6 +85,8 @@ The expiry reference is the **datetime in the filename**, not the file's `mtime`
|
||||
|
||||
On the **first lift run after startup**, all backup files are scanned unconditionally (full scan). This catches orphaned immutable files left by a previous partial or interrupted lock. Subsequent runs use a fast-path: only backups whose `.json` sentinel is currently immutable are processed.
|
||||
|
||||
The first run also walks the disk directories (`xo-vm-backups/<vmUUID>/vdis/<jobId>/<vdiId>/`) directly and lifts any expired disk found there, still using the datetime in its own filename. Both the locking and the regular lifting name a backup's disks from its `<datetime>.json`, so a disk stops being reachable that way once XO's retention has deleted that json — or once a merge has renamed the disk, since the surviving `data/<datetime>.vhd` then carries the datetime of the older backup its blocks came from. Such a disk would otherwise stay immutable forever, and an immutable disk prevents XO from ever merging or deleting the backups of that VDI.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Some files are still immutable after the duration expired
|
||||
@@ -113,8 +114,10 @@ If one or a few VM had an issue and need manual cleanup, you can manually lift t
|
||||
4. As root on the file server, run:
|
||||
```bash
|
||||
chattr +i /path/to/remote/on/fileserver/xo-vm-backups/<vm uuid>/*.json
|
||||
chattr +i -R /path/to/remote/on/fileserver/xo-vm-backups/<vm uuid>/vdis/
|
||||
chattr +i -R /path/to/remote/on/fileserver/xo-vm-backups/<vm uuid>/vdis/*/*/*.vhd
|
||||
chattr +i -R /path/to/remote/on/fileserver/xo-vm-backups/<vm uuid>/vdis/*/*/data/*.vhd
|
||||
```
|
||||
Lock the disks, **not** the directories that hold them: `chattr +i -R …/vdis/` also locks `vdis`, the job and VDI directories and `data`, and an immutable directory rejects the files of the next backup, so every later run of that VM would fail. Depending on whether the remote uses VHD directories, one of the two commands above may report that it matched nothing.
|
||||
|
||||
Note that this VM will be mutable between step 2 and 4, it's up to you to document and test the backup after.
|
||||
|
||||
@@ -124,7 +127,7 @@ Change the setting. The next lift cycle will use the new duration; files already
|
||||
|
||||
### Reducing the immutability duration
|
||||
|
||||
Change the setting, then run `xo-lift-remote-immutability` to apply immediately, or wait for the next scheduled `liftEvery` cycle.
|
||||
Change the setting, then restart `xo-immutable-remote` to apply immediately, or wait for the next scheduled `liftEvery` cycle.
|
||||
|
||||
### Why are my incremental backups not marked as protected in XO?
|
||||
|
||||
|
||||
@@ -54,8 +54,7 @@ immutabilityDuration = "7d"
|
||||
|
||||
## CLI commands
|
||||
|
||||
- **`xo-immutable-remote`**: Start the watching daemon. Must be kept running to protect new backups reliably.
|
||||
- **`xo-lift-remote-immutability`**: Manually trigger a lifting pass. If `liftEvery` is set in the config, the process continues running and repeats the check on that interval.
|
||||
- **`xo-immutable-remote`**: Start the watching daemon. Must be kept running to protect new backups reliably. It lifts expired immutability on startup, then every `liftEvery`.
|
||||
|
||||
## How protection works
|
||||
|
||||
@@ -102,6 +101,8 @@ The expiry reference is the **datetime in the filename**, not the file's `mtime`
|
||||
|
||||
On the **first lift run after startup**, all backup files are scanned unconditionally (full scan). This catches orphaned immutable files left by a previous partial or interrupted lock. Subsequent runs use a fast-path: only backups whose `.json` sentinel is currently immutable are processed.
|
||||
|
||||
The first run also walks the disk directories (`xo-vm-backups/<vmUUID>/vdis/<jobId>/<vdiId>/`) directly and lifts any expired disk found there, still using the datetime in its own filename. Both the locking and the regular lifting name a backup's disks from its `<datetime>.json`, so a disk stops being reachable that way once XO's retention has deleted that json — or once a merge has renamed the disk, since the surviving `data/<datetime>.vhd` then carries the datetime of the older backup its blocks came from. Such a disk would otherwise stay immutable forever, and an immutable disk prevents XO from ever merging or deleting the backups of that VDI.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Some files are still immutable after the duration expired
|
||||
@@ -116,7 +117,7 @@ Restart `xo-immutable-remote`. The first lift run after startup always performs
|
||||
chattr -i -R /path/to/remote/on/fileserver/
|
||||
```
|
||||
|
||||
### Make one VM mutable again temporarly
|
||||
### Make one VM temporarily mutable again
|
||||
|
||||
If one or a few VM had an issue and need manual cleanup, you can manually lift the immutability for one VM.
|
||||
|
||||
@@ -125,14 +126,16 @@ If one or a few VM had an issue and need manual cleanup, you can manually lift t
|
||||
```bash
|
||||
chattr -i -R /path/to/remote/on/fileserver/xo-vm-backups/<vm uuid>
|
||||
```
|
||||
3. run the backup job, it will fix what is reparable and purge the non recoverable backups
|
||||
3. Run the backup job, it will fix what is repairable and purge the non recoverable backups
|
||||
4. As root on the file server, run:
|
||||
```bash
|
||||
chattr +i /path/to/remote/on/fileserver/xo-vm-backups/<vm uuid>/*.json
|
||||
chattr +i -R /path/to/remote/on/fileserver/xo-vm-backups/<vm uuid>/vdis/
|
||||
chattr +i -R /path/to/remote/on/fileserver/xo-vm-backups/<vm uuid>/vdis/*/*/*.vhd
|
||||
chattr +i -R /path/to/remote/on/fileserver/xo-vm-backups/<vm uuid>/vdis/*/*/data/*.vhd
|
||||
```
|
||||
Lock the disks, **not** the directories that hold them: `chattr +i -R …/vdis/` also locks `vdis`, the job and VDI directories and `data`, and an immutable directory rejects the files of the next backup, so every later run of that VM would fail. Depending on whether the remote uses VHD directories, one of the two commands above may report that it matched nothing.
|
||||
|
||||
Note that this VM will be mutable between step 2 and 4, it's up to you to document and test the backup after
|
||||
Note that this VM will be mutable between step 2 and 4, it's up to you to document and test the backup after.
|
||||
|
||||
### Increasing the immutability duration
|
||||
|
||||
@@ -140,7 +143,7 @@ Change the setting. The next lift cycle will use the new duration; files already
|
||||
|
||||
### Reducing the immutability duration
|
||||
|
||||
Change the setting, then run `xo-lift-remote-immutability` to apply immediately, or wait for the next scheduled `liftEvery` cycle.
|
||||
Change the setting, then restart `xo-immutable-remote` to apply immediately, or wait for the next scheduled `liftEvery` cycle.
|
||||
|
||||
### Why are my incremental backups not marked as protected in XO?
|
||||
|
||||
|
||||
@@ -16,13 +16,13 @@
|
||||
"xo-immutable-remote": "./dist/protectRemotes.mjs"
|
||||
},
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"version": "3.0.3",
|
||||
"version": "3.0.4",
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@vates/async-each": "^1.0.3",
|
||||
"@xen-orchestra/backups": "^0.73.8",
|
||||
"@xen-orchestra/backups": "^0.73.10",
|
||||
"@xen-orchestra/log": "^0.7.2",
|
||||
"app-conf": "^3.0.0",
|
||||
"execa": "^5.0.0",
|
||||
|
||||
@@ -8,17 +8,18 @@ export async function makeImmutable(dirPath: string): Promise<void> {
|
||||
// chattr processes all paths even when some are missing (it does not abort on the first
|
||||
// error), so every existing path is correctly lifted.
|
||||
//
|
||||
// Per-path "while trying to stat" messages (ENOENT) are silently ignored regardless of
|
||||
// locale — these are always expected for optional paths (.xva, .alias.vhd, …) that are
|
||||
// absent in delta backups. chattr localises the error description but "while trying to
|
||||
// stat" is always emitted in English, so we match on that suffix only.
|
||||
// Per-path "while trying to stat" messages (ENOENT) are silently ignored — these are always
|
||||
// expected for optional paths (.xva, .alias.vhd, …) that are absent in delta backups. chattr
|
||||
// translates that whole message, so it is run under `LC_ALL=C`: without it, every batch
|
||||
// containing an optional missing path fails on a localised system, which means no backup ever
|
||||
// gets locked there.
|
||||
//
|
||||
// Any other error (e.g. EAGAIN on NFS when the file is still open, permission denied) is
|
||||
// retried up to 3 times with a 1 s delay before being re-thrown.
|
||||
async function execChattrWithMissingFiles(args: string[]): Promise<void> {
|
||||
for (let attempt = 0; ; attempt++) {
|
||||
try {
|
||||
await execa('chattr', args)
|
||||
await execa('chattr', args, { env: { LC_ALL: 'C' } })
|
||||
return
|
||||
} catch (err) {
|
||||
const stderr = (err as ExecaError).stderr ?? ''
|
||||
|
||||
177
@xen-orchestra/immutable-backups/src/liftProtection.integ.mts
Normal file
177
@xen-orchestra/immutable-backups/src/liftProtection.integ.mts
Normal file
@@ -0,0 +1,177 @@
|
||||
import { describe, it } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
import fs from 'node:fs/promises'
|
||||
import path from 'node:path'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { rimraf } from 'rimraf'
|
||||
import execa from 'execa'
|
||||
|
||||
import * as Directory from './directory.mjs'
|
||||
import { liftRemoteImmutability } from './liftProtection.mjs'
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Constants
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
const ONE_DAY_MS = 24 * 60 * 60 * 1000
|
||||
|
||||
const VM_UUID = 'aaaaaaaa-0000-0000-0000-000000000001'
|
||||
const JOB_UUID = 'bbbbbbbb-0000-0000-0000-000000000001'
|
||||
const VDI_UUID = 'cccccccc-0000-0000-0000-000000000001'
|
||||
|
||||
/** Well past any reasonable immutabilityDuration. */
|
||||
const EXPIRED_DATE = '20240115T120000Z'
|
||||
/** Inside the window: the expiry reference is the datetime in the name, not the file's dates. */
|
||||
const RECENT_DATE = new Date().toISOString().replace(/[-:.]/g, '').slice(0, 15) + 'Z'
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Helpers
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
// Recursively lift all immutable flags inside `root`, then delete the tree.
|
||||
// Must be run as root since chattr requires elevated privileges.
|
||||
async function cleanupRoot(root: string): Promise<void> {
|
||||
try {
|
||||
await execa('chattr', ['-i', '-R', root])
|
||||
} catch (_err) {}
|
||||
await rimraf(root)
|
||||
}
|
||||
|
||||
async function makeRoot(): Promise<string> {
|
||||
return await fs.mkdtemp(path.join(tmpdir(), 'immut-lift-test-'))
|
||||
}
|
||||
|
||||
function vmDirOf(root: string): string {
|
||||
return path.join(root, 'xo-vm-backups', VM_UUID)
|
||||
}
|
||||
|
||||
function vdiDirOf(root: string): string {
|
||||
return path.join(vmDirOf(root), 'vdis', JOB_UUID, VDI_UUID)
|
||||
}
|
||||
|
||||
// Creates `vdis/<jobId>/<vdiId>/<datetime>.alias.vhd` plus the VHD directory it points at, the way
|
||||
// XO lays them out, and returns both paths along with one block file inside the VHD directory.
|
||||
async function writeDisk(root: string, datetime: string) {
|
||||
const vdiDir = vdiDirOf(root)
|
||||
const dataDir = path.join(vdiDir, 'data')
|
||||
const vhdDir = path.join(dataDir, `${datetime}.vhd`)
|
||||
const blockFile = path.join(vhdDir, 'blocks', '0', '0')
|
||||
|
||||
await fs.mkdir(path.dirname(blockFile), { recursive: true })
|
||||
await fs.writeFile(blockFile, 'block')
|
||||
await fs.writeFile(path.join(vhdDir, 'footer'), 'footer')
|
||||
|
||||
const alias = path.join(vdiDir, `${datetime}.alias.vhd`)
|
||||
await fs.writeFile(alias, path.relative(vdiDir, vhdDir))
|
||||
|
||||
return { alias, vhdDir, blockFile }
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Tests
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
describe('liftProtection/liftRemoteImmutability', async () => {
|
||||
it('lifts expired disks that no metadata json names any more', async () => {
|
||||
const root = await makeRoot()
|
||||
try {
|
||||
// Retention deletes the json first and leaves the disks to the next cleanVm, so nothing names
|
||||
// them: this is the state the sentinel-driven pass cannot reach.
|
||||
const { alias, vhdDir, blockFile } = await writeDisk(root, EXPIRED_DATE)
|
||||
await Directory.makeImmutableBatch([alias, vhdDir])
|
||||
|
||||
assert.strictEqual(await Directory.isImmutable(alias), true, 'alias should start immutable')
|
||||
assert.strictEqual(await Directory.isImmutable(vhdDir), true, 'VHD directory should start immutable')
|
||||
|
||||
await liftRemoteImmutability(root, ONE_DAY_MS, true)
|
||||
|
||||
assert.strictEqual(await Directory.isImmutable(alias), false, 'alias should be lifted')
|
||||
assert.strictEqual(await Directory.isImmutable(vhdDir), false, 'VHD directory should be lifted')
|
||||
// A VHD directory is useless to XO unless its blocks are writable too: the merge moves block
|
||||
// files out of it.
|
||||
assert.strictEqual(await Directory.isImmutable(blockFile), false, 'blocks should be lifted too')
|
||||
|
||||
// and the files are really usable again
|
||||
await fs.unlink(blockFile)
|
||||
await fs.unlink(alias)
|
||||
} finally {
|
||||
await cleanupRoot(root)
|
||||
}
|
||||
})
|
||||
|
||||
it('keeps disks inside the immutability window locked', async () => {
|
||||
const root = await makeRoot()
|
||||
try {
|
||||
const { alias, vhdDir, blockFile } = await writeDisk(root, RECENT_DATE)
|
||||
await Directory.makeImmutableBatch([alias, vhdDir])
|
||||
|
||||
await liftRemoteImmutability(root, ONE_DAY_MS, true)
|
||||
|
||||
assert.strictEqual(await Directory.isImmutable(alias), true, 'recent alias must stay immutable')
|
||||
assert.strictEqual(await Directory.isImmutable(vhdDir), true, 'recent VHD directory must stay immutable')
|
||||
assert.strictEqual(await Directory.isImmutable(blockFile), true, 'recent blocks must stay immutable')
|
||||
|
||||
await assert.rejects(fs.unlink(alias), { code: 'EPERM' })
|
||||
} finally {
|
||||
await cleanupRoot(root)
|
||||
}
|
||||
})
|
||||
|
||||
it('does not sweep the disk directories outside of a full scan', async () => {
|
||||
const root = await makeRoot()
|
||||
try {
|
||||
const { alias, vhdDir } = await writeDisk(root, EXPIRED_DATE)
|
||||
await Directory.makeImmutableBatch([alias, vhdDir])
|
||||
|
||||
await liftRemoteImmutability(root, ONE_DAY_MS, false)
|
||||
|
||||
assert.strictEqual(await Directory.isImmutable(alias), true, 'alias should be untouched')
|
||||
assert.strictEqual(await Directory.isImmutable(vhdDir), true, 'VHD directory should be untouched')
|
||||
} finally {
|
||||
await cleanupRoot(root)
|
||||
}
|
||||
})
|
||||
|
||||
it('lifts a disk whose name does not match the datetime of the backup referencing it', async () => {
|
||||
const root = await makeRoot()
|
||||
try {
|
||||
// Shape left by a merge: the alias of the recent backup points at the VHD directory of the
|
||||
// older one, whose blocks it now holds.
|
||||
const { vhdDir, blockFile } = await writeDisk(root, EXPIRED_DATE)
|
||||
const alias = path.join(vdiDirOf(root), `${RECENT_DATE}.alias.vhd`)
|
||||
await fs.writeFile(alias, path.relative(vdiDirOf(root), vhdDir))
|
||||
await fs.unlink(path.join(vdiDirOf(root), `${EXPIRED_DATE}.alias.vhd`))
|
||||
await Directory.makeImmutableBatch([alias, vhdDir])
|
||||
|
||||
await liftRemoteImmutability(root, ONE_DAY_MS, true)
|
||||
|
||||
// The VHD directory carries an expired datetime, so it is released and stays mergeable — the
|
||||
// reason mtime cannot be the reference: every merge would push it forward and it would never
|
||||
// expire.
|
||||
assert.strictEqual(await Directory.isImmutable(vhdDir), false, 'merged VHD directory should be lifted')
|
||||
assert.strictEqual(await Directory.isImmutable(blockFile), false, 'its blocks should be lifted')
|
||||
assert.strictEqual(await Directory.isImmutable(alias), true, 'the recent alias keeps its lock')
|
||||
} finally {
|
||||
await cleanupRoot(root)
|
||||
}
|
||||
})
|
||||
|
||||
it('still lifts through the metadata json when it is present', async () => {
|
||||
const root = await makeRoot()
|
||||
try {
|
||||
const { alias, vhdDir } = await writeDisk(root, EXPIRED_DATE)
|
||||
const json = path.join(vmDirOf(root), `${EXPIRED_DATE}.json`)
|
||||
await fs.writeFile(json, '{}')
|
||||
await Directory.makeImmutableBatch([json, alias, vhdDir])
|
||||
|
||||
// not a full scan: the fast path applies, and the json is immutable so it is picked up
|
||||
await liftRemoteImmutability(root, ONE_DAY_MS, false)
|
||||
|
||||
assert.strictEqual(await Directory.isImmutable(json), false, 'json should be lifted')
|
||||
assert.strictEqual(await Directory.isImmutable(alias), false, 'alias should be lifted')
|
||||
assert.strictEqual(await Directory.isImmutable(vhdDir), false, 'VHD directory should be lifted')
|
||||
} finally {
|
||||
await cleanupRoot(root)
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -118,6 +118,68 @@ async function liftExpiredVmBackups(root: string, immutabilityDuration: number,
|
||||
})
|
||||
}
|
||||
|
||||
// `liftExpiredVmBackups` names the files of a backup from the datetime of its `<datetime>.json`,
|
||||
// like the watcher does when locking them. A disk can outlive that name:
|
||||
//
|
||||
// - retention deletes the metadata json first and leaves the disks to the next `cleanVm`, so
|
||||
// nothing names them any more;
|
||||
// - a merge renames a disk, and the surviving `data/<datetime>.vhd` keeps the name of the older
|
||||
// backup its blocks came from.
|
||||
//
|
||||
// Such a disk would stay immutable forever — a full scan does not help, it only bypasses the
|
||||
// `isImmutable` fast-path — and an immutable disk blocks every future merge and deletion in its VDI
|
||||
// directory. So walk the VDI directories themselves and lift what is expired, using the datetime in
|
||||
// each entry's own name, which is the reference the other passes use too.
|
||||
//
|
||||
// Only runs on the first pass after startup: it recovers states that should not happen, and looking
|
||||
// hourly would not make it more effective.
|
||||
async function liftExpiredOrphanDisks(root: string, immutabilityDuration: number): Promise<void> {
|
||||
const threshold = Date.now() - immutabilityDuration
|
||||
const vmDirs = await listDirs(join(root, 'xo-vm-backups'))
|
||||
debug('scanning VDI directories for expired disks', { count: vmDirs.length })
|
||||
await asyncEach(vmDirs, async vmDir => {
|
||||
// disks live under `vdis/<jobId>/<vdiId>/`, so two levels of directories to walk first
|
||||
const jobDirs = await listDirs(join(vmDir, 'vdis'))
|
||||
const vdiDirs = (await Promise.all(jobDirs.map(jobDir => listDirs(jobDir)))).flat()
|
||||
|
||||
await asyncEach(vdiDirs, async vdiDir => {
|
||||
try {
|
||||
// `<datetime>.vhd` (flat VHD or alias) and `<datetime>.alias.vhd`
|
||||
const entries = await fsp.readdir(vdiDir, { withFileTypes: true })
|
||||
const candidates = entries.map(entry => join(vdiDir, entry.name))
|
||||
|
||||
// `data/<datetime>.vhd` VHD directories. They are locked recursively, but the attribute is
|
||||
// set on the directory itself too, so its own entry is enough to decide — no need to look
|
||||
// at the blocks inside.
|
||||
if (entries.some(entry => entry.name === 'data' && entry.isDirectory())) {
|
||||
const dataDir = join(vdiDir, 'data')
|
||||
candidates.push(...(await fsp.readdir(dataDir)).map(name => join(dataDir, name)))
|
||||
}
|
||||
|
||||
const expired: string[] = []
|
||||
for (const path of candidates) {
|
||||
// Entries without a datetime — `data` itself, merge state files — are left alone: there
|
||||
// is nothing to compare them to.
|
||||
const datetime = extractDatetime(basename(path))
|
||||
if (datetime === undefined) continue
|
||||
const backupTimestamp = parseDatetime(datetime)
|
||||
if (backupTimestamp === undefined || backupTimestamp > threshold) continue
|
||||
expired.push(path)
|
||||
}
|
||||
|
||||
if (expired.length === 0) return
|
||||
debug('lifting expired disks', { vdiDir, count: expired.length })
|
||||
// Recursive: a VHD directory must be released together with its blocks, and `-R` is a no-op
|
||||
// on the flat VHDs and aliases sharing the batch.
|
||||
await Directory.liftImmutabilityBatch(expired)
|
||||
} catch (err) {
|
||||
// `cleanVm` may be merging or deleting these files at the same time
|
||||
if (err.code !== 'ENOENT') warn('error lifting expired disks', { err, vdiDir })
|
||||
}
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
// Walk `xo-config-backups/<scheduleId>/<datetime>/metadata.json` files and
|
||||
// lift immutability on any backup directory whose metadata mtime is expired.
|
||||
async function liftExpiredConfigBackups(root: string, immutabilityDuration: number, fullScan: boolean): Promise<void> {
|
||||
@@ -180,6 +242,12 @@ export async function liftRemoteImmutability(
|
||||
liftExpiredConfigBackups(root, immutabilityDuration, fullScan),
|
||||
liftExpiredPoolBackups(root, immutabilityDuration, fullScan),
|
||||
])
|
||||
|
||||
// after the passes above: every disk still named by a metadata json has been handled, so this one
|
||||
// only has the leftovers to look at
|
||||
if (fullScan) {
|
||||
await liftExpiredOrphanDisks(root, immutabilityDuration)
|
||||
}
|
||||
}
|
||||
|
||||
// Lift immutability on all expired backups across every configured remote.
|
||||
|
||||
@@ -13,6 +13,7 @@ for (const [remoteId, remote] of Object.entries(remotes)) {
|
||||
}
|
||||
|
||||
info('setup watcher for immutability lifting')
|
||||
await liftImmutability(remotes).catch(error => warn('error while lifting immutability', error))
|
||||
setInterval(async () => {
|
||||
await liftImmutability(remotes).catch(error => warn('error while lifting immutability', error))
|
||||
}, liftEvery)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
# ChangeLog
|
||||
|
||||
## **next**
|
||||
## **0.24.0** (2026-07-30)
|
||||
|
||||
- [Host/dashboard] Switch CPU and RAM panels order to match Pool dashboard layout (PR [#10059](https://github.com/vatesfr/xen-orchestra/pull/10059))
|
||||
- Remove all "coming soon" disabled button placeholders from network, VM, and pool components (PR [#10068](https://github.com/vatesfr/xen-orchestra/pull/10068))
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@xen-orchestra/lite",
|
||||
"version": "0.23.0",
|
||||
"version": "0.24.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "GIT_HEAD=$(git rev-parse HEAD) vite",
|
||||
@@ -28,13 +28,13 @@
|
||||
"@types/file-saver": "^2.0.7",
|
||||
"@types/lodash-es": "^4.17.12",
|
||||
"@types/node": "^18.19.80",
|
||||
"@vates/types": "^1.29.0",
|
||||
"@vates/types": "^1.30.1",
|
||||
"@vitejs/plugin-vue": "^6.0.0",
|
||||
"@vue/tsconfig": "^0.9.0",
|
||||
"@vueuse/core": "^14.0.0",
|
||||
"@vueuse/math": "^14.0.0",
|
||||
"@vueuse/shared": "^14.0.0",
|
||||
"@xen-orchestra/web-core": "^0.57.0",
|
||||
"@xen-orchestra/web-core": "^0.58.0",
|
||||
"complex-matcher": "^1.1.1",
|
||||
"d3-time-format": "^4.1.0",
|
||||
"decorator-synchronized": "^0.6.0",
|
||||
|
||||
@@ -11,8 +11,7 @@
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
<VtsModalList />
|
||||
<VtsDrawerList />
|
||||
<VtsOverlayList />
|
||||
<VtsTooltipList />
|
||||
</template>
|
||||
|
||||
@@ -23,8 +22,7 @@ import AppNavigation from '@/components/AppNavigation.vue'
|
||||
import { useUnreachableHosts } from '@/composables/unreachable-hosts.composable'
|
||||
import { usePoolStore } from '@/stores/xen-api/pool.store'
|
||||
import { useXenApiStore } from '@/stores/xen-api.store'
|
||||
import VtsDrawerList from '@core/components/drawer/VtsDrawerList.vue'
|
||||
import VtsModalList from '@core/components/modal/VtsModalList.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'
|
||||
import { useUiStore } from '@core/stores/ui.store'
|
||||
|
||||
@@ -20,8 +20,7 @@ import UiActionButton from '@/components/ui/UiActionButton.vue'
|
||||
import UiFilter from '@/components/ui/UiFilter.vue'
|
||||
import UiFilterGroup from '@/components/ui/UiFilterGroup.vue'
|
||||
import type { Filters } from '@/types/filter'
|
||||
import { useModal } from '@core/packages/modal/use-modal.ts'
|
||||
import { computed } from 'vue'
|
||||
import { useOverlay } from '@core/packages/overlay/use-overlay.ts'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const { availableFilters } = defineProps<{
|
||||
@@ -36,18 +35,25 @@ const emit = defineEmits<{
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const openFilterModal = useModal((editedFilter?: string) => ({
|
||||
component: import('@/components/modals/CollectionFilterModal.vue'),
|
||||
props: {
|
||||
editedFilter,
|
||||
availableFilters: computed(() => availableFilters),
|
||||
const { open } = useOverlay({
|
||||
component: () => import('@/components/modals/CollectionFilterModal.vue'),
|
||||
events: {
|
||||
onCancel: true,
|
||||
},
|
||||
onConfirm: async newFilter => {
|
||||
if (editedFilter !== undefined) {
|
||||
emit('removeFilter', editedFilter)
|
||||
}
|
||||
})
|
||||
|
||||
emit('addFilter', newFilter)
|
||||
},
|
||||
}))
|
||||
function openFilterModal(editedFilter?: string) {
|
||||
return open({
|
||||
props: { editedFilter, availableFilters },
|
||||
events: {
|
||||
onConfirm: newFilter => {
|
||||
if (editedFilter !== undefined) {
|
||||
emit('removeFilter', editedFilter)
|
||||
}
|
||||
|
||||
emit('addFilter', newFilter)
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -24,8 +24,7 @@ import UiFilter from '@/components/ui/UiFilter.vue'
|
||||
import UiFilterGroup from '@/components/ui/UiFilterGroup.vue'
|
||||
import type { ActiveSorts, Sorts } from '@/types/sort'
|
||||
import VtsIcon from '@core/components/icon/VtsIcon.vue'
|
||||
import { useModal } from '@core/packages/modal/use-modal.ts'
|
||||
import { computed } from 'vue'
|
||||
import { useOverlay } from '@core/packages/overlay/use-overlay.ts'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const { availableSorts } = defineProps<{
|
||||
@@ -41,11 +40,17 @@ const emit = defineEmits<{
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const openFormModal = useModal({
|
||||
component: import('@/components/modals/CollectionSorterModal.vue'),
|
||||
props: { availableSorts: computed(() => availableSorts) },
|
||||
onConfirm: ({ property, isAscending }) => emit('addSort', property as TProperty, isAscending),
|
||||
const { open } = useOverlay({
|
||||
component: () => import('@/components/modals/CollectionSorterModal.vue'),
|
||||
events: {
|
||||
onConfirm: ({ property, isAscending }) => emit('addSort', property as TProperty, isAscending),
|
||||
onCancel: true,
|
||||
},
|
||||
})
|
||||
|
||||
function openFormModal() {
|
||||
return open({ props: { availableSorts } })
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
|
||||
@@ -87,7 +87,7 @@ import useSortedCollection from '@/composables/sorted-collection.composable'
|
||||
import type { PropParam } from '@/libs/story/story-param'
|
||||
import VtsIcon from '@core/components/icon/VtsIcon.vue'
|
||||
import { vTooltip } from '@core/directives/tooltip.directive'
|
||||
import { useModal } from '@core/packages/modal/use-modal.ts'
|
||||
import { useOverlay } from '@core/packages/overlay/use-overlay.ts'
|
||||
import { useVModel } from '@vueuse/core'
|
||||
import { toRef } from 'vue'
|
||||
|
||||
@@ -111,10 +111,16 @@ const params = useSortedCollection(toRef(props, 'params'), (p1, p2) => {
|
||||
|
||||
const model = useVModel(props, 'modelValue', emit)
|
||||
|
||||
const openRawValueModal = useModal((code: string) => ({
|
||||
component: import('@/components/modals/CodeHighlightModal.vue'),
|
||||
props: { code },
|
||||
}))
|
||||
const { open } = useOverlay({
|
||||
component: () => import('@/components/modals/CodeHighlightModal.vue'),
|
||||
events: {
|
||||
onClose: true,
|
||||
},
|
||||
})
|
||||
|
||||
function openRawValueModal(code: string) {
|
||||
return open({ props: { code } })
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
|
||||
<script lang="ts" setup>
|
||||
import FormInput from '@/components/form/FormInput.vue'
|
||||
import { useModal } from '@core/packages/modal/use-modal.ts'
|
||||
import { useOverlay } from '@core/packages/overlay/use-overlay.ts'
|
||||
import { useVModel } from '@vueuse/core'
|
||||
import { computed } from 'vue'
|
||||
|
||||
@@ -20,11 +20,17 @@ const model = useVModel(props, 'modelValue', emit)
|
||||
|
||||
const jsonValue = computed(() => JSON.stringify(model.value, undefined, 2))
|
||||
|
||||
const openJsonModal = useModal({
|
||||
component: import('@/components/modals/JsonEditorModal.vue'),
|
||||
props: { initialValue: computed(() => jsonValue.value) },
|
||||
onConfirm: newValue => {
|
||||
model.value = JSON.parse(newValue)
|
||||
const { open } = useOverlay({
|
||||
component: () => import('@/components/modals/JsonEditorModal.vue'),
|
||||
events: {
|
||||
onConfirm: (newValue: string) => {
|
||||
model.value = JSON.parse(newValue)
|
||||
},
|
||||
onCancel: true,
|
||||
},
|
||||
})
|
||||
|
||||
function openJsonModal() {
|
||||
return open({ props: { initialValue: jsonValue.value } })
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -1,16 +1,20 @@
|
||||
<template>
|
||||
<VtsModal accent="info" dismissible>
|
||||
<UiModal accent="info" @dismiss="emit('close')">
|
||||
<template #content>
|
||||
<CodeHighlight :code />
|
||||
</template>
|
||||
</VtsModal>
|
||||
</UiModal>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import CodeHighlight from '@/components/CodeHighlight.vue'
|
||||
import VtsModal from '@core/components/modal/VtsModal.vue'
|
||||
import UiModal from '@core/components/ui/modal/UiModal.vue'
|
||||
|
||||
defineProps<{
|
||||
code: any
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
close: []
|
||||
}>()
|
||||
</script>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<VtsModal accent="info" dismissible @confirm="emit('confirm', generatedFilter)">
|
||||
<UiModal accent="info" @dismiss="emit('cancel')" @confirm="emit('confirm', generatedFilter)">
|
||||
<template #content>
|
||||
<div class="rows">
|
||||
<CollectionFilterRow
|
||||
@@ -10,9 +10,9 @@
|
||||
@remove="removeNewFilter($event)"
|
||||
/>
|
||||
<div>
|
||||
<VtsModalButton variant="tertiary" @click="addNewFilter()">
|
||||
<VtsOverlayButton variant="tertiary" @click="addNewFilter()">
|
||||
{{ t('add-or') }}
|
||||
</VtsModalButton>
|
||||
</VtsOverlayButton>
|
||||
</div>
|
||||
</div>
|
||||
<div v-if="newFilters.some(filter => filter.isAdvanced)" class="available-properties">
|
||||
@@ -25,12 +25,12 @@
|
||||
</div>
|
||||
</template>
|
||||
<template #buttons>
|
||||
<VtsModalCancelButton />
|
||||
<VtsModalConfirmButton :disabled="!isFilterValid">
|
||||
<VtsOverlayCancelButton @click="emit('cancel')" />
|
||||
<VtsOverlayConfirmButton :disabled="!isFilterValid">
|
||||
{{ editedFilter ? t('action:update') : t('action:add') }}
|
||||
</VtsModalConfirmButton>
|
||||
</VtsOverlayConfirmButton>
|
||||
</template>
|
||||
</VtsModal>
|
||||
</UiModal>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
@@ -38,10 +38,10 @@ import CollectionFilterRow from '@/components/CollectionFilterRow.vue'
|
||||
import UiBadge from '@/components/ui/UiBadge.vue'
|
||||
import { getFilterIcon } from '@/libs/utils'
|
||||
import type { Filters, NewFilter } from '@/types/filter'
|
||||
import VtsModal from '@core/components/modal/VtsModal.vue'
|
||||
import VtsModalButton from '@core/components/modal/VtsModalButton.vue'
|
||||
import VtsModalCancelButton from '@core/components/modal/VtsModalCancelButton.vue'
|
||||
import VtsModalConfirmButton from '@core/components/modal/VtsModalConfirmButton.vue'
|
||||
import VtsOverlayButton from '@core/components/overlay/VtsOverlayButton.vue'
|
||||
import VtsOverlayCancelButton from '@core/components/overlay/VtsOverlayCancelButton.vue'
|
||||
import VtsOverlayConfirmButton from '@core/components/overlay/VtsOverlayConfirmButton.vue'
|
||||
import UiModal from '@core/components/ui/modal/UiModal.vue'
|
||||
import { Or, parse } from 'complex-matcher'
|
||||
import { computed, onMounted, ref } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
@@ -53,6 +53,7 @@ const { editedFilter } = defineProps<{
|
||||
|
||||
const emit = defineEmits<{
|
||||
confirm: [filter: string]
|
||||
cancel: []
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<VtsModal accent="info" dismissible @confirm="handleSubmit()">
|
||||
<UiModal accent="info" @dismiss="emit('cancel')" @confirm="handleSubmit()">
|
||||
<template #content>
|
||||
<div class="form-selects">
|
||||
<VtsSelect :id="sortPropertySelectId" accent="brand" />
|
||||
@@ -8,18 +8,18 @@
|
||||
</template>
|
||||
|
||||
<template #buttons>
|
||||
<VtsModalCancelButton />
|
||||
<VtsModalConfirmButton :disabled="!newSortProperty">{{ t('action:add') }}</VtsModalConfirmButton>
|
||||
<VtsOverlayCancelButton @click="emit('cancel')" />
|
||||
<VtsOverlayConfirmButton :disabled="!newSortProperty">{{ t('action:add') }}</VtsOverlayConfirmButton>
|
||||
</template>
|
||||
</VtsModal>
|
||||
</UiModal>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import type { NewSort, Sorts } from '@/types/sort'
|
||||
import VtsModal from '@core/components/modal/VtsModal.vue'
|
||||
import VtsModalCancelButton from '@core/components/modal/VtsModalCancelButton.vue'
|
||||
import VtsModalConfirmButton from '@core/components/modal/VtsModalConfirmButton.vue'
|
||||
import VtsOverlayCancelButton from '@core/components/overlay/VtsOverlayCancelButton.vue'
|
||||
import VtsOverlayConfirmButton from '@core/components/overlay/VtsOverlayConfirmButton.vue'
|
||||
import VtsSelect from '@core/components/select/VtsSelect.vue'
|
||||
import UiModal from '@core/components/ui/modal/UiModal.vue'
|
||||
import { useFormSelect } from '@core/packages/form-select'
|
||||
import { ref } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
@@ -30,6 +30,7 @@ const { availableSorts } = defineProps<{
|
||||
|
||||
const emit = defineEmits<{
|
||||
confirm: [sort: NewSort]
|
||||
cancel: []
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
@@ -1,23 +1,27 @@
|
||||
<template>
|
||||
<VtsModal accent="danger" dismissible icon="fa:exclamation-circle">
|
||||
<UiModal accent="danger" icon="fa:exclamation-circle" @dismiss="emit('close')" @confirm="emit('close')">
|
||||
<template #title>{{ t('invalid-field') }}</template>
|
||||
<template #content>{{ message }}</template>
|
||||
<template #buttons>
|
||||
<VtsModalConfirmButton>
|
||||
<VtsOverlayConfirmButton>
|
||||
{{ t('ok') }}
|
||||
</VtsModalConfirmButton>
|
||||
</VtsOverlayConfirmButton>
|
||||
</template>
|
||||
</VtsModal>
|
||||
</UiModal>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import VtsModal from '@core/components/modal/VtsModal.vue'
|
||||
import VtsModalConfirmButton from '@core/components/modal/VtsModalConfirmButton.vue'
|
||||
import VtsOverlayConfirmButton from '@core/components/overlay/VtsOverlayConfirmButton.vue'
|
||||
import UiModal from '@core/components/ui/modal/UiModal.vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
defineProps<{
|
||||
message: string
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
close: []
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
</script>
|
||||
|
||||
@@ -1,32 +1,32 @@
|
||||
<template>
|
||||
<VtsModal
|
||||
<UiModal
|
||||
:accent="isJsonValid ? 'info' : 'danger'"
|
||||
class="json-editor-modal"
|
||||
icon="fa:code"
|
||||
dismissible
|
||||
@confirm="handleSubmit()"
|
||||
@dismiss="emit('cancel')"
|
||||
>
|
||||
<template #content>
|
||||
<UiTextarea v-model="editedJson" accent="brand" class="modal-textarea" />
|
||||
<VtsModalButton variant="tertiary" @click="formatJson()">
|
||||
<VtsOverlayButton variant="tertiary" @click="formatJson()">
|
||||
{{ t('action:reformat') }}
|
||||
</VtsModalButton>
|
||||
</VtsOverlayButton>
|
||||
</template>
|
||||
|
||||
<template #buttons>
|
||||
<VtsModalCancelButton />
|
||||
<VtsModalConfirmButton :disabled="!isJsonValid">
|
||||
<VtsOverlayCancelButton @click="emit('cancel')" />
|
||||
<VtsOverlayConfirmButton :disabled="!isJsonValid">
|
||||
{{ t('action:save') }}
|
||||
</VtsModalConfirmButton>
|
||||
</VtsOverlayConfirmButton>
|
||||
</template>
|
||||
</VtsModal>
|
||||
</UiModal>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import VtsModal from '@core/components/modal/VtsModal.vue'
|
||||
import VtsModalButton from '@core/components/modal/VtsModalButton.vue'
|
||||
import VtsModalCancelButton from '@core/components/modal/VtsModalCancelButton.vue'
|
||||
import VtsModalConfirmButton from '@core/components/modal/VtsModalConfirmButton.vue'
|
||||
import VtsOverlayButton from '@core/components/overlay/VtsOverlayButton.vue'
|
||||
import VtsOverlayCancelButton from '@core/components/overlay/VtsOverlayCancelButton.vue'
|
||||
import VtsOverlayConfirmButton from '@core/components/overlay/VtsOverlayConfirmButton.vue'
|
||||
import UiModal from '@core/components/ui/modal/UiModal.vue'
|
||||
import UiTextarea from '@core/components/ui/text-area/UiTextarea.vue'
|
||||
import { computed, ref } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
@@ -37,6 +37,7 @@ const { initialValue } = defineProps<{
|
||||
|
||||
const emit = defineEmits<{
|
||||
confirm: [editedJson: string]
|
||||
cancel: []
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<VtsModal accent="danger" icon="object:host">
|
||||
<UiModal accent="danger" icon="object:host" @confirm="emit('confirm')">
|
||||
<template #title>{{ t('unreachable-hosts') }}</template>
|
||||
<template #content>
|
||||
<div class="description">
|
||||
@@ -13,25 +13,30 @@
|
||||
</div>
|
||||
</template>
|
||||
<template #buttons>
|
||||
<VtsModalCancelButton />
|
||||
<VtsModalConfirmButton>
|
||||
<VtsOverlayCancelButton @click="emit('cancel')" />
|
||||
<VtsOverlayConfirmButton>
|
||||
{{ t('unreachable-hosts-reload-page') }}
|
||||
</VtsModalConfirmButton>
|
||||
</VtsOverlayConfirmButton>
|
||||
</template>
|
||||
</VtsModal>
|
||||
</UiModal>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import VtsModal from '@core/components/modal/VtsModal.vue'
|
||||
import VtsModalCancelButton from '@core/components/modal/VtsModalCancelButton.vue'
|
||||
import VtsModalConfirmButton from '@core/components/modal/VtsModalConfirmButton.vue'
|
||||
import VtsOverlayCancelButton from '@core/components/overlay/VtsOverlayCancelButton.vue'
|
||||
import VtsOverlayConfirmButton from '@core/components/overlay/VtsOverlayConfirmButton.vue'
|
||||
import UiLink from '@core/components/ui/link/UiLink.vue'
|
||||
import UiModal from '@core/components/ui/modal/UiModal.vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
defineProps<{
|
||||
urls: string[]
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
confirm: []
|
||||
cancel: []
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
</script>
|
||||
|
||||
|
||||
@@ -1,22 +0,0 @@
|
||||
<template>
|
||||
<VtsDeleteModal>
|
||||
<template #title>
|
||||
{{ t('n-vms', { n: count }) }}
|
||||
</template>
|
||||
|
||||
<template #confirm>
|
||||
{{ t(`action:delete-n-vms`, { n: count }) }}
|
||||
</template>
|
||||
</VtsDeleteModal>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import VtsDeleteModal from '@core/components/modal/VtsDeleteModal.vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
defineProps<{
|
||||
count: number
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
</script>
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<VtsModal accent="info" icon="object:vm" dismissible>
|
||||
<UiModal accent="info" icon="object:vm" @confirm="emit('close')" @dismiss="emit('close')">
|
||||
<template #title>
|
||||
{{ t('action:export-n-vms-manually', { n: labelWithUrl.length }) }}
|
||||
</template>
|
||||
@@ -18,16 +18,16 @@
|
||||
</template>
|
||||
|
||||
<template #buttons>
|
||||
<VtsModalConfirmButton>{{ t('action:close') }}</VtsModalConfirmButton>
|
||||
<VtsOverlayConfirmButton>{{ t('action:close') }}</VtsOverlayConfirmButton>
|
||||
</template>
|
||||
</VtsModal>
|
||||
</UiModal>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import type { XenApiVm } from '@/libs/xen-api/xen-api.types'
|
||||
import { useVmStore } from '@/stores/xen-api/vm.store'
|
||||
import VtsModal from '@core/components/modal/VtsModal.vue'
|
||||
import VtsModalConfirmButton from '@core/components/modal/VtsModalConfirmButton.vue'
|
||||
import VtsOverlayConfirmButton from '@core/components/overlay/VtsOverlayConfirmButton.vue'
|
||||
import UiModal from '@core/components/ui/modal/UiModal.vue'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
@@ -35,6 +35,10 @@ const { blockedUrls } = defineProps<{
|
||||
blockedUrls: URL[]
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
close: []
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const { getByOpaqueRef } = useVmStore().subscribe()
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<VtsModal accent="info" icon="object:vm" dismissible @confirm="emit('confirm', compressionType)">
|
||||
<UiModal accent="info" icon="object:vm" @confirm="emit('confirm', compressionType)" @dismiss="emit('cancel')">
|
||||
<template #title>
|
||||
{{ t('action:export-n-vms', { n: count }) }}
|
||||
</template>
|
||||
@@ -12,21 +12,21 @@
|
||||
</VtsInputWrapper>
|
||||
</template>
|
||||
<template #buttons>
|
||||
<VtsModalCancelButton />
|
||||
<VtsModalConfirmButton>
|
||||
<VtsOverlayCancelButton @click="emit('cancel')" />
|
||||
<VtsOverlayConfirmButton>
|
||||
{{ t('action:export-n-vms', { n: count }) }}
|
||||
</VtsModalConfirmButton>
|
||||
</VtsOverlayConfirmButton>
|
||||
</template>
|
||||
</VtsModal>
|
||||
</UiModal>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { VM_COMPRESSION_TYPE } from '@/libs/xen-api/xen-api.enums'
|
||||
import VtsInputWrapper from '@core/components/input-wrapper/VtsInputWrapper.vue'
|
||||
import VtsModal from '@core/components/modal/VtsModal.vue'
|
||||
import VtsModalCancelButton from '@core/components/modal/VtsModalCancelButton.vue'
|
||||
import VtsModalConfirmButton from '@core/components/modal/VtsModalConfirmButton.vue'
|
||||
import VtsOverlayCancelButton from '@core/components/overlay/VtsOverlayCancelButton.vue'
|
||||
import VtsOverlayConfirmButton from '@core/components/overlay/VtsOverlayConfirmButton.vue'
|
||||
import VtsSelect from '@core/components/select/VtsSelect.vue'
|
||||
import UiModal from '@core/components/ui/modal/UiModal.vue'
|
||||
import { useFormSelect } from '@core/packages/form-select'
|
||||
import { ref } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
@@ -37,6 +37,7 @@ defineProps<{
|
||||
|
||||
const emit = defineEmits<{
|
||||
confirm: [compressionType: VM_COMPRESSION_TYPE]
|
||||
cancel: []
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<VtsModal accent="info" dismissible @confirm="emit('confirm', selectedHost)">
|
||||
<UiModal accent="info" @confirm="emit('confirm', selectedHost)" @dismiss="emit('cancel')">
|
||||
<template #title>
|
||||
{{ t('action:migrate-n-vms', { n: count }) }}
|
||||
</template>
|
||||
@@ -13,21 +13,21 @@
|
||||
</template>
|
||||
|
||||
<template #buttons>
|
||||
<VtsModalCancelButton />
|
||||
<VtsModalConfirmButton :disabled="!selectedHost">
|
||||
<VtsOverlayCancelButton @click="emit('cancel')" />
|
||||
<VtsOverlayConfirmButton :disabled="!selectedHost">
|
||||
{{ t('action:migrate-n-vms', { n: count }) }}
|
||||
</VtsModalConfirmButton>
|
||||
</VtsOverlayConfirmButton>
|
||||
</template>
|
||||
</VtsModal>
|
||||
</UiModal>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import type { XenApiHost } from '@/libs/xen-api/xen-api.types'
|
||||
import VtsInputWrapper from '@core/components/input-wrapper/VtsInputWrapper.vue'
|
||||
import VtsModal from '@core/components/modal/VtsModal.vue'
|
||||
import VtsModalCancelButton from '@core/components/modal/VtsModalCancelButton.vue'
|
||||
import VtsModalConfirmButton from '@core/components/modal/VtsModalConfirmButton.vue'
|
||||
import VtsOverlayCancelButton from '@core/components/overlay/VtsOverlayCancelButton.vue'
|
||||
import VtsOverlayConfirmButton from '@core/components/overlay/VtsOverlayConfirmButton.vue'
|
||||
import VtsSelect from '@core/components/select/VtsSelect.vue'
|
||||
import UiModal from '@core/components/ui/modal/UiModal.vue'
|
||||
import { useFormSelect } from '@core/packages/form-select'
|
||||
import { ref } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
@@ -39,6 +39,7 @@ const { availableHosts } = defineProps<{
|
||||
|
||||
const emit = defineEmits<{
|
||||
confirm: [selectedHost: XenApiHost | undefined]
|
||||
cancel: []
|
||||
}>()
|
||||
|
||||
const selectedHost = ref<XenApiHost>()
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
v-tooltip="areSomeVmsInExecution && t('selected-vms-in-execution')"
|
||||
:disabled="isDisabled"
|
||||
icon="fa:trash"
|
||||
@click="openDeleteModal"
|
||||
@click="openDeleteModal()"
|
||||
>
|
||||
{{ t('action:delete') }}
|
||||
</MenuItem>
|
||||
@@ -15,8 +15,8 @@ import type { XenApiVm } from '@/libs/xen-api/xen-api.types'
|
||||
import { useVmStore } from '@/stores/xen-api/vm.store'
|
||||
import { useXenApiStore } from '@/stores/xen-api.store.ts'
|
||||
import MenuItem from '@core/components/menu/MenuItem.vue'
|
||||
import { useDeleteModal } from '@core/composables/modals/use-delete-modal.ts'
|
||||
import { vTooltip } from '@core/directives/tooltip.directive'
|
||||
import { useModal } from '@core/packages/modal/use-modal.ts'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
@@ -36,9 +36,15 @@ const isDisabled = computed(() => vms.value.length === 0 || areSomeVmsInExecutio
|
||||
|
||||
const xenApi = useXenApiStore().getXapi()
|
||||
|
||||
const openDeleteModal = useModal({
|
||||
component: import('@/components/modals/VmDeleteModal.vue'),
|
||||
props: { count: computed(() => vmRefs.length) },
|
||||
onConfirm: () => xenApi.vm.delete(vmRefs),
|
||||
})
|
||||
const { open: openModal } = useDeleteModal()
|
||||
|
||||
function openDeleteModal() {
|
||||
return openModal({
|
||||
events: { onConfirm: () => xenApi.vm.delete(vmRefs) },
|
||||
props: {
|
||||
subject: t('n-vms', { n: vmRefs.length }),
|
||||
confirmLabel: t('action:delete-n-vms', { n: vmRefs.length }),
|
||||
},
|
||||
})
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -5,22 +5,22 @@
|
||||
"
|
||||
:disabled="isDisabled"
|
||||
icon="action:download"
|
||||
@click="openExportModal"
|
||||
@click="openExportModal()"
|
||||
>
|
||||
{{ t('action:export-vm', isSingleAction ? 1 : 2) }}
|
||||
</MenuItem>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { useVmExport } from '@/composables/vm-export.composable.ts'
|
||||
import { areSomeVmOperationAllowed } from '@/libs/vm'
|
||||
import { VM_OPERATION } from '@/libs/xen-api/xen-api.enums'
|
||||
import type { XenApiVm } from '@/libs/xen-api/xen-api.types'
|
||||
import { useVmStore } from '@/stores/xen-api/vm.store'
|
||||
import { useXenApiStore } from '@/stores/xen-api.store.ts'
|
||||
import MenuItem from '@core/components/menu/MenuItem.vue'
|
||||
import { useDisabled } from '@core/composables/disabled.composable'
|
||||
import { vTooltip } from '@core/directives/tooltip.directive'
|
||||
import { useModal } from '@core/packages/modal/use-modal.ts'
|
||||
import { useOverlay } from '@core/packages/overlay/use-overlay.ts'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
@@ -39,13 +39,17 @@ const isSomeExportable = computed(() =>
|
||||
|
||||
const isDisabled = useDisabled(() => !isSomeExportable.value)
|
||||
|
||||
const xenApi = useXenApiStore().getXapi()
|
||||
const { exportVms } = useVmExport()
|
||||
|
||||
const openModal = useModal()
|
||||
|
||||
const openExportModal = useModal({
|
||||
component: import('@/components/modals/VmExportModal.vue'),
|
||||
props: { count: computed(() => vmRefs.length) },
|
||||
onConfirm: compressionType => xenApi.vm.export(vmRefs, compressionType, openModal),
|
||||
const { open: openModal } = useOverlay({
|
||||
component: () => import('@/components/modals/VmExportModal.vue'),
|
||||
events: {
|
||||
onConfirm: compressionType => exportVms(vmRefs, compressionType),
|
||||
onCancel: true,
|
||||
},
|
||||
})
|
||||
|
||||
function openExportModal() {
|
||||
return openModal({ props: { count: vmRefs.length } })
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -23,8 +23,9 @@ import { useVmStore } from '@/stores/xen-api/vm.store'
|
||||
import MenuItem from '@core/components/menu/MenuItem.vue'
|
||||
import { useDisabled } from '@core/composables/disabled.composable'
|
||||
import { vTooltip } from '@core/directives/tooltip.directive'
|
||||
import { ABORT_MODAL } from '@core/packages/modal/types.ts'
|
||||
import { useModal } from '@core/packages/modal/use-modal.ts'
|
||||
import { KEEP_OVERLAY_OPEN } from '@core/packages/overlay/symbols.ts'
|
||||
import { useOverlay } from '@core/packages/overlay/use-overlay.ts'
|
||||
import { reactiveComputed } from '@vueuse/core'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
@@ -53,20 +54,28 @@ const isDisabled = useDisabled(() => !isMigratable.value)
|
||||
|
||||
const { selectedHost, availableHosts, isValid, migrate } = useVmMigration(() => selectedRefs)
|
||||
|
||||
const openMigrateModal = useModal({
|
||||
component: import('@/components/modals/VmMigrateModal.vue'),
|
||||
props: {
|
||||
count: computed(() => selectedRefs.length),
|
||||
availableHosts,
|
||||
},
|
||||
onConfirm: async host => {
|
||||
selectedHost.value = host
|
||||
const { open: openModal } = useOverlay({
|
||||
component: () => import('@/components/modals/VmMigrateModal.vue'),
|
||||
events: {
|
||||
onConfirm: async host => {
|
||||
selectedHost.value = host
|
||||
|
||||
if (!isValid.value) {
|
||||
return ABORT_MODAL
|
||||
}
|
||||
if (!isValid.value) {
|
||||
return KEEP_OVERLAY_OPEN
|
||||
}
|
||||
|
||||
await migrate()
|
||||
await migrate()
|
||||
},
|
||||
onCancel: true,
|
||||
},
|
||||
})
|
||||
|
||||
const modalProps = reactiveComputed(() => ({
|
||||
count: selectedRefs.length,
|
||||
availableHosts: availableHosts.value,
|
||||
}))
|
||||
|
||||
function openMigrateModal() {
|
||||
return openModal({ props: modalProps })
|
||||
}
|
||||
</script>
|
||||
|
||||
@@ -25,7 +25,7 @@
|
||||
|
||||
<script lang="ts" setup>
|
||||
import type { XenApiNetwork, XenApiVif, XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { useVifConnectionToggleModal } from '@/modules/vif/composables/use-vif-connection-toggle-modal.composable.ts'
|
||||
import { useVifConnection } from '@/modules/vif/composables/use-vif-connection.composable.ts'
|
||||
import { useNetworkStore } from '@/stores/xen-api/network.store'
|
||||
import { useVifStore } from '@/stores/xen-api/vif.store'
|
||||
import { useVmGuestMetricsStore } from '@/stores/xen-api/vm-guest-metrics.store'
|
||||
@@ -36,6 +36,8 @@ import UiTitle from '@core/components/ui/title/UiTitle.vue'
|
||||
import { usePagination } from '@core/composables/pagination.composable'
|
||||
import { useRouteQuery } from '@core/composables/route-query.composable'
|
||||
import { useTableState } from '@core/composables/table-state.composable'
|
||||
import { useMapper } from '@core/packages/mapper'
|
||||
import { type ActionItem } from '@core/tables/column-definitions/action-column.ts'
|
||||
import { useVifColumns } from '@core/tables/column-sets/vif-columns'
|
||||
import { CONNECTION_ACTION } from '@core/types/connection.ts'
|
||||
import { getUniqueIpAddressesForDevice } from '@core/utils/ip-address.utils.ts'
|
||||
@@ -95,14 +97,40 @@ const { HeadCells, BodyCells } = useVifColumns({
|
||||
const ipAddresses = computed(() => getIpAddresses(vif))
|
||||
|
||||
const {
|
||||
openModal: openVifConnectionToggleModal,
|
||||
canRun: canToggleVifConnection,
|
||||
isRunning: isTogglingVifConnection,
|
||||
errorMessage: toggleConnectionErrorMessage,
|
||||
} = useVifConnectionToggleModal(
|
||||
connectVifs,
|
||||
disconnectVifs,
|
||||
canConnectVifs,
|
||||
canDisconnectVifs,
|
||||
isConnectingVifs,
|
||||
isDisconnectingVifs,
|
||||
connectVifsErrorMessage,
|
||||
disconnectVifsErrorMessage,
|
||||
} = useVifConnection({
|
||||
vifs: () => [vif],
|
||||
vm: () => vm,
|
||||
})
|
||||
|
||||
const connectionAction = useMapper(
|
||||
() => (vif.currently_attached ? CONNECTION_ACTION.DISCONNECT : CONNECTION_ACTION.CONNECT),
|
||||
() => [vif],
|
||||
() => vm
|
||||
() => ({
|
||||
connect: {
|
||||
label: t('action:connect'),
|
||||
icon: 'action:connect',
|
||||
onClick: () => connectVifs(),
|
||||
disabled: !canConnectVifs.value,
|
||||
busy: isConnectingVifs.value,
|
||||
hint: canConnectVifs.value ? undefined : connectVifsErrorMessage.value,
|
||||
} satisfies ActionItem,
|
||||
disconnect: {
|
||||
label: t('action:disconnect'),
|
||||
icon: 'action:disconnect',
|
||||
onClick: () => disconnectVifs(),
|
||||
disabled: !canDisconnectVifs.value,
|
||||
busy: isDisconnectingVifs.value,
|
||||
hint: canDisconnectVifs.value ? undefined : disconnectVifsErrorMessage.value,
|
||||
} satisfies ActionItem,
|
||||
}),
|
||||
'connect'
|
||||
)
|
||||
|
||||
return {
|
||||
@@ -116,16 +144,7 @@ const { HeadCells, BodyCells } = useVifColumns({
|
||||
actions: r =>
|
||||
r({
|
||||
onClick: () => (selectedVifId.value = vif.uuid),
|
||||
actions: [
|
||||
{
|
||||
label: vif.currently_attached ? t('action:disconnect') : t('action:connect'),
|
||||
hint: !canToggleVifConnection.value ? toggleConnectionErrorMessage.value : undefined,
|
||||
icon: vif.currently_attached ? 'action:disconnect' : 'action:connect',
|
||||
onClick: () => openVifConnectionToggleModal(),
|
||||
disabled: !canToggleVifConnection.value,
|
||||
busy: isTogglingVifConnection.value,
|
||||
},
|
||||
],
|
||||
actions: [connectionAction.value],
|
||||
}),
|
||||
}
|
||||
},
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
import { ipToHostname } from '@/libs/utils'
|
||||
import { useHostStore } from '@/stores/xen-api/host.store'
|
||||
import { useModal } from '@core/packages/modal/use-modal.ts'
|
||||
import { whenever } from '@vueuse/core'
|
||||
import { useOverlay } from '@core/packages/overlay/use-overlay.ts'
|
||||
import { reactiveComputed, whenever } from '@vueuse/core'
|
||||
import { difference } from 'lodash-es'
|
||||
import { computed, ref, watch } from 'vue'
|
||||
import { ref, watch } from 'vue'
|
||||
|
||||
export const useUnreachableHosts = () => {
|
||||
const { records: hosts } = useHostStore().subscribe()
|
||||
@@ -18,15 +18,33 @@ export const useUnreachableHosts = () => {
|
||||
})
|
||||
})
|
||||
|
||||
const openModal = useModal({
|
||||
keepOpenOnRouteChange: true,
|
||||
component: import('@/components/modals/UnreachableHostsModal.vue'),
|
||||
props: { urls: computed(() => Array.from(unreachableHostsUrls.value.values())) },
|
||||
onConfirm: () => window.location.reload(),
|
||||
onCancel: () => unreachableHostsUrls.value.clear(),
|
||||
const { open } = useOverlay({
|
||||
component: () => import('@/components/modals/UnreachableHostsModal.vue'),
|
||||
events: {
|
||||
onConfirm: true,
|
||||
onCancel: true,
|
||||
},
|
||||
})
|
||||
|
||||
whenever(() => unreachableHostsUrls.value.size > 0, openModal, {
|
||||
immediate: true,
|
||||
})
|
||||
const modalProps = reactiveComputed(() => ({
|
||||
urls: Array.from(unreachableHostsUrls.value.values()),
|
||||
}))
|
||||
|
||||
async function openModal() {
|
||||
const { event } = await open({ props: modalProps })
|
||||
|
||||
if (event === 'onConfirm') {
|
||||
window.location.reload()
|
||||
}
|
||||
|
||||
unreachableHostsUrls.value.clear()
|
||||
}
|
||||
|
||||
whenever(
|
||||
() => unreachableHostsUrls.value.size > 0,
|
||||
() => openModal(),
|
||||
{
|
||||
immediate: true,
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
27
@xen-orchestra/lite/src/composables/vm-export.composable.ts
Normal file
27
@xen-orchestra/lite/src/composables/vm-export.composable.ts
Normal file
@@ -0,0 +1,27 @@
|
||||
import type { VM_COMPRESSION_TYPE } from '@/libs/xen-api/xen-api.enums.ts'
|
||||
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { useXenApiStore } from '@/stores/xen-api.store.ts'
|
||||
import { useOverlay } from '@core/packages/overlay/use-overlay.ts'
|
||||
|
||||
export function useVmExport() {
|
||||
const xapi = useXenApiStore().getXapi()
|
||||
|
||||
const { open: openBlockedUrlsModal } = useOverlay({
|
||||
component: () => import('@/components/modals/VmExportBlockedUrlsModal.vue'),
|
||||
events: {
|
||||
onClose: true,
|
||||
},
|
||||
})
|
||||
|
||||
async function exportVms(vmRefs: XenApiVm['$ref'][], compression: VM_COMPRESSION_TYPE) {
|
||||
const { blockedUrls } = await xapi.vm.export(vmRefs, compression)
|
||||
|
||||
if (blockedUrls.length === 0) {
|
||||
return
|
||||
}
|
||||
|
||||
openBlockedUrlsModal({ props: { blockedUrls } })
|
||||
}
|
||||
|
||||
return { exportVms }
|
||||
}
|
||||
@@ -1,9 +1,8 @@
|
||||
import { useVmExport } from '@/composables/vm-export.composable.ts'
|
||||
import { vmsArg } from '@/jobs/args'
|
||||
import { areSomeVmOperationAllowed, isVmOperationPending } from '@/libs/vm'
|
||||
import { VM_COMPRESSION_TYPE, VM_OPERATION } from '@/libs/xen-api/xen-api.enums'
|
||||
import { useXenApiStore } from '@/stores/xen-api.store'
|
||||
import { defineJob, defineJobArg, JobError, JobRunningError } from '@core/packages/job'
|
||||
import { useModal } from '@core/packages/modal/use-modal.ts'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const compressionArg = defineJobArg<VM_COMPRESSION_TYPE>({
|
||||
@@ -12,16 +11,15 @@ const compressionArg = defineJobArg<VM_COMPRESSION_TYPE>({
|
||||
})
|
||||
|
||||
export const useVmExportJob = defineJob('vm.export', [vmsArg, compressionArg], () => {
|
||||
const xapi = useXenApiStore().getXapi()
|
||||
const { t } = useI18n()
|
||||
const openModal = useModal()
|
||||
|
||||
const { exportVms } = useVmExport()
|
||||
|
||||
return {
|
||||
run: (vms, compression) =>
|
||||
xapi.vm.export(
|
||||
exportVms(
|
||||
vms.map(vm => vm.$ref),
|
||||
compression,
|
||||
openModal
|
||||
compression
|
||||
),
|
||||
validate: (isRunning, vms, compression) => {
|
||||
if (vms.length === 0) {
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import type XenApi from '@/libs/xen-api/xen-api'
|
||||
import type { VM_COMPRESSION_TYPE } from '@/libs/xen-api/xen-api.enums'
|
||||
import type { XenApiHost, XenApiSr, XenApiVm } from '@/libs/xen-api/xen-api.types'
|
||||
import type { OpenModal } from '@core/packages/modal/types.ts'
|
||||
import type { MaybeArray } from '@core/types/utility.type.ts'
|
||||
import { toArray } from '@core/utils/to-array.utils'
|
||||
import type { OPAQUE_REF_NULL } from '@vates/types/common'
|
||||
@@ -42,7 +41,7 @@ export function createVmOperations(xenApi: XenApi) {
|
||||
|
||||
delete: (vmRefs: VmRefs) => Promise.all(toArray(vmRefs).map(vmRef => xenApi.call('VM.destroy', [vmRef]))),
|
||||
|
||||
export: async (vmRefs: VmRefs, compression: VM_COMPRESSION_TYPE, openModal: OpenModal) => {
|
||||
export: async (vmRefs: VmRefs, compression: VM_COMPRESSION_TYPE) => {
|
||||
const blockedUrls: URL[] = []
|
||||
|
||||
toArray(vmRefs).forEach(vmRef => {
|
||||
@@ -54,22 +53,14 @@ export function createVmOperations(xenApi: XenApi) {
|
||||
use_compression: compression,
|
||||
}).toString()
|
||||
|
||||
const _window = window.open(url.href, '_blank')
|
||||
const openedWindow = window.open(url.href, '_blank')
|
||||
|
||||
if (_window === null) {
|
||||
if (openedWindow === null) {
|
||||
blockedUrls.push(url)
|
||||
} else {
|
||||
URL.revokeObjectURL(url.toString())
|
||||
}
|
||||
})
|
||||
|
||||
if (blockedUrls.length > 0) {
|
||||
await openModal('blocked-urls', {
|
||||
component: import('@/components/modals/VmExportBlockedUrlsModal.vue'),
|
||||
props: { blockedUrls },
|
||||
onConfirm: () => blockedUrls.forEach(url => URL.revokeObjectURL(url.toString())),
|
||||
})
|
||||
}
|
||||
return { blockedUrls }
|
||||
},
|
||||
|
||||
getAllowedVbdDevices: (vmRefs: VmRefs): Promise<string[][]> =>
|
||||
|
||||
@@ -1,18 +1,18 @@
|
||||
<template>
|
||||
<UiButton
|
||||
v-tooltip="!canConnectSr && connectSrErrorMessage"
|
||||
v-tooltip="!canConnectSrs && connectSrsErrorMessage"
|
||||
size="medium"
|
||||
variant="tertiary"
|
||||
accent="brand"
|
||||
:disabled="!canConnectSr"
|
||||
:disabled="!canConnectSrs"
|
||||
left-icon="action:connect"
|
||||
:busy="isConnectingSr"
|
||||
@click="openSrConnectModal()"
|
||||
:busy="isConnectingSrs"
|
||||
@click="connectSrs()"
|
||||
>
|
||||
{{ t('action:connect') }}
|
||||
<UiCounter
|
||||
v-if="isPartiallyConnectedInScope"
|
||||
:value="targetCount"
|
||||
:value="connectionTargetCount"
|
||||
accent="brand"
|
||||
variant="secondary"
|
||||
size="small"
|
||||
@@ -23,7 +23,7 @@
|
||||
<script lang="ts" setup>
|
||||
import type { XenApiSr } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { useSrUtils } from '@/modules/storage-repository/composables/sr-utils.composable.ts'
|
||||
import { useSrConnectModal } from '@/modules/storage-repository/composables/use-sr-connect-modal.composable.ts'
|
||||
import { useSrConnection } from '@/modules/storage-repository/composables/use-sr-connection.composable.ts'
|
||||
import type { SrScope } from '@core/types/storage-repository.type.ts'
|
||||
import UiButton from '@core/components/ui/button/UiButton.vue'
|
||||
import UiCounter from '@core/components/ui/counter/UiCounter.vue'
|
||||
@@ -42,14 +42,8 @@ const { isPartiallyConnectedInScope } = useSrUtils(
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const {
|
||||
openModal: openSrConnectModal,
|
||||
canRun: canConnectSr,
|
||||
isRunning: isConnectingSr,
|
||||
errorMessage: connectSrErrorMessage,
|
||||
targetCount,
|
||||
} = useSrConnectModal(
|
||||
() => [sr],
|
||||
() => scope
|
||||
)
|
||||
const { connectSrs, canConnectSrs, isConnectingSrs, connectSrsErrorMessage, connectionTargetCount } = useSrConnection({
|
||||
srs: () => [sr],
|
||||
scope: () => scope,
|
||||
})
|
||||
</script>
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
<template>
|
||||
<MenuItem
|
||||
v-tooltip="!canDeleteSr && deleteSrErrorMessage"
|
||||
v-tooltip="!canDeleteSrs && deleteSrsErrorMessage"
|
||||
icon="action:delete"
|
||||
:disabled="!canDeleteSr"
|
||||
:busy="isDeletingSr"
|
||||
:disabled="!canDeleteSrs"
|
||||
:busy="isDeletingSrs"
|
||||
class="delete"
|
||||
@click="openSrDeleteModal()"
|
||||
@click="deleteSrs()"
|
||||
>
|
||||
{{ t('action:delete') }}
|
||||
</MenuItem>
|
||||
@@ -13,7 +13,7 @@
|
||||
|
||||
<script lang="ts" setup>
|
||||
import type { XenApiSr } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { useSrDeleteModal } from '@/modules/storage-repository/composables/use-sr-delete-modal.composable.ts'
|
||||
import { useSrDelete } from '@/modules/storage-repository/composables/use-sr-delete.composable.ts'
|
||||
import MenuItem from '@core/components/menu/MenuItem.vue'
|
||||
import { vTooltip } from '@core/directives/tooltip.directive.ts'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
@@ -24,12 +24,7 @@ const { sr } = defineProps<{
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const {
|
||||
openModal: openSrDeleteModal,
|
||||
canRun: canDeleteSr,
|
||||
isRunning: isDeletingSr,
|
||||
errorMessage: deleteSrErrorMessage,
|
||||
} = useSrDeleteModal(() => [sr])
|
||||
const { deleteSrs, canDeleteSrs, isDeletingSrs, deleteSrsErrorMessage } = useSrDelete(() => [sr])
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
<template>
|
||||
<MenuItem
|
||||
v-tooltip="!canDisconnectSr && disconnectSrErrorMessage"
|
||||
v-tooltip="!canDisconnectSrs && disconnectSrsErrorMessage"
|
||||
icon="action:disconnect"
|
||||
:disabled="!canDisconnectSr"
|
||||
:busy="isDisconnectingSr"
|
||||
@click="openSrDisconnectModal()"
|
||||
:disabled="!canDisconnectSrs"
|
||||
:busy="isDisconnectingSrs"
|
||||
@click="disconnectSrs()"
|
||||
>
|
||||
{{ t('action:disconnect') }}
|
||||
<UiCounter
|
||||
v-if="shouldShowTargetCount(scope, targetCount)"
|
||||
:value="targetCount"
|
||||
v-if="shouldShowTargetCount(scope, disconnectionTargetCount)"
|
||||
:value="disconnectionTargetCount"
|
||||
accent="brand"
|
||||
variant="secondary"
|
||||
size="small"
|
||||
@@ -20,7 +20,7 @@
|
||||
|
||||
<script lang="ts" setup>
|
||||
import type { XenApiSr } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { useSrDisconnectModal } from '@/modules/storage-repository/composables/use-sr-disconnect-modal.composable.ts'
|
||||
import { useSrConnection } from '@/modules/storage-repository/composables/use-sr-connection.composable.ts'
|
||||
import MenuItem from '@core/components/menu/MenuItem.vue'
|
||||
import UiCounter from '@core/components/ui/counter/UiCounter.vue'
|
||||
import { vTooltip } from '@core/directives/tooltip.directive.ts'
|
||||
@@ -36,16 +36,11 @@ const { sr, scope } = defineProps<{
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const {
|
||||
openModal: openSrDisconnectModal,
|
||||
canRun: canDisconnectSr,
|
||||
isRunning: isDisconnectingSr,
|
||||
errorMessage: disconnectSrErrorMessage,
|
||||
targetCount,
|
||||
} = useSrDisconnectModal(
|
||||
() => [sr],
|
||||
() => scope
|
||||
)
|
||||
const { disconnectSrs, canDisconnectSrs, isDisconnectingSrs, disconnectSrsErrorMessage, disconnectionTargetCount } =
|
||||
useSrConnection({
|
||||
srs: () => [sr],
|
||||
scope: () => scope,
|
||||
})
|
||||
|
||||
const hint = computed(() => (!canDisconnectSr.value ? disconnectSrErrorMessage.value : undefined))
|
||||
const hint = computed(() => (!canDisconnectSrs.value ? disconnectSrsErrorMessage.value : undefined))
|
||||
</script>
|
||||
|
||||
@@ -24,9 +24,8 @@
|
||||
<script setup lang="ts">
|
||||
import type { XenApiPool, XenApiSr } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { useGetPbdsInScope, useSrUtils } from '@/modules/storage-repository/composables/sr-utils.composable.ts'
|
||||
import { useSrConnectModal } from '@/modules/storage-repository/composables/use-sr-connect-modal.composable.ts'
|
||||
import { useSrDeleteModal } from '@/modules/storage-repository/composables/use-sr-delete-modal.composable.ts'
|
||||
import { useSrDisconnectModal } from '@/modules/storage-repository/composables/use-sr-disconnect-modal.composable.ts'
|
||||
import { useSrConnection } from '@/modules/storage-repository/composables/use-sr-connection.composable.ts'
|
||||
import { useSrDelete } from '@/modules/storage-repository/composables/use-sr-delete.composable.ts'
|
||||
import { useSrStore } from '@/stores/xen-api/sr.store.ts'
|
||||
import VtsRow from '@core/components/table/VtsRow.vue'
|
||||
import VtsTable from '@core/components/table/VtsTable.vue'
|
||||
@@ -111,44 +110,33 @@ const { HeadCells, BodyCells } = useSrColumns({
|
||||
|
||||
const { srStatusIcon } = useSrUtils(sr, () => scope)
|
||||
|
||||
const {
|
||||
openModal: openSrDeleteModal,
|
||||
canRun: canDeleteSr,
|
||||
isRunning: isDeletingSr,
|
||||
errorMessage: deleteSrErrorMessage,
|
||||
} = useSrDeleteModal(() => [sr])
|
||||
const { deleteSrs, canDeleteSrs, isDeletingSrs, deleteSrsErrorMessage } = useSrDelete(() => [sr])
|
||||
|
||||
const {
|
||||
openModal: openSrConnectModal,
|
||||
canRun: canConnectSr,
|
||||
isRunning: isConnectingSr,
|
||||
errorMessage: connectSrErrorMessage,
|
||||
targetCount: connectTargetCount,
|
||||
} = useSrConnectModal(
|
||||
() => [sr],
|
||||
() => scope
|
||||
)
|
||||
|
||||
const {
|
||||
openModal: openSrDisconnectModal,
|
||||
canRun: canDisconnectSr,
|
||||
isRunning: isDisconnectingSr,
|
||||
errorMessage: disconnectSrErrorMessage,
|
||||
targetCount: disconnectTargetCount,
|
||||
} = useSrDisconnectModal(
|
||||
() => [sr],
|
||||
() => scope
|
||||
)
|
||||
connectSrs,
|
||||
disconnectSrs,
|
||||
canConnectSrs,
|
||||
canDisconnectSrs,
|
||||
isConnectingSrs,
|
||||
isDisconnectingSrs,
|
||||
connectSrsErrorMessage,
|
||||
disconnectSrsErrorMessage,
|
||||
connectionTargetCount,
|
||||
disconnectionTargetCount,
|
||||
} = useSrConnection({
|
||||
srs: () => [sr],
|
||||
scope: () => scope,
|
||||
})
|
||||
|
||||
const connectLabel = computed(() =>
|
||||
shouldShowTargetCount(scope, connectTargetCount.value)
|
||||
? t('action:connect-n', { n: connectTargetCount.value })
|
||||
shouldShowTargetCount(scope, connectionTargetCount.value)
|
||||
? t('action:connect-n', { n: connectionTargetCount.value })
|
||||
: t('action:connect')
|
||||
)
|
||||
|
||||
const disconnectLabel = computed(() =>
|
||||
shouldShowTargetCount(scope, disconnectTargetCount.value)
|
||||
? t('action:disconnect-n', { n: disconnectTargetCount.value })
|
||||
shouldShowTargetCount(scope, disconnectionTargetCount.value)
|
||||
? t('action:disconnect-n', { n: disconnectionTargetCount.value })
|
||||
: t('action:disconnect')
|
||||
)
|
||||
|
||||
@@ -170,26 +158,26 @@ const { HeadCells, BodyCells } = useSrColumns({
|
||||
{
|
||||
label: connectLabel.value,
|
||||
icon: 'action:connect',
|
||||
onClick: () => openSrConnectModal(),
|
||||
busy: isConnectingSr.value,
|
||||
disabled: !canConnectSr.value,
|
||||
hint: connectSrErrorMessage.value,
|
||||
onClick: () => connectSrs(),
|
||||
busy: isConnectingSrs.value,
|
||||
disabled: !canConnectSrs.value,
|
||||
hint: connectSrsErrorMessage.value,
|
||||
},
|
||||
{
|
||||
label: disconnectLabel.value,
|
||||
icon: 'action:disconnect',
|
||||
onClick: () => openSrDisconnectModal(),
|
||||
busy: isDisconnectingSr.value,
|
||||
disabled: !canDisconnectSr.value,
|
||||
hint: disconnectSrErrorMessage.value,
|
||||
onClick: () => disconnectSrs(),
|
||||
busy: isDisconnectingSrs.value,
|
||||
disabled: !canDisconnectSrs.value,
|
||||
hint: disconnectSrsErrorMessage.value,
|
||||
},
|
||||
{
|
||||
label: t('action:delete'),
|
||||
icon: 'action:delete',
|
||||
onClick: () => openSrDeleteModal(),
|
||||
busy: isDeletingSr.value,
|
||||
disabled: !canDeleteSr.value,
|
||||
hint: deleteSrErrorMessage.value,
|
||||
onClick: () => deleteSrs(),
|
||||
busy: isDeletingSrs.value,
|
||||
disabled: !canDeleteSrs.value,
|
||||
hint: deleteSrsErrorMessage.value,
|
||||
},
|
||||
],
|
||||
}),
|
||||
|
||||
@@ -1,56 +0,0 @@
|
||||
<template>
|
||||
<VtsModal accent="info" icon="status:info-picto" dismissible>
|
||||
<template #title>
|
||||
{{ title }}
|
||||
</template>
|
||||
|
||||
<template #content>
|
||||
{{ info }}
|
||||
</template>
|
||||
|
||||
<template #buttons>
|
||||
<VtsModalCancelButton>{{ t('action:go-back') }}</VtsModalCancelButton>
|
||||
<VtsModalConfirmButton>
|
||||
{{ confirmLabel }}
|
||||
</VtsModalConfirmButton>
|
||||
</template>
|
||||
</VtsModal>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { useSrModalMessages } from '@/modules/storage-repository/composables/use-sr-modal-messages.composable.ts'
|
||||
import type { SrAccessMode, SrScope } from '@core/types/storage-repository.type.ts'
|
||||
import VtsModal from '@core/components/modal/VtsModal.vue'
|
||||
import VtsModalCancelButton from '@core/components/modal/VtsModalCancelButton.vue'
|
||||
import VtsModalConfirmButton from '@core/components/modal/VtsModalConfirmButton.vue'
|
||||
import { useMapper } from '@core/packages/mapper'
|
||||
import { CONNECTION_ACTION, type ConnectionAction } from '@core/types/connection.ts'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const { action, count, scope, accessMode, hostsCount } = defineProps<{
|
||||
action: ConnectionAction
|
||||
count: number
|
||||
scope: SrScope
|
||||
accessMode: SrAccessMode
|
||||
hostsCount: number
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const { title, info } = useSrModalMessages({
|
||||
action,
|
||||
count: () => count,
|
||||
scope: () => scope,
|
||||
accessMode: () => accessMode,
|
||||
hostsCount: () => hostsCount,
|
||||
})
|
||||
|
||||
const confirmLabel = useMapper(
|
||||
() => action,
|
||||
() => ({
|
||||
[CONNECTION_ACTION.CONNECT]: t('action:connect-n-srs', { n: count }),
|
||||
[CONNECTION_ACTION.DISCONNECT]: t('action:disconnect-n-srs', { n: count }),
|
||||
}),
|
||||
CONNECTION_ACTION.CONNECT
|
||||
)
|
||||
</script>
|
||||
@@ -1,27 +0,0 @@
|
||||
<template>
|
||||
<VtsDeleteModal dismissible>
|
||||
<template #title>
|
||||
{{ t('n-srs', { n: count }) }}
|
||||
</template>
|
||||
|
||||
<template #content>
|
||||
{{ t('sr-delete-info', { n: count }) }}
|
||||
<!-- TODO Add a type-to-confirm input if count > 1 -->
|
||||
</template>
|
||||
|
||||
<template #confirm>
|
||||
{{ t(`action:delete-n-srs`, { n: count }) }}
|
||||
</template>
|
||||
</VtsDeleteModal>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import VtsDeleteModal from '@core/components/modal/VtsDeleteModal.vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
defineProps<{
|
||||
count: number
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
</script>
|
||||
@@ -1,41 +0,0 @@
|
||||
import { usePbdPlugJob } from '@/jobs/pbd-plug.job.ts'
|
||||
import type { XenApiSr } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { useGetPbdsInScope } from '@/modules/storage-repository/composables/sr-utils.composable.ts'
|
||||
import type { SrScope } from '@core/types/storage-repository.type.ts'
|
||||
import { useModal } from '@core/packages/modal/use-modal.ts'
|
||||
import { CONNECTION_ACTION } from '@core/types/connection.ts'
|
||||
import { getSrAccessMode } from '@core/utils/sr.utils.ts'
|
||||
import { toComputed } from '@core/utils/to-computed.util.ts'
|
||||
import { computed, type MaybeRefOrGetter } from 'vue'
|
||||
|
||||
export function useSrConnectModal(rawSrs: MaybeRefOrGetter<XenApiSr[]>, rawScope: MaybeRefOrGetter<SrScope>) {
|
||||
const srs = toComputed(rawSrs)
|
||||
const scope = toComputed(rawScope)
|
||||
|
||||
const { getDetachedPbdsInScope } = useGetPbdsInScope()
|
||||
|
||||
const plugTargets = computed(() => srs.value.flatMap(sr => getDetachedPbdsInScope(sr, scope.value)))
|
||||
const targetCount = computed(() => plugTargets.value.length)
|
||||
|
||||
const { run, canRun, isRunning, errorMessage } = usePbdPlugJob(plugTargets)
|
||||
|
||||
const openModal = useModal(() => ({
|
||||
component: import('@/modules/storage-repository/components/modal/SrConnectionToggleModal.vue'),
|
||||
props: {
|
||||
action: CONNECTION_ACTION.CONNECT,
|
||||
count: srs.value.length,
|
||||
scope: scope.value,
|
||||
accessMode: getSrAccessMode(srs.value),
|
||||
hostsCount: targetCount.value,
|
||||
},
|
||||
onConfirm: async () => {
|
||||
try {
|
||||
await run()
|
||||
} catch (error) {
|
||||
console.error(`Error when connecting SR:`, error)
|
||||
}
|
||||
},
|
||||
}))
|
||||
|
||||
return { openModal, canRun, isRunning, errorMessage, targetCount }
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
import { usePbdPlugJob } from '@/jobs/pbd-plug.job.ts'
|
||||
import { usePbdUnplugJob } from '@/jobs/pbd-unplug.job.ts'
|
||||
import type { XenApiSr } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { useGetPbdsInScope } from '@/modules/storage-repository/composables/sr-utils.composable.ts'
|
||||
import type { SrScope } from '@core/types/storage-repository.type.ts'
|
||||
import { useOverlay } from '@core/packages/overlay/use-overlay.ts'
|
||||
import { CONNECTION_ACTION } from '@core/types/connection.ts'
|
||||
import { getSrAccessMode } from '@core/utils/sr.utils.ts'
|
||||
import { toComputed } from '@core/utils/to-computed.util.ts'
|
||||
import { computed, type MaybeRefOrGetter } from 'vue'
|
||||
|
||||
export function useSrConnection(options: { srs: MaybeRefOrGetter<XenApiSr[]>; scope: MaybeRefOrGetter<SrScope> }) {
|
||||
const srs = toComputed(options.srs)
|
||||
const scope = toComputed(options.scope)
|
||||
|
||||
const { getAttachedPbdsInScope, getDetachedPbdsInScope } = useGetPbdsInScope()
|
||||
|
||||
const connectionTargets = computed(() => srs.value.flatMap(sr => getDetachedPbdsInScope(sr, scope.value)))
|
||||
const disconnectionTargets = computed(() => srs.value.flatMap(sr => getAttachedPbdsInScope(sr, scope.value)))
|
||||
|
||||
const connectionTargetCount = computed(() => connectionTargets.value.length)
|
||||
const disconnectionTargetCount = computed(() => disconnectionTargets.value.length)
|
||||
|
||||
const {
|
||||
run: runConnect,
|
||||
canRun: canConnectSrs,
|
||||
isRunning: isConnectingSrs,
|
||||
errorMessage: connectSrsErrorMessage,
|
||||
} = usePbdPlugJob(connectionTargets)
|
||||
|
||||
const {
|
||||
run: runDisconnect,
|
||||
canRun: canDisconnectSrs,
|
||||
isRunning: isDisconnectingSrs,
|
||||
errorMessage: disconnectSrsErrorMessage,
|
||||
} = usePbdUnplugJob(disconnectionTargets)
|
||||
|
||||
const { open } = useOverlay({
|
||||
component: () => import('@core/components/sr-connection-modal/VtsSrConnectionModal.vue'),
|
||||
events: {
|
||||
onConfirm: true,
|
||||
onCancel: true,
|
||||
},
|
||||
})
|
||||
|
||||
function connectSrs() {
|
||||
return open({
|
||||
props: {
|
||||
action: CONNECTION_ACTION.CONNECT,
|
||||
count: srs.value.length,
|
||||
scope: scope.value,
|
||||
accessMode: getSrAccessMode(srs.value),
|
||||
hostsCount: connectionTargetCount.value,
|
||||
},
|
||||
events: {
|
||||
onConfirm: async () => {
|
||||
try {
|
||||
await runConnect()
|
||||
} catch (error) {
|
||||
console.error('Error when connecting SR:', error)
|
||||
}
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
function disconnectSrs() {
|
||||
return open({
|
||||
props: {
|
||||
action: CONNECTION_ACTION.DISCONNECT,
|
||||
count: srs.value.length,
|
||||
scope: scope.value,
|
||||
accessMode: getSrAccessMode(srs.value),
|
||||
hostsCount: disconnectionTargetCount.value,
|
||||
},
|
||||
events: {
|
||||
onConfirm: async () => {
|
||||
try {
|
||||
await runDisconnect()
|
||||
} catch (error) {
|
||||
console.error('Error when disconnecting SR:', error)
|
||||
}
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
connectSrs,
|
||||
disconnectSrs,
|
||||
canConnectSrs,
|
||||
canDisconnectSrs,
|
||||
isConnectingSrs,
|
||||
isDisconnectingSrs,
|
||||
connectSrsErrorMessage,
|
||||
disconnectSrsErrorMessage,
|
||||
connectionTargetCount,
|
||||
disconnectionTargetCount,
|
||||
}
|
||||
}
|
||||
@@ -1,32 +0,0 @@
|
||||
import { useSrDeleteJob } from '@/jobs/sr-delete.job.ts'
|
||||
import type { XenApiSr } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { useRouteQuery } from '@core/composables/route-query.composable.ts'
|
||||
import { useModal } from '@core/packages/modal/use-modal.ts'
|
||||
import { toComputed } from '@core/utils/to-computed.util.ts'
|
||||
import type { MaybeRefOrGetter } from 'vue'
|
||||
|
||||
export function useSrDeleteModal(rawSrs: MaybeRefOrGetter<XenApiSr[]>) {
|
||||
const srs = toComputed(rawSrs)
|
||||
|
||||
const selectedSrId = useRouteQuery('id')
|
||||
|
||||
const { run, canRun, isRunning, errorMessage } = useSrDeleteJob(srs)
|
||||
|
||||
const openModal = useModal(() => ({
|
||||
component: import('@/modules/storage-repository/components/modal/SrDeleteModal.vue'),
|
||||
props: { count: srs.value.length },
|
||||
onConfirm: async () => {
|
||||
try {
|
||||
await run()
|
||||
|
||||
if (srs.value.some(sr => sr.uuid === selectedSrId.value)) {
|
||||
selectedSrId.value = ''
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error when deleting SR:', error)
|
||||
}
|
||||
},
|
||||
}))
|
||||
|
||||
return { openModal, canRun, isRunning, errorMessage }
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { useSrDeleteJob } from '@/jobs/sr-delete.job.ts'
|
||||
import type { XenApiSr } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { useDeleteModal } from '@core/composables/modals/use-delete-modal.ts'
|
||||
import { useRouteQuery } from '@core/composables/route-query.composable.ts'
|
||||
import { toComputed } from '@core/utils/to-computed.util.ts'
|
||||
import type { MaybeRefOrGetter } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
export function useSrDelete(rawSrs: MaybeRefOrGetter<XenApiSr[]>) {
|
||||
const srs = toComputed(rawSrs)
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const selectedSrId = useRouteQuery('id')
|
||||
|
||||
const {
|
||||
run,
|
||||
canRun: canDeleteSrs,
|
||||
isRunning: isDeletingSrs,
|
||||
errorMessage: deleteSrsErrorMessage,
|
||||
} = useSrDeleteJob(srs)
|
||||
|
||||
const { open } = useDeleteModal()
|
||||
|
||||
function deleteSrs() {
|
||||
const count = srs.value.length
|
||||
|
||||
// TODO Add a type-to-confirm input if count > 1
|
||||
return open({
|
||||
props: {
|
||||
subject: t('n-srs', { n: count }),
|
||||
description: t('sr-delete-info', { n: count }),
|
||||
confirmLabel: t('action:delete-n-srs', { n: count }),
|
||||
},
|
||||
events: {
|
||||
onConfirm: async () => {
|
||||
try {
|
||||
await run()
|
||||
|
||||
if (srs.value.some(sr => sr.uuid === selectedSrId.value)) {
|
||||
selectedSrId.value = ''
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error when deleting SR:', error)
|
||||
}
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
return { deleteSrs, canDeleteSrs, isDeletingSrs, deleteSrsErrorMessage }
|
||||
}
|
||||
@@ -1,42 +0,0 @@
|
||||
import { usePbdUnplugJob } from '@/jobs/pbd-unplug.job.ts'
|
||||
import type { XenApiSr } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { useGetPbdsInScope } from '@/modules/storage-repository/composables/sr-utils.composable.ts'
|
||||
import type { SrScope } from '@core/types/storage-repository.type.ts'
|
||||
import { useModal } from '@core/packages/modal/use-modal.ts'
|
||||
import { CONNECTION_ACTION } from '@core/types/connection.ts'
|
||||
import { getSrAccessMode } from '@core/utils/sr.utils.ts'
|
||||
import { toComputed } from '@core/utils/to-computed.util.ts'
|
||||
import { computed, type MaybeRefOrGetter } from 'vue'
|
||||
|
||||
export function useSrDisconnectModal(rawSrs: MaybeRefOrGetter<XenApiSr[]>, rawScope: MaybeRefOrGetter<SrScope>) {
|
||||
const srs = toComputed(rawSrs)
|
||||
const scope = toComputed(rawScope)
|
||||
|
||||
const { getAttachedPbdsInScope } = useGetPbdsInScope()
|
||||
|
||||
const unplugTargets = computed(() => srs.value.flatMap(sr => getAttachedPbdsInScope(sr, scope.value)))
|
||||
|
||||
const targetCount = computed(() => unplugTargets.value.length)
|
||||
|
||||
const { run, canRun, isRunning, errorMessage } = usePbdUnplugJob(unplugTargets)
|
||||
|
||||
const openModal = useModal(() => ({
|
||||
component: import('@/modules/storage-repository/components/modal/SrConnectionToggleModal.vue'),
|
||||
props: {
|
||||
action: CONNECTION_ACTION.DISCONNECT,
|
||||
count: srs.value.length,
|
||||
scope: scope.value,
|
||||
accessMode: getSrAccessMode(srs.value),
|
||||
hostsCount: targetCount.value,
|
||||
},
|
||||
onConfirm: async () => {
|
||||
try {
|
||||
await run()
|
||||
} catch (error) {
|
||||
console.error(`Error when disconnecting SR:`, error)
|
||||
}
|
||||
},
|
||||
}))
|
||||
|
||||
return { openModal, canRun, isRunning, errorMessage, targetCount }
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
import type { SrAccessMode, SrScope } from '@core/types/storage-repository.type.ts'
|
||||
import { useMapper } from '@core/packages/mapper'
|
||||
import { CONNECTION_ACTION, type ConnectionAction } from '@core/types/connection.ts'
|
||||
import { getSrModalInfoVariant } from '@core/utils/sr.utils.ts'
|
||||
import { toComputed } from '@core/utils/to-computed.util.ts'
|
||||
import { type MaybeRefOrGetter } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
export function useSrModalMessages(options: {
|
||||
action: ConnectionAction
|
||||
count: MaybeRefOrGetter<number>
|
||||
scope: MaybeRefOrGetter<SrScope>
|
||||
accessMode: MaybeRefOrGetter<SrAccessMode>
|
||||
hostsCount: MaybeRefOrGetter<number>
|
||||
}) {
|
||||
const { t } = useI18n()
|
||||
|
||||
const count = toComputed(options.count)
|
||||
const scope = toComputed(options.scope)
|
||||
const accessMode = toComputed(options.accessMode)
|
||||
const hostsCount = toComputed(options.hostsCount)
|
||||
|
||||
const title = useMapper(
|
||||
() => options.action,
|
||||
() => ({
|
||||
[CONNECTION_ACTION.CONNECT]: t('sr-connect-title', { n: count.value }),
|
||||
[CONNECTION_ACTION.DISCONNECT]: t('sr-disconnect-title', { n: count.value }),
|
||||
}),
|
||||
CONNECTION_ACTION.CONNECT
|
||||
)
|
||||
|
||||
const info = useMapper(
|
||||
() => `${options.action}-${getSrModalInfoVariant(scope.value, accessMode.value)}`,
|
||||
() => ({
|
||||
'connect-host': t('sr-connect-info-host', { n: count.value }),
|
||||
'connect-pool-local': t('sr-connect-info-pool-local', { n: count.value }),
|
||||
'connect-pool-mixed': t('sr-connect-info-pool-mixed'),
|
||||
'connect-pool-shared': t('sr-connect-info-pool-shared', {
|
||||
n: count.value,
|
||||
hostsCount: hostsCount.value,
|
||||
}),
|
||||
'disconnect-host': t('sr-disconnect-info-host', { n: count.value }),
|
||||
'disconnect-pool-local': t('sr-disconnect-info-pool-local', { n: count.value }),
|
||||
'disconnect-pool-mixed': t('sr-disconnect-info-pool-mixed'),
|
||||
'disconnect-pool-shared': t('sr-disconnect-info-pool-shared', {
|
||||
n: count.value,
|
||||
hostsCount: hostsCount.value,
|
||||
}),
|
||||
}),
|
||||
'connect-pool-shared'
|
||||
)
|
||||
|
||||
return { title, info }
|
||||
}
|
||||
@@ -1,13 +1,13 @@
|
||||
<template>
|
||||
<UiButton
|
||||
v-tooltip="!canToggleVifConnection && toggleConnectionErrorMessage"
|
||||
v-tooltip="!connection.canToggle && connection.errorMessage"
|
||||
size="medium"
|
||||
variant="tertiary"
|
||||
accent="brand"
|
||||
:disabled="!canToggleVifConnection"
|
||||
:disabled="!connection.canToggle"
|
||||
:left-icon="connection.icon"
|
||||
:busy="isTogglingVifConnection"
|
||||
@click="openVifConnectionToggleModal()"
|
||||
:busy="connection.isToggling"
|
||||
@click="connection.toggle()"
|
||||
>
|
||||
{{ connection.label }}
|
||||
</UiButton>
|
||||
@@ -15,12 +15,11 @@
|
||||
|
||||
<script lang="ts" setup>
|
||||
import type { XenApiVif, XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { useVifConnectionToggleModal } from '@/modules/vif/composables/use-vif-connection-toggle-modal.composable.ts'
|
||||
import { useVifConnection } from '@/modules/vif/composables/use-vif-connection.composable.ts'
|
||||
import UiButton from '@core/components/ui/button/UiButton.vue'
|
||||
import { vTooltip } from '@core/directives/tooltip.directive.ts'
|
||||
import { useMapper } from '@core/packages/mapper'
|
||||
import { CONNECTION_ACTION } from '@core/types/connection.ts'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const { vif, vm } = defineProps<{
|
||||
@@ -30,25 +29,40 @@ const { vif, vm } = defineProps<{
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const action = computed(() => (vif.currently_attached ? CONNECTION_ACTION.DISCONNECT : CONNECTION_ACTION.CONNECT))
|
||||
const {
|
||||
connectVifs,
|
||||
disconnectVifs,
|
||||
canConnectVifs,
|
||||
canDisconnectVifs,
|
||||
isConnectingVifs,
|
||||
isDisconnectingVifs,
|
||||
connectVifsErrorMessage,
|
||||
disconnectVifsErrorMessage,
|
||||
} = useVifConnection({
|
||||
vifs: () => [vif],
|
||||
vm: () => vm,
|
||||
})
|
||||
|
||||
const connection = useMapper(
|
||||
() => action.value,
|
||||
() => (vif.currently_attached ? CONNECTION_ACTION.DISCONNECT : CONNECTION_ACTION.CONNECT),
|
||||
() => ({
|
||||
connect: { label: t('action:connect'), icon: 'action:connect' },
|
||||
disconnect: { label: t('action:disconnect'), icon: 'action:disconnect' },
|
||||
connect: {
|
||||
label: t('action:connect'),
|
||||
icon: 'action:connect' as const,
|
||||
toggle: connectVifs,
|
||||
canToggle: canConnectVifs.value,
|
||||
isToggling: isConnectingVifs.value,
|
||||
errorMessage: connectVifsErrorMessage.value,
|
||||
},
|
||||
disconnect: {
|
||||
label: t('action:disconnect'),
|
||||
icon: 'action:disconnect' as const,
|
||||
toggle: disconnectVifs,
|
||||
canToggle: canDisconnectVifs.value,
|
||||
isToggling: isDisconnectingVifs.value,
|
||||
errorMessage: disconnectVifsErrorMessage.value,
|
||||
},
|
||||
}),
|
||||
'connect'
|
||||
)
|
||||
|
||||
const {
|
||||
openModal: openVifConnectionToggleModal,
|
||||
canRun: canToggleVifConnection,
|
||||
isRunning: isTogglingVifConnection,
|
||||
errorMessage: toggleConnectionErrorMessage,
|
||||
} = useVifConnectionToggleModal(
|
||||
action,
|
||||
() => [vif],
|
||||
() => vm
|
||||
)
|
||||
</script>
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
import type { XenApiVif, XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { useVifConnectJob } from '@/modules/vif/jobs/vif-connect.job.ts'
|
||||
import { useVifDisconnectJob } from '@/modules/vif/jobs/vif-disconnect.job.ts'
|
||||
import { useModal } from '@core/packages/modal/use-modal.ts'
|
||||
import { CONNECTION_ACTION, type ConnectionAction } from '@core/types/connection.ts'
|
||||
import { toComputed } from '@core/utils/to-computed.util.ts'
|
||||
import { computed, type MaybeRefOrGetter } from 'vue'
|
||||
|
||||
export function useVifConnectionToggleModal(
|
||||
rawAction: MaybeRefOrGetter<ConnectionAction>,
|
||||
rawVifs: MaybeRefOrGetter<XenApiVif[]>,
|
||||
rawVm: MaybeRefOrGetter<XenApiVm>
|
||||
) {
|
||||
const action = toComputed(rawAction)
|
||||
const vifs = toComputed(rawVifs)
|
||||
const vm = toComputed(rawVm)
|
||||
|
||||
const connectJob = useVifConnectJob(vifs, vm)
|
||||
const disconnectJob = useVifDisconnectJob(vifs, vm)
|
||||
|
||||
const job = computed(() => (action.value === CONNECTION_ACTION.CONNECT ? connectJob : disconnectJob))
|
||||
|
||||
const canRun = computed(() => job.value.canRun.value)
|
||||
const isRunning = computed(() => job.value.isRunning.value)
|
||||
const errorMessage = computed(() => job.value.errorMessage.value)
|
||||
|
||||
const openModal = useModal(() => ({
|
||||
component: import('@core/components/vif-connection-toggle-modal/VtsVifConnectionToggleModal.vue'),
|
||||
props: { action: action.value, count: vifs.value.length },
|
||||
onConfirm: async () => {
|
||||
try {
|
||||
await job.value.run()
|
||||
} catch (error) {
|
||||
console.error(`Error when ${action.value}ing VIF:`, error)
|
||||
}
|
||||
},
|
||||
}))
|
||||
|
||||
return { openModal, canRun, isRunning, errorMessage }
|
||||
}
|
||||
@@ -0,0 +1,81 @@
|
||||
import type { XenApiVif, XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { useVifConnectJob } from '@/modules/vif/jobs/vif-connect.job.ts'
|
||||
import { useVifDisconnectJob } from '@/modules/vif/jobs/vif-disconnect.job.ts'
|
||||
import { useOverlay } from '@core/packages/overlay/use-overlay.ts'
|
||||
import { CONNECTION_ACTION } from '@core/types/connection.ts'
|
||||
import { toComputed } from '@core/utils/to-computed.util.ts'
|
||||
import type { MaybeRefOrGetter } from 'vue'
|
||||
|
||||
export function useVifConnection(options: { vifs: MaybeRefOrGetter<XenApiVif[]>; vm: MaybeRefOrGetter<XenApiVm> }) {
|
||||
const vifs = toComputed(options.vifs)
|
||||
const vm = toComputed(options.vm)
|
||||
|
||||
const {
|
||||
run: runConnect,
|
||||
canRun: canConnectVifs,
|
||||
isRunning: isConnectingVifs,
|
||||
errorMessage: connectVifsErrorMessage,
|
||||
} = useVifConnectJob(vifs, vm)
|
||||
|
||||
const {
|
||||
run: runDisconnect,
|
||||
canRun: canDisconnectVifs,
|
||||
isRunning: isDisconnectingVifs,
|
||||
errorMessage: disconnectVifsErrorMessage,
|
||||
} = useVifDisconnectJob(vifs, vm)
|
||||
|
||||
const { open } = useOverlay({
|
||||
component: () => import('@core/components/vif-connection-modal/VtsVifConnectionModal.vue'),
|
||||
events: {
|
||||
onConfirm: true,
|
||||
onCancel: true,
|
||||
},
|
||||
})
|
||||
|
||||
function connectVifs() {
|
||||
return open({
|
||||
props: {
|
||||
action: CONNECTION_ACTION.CONNECT,
|
||||
count: vifs.value.length,
|
||||
},
|
||||
events: {
|
||||
onConfirm: async () => {
|
||||
try {
|
||||
await runConnect()
|
||||
} catch (error) {
|
||||
console.error('Error when connecting VIF:', error)
|
||||
}
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
function disconnectVifs() {
|
||||
return open({
|
||||
props: {
|
||||
action: CONNECTION_ACTION.DISCONNECT,
|
||||
count: vifs.value.length,
|
||||
},
|
||||
events: {
|
||||
onConfirm: async () => {
|
||||
try {
|
||||
await runDisconnect()
|
||||
} catch (error) {
|
||||
console.error('Error when disconnecting VIF:', error)
|
||||
}
|
||||
},
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
return {
|
||||
connectVifs,
|
||||
disconnectVifs,
|
||||
canConnectVifs,
|
||||
canDisconnectVifs,
|
||||
isConnectingVifs,
|
||||
isDisconnectingVifs,
|
||||
connectVifsErrorMessage,
|
||||
disconnectVifsErrorMessage,
|
||||
}
|
||||
}
|
||||
@@ -205,7 +205,7 @@ import UiRadioButton from '@core/components/ui/radio-button/UiRadioButton.vue'
|
||||
import UiRadioButtonGroup from '@core/components/ui/radio-button-group/UiRadioButtonGroup.vue'
|
||||
import UiToggle from '@core/components/ui/toggle/UiToggle.vue'
|
||||
import { useFormSelect } from '@core/packages/form-select'
|
||||
import { useModal } from '@core/packages/modal/use-modal.ts'
|
||||
import { useOverlay } from '@core/packages/overlay/use-overlay.ts'
|
||||
import { useUiStore } from '@core/stores/ui.store'
|
||||
import { logicNot } from '@vueuse/math'
|
||||
import { computed, onUnmounted, ref, watch } from 'vue'
|
||||
@@ -219,10 +219,16 @@ const router = useRouter()
|
||||
|
||||
usePageTitleStore().setTitle(() => t('action:deploy-xoa'))
|
||||
|
||||
const openInvalidFieldModal = useModal((message: string) => ({
|
||||
component: import('@/components/modals/InvalidFieldModal.vue'),
|
||||
props: { message },
|
||||
}))
|
||||
const { open: openModal } = useOverlay({
|
||||
component: () => import('@/components/modals/InvalidFieldModal.vue'),
|
||||
events: {
|
||||
onClose: true,
|
||||
},
|
||||
})
|
||||
|
||||
function openInvalidFieldModal(message: string) {
|
||||
return openModal({ props: { message } })
|
||||
}
|
||||
|
||||
const uiStore = useUiStore()
|
||||
|
||||
|
||||
76
@xen-orchestra/lite/src/route-map.d.ts
vendored
76
@xen-orchestra/lite/src/route-map.d.ts
vendored
@@ -233,6 +233,13 @@ declare module 'vue-router/auto-routes' {
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/overlay': RouteRecordInfo<
|
||||
'/story/overlay',
|
||||
'/story/overlay',
|
||||
Record<never, never>,
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/power-state-icon': RouteRecordInfo<
|
||||
'/story/power-state-icon',
|
||||
'/story/power-state-icon',
|
||||
@@ -331,13 +338,6 @@ declare module 'vue-router/auto-routes' {
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/drawer/vts-drawer': RouteRecordInfo<
|
||||
'/story/web-core/drawer/vts-drawer',
|
||||
'/story/web-core/drawer/vts-drawer',
|
||||
Record<never, never>,
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/dropdown-title/vts-dropdown-title': RouteRecordInfo<
|
||||
'/story/web-core/dropdown-title/vts-dropdown-title',
|
||||
'/story/web-core/dropdown-title/vts-dropdown-title',
|
||||
@@ -387,16 +387,30 @@ declare module 'vue-router/auto-routes' {
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/modal/vts-modal': RouteRecordInfo<
|
||||
'/story/web-core/modal/vts-modal',
|
||||
'/story/web-core/modal/vts-modal',
|
||||
'/story/web-core/object-icon/vts-object-icon': RouteRecordInfo<
|
||||
'/story/web-core/object-icon/vts-object-icon',
|
||||
'/story/web-core/object-icon/vts-object-icon',
|
||||
Record<never, never>,
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/object-icon/vts-object-icon': RouteRecordInfo<
|
||||
'/story/web-core/object-icon/vts-object-icon',
|
||||
'/story/web-core/object-icon/vts-object-icon',
|
||||
'/story/web-core/overlay/vts-overlay-button': RouteRecordInfo<
|
||||
'/story/web-core/overlay/vts-overlay-button',
|
||||
'/story/web-core/overlay/vts-overlay-button',
|
||||
Record<never, never>,
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/overlay/vts-overlay-cancel-button': RouteRecordInfo<
|
||||
'/story/web-core/overlay/vts-overlay-cancel-button',
|
||||
'/story/web-core/overlay/vts-overlay-cancel-button',
|
||||
Record<never, never>,
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/overlay/vts-overlay-confirm-button': RouteRecordInfo<
|
||||
'/story/web-core/overlay/vts-overlay-confirm-button',
|
||||
'/story/web-core/overlay/vts-overlay-confirm-button',
|
||||
Record<never, never>,
|
||||
Record<never, never>,
|
||||
| never
|
||||
@@ -1200,6 +1214,12 @@ declare module 'vue-router/auto-routes' {
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/overlay.story.vue': {
|
||||
routes:
|
||||
| '/story/overlay'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/power-state-icon.story.vue': {
|
||||
routes:
|
||||
| '/story/power-state-icon'
|
||||
@@ -1284,12 +1304,6 @@ declare module 'vue-router/auto-routes' {
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/drawer/vts-drawer.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/drawer/vts-drawer'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/dropdown-title/vts-dropdown-title.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/dropdown-title/vts-dropdown-title'
|
||||
@@ -1332,18 +1346,30 @@ declare module 'vue-router/auto-routes' {
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/modal/vts-modal.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/modal/vts-modal'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/object-icon/vts-object-icon.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/object-icon/vts-object-icon'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/overlay/vts-overlay-button.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/overlay/vts-overlay-button'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/overlay/vts-overlay-cancel-button.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/overlay/vts-overlay-cancel-button'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/overlay/vts-overlay-confirm-button.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/overlay/vts-overlay-confirm-button'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/panel/vts-panel.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/panel/vts-panel'
|
||||
|
||||
91
@xen-orchestra/lite/src/stories/overlay.story.vue
Normal file
91
@xen-orchestra/lite/src/stories/overlay.story.vue
Normal file
@@ -0,0 +1,91 @@
|
||||
<template>
|
||||
<UiCard class="overlay-story">
|
||||
<UiCardTitle>Overlay system demo</UiCardTitle>
|
||||
|
||||
<p class="row">
|
||||
VM name: <strong>{{ vmName }}</strong>
|
||||
</p>
|
||||
|
||||
<p class="row">
|
||||
The button opens a drawer, which opens a rename modal, which opens a confirmation modal. The confirmed name is
|
||||
trimmed by the drawer, then propagated back here, where the drawer is kept open with the updated name (reactive
|
||||
props).
|
||||
</p>
|
||||
|
||||
<div class="row">
|
||||
<UiButton accent="brand" size="medium" variant="primary" @click="openDrawer()">Open VM drawer</UiButton>
|
||||
</div>
|
||||
|
||||
<div v-if="logs.length > 0" class="logs">
|
||||
<UiCardTitle>Responses</UiCardTitle>
|
||||
<ul>
|
||||
<li v-for="(log, index) of logs" :key="index" class="row">{{ log }}</li>
|
||||
</ul>
|
||||
</div>
|
||||
</UiCard>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import UiButton from '@core/components/ui/button/UiButton.vue'
|
||||
import UiCard from '@core/components/ui/card/UiCard.vue'
|
||||
import UiCardTitle from '@core/components/ui/card-title/UiCardTitle.vue'
|
||||
import { KEEP_OVERLAY_OPEN, OVERLAY_ABORT_EVENT } from '@core/packages/overlay/symbols.ts'
|
||||
import { useOverlay } from '@core/packages/overlay/use-overlay.ts'
|
||||
import { reactiveComputed } from '@vueuse/core'
|
||||
import { ref } from 'vue'
|
||||
|
||||
const vmName = ref('XO Lite VM')
|
||||
|
||||
const logs = ref<string[]>([])
|
||||
|
||||
function addLog(message: string) {
|
||||
logs.value.unshift(message)
|
||||
}
|
||||
|
||||
const { open: openVmDrawer } = useOverlay({
|
||||
component: () => import('@/stories/overlay/DemoVmDrawer.vue'),
|
||||
events: {
|
||||
onDismiss: true,
|
||||
},
|
||||
})
|
||||
|
||||
// `reactiveComputed` keeps the drawer in sync when the name changes while it is open
|
||||
const drawerProps = reactiveComputed(() => ({ name: vmName.value }))
|
||||
|
||||
async function openDrawer() {
|
||||
const response = await openVmDrawer({
|
||||
props: drawerProps,
|
||||
events: {
|
||||
onRename: newName => {
|
||||
vmName.value = newName
|
||||
|
||||
addLog(`onRename → "${newName}" (drawer kept open, showing the new name)`)
|
||||
|
||||
return KEEP_OVERLAY_OPEN
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
if (response.event === OVERLAY_ABORT_EVENT) {
|
||||
addLog('Drawer aborted (opener disposed or replaced)')
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
addLog(`${response.event} → drawer closed`)
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
.overlay-story {
|
||||
margin: 1rem;
|
||||
|
||||
.row {
|
||||
font-size: 1.6rem;
|
||||
}
|
||||
|
||||
.logs {
|
||||
margin-block-start: 1.6rem;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
43
@xen-orchestra/lite/src/stories/overlay/DemoConfirmModal.vue
Normal file
43
@xen-orchestra/lite/src/stories/overlay/DemoConfirmModal.vue
Normal file
@@ -0,0 +1,43 @@
|
||||
<template>
|
||||
<UiModal accent="warning" @confirm="emit('confirm')" @dismiss="emit('cancel')">
|
||||
<template #title>Confirm rename</template>
|
||||
<template #content>
|
||||
<div class="demo-confirm-modal-content">
|
||||
<p>
|
||||
Rename "<strong>{{ currentName }}</strong
|
||||
>" to "<strong>{{ newName }}</strong
|
||||
>"?
|
||||
</p>
|
||||
<p>Confirming runs a fake 1.5s API call: the Rename button turns busy and the Cancel button is locked.</p>
|
||||
</div>
|
||||
</template>
|
||||
<template #buttons>
|
||||
<VtsOverlayCancelButton @click="emit('cancel')" />
|
||||
<VtsOverlayConfirmButton>Rename</VtsOverlayConfirmButton>
|
||||
</template>
|
||||
</UiModal>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import VtsOverlayCancelButton from '@core/components/overlay/VtsOverlayCancelButton.vue'
|
||||
import VtsOverlayConfirmButton from '@core/components/overlay/VtsOverlayConfirmButton.vue'
|
||||
import UiModal from '@core/components/ui/modal/UiModal.vue'
|
||||
|
||||
defineProps<{
|
||||
currentName: string
|
||||
newName: string
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
confirm: []
|
||||
cancel: []
|
||||
}>()
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
.demo-confirm-modal-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.6rem;
|
||||
}
|
||||
</style>
|
||||
96
@xen-orchestra/lite/src/stories/overlay/DemoRenameModal.vue
Normal file
96
@xen-orchestra/lite/src/stories/overlay/DemoRenameModal.vue
Normal file
@@ -0,0 +1,96 @@
|
||||
<template>
|
||||
<UiModal accent="info" @confirm="handleSubmit()" @dismiss="emit('cancel')">
|
||||
<template #title>Rename VM</template>
|
||||
<template #content>
|
||||
<div class="demo-rename-modal-content">
|
||||
<VtsInputWrapper label="New name">
|
||||
<UiInput v-model.trim="newName" accent="brand" required />
|
||||
</VtsInputWrapper>
|
||||
<p>
|
||||
Tip: name the VM "fail" to make the fake API call fail: the confirmation modal closes and this modal stays
|
||||
open to pick another name.
|
||||
</p>
|
||||
<p v-if="hasRenameFailed" class="error">The rename failed. Try another name.</p>
|
||||
</div>
|
||||
</template>
|
||||
<template #buttons>
|
||||
<VtsOverlayCancelButton @click="emit('cancel')" />
|
||||
<VtsOverlayConfirmButton>Save</VtsOverlayConfirmButton>
|
||||
</template>
|
||||
</UiModal>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import VtsInputWrapper from '@core/components/input-wrapper/VtsInputWrapper.vue'
|
||||
import VtsOverlayCancelButton from '@core/components/overlay/VtsOverlayCancelButton.vue'
|
||||
import VtsOverlayConfirmButton from '@core/components/overlay/VtsOverlayConfirmButton.vue'
|
||||
import UiInput from '@core/components/ui/input/UiInput.vue'
|
||||
import UiModal from '@core/components/ui/modal/UiModal.vue'
|
||||
import { useOverlay } from '@core/packages/overlay/use-overlay.ts'
|
||||
import { ref } from 'vue'
|
||||
|
||||
const { name } = defineProps<{
|
||||
name: string
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
submit: [newName: string]
|
||||
cancel: []
|
||||
}>()
|
||||
|
||||
const newName = ref(name)
|
||||
|
||||
const hasRenameFailed = ref(false)
|
||||
|
||||
const { open: openConfirmModal } = useOverlay({
|
||||
component: () => import('@/stories/overlay/DemoConfirmModal.vue'),
|
||||
events: {
|
||||
onConfirm: true,
|
||||
onCancel: true,
|
||||
},
|
||||
})
|
||||
|
||||
// Simulated API call, to showcase the busy state. Renaming to "fail" fails.
|
||||
async function renameVm(value: string) {
|
||||
await new Promise(resolve => setTimeout(resolve, 1500))
|
||||
|
||||
return value.toLowerCase() !== 'fail'
|
||||
}
|
||||
|
||||
async function handleSubmit() {
|
||||
hasRenameFailed.value = false
|
||||
|
||||
const response = await openConfirmModal({
|
||||
props: { currentName: name, newName: newName.value },
|
||||
events: {
|
||||
// Per-call async handler: the confirmation modal is busy while it runs,
|
||||
// then closes, and the API result becomes the response payload
|
||||
onConfirm: () => renameVm(newName.value),
|
||||
},
|
||||
})
|
||||
|
||||
if (response.event !== 'onConfirm') {
|
||||
return
|
||||
}
|
||||
|
||||
if (!response.payload) {
|
||||
hasRenameFailed.value = true
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
emit('submit', newName.value)
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
.demo-rename-modal-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.6rem;
|
||||
|
||||
.error {
|
||||
color: var(--color-danger-txt-base);
|
||||
}
|
||||
}
|
||||
</style>
|
||||
57
@xen-orchestra/lite/src/stories/overlay/DemoVmDrawer.vue
Normal file
57
@xen-orchestra/lite/src/stories/overlay/DemoVmDrawer.vue
Normal file
@@ -0,0 +1,57 @@
|
||||
<template>
|
||||
<UiDrawer title="VM settings" @confirm="handleRename()" @dismiss="emit('dismiss')">
|
||||
<template #content>
|
||||
<div class="demo-vm-drawer-content">
|
||||
<p>
|
||||
Current name: <strong>{{ name }}</strong>
|
||||
</p>
|
||||
<p>"Rename…" opens a modal on top of this drawer, which itself opens a confirmation modal.</p>
|
||||
</div>
|
||||
</template>
|
||||
<template #buttons>
|
||||
<VtsOverlayCancelButton @click="emit('dismiss')">Close</VtsOverlayCancelButton>
|
||||
<VtsOverlayConfirmButton>Rename…</VtsOverlayConfirmButton>
|
||||
</template>
|
||||
</UiDrawer>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import VtsOverlayCancelButton from '@core/components/overlay/VtsOverlayCancelButton.vue'
|
||||
import VtsOverlayConfirmButton from '@core/components/overlay/VtsOverlayConfirmButton.vue'
|
||||
import UiDrawer from '@core/components/ui/drawer/UiDrawer.vue'
|
||||
import { useOverlay } from '@core/packages/overlay/use-overlay.ts'
|
||||
|
||||
const { name } = defineProps<{
|
||||
name: string
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
rename: [newName: string]
|
||||
dismiss: []
|
||||
}>()
|
||||
|
||||
const { open: openRenameModal } = useOverlay({
|
||||
component: () => import('@/stories/overlay/DemoRenameModal.vue'),
|
||||
events: {
|
||||
// Transforms the raw emitted value: the trimmed name becomes the payload
|
||||
onSubmit: (newName: string) => newName.trim(),
|
||||
onCancel: true,
|
||||
},
|
||||
})
|
||||
|
||||
async function handleRename() {
|
||||
const response = await openRenameModal({ props: { name } })
|
||||
|
||||
if (response.event === 'onSubmit') {
|
||||
emit('rename', response.payload)
|
||||
}
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
.demo-vm-drawer-content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.6rem;
|
||||
}
|
||||
</style>
|
||||
@@ -1,121 +0,0 @@
|
||||
<template>
|
||||
<ComponentStory
|
||||
v-slot="{ properties, settings }"
|
||||
:params="[
|
||||
prop('isOpen').bool().help('Controls drawer visibility'),
|
||||
prop('dismissible').bool().widget().help('Allow closing via backdrop click, dismiss button and Escape key'),
|
||||
prop('current').bool().widget().help('Only the current (topmost) drawer reacts to Escape'),
|
||||
event('dismiss').help('Emitted when the drawer is dismissed'),
|
||||
slot('title').help('Drawer title'),
|
||||
slot('content').help('Main content area'),
|
||||
slot('buttons').help('Footer buttons area (wrapped in VtsButtonGroup)'),
|
||||
setting('showForm').widget(boolean()).preset(false).help('Show a form example inside content'),
|
||||
]"
|
||||
:presets="{
|
||||
Default: {
|
||||
props: { isOpen: true, dismissible: true, current: true },
|
||||
},
|
||||
'With form': {
|
||||
props: { isOpen: true, dismissible: true, current: true },
|
||||
settings: { showForm: true },
|
||||
},
|
||||
}"
|
||||
>
|
||||
<UiButton variant="primary" accent="brand" size="medium" @click="isOpen = true">Open Drawer</UiButton>
|
||||
|
||||
<VtsDrawer
|
||||
:is-open="isOpen"
|
||||
:dismissible="properties.dismissible"
|
||||
:current="properties.current"
|
||||
@dismiss="handleDismiss()"
|
||||
>
|
||||
<template #title>Drawer Title</template>
|
||||
<template #content>
|
||||
<form v-if="settings.showForm" class="form" @submit.prevent="handleSubmit()">
|
||||
<VtsInputWrapper
|
||||
label="Name"
|
||||
:message="isNameEmpty ? { content: 'Name is required', accent: 'danger' } : undefined"
|
||||
>
|
||||
<UiInput v-model.trim="form.name" required :accent="isNameEmpty ? 'danger' : 'brand'" />
|
||||
</VtsInputWrapper>
|
||||
<VtsInputWrapper label="Description">
|
||||
<UiInput v-model="form.description" accent="brand" />
|
||||
</VtsInputWrapper>
|
||||
<div class="actions">
|
||||
<UiButton variant="secondary" accent="brand" size="medium" @click="handleDismiss()">Cancel</UiButton>
|
||||
<UiButton variant="primary" accent="brand" size="medium" type="submit" :disabled="isNameEmpty">
|
||||
Save
|
||||
</UiButton>
|
||||
</div>
|
||||
</form>
|
||||
<p v-else>This is the drawer content.</p>
|
||||
</template>
|
||||
<template v-if="!settings.showForm" #buttons>
|
||||
<UiButton
|
||||
v-if="properties.dismissible"
|
||||
variant="secondary"
|
||||
accent="brand"
|
||||
size="medium"
|
||||
@click="handleDismiss()"
|
||||
>
|
||||
Cancel
|
||||
</UiButton>
|
||||
<UiButton variant="primary" accent="brand" size="medium" @click="handleDismiss()">Confirm</UiButton>
|
||||
</template>
|
||||
</VtsDrawer>
|
||||
</ComponentStory>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { event, prop, setting, slot } from '@/libs/story/story-param'
|
||||
import { boolean } from '@/libs/story/story-widget'
|
||||
import VtsDrawer from '@core/components/drawer/VtsDrawer.vue'
|
||||
import VtsInputWrapper from '@core/components/input-wrapper/VtsInputWrapper.vue'
|
||||
import UiButton from '@core/components/ui/button/UiButton.vue'
|
||||
import UiInput from '@core/components/ui/input/UiInput.vue'
|
||||
import { computed, reactive, ref } from 'vue'
|
||||
|
||||
const isOpen = ref(false)
|
||||
|
||||
const form = reactive({
|
||||
name: '',
|
||||
description: '',
|
||||
})
|
||||
|
||||
const isNameEmpty = computed(() => form.name.trim() === '')
|
||||
|
||||
function handleSubmit() {
|
||||
if (isNameEmpty.value) {
|
||||
return
|
||||
}
|
||||
|
||||
resetForm()
|
||||
}
|
||||
|
||||
function handleDismiss() {
|
||||
resetForm()
|
||||
}
|
||||
|
||||
function resetForm() {
|
||||
isOpen.value = false
|
||||
form.name = ''
|
||||
form.description = ''
|
||||
}
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
.form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.6rem;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 0.8rem;
|
||||
margin-top: 1.6rem;
|
||||
}
|
||||
</style>
|
||||
@@ -1,52 +0,0 @@
|
||||
<template>
|
||||
<ComponentStory
|
||||
v-slot="{ properties, settings }"
|
||||
:params="[
|
||||
prop('accent').required().enum('info', 'warning', 'danger').preset('info').widget(),
|
||||
iconProp(),
|
||||
prop('dismissible').bool().widget(),
|
||||
prop('onDismiss').type('function').widget(),
|
||||
prop('onConfirm').type('function').widget(),
|
||||
prop('current').bool().widget(),
|
||||
event('confirm'),
|
||||
event('dismiss'),
|
||||
slot('title'),
|
||||
slot('content'),
|
||||
slot('buttons'),
|
||||
setting('titleSlotContent')
|
||||
.preset('Example content for title slot')
|
||||
.widget(text())
|
||||
.help('Content for title slot'),
|
||||
setting('contentSlotContent')
|
||||
.preset('Example content for content slot')
|
||||
.widget(text())
|
||||
.help('Content for content slot'),
|
||||
setting('showDemoButtons').widget(boolean()),
|
||||
]"
|
||||
>
|
||||
<VtsModal class="story" v-bind="properties">
|
||||
<template #title>{{ settings.titleSlotContent }}</template>
|
||||
<template #content>{{ settings.contentSlotContent }}</template>
|
||||
<template v-if="settings.showDemoButtons" #buttons>
|
||||
<VtsModalCancelButton>Cancel</VtsModalCancelButton>
|
||||
<VtsModalConfirmButton> Confirm </VtsModalConfirmButton>
|
||||
</template>
|
||||
</VtsModal>
|
||||
</ComponentStory>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { iconProp, prop, event, slot, setting } from '@/libs/story/story-param'
|
||||
import { text, boolean } from '@/libs/story/story-widget'
|
||||
import VtsModal from '@core/components/modal/VtsModal.vue'
|
||||
import VtsModalCancelButton from '@core/components/modal/VtsModalCancelButton.vue'
|
||||
import VtsModalConfirmButton from '@core/components/modal/VtsModalConfirmButton.vue'
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
.story {
|
||||
position: relative;
|
||||
height: 100%;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,19 @@
|
||||
<template>
|
||||
<ComponentStory
|
||||
v-slot="{ properties, settings }"
|
||||
:params="[
|
||||
prop('variant').required().enum('primary', 'secondary', 'tertiary').preset('primary').widget(),
|
||||
slot().help('Button label'),
|
||||
setting('label').preset('Click me').widget(text()),
|
||||
]"
|
||||
>
|
||||
<VtsOverlayButton v-bind="properties">{{ settings.label }}</VtsOverlayButton>
|
||||
</ComponentStory>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { prop, setting, slot } from '@/libs/story/story-param'
|
||||
import { text } from '@/libs/story/story-widget'
|
||||
import VtsOverlayButton from '@core/components/overlay/VtsOverlayButton.vue'
|
||||
</script>
|
||||
@@ -0,0 +1,20 @@
|
||||
<template>
|
||||
<ComponentStory
|
||||
v-slot="{ settings }"
|
||||
:params="[
|
||||
slot().help('Button label. Defaults to the translated \'Cancel\' label'),
|
||||
setting('label').preset('').widget(text()).help('Leave empty to use the default label'),
|
||||
]"
|
||||
>
|
||||
<VtsOverlayCancelButton>
|
||||
<template v-if="settings.label" #default>{{ settings.label }}</template>
|
||||
</VtsOverlayCancelButton>
|
||||
</ComponentStory>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { setting, slot } from '@/libs/story/story-param'
|
||||
import { text } from '@/libs/story/story-widget'
|
||||
import VtsOverlayCancelButton from '@core/components/overlay/VtsOverlayCancelButton.vue'
|
||||
</script>
|
||||
@@ -0,0 +1,21 @@
|
||||
<template>
|
||||
<ComponentStory
|
||||
v-slot="{ properties, settings }"
|
||||
:params="[
|
||||
event('click').help(
|
||||
'When a listener is present, the button is of type \'button\' and emits this event. Otherwise it is of type \'submit\' and submits the surrounding overlay form'
|
||||
),
|
||||
slot().help('Button label'),
|
||||
setting('label').preset('Confirm').widget(text()),
|
||||
]"
|
||||
>
|
||||
<VtsOverlayConfirmButton v-bind="properties">{{ settings.label }}</VtsOverlayConfirmButton>
|
||||
</ComponentStory>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { event, setting, slot } from '@/libs/story/story-param'
|
||||
import { text } from '@/libs/story/story-widget'
|
||||
import VtsOverlayConfirmButton from '@core/components/overlay/VtsOverlayConfirmButton.vue'
|
||||
</script>
|
||||
@@ -3,44 +3,22 @@
|
||||
v-slot="{ properties, settings }"
|
||||
:params="[
|
||||
prop('title').str().widget().preset('Drawer Title'),
|
||||
prop('isOpen').bool().widget(),
|
||||
prop('isDismissible').bool().help('Show dismiss button and enable backdrop click'),
|
||||
event('dismiss').help('Emitted when dismiss button or backdrop is clicked'),
|
||||
event('confirm').help('Emitted when the form is submitted (e.g. a submit button is clicked or Enter is pressed)'),
|
||||
event('dismiss').help('Emitted when the dismiss button or backdrop is clicked, or Escape is pressed'),
|
||||
slot('title').help('Overrides the title prop'),
|
||||
slot('content').help('Main content area'),
|
||||
slot('buttons').help('Footer buttons area'),
|
||||
setting('dismissible').widget(boolean()).preset(true).help('Toggle dismiss behavior in this story'),
|
||||
setting('contentSlotContent')
|
||||
.preset('This is the drawer content.')
|
||||
.widget(text())
|
||||
.help('Content for content slot'),
|
||||
setting('showButtons').widget(boolean()).preset(true),
|
||||
]"
|
||||
:presets="{
|
||||
Dismissible: {
|
||||
props: { isOpen: true },
|
||||
settings: { dismissible: true },
|
||||
},
|
||||
Persistent: {
|
||||
props: { isOpen: true },
|
||||
settings: { dismissible: false },
|
||||
},
|
||||
'No title': {
|
||||
props: { isOpen: true, title: '' },
|
||||
settings: { dismissible: true },
|
||||
},
|
||||
'No buttons': {
|
||||
props: { isOpen: true },
|
||||
settings: { dismissible: true, showButtons: false },
|
||||
},
|
||||
}"
|
||||
>
|
||||
<UiButton variant="primary" accent="brand" size="medium" @click="isOpen = true">Open Drawer</UiButton>
|
||||
|
||||
<UiDrawer :is-open :title="properties.title" :is-dismissible="settings.dismissible" @dismiss="isOpen = false">
|
||||
<template #content>
|
||||
<p>This is the drawer content.</p>
|
||||
</template>
|
||||
<UiDrawer class="story" v-bind="properties">
|
||||
<template #content>{{ settings.contentSlotContent }}</template>
|
||||
<template v-if="settings.showButtons" #buttons>
|
||||
<UiButton v-if="settings.dismissible" variant="secondary" accent="brand" size="medium" @click="isOpen = false">
|
||||
Cancel
|
||||
</UiButton>
|
||||
<UiButton variant="primary" accent="brand" size="medium" @click="isOpen = false">Confirm</UiButton>
|
||||
<VtsOverlayConfirmButton>Confirm</VtsOverlayConfirmButton>
|
||||
</template>
|
||||
</UiDrawer>
|
||||
</ComponentStory>
|
||||
@@ -49,10 +27,18 @@
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { event, prop, setting, slot } from '@/libs/story/story-param'
|
||||
import { boolean } from '@/libs/story/story-widget'
|
||||
import UiButton from '@core/components/ui/button/UiButton.vue'
|
||||
import { boolean, text } from '@/libs/story/story-widget'
|
||||
import VtsOverlayConfirmButton from '@core/components/overlay/VtsOverlayConfirmButton.vue'
|
||||
import UiDrawer from '@core/components/ui/drawer/UiDrawer.vue'
|
||||
import { ref } from 'vue'
|
||||
|
||||
const isOpen = ref(false)
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
.story {
|
||||
position: relative;
|
||||
height: 100%;
|
||||
|
||||
:deep(.drawer) {
|
||||
min-height: 100%;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -4,9 +4,10 @@
|
||||
:params="[
|
||||
prop('accent').required().enum('info', 'warning', 'danger').preset('info').widget(),
|
||||
iconProp(),
|
||||
prop('dismissible').bool().widget(),
|
||||
prop('onDismiss').type('function').widget(),
|
||||
event('dismiss'),
|
||||
event('confirm').help('Emitted when the form is submitted (e.g. a submit button is clicked or Enter is pressed)'),
|
||||
event('dismiss').help(
|
||||
'When a listener is present, the dismiss button is displayed. Also emitted on Escape or backdrop click'
|
||||
),
|
||||
slot('title'),
|
||||
slot('content'),
|
||||
slot('buttons'),
|
||||
@@ -25,9 +26,7 @@
|
||||
<template #title>{{ settings.titleSlotContent }}</template>
|
||||
<template #content>{{ settings.contentSlotContent }}</template>
|
||||
<template v-if="settings.showDemoButton" #buttons>
|
||||
<UiButton :accent="properties.accent === 'info' ? 'brand' : properties.accent" variant="primary" size="medium">
|
||||
Confirm
|
||||
</UiButton>
|
||||
<VtsOverlayConfirmButton>Confirm</VtsOverlayConfirmButton>
|
||||
</template>
|
||||
</UiModal>
|
||||
</ComponentStory>
|
||||
@@ -37,7 +36,7 @@
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { iconProp, prop, event, slot, setting } from '@/libs/story/story-param'
|
||||
import { text, boolean } from '@/libs/story/story-widget'
|
||||
import UiButton from '@core/components/ui/button/UiButton.vue'
|
||||
import VtsOverlayConfirmButton from '@core/components/overlay/VtsOverlayConfirmButton.vue'
|
||||
import UiModal from '@core/components/ui/modal/UiModal.vue'
|
||||
</script>
|
||||
|
||||
|
||||
@@ -34,7 +34,7 @@
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.19.0",
|
||||
"@types/node": "^22.3.0",
|
||||
"@vates/types": "^1.29.0",
|
||||
"@vates/types": "^1.30.1",
|
||||
"rimraf": "^6.0.0",
|
||||
"typescript": "~5.6.3",
|
||||
"typescript-eslint": "^8.61.0"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"private": true,
|
||||
"name": "@xen-orchestra/proxy",
|
||||
"version": "0.31.3",
|
||||
"version": "0.31.6",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"description": "XO Proxy used to remotely execute backup jobs",
|
||||
"keywords": [
|
||||
@@ -33,13 +33,13 @@
|
||||
"@vates/disposable": "^0.1.6",
|
||||
"@vates/task": "^0.7.0",
|
||||
"@xen-orchestra/async-map": "^0.1.3",
|
||||
"@xen-orchestra/backups": "^0.73.8",
|
||||
"@xen-orchestra/fs": "^4.9.2",
|
||||
"@xen-orchestra/backups": "^0.73.10",
|
||||
"@xen-orchestra/fs": "^4.9.3",
|
||||
"@xen-orchestra/log": "^0.7.2",
|
||||
"@xen-orchestra/mixin": "^0.2.1",
|
||||
"@xen-orchestra/mixins": "^0.20.1",
|
||||
"@xen-orchestra/self-signed": "^0.2.1",
|
||||
"@xen-orchestra/xapi": "^8.10.0",
|
||||
"@xen-orchestra/xapi": "^8.10.2",
|
||||
"ajv": "^8.0.3",
|
||||
"app-conf": "^3.0.0",
|
||||
"async-iterator-to-stream": "^1.1.0",
|
||||
|
||||
@@ -67,6 +67,38 @@ SDN_CONTROLLER_VM_ID=
|
||||
# Must be a test-scoped path (containing 'test', 'qa', or 'tmp/') for cleanup safety
|
||||
VHD_EXPORT_PATH=/tmp/xo-test-exports
|
||||
|
||||
# ===========================================
|
||||
# ESXI MIGRATION (V2V) TEST CONFIGURATION
|
||||
# ===========================================
|
||||
|
||||
# `yarn qa:import:esxi` is skipped unless all four of these are set.
|
||||
# The source VM must be RUNNING and have NO SNAPSHOT: the test migrates a live VM and checks
|
||||
# that XO takes its own snapshot. It leaves the VM halted, with that snapshot — restart is
|
||||
# automatic, but the snapshot has to be removed by hand before the next run.
|
||||
# ESXI_VM_ID is the VMware MoRef id (a number, as shown by esxi.listVms), not a UUID.
|
||||
ESXI_HOST=
|
||||
ESXI_USER=root
|
||||
ESXI_PASSWORD=
|
||||
ESXI_VM_ID=
|
||||
|
||||
# Set to "true" to validate the ESXi certificate — off by default, lab hosts are self-signed
|
||||
ESXI_SSL_VERIFY=false
|
||||
|
||||
# The target SR is SR_ID above. Network and template are looked up on that SR's pool:
|
||||
# the first network with a PIF, and a template named ESXI_TEMPLATE_NAME. Override either
|
||||
# with an explicit UUID when the guess is wrong.
|
||||
ESXI_NETWORK_ID=
|
||||
ESXI_TEMPLATE_ID=
|
||||
ESXI_TEMPLATE_NAME=Other install media
|
||||
|
||||
# Per-request timeout for the migrations and the raw disk comparison (default 4 h)
|
||||
ESXI_TEST_TIMEOUT_MS=
|
||||
|
||||
# Between the two transfers the source guest is hard reset so it writes to its active disk,
|
||||
# giving the delta pass something real to move. This is how long it is then given to boot and
|
||||
# flush — raise it if the test reports an empty delta (default 90 s)
|
||||
ESXI_RESET_SETTLE_MS=
|
||||
|
||||
# Gmail: enable 2-Step Verification then generate an App Password at
|
||||
# https://myaccount.google.com/apppasswords
|
||||
SMTP_HOST=smtp.gmail.com
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"name": "@xen-orchestra/qa-test",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"version": "1.1.0",
|
||||
"version": "1.1.1",
|
||||
"description": "XenOrchestra QA Test Suite",
|
||||
"author": {
|
||||
"name": "Vates SAS",
|
||||
@@ -21,9 +21,11 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@vates/async-each": "^1.0.3",
|
||||
"@xen-orchestra/backups": "^0.73.8",
|
||||
"@xen-orchestra/fs": "^4.9.2",
|
||||
"@vates/read-chunk": "^1.2.1",
|
||||
"@xen-orchestra/backups": "^0.73.10",
|
||||
"@xen-orchestra/fs": "^4.9.3",
|
||||
"@xen-orchestra/log": "^0.7.2",
|
||||
"@xen-orchestra/vmware-explorer": "^0.15.0",
|
||||
"nodemailer": "^7.0.13",
|
||||
"xo-lib": "^0.11.2"
|
||||
},
|
||||
@@ -48,6 +50,7 @@
|
||||
"report": "node --env-file-if-exists=.env scripts/run-and-report.mjs",
|
||||
"report:smtp-test": "node --env-file-if-exists=.env scripts/run-and-report.mjs --smtp-test",
|
||||
"qa:backup:file-restore": "node --env-file-if-exists=.env --test tests/backup.file-restore.test.js",
|
||||
"qa:import:esxi": "node --env-file-if-exists=.env --test --test-force-exit tests/import.esxi.test.js",
|
||||
"qa:load:backup:delta": "node --env-file-if-exists=.env scripts/backup-load-delta.mjs"
|
||||
}
|
||||
}
|
||||
|
||||
355
@xen-orchestra/qa-test/tests/import.esxi.test.js
Normal file
355
@xen-orchestra/qa-test/tests/import.esxi.test.js
Normal file
@@ -0,0 +1,355 @@
|
||||
// installs the transports, including the one capturing every debug record to a file in
|
||||
// os.tmpdir() — must come first so nothing is logged before it is configured
|
||||
import '../logSetup.js'
|
||||
|
||||
import assert from 'node:assert/strict'
|
||||
import { after, before, describe, it } from 'node:test'
|
||||
|
||||
import { createLogger } from '@xen-orchestra/log'
|
||||
|
||||
import { DispatchClient } from '../client/dispatchClient.js'
|
||||
import { createResourceTracker } from '../utils/resourceTracker.js'
|
||||
import { getRequiredEnv } from '../utils/index.js'
|
||||
import { formatBytes } from '../utils/exportUtils.js'
|
||||
import {
|
||||
assertRawExportsAreIdentical,
|
||||
assertSourceIsRunningWithoutSnapshot,
|
||||
assertTransferSequence,
|
||||
churnSourceByReset,
|
||||
connectToEsxi,
|
||||
getAndLogSourceState,
|
||||
getEsxiConfig,
|
||||
getEsxiSkipReason,
|
||||
getOrderedDisks,
|
||||
optionalEnv,
|
||||
resetSourceState,
|
||||
waitForBlockedOperations,
|
||||
waitForSourceSnapshot,
|
||||
} from '../utils/esxiMigrationUtils.js'
|
||||
|
||||
const log = createLogger('qa:import:esxi')
|
||||
|
||||
const XO_SNAPSHOT_NAME = '[V2V] migration to XCP-ng'
|
||||
|
||||
describe('ESXi migration (V2V)', { skip: getEsxiSkipReason() }, () => {
|
||||
/** @type {import('../client/dispatchClient.js').DispatchClient} */
|
||||
let dispatchClient
|
||||
/** @type {Object} */
|
||||
let tracker
|
||||
/** @type {import('@xen-orchestra/vmware-explorer/esxi.mjs').default} */
|
||||
let esxi
|
||||
/** @type {ReturnType<typeof getEsxiConfig>} */
|
||||
let esxiConfig
|
||||
/** @type {Object} */
|
||||
let sourceMetadata
|
||||
/** Parameters shared by every `vm.importFromEsxi` call */
|
||||
let migrationParams
|
||||
|
||||
before(async () => {
|
||||
esxiConfig = getEsxiConfig()
|
||||
|
||||
dispatchClient = new DispatchClient()
|
||||
await dispatchClient.initialize()
|
||||
tracker = createResourceTracker()
|
||||
|
||||
esxi = await connectToEsxi(esxiConfig)
|
||||
sourceMetadata = await assertSourceIsRunningWithoutSnapshot(esxi, esxiConfig.vmId)
|
||||
|
||||
const sr = await dispatchClient.sr.details(getRequiredEnv('SR_ID'))
|
||||
assert.notEqual(sr, undefined, 'SR_ID does not resolve to an SR')
|
||||
|
||||
migrationParams = {
|
||||
host: esxiConfig.host,
|
||||
user: esxiConfig.user,
|
||||
password: esxiConfig.password,
|
||||
sslVerify: esxiConfig.sslVerify,
|
||||
vm: esxiConfig.vmId,
|
||||
sr: sr.uuid,
|
||||
network: await findNetwork(dispatchClient, sr.$pool),
|
||||
template: await findTemplate(dispatchClient, sr.$pool),
|
||||
}
|
||||
|
||||
log.info('Ready to migrate source VM', {
|
||||
name: sourceMetadata.name_label,
|
||||
vmId: esxiConfig.vmId,
|
||||
disks: sourceMetadata.disks.length,
|
||||
sr: sr.name_label,
|
||||
})
|
||||
log.debug('Migration parameters', { ...migrationParams, password: '<redacted>' })
|
||||
log.debug('Resolved timings', {
|
||||
requestTimeoutMinutes: Math.round(esxiConfig.timeout / 60_000),
|
||||
resetSettleSeconds: Math.round(esxiConfig.resetSettleMs / 1000),
|
||||
})
|
||||
log.debug('Target pool objects resolved', {
|
||||
pool: sr.$pool,
|
||||
sr: { uuid: sr.uuid, name_label: sr.name_label },
|
||||
network: migrationParams.network,
|
||||
template: migrationParams.template,
|
||||
})
|
||||
})
|
||||
|
||||
after(async () => {
|
||||
// put the source back to running without snapshots, so the suite can be run again
|
||||
// without touching ESXi by hand
|
||||
if (esxi !== undefined) {
|
||||
try {
|
||||
await resetSourceState(esxi, esxiConfig.vmId)
|
||||
} catch (error) {
|
||||
log.warn(`Failed to reset the source VM, remove its "${XO_SNAPSHOT_NAME}" snapshot by hand`, { error })
|
||||
}
|
||||
}
|
||||
|
||||
if (tracker !== undefined) {
|
||||
const vmIds = tracker.getTrackedResourcesByType('vm').map(({ id }) => id)
|
||||
if (vmIds.length > 0) {
|
||||
try {
|
||||
await dispatchClient.cleanup.fullCleanup({
|
||||
cleanupVMs: true,
|
||||
cleanupBackupJobs: false,
|
||||
cleanupSchedules: false,
|
||||
additionalVmIds: vmIds,
|
||||
})
|
||||
} catch (error) {
|
||||
log.warn('Failed to delete the migrated VMs', { vmIds, error })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
await dispatchClient?.close()
|
||||
})
|
||||
|
||||
// -----------------------------------------------------------------------------
|
||||
// The scenario XO users actually run: one call, source running, no snapshot yet. XO
|
||||
// snapshots the source, transfers everything up to that snapshot while the guest keeps
|
||||
// running, then stops it and transfers what was written since.
|
||||
//
|
||||
// What makes this the scenario that covers the regression: `migrationfromEsxi` reads the
|
||||
// source metadata once, right after taking its snapshot, and `#importDisks` uses that same
|
||||
// chain for both passes. At that instant the delta still carries the CID of its parent, so
|
||||
// the delta pass always sees the two disks with an identical CID — whatever the guest wrote
|
||||
// in between. Matching disks on their CID made the delta look already imported and skipped
|
||||
// it silently. Re-reading the metadata later, as a second migration would, hides this: by
|
||||
// then VMware has rewritten the CID of any disk the guest touched.
|
||||
//
|
||||
// The guest is rebooted while the base transfers, so the delta holds real data and the byte
|
||||
// comparison in step 3 has something to chew on.
|
||||
//
|
||||
// step 1: one call, stopSource → base + delta, VM startable afterwards
|
||||
// step 2: same, now halted source → new VM, whole chain in one pass
|
||||
// step 3: step 1 and step 2 disks must be byte for byte identical
|
||||
// step 4: from a clean source again, the resume path and its unstartable partial VM
|
||||
//
|
||||
// Kept in a single test because every step depends on the state left by the previous one:
|
||||
// splitting them would report several misleading failures instead of the one that matters.
|
||||
// -----------------------------------------------------------------------------
|
||||
it('rebuilds the same disks from a snapshot plus its delta as from a single full transfer', async () => {
|
||||
// --- Step 1/4: one migration, with the guest writing while the base transfers ---
|
||||
log.info('Step 1/4: migrating a running source in one call, churning the guest meanwhile')
|
||||
const migration = migrate({ stopSource: true })
|
||||
let migrationSettled = false
|
||||
migration.then(
|
||||
() => {
|
||||
migrationSettled = true
|
||||
},
|
||||
() => {
|
||||
migrationSettled = true
|
||||
}
|
||||
)
|
||||
|
||||
// churn failures must not fail the run: the delta is then only what the guest happened to
|
||||
// write, which still exercises the regression, just with less data
|
||||
const churning = (async () => {
|
||||
await waitForSourceSnapshot(esxi, esxiConfig.vmId)
|
||||
if (migrationSettled) {
|
||||
log.warn('Migration finished before the guest could be churned, the delta will be small')
|
||||
return
|
||||
}
|
||||
await churnSourceByReset(esxi, esxiConfig.vmId, { settleMs: esxiConfig.resetSettleMs })
|
||||
})().catch(error => log.warn('Could not churn the source during the transfer', { error }))
|
||||
|
||||
const twoStepVmUuid = await migration
|
||||
await churning
|
||||
tracker.trackResource('vm', twoStepVmUuid, { name: 'V2V two step' })
|
||||
|
||||
const sourceAfter = await getAndLogSourceState(esxi, esxiConfig.vmId, 'after the two step migration')
|
||||
assert.equal(sourceAfter.powerState, 'poweredOff', 'the source should have been stopped before the last transfer')
|
||||
assert.equal(
|
||||
sourceAfter.snapshots?.snapshots.find(({ uid }) => uid === sourceAfter.snapshots.current)?.displayName,
|
||||
XO_SNAPSHOT_NAME,
|
||||
'the current source snapshot should be the one XO took for the migration'
|
||||
)
|
||||
|
||||
const twoStepDisks = await getOrderedDisks(dispatchClient, twoStepVmUuid)
|
||||
assert.equal(twoStepDisks.length, sourceMetadata.disks.length, 'every source disk should have been created')
|
||||
for (const disk of twoStepDisks) {
|
||||
// a single `base` is the regression: the delta pass decided there was nothing to import.
|
||||
// A second `base` would mean the whole disk was transferred again instead of a delta
|
||||
const [base, delta] = assertTransferSequence(disk, ['base', 'snapshot'])
|
||||
assert.ok(
|
||||
delta.megabytes <= base.megabytes,
|
||||
`the delta of disk ${disk.position} should not be larger than the base transfer ` +
|
||||
`(delta ${delta.megabytes} MB, base ${base.megabytes} MB)`
|
||||
)
|
||||
log.info('Disk transferred in two passes', {
|
||||
position: disk.position,
|
||||
vdi: disk.uuid,
|
||||
baseMB: base.megabytes,
|
||||
deltaMB: delta.megabytes,
|
||||
})
|
||||
if (delta.megabytes === 0) {
|
||||
// not a failure: the sequence assertion above already proves the delta pass ran. But
|
||||
// step 3 only compares zeroes then, so the run is weaker than it looks
|
||||
log.warn('Empty delta, the raw comparison will not exercise much', {
|
||||
position: disk.position,
|
||||
hint: 'raise ESXI_RESET_SETTLE_MS so the guest has time to write after the reset',
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
await waitForBlockedOperations(dispatchClient, twoStepVmUuid, { blocked: false })
|
||||
|
||||
// --- Step 2/4: migrate the now halted source in one pass ---------------------
|
||||
// the source has not been touched since, so this VM must hold exactly the same content
|
||||
log.info('Step 2/4: migrating the halted source')
|
||||
const fullTransferVmUuid = await migrate({ stopSource: true })
|
||||
tracker.trackResource('vm', fullTransferVmUuid, { name: 'V2V full transfer' })
|
||||
|
||||
assert.notEqual(
|
||||
fullTransferVmUuid,
|
||||
twoStepVmUuid,
|
||||
'migrating a completed source again should create a new VM, not reuse the previous one'
|
||||
)
|
||||
|
||||
await waitForBlockedOperations(dispatchClient, fullTransferVmUuid, { blocked: false })
|
||||
|
||||
const fullTransferDisks = await getOrderedDisks(dispatchClient, fullTransferVmUuid)
|
||||
assert.equal(fullTransferDisks.length, twoStepDisks.length, 'both VMs should have the same number of disks')
|
||||
for (const disk of fullTransferDisks) {
|
||||
assertTransferSequence(disk, ['base'])
|
||||
}
|
||||
|
||||
// --- Step 3/4: both reconstructions must be identical ------------------------
|
||||
log.info('Step 3/4: comparing the raw exports')
|
||||
for (const [index, twoStepDisk] of twoStepDisks.entries()) {
|
||||
const fullTransferDisk = fullTransferDisks[index]
|
||||
|
||||
assert.equal(
|
||||
twoStepDisk.size,
|
||||
fullTransferDisk.size,
|
||||
`disk ${twoStepDisk.position} should have the same virtual size in both VMs`
|
||||
)
|
||||
|
||||
log.info('Comparing raw exports', {
|
||||
position: twoStepDisk.position,
|
||||
size: formatBytes(twoStepDisk.size),
|
||||
twoStep: twoStepDisk.uuid,
|
||||
fullTransfer: fullTransferDisk.uuid,
|
||||
})
|
||||
|
||||
await assertRawExportsAreIdentical(dispatchClient.restApiClient, {
|
||||
referenceVdi: fullTransferDisk.uuid,
|
||||
candidateVdi: twoStepDisk.uuid,
|
||||
size: fullTransferDisk.size,
|
||||
timeout: esxiConfig.timeout,
|
||||
})
|
||||
}
|
||||
|
||||
// --- Step 4/4: the resume path, from a clean source again --------------------
|
||||
// a migration that leaves the source running produces a VM holding only the data up to
|
||||
// the snapshot: it must not be bootable, and a later run must continue it rather than
|
||||
// start over. This needs a snapshot free source, hence the reset
|
||||
log.info('Step 4/4: resuming an interrupted migration, from a clean source')
|
||||
await resetSourceState(esxi, esxiConfig.vmId)
|
||||
await getAndLogSourceState(esxi, esxiConfig.vmId, 'before the resume scenario')
|
||||
|
||||
const partialVmUuid = await migrate({ stopSource: false })
|
||||
tracker.trackResource('vm', partialVmUuid, { name: 'V2V resume' })
|
||||
|
||||
const partialDisks = await getOrderedDisks(dispatchClient, partialVmUuid)
|
||||
assert.equal(partialDisks.length, sourceMetadata.disks.length, 'every source disk should have been created')
|
||||
for (const disk of partialDisks) {
|
||||
assertTransferSequence(disk, ['base'])
|
||||
}
|
||||
|
||||
await waitForBlockedOperations(dispatchClient, partialVmUuid, { blocked: true })
|
||||
await assert.rejects(
|
||||
() => dispatchClient.vm.start(partialVmUuid),
|
||||
'starting a partially transferred VM should be refused'
|
||||
)
|
||||
|
||||
const resumedVmUuid = await migrate({ stopSource: true })
|
||||
assert.equal(
|
||||
resumedVmUuid,
|
||||
partialVmUuid,
|
||||
'the second migration should resume the VM left by the first one, not create another'
|
||||
)
|
||||
|
||||
for (const disk of await getOrderedDisks(dispatchClient, resumedVmUuid)) {
|
||||
assertTransferSequence(disk, ['base', 'snapshot'])
|
||||
}
|
||||
await waitForBlockedOperations(dispatchClient, resumedVmUuid, { blocked: false })
|
||||
})
|
||||
|
||||
/**
|
||||
* Runs a migration of the configured source VM and returns the UUID of the XCP-ng VM.
|
||||
* @private
|
||||
*/
|
||||
async function migrate({ stopSource }) {
|
||||
const startTime = Date.now()
|
||||
log.debug('Calling vm.importFromEsxi', { vm: esxiConfig.vmId, stopSource })
|
||||
|
||||
let result
|
||||
try {
|
||||
result = await dispatchClient.xoClient.call('vm.importFromEsxi', { ...migrationParams, stopSource })
|
||||
} catch (cause) {
|
||||
// `succeeded` maps the source VM to the XCP-ng VM created before the failure, and is
|
||||
// the only way to find the leftover VM to clean up
|
||||
log.warn('Migration failed', { stopSource, succeeded: cause.succeeded, error: cause })
|
||||
throw cause
|
||||
}
|
||||
|
||||
const vmUuid = result[esxiConfig.vmId]
|
||||
log.debug('vm.importFromEsxi returned', { result })
|
||||
|
||||
assert.equal(typeof vmUuid, 'string', `vm.importFromEsxi did not return a VM for ${esxiConfig.vmId}`)
|
||||
log.info('Migration done', { stopSource, vmUuid, durationSeconds: Math.round((Date.now() - startTime) / 1000) })
|
||||
|
||||
return vmUuid
|
||||
}
|
||||
})
|
||||
|
||||
/**
|
||||
* Picks a network the migrated VM can be attached to, on the same pool as the target SR.
|
||||
* @private
|
||||
*/
|
||||
async function findNetwork(dispatchClient, poolId) {
|
||||
const override = optionalEnv('ESXI_NETWORK_ID')
|
||||
if (override !== undefined) {
|
||||
return override
|
||||
}
|
||||
|
||||
const networks = await dispatchClient.restApiClient.getObjects('/rest/v0/networks')
|
||||
// a network without PIF is not connected to anything physical
|
||||
const network = networks.find(candidate => candidate.$pool === poolId && candidate.PIFs?.length > 0)
|
||||
|
||||
assert.notEqual(network, undefined, `no network with a PIF found on pool ${poolId} — set ESXI_NETWORK_ID`)
|
||||
return network.uuid
|
||||
}
|
||||
|
||||
/**
|
||||
* Picks the template the migrated VM is built from, on the same pool as the target SR.
|
||||
* @private
|
||||
*/
|
||||
async function findTemplate(dispatchClient, poolId) {
|
||||
const override = optionalEnv('ESXI_TEMPLATE_ID')
|
||||
if (override !== undefined) {
|
||||
return override
|
||||
}
|
||||
|
||||
const name = optionalEnv('ESXI_TEMPLATE_NAME') ?? 'Other install media'
|
||||
const templates = await dispatchClient.restApiClient.getObjects('/rest/v0/vm-templates')
|
||||
const template = templates.find(candidate => candidate.$pool === poolId && candidate.name_label === name)
|
||||
|
||||
assert.notEqual(template, undefined, `template "${name}" not found on pool ${poolId} — set ESXI_TEMPLATE_ID`)
|
||||
return template.uuid
|
||||
}
|
||||
552
@xen-orchestra/qa-test/utils/esxiMigrationUtils.js
Normal file
552
@xen-orchestra/qa-test/utils/esxiMigrationUtils.js
Normal file
@@ -0,0 +1,552 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { once } from 'node:events'
|
||||
import { Readable } from 'node:stream'
|
||||
|
||||
import { createLogger } from '@xen-orchestra/log'
|
||||
import { readChunk, readChunkStrict } from '@vates/read-chunk'
|
||||
import Esxi from '@xen-orchestra/vmware-explorer/esxi.mjs'
|
||||
|
||||
import { formatBytes } from './exportUtils.js'
|
||||
import { waitUntil } from './index.js'
|
||||
|
||||
const log = createLogger('xo:qa-test:esxi-migration')
|
||||
|
||||
// =============================================================================
|
||||
// CONFIGURATION
|
||||
// =============================================================================
|
||||
|
||||
/**
|
||||
* Environment variables without which the ESXi migration tests cannot run at all.
|
||||
* @constant {ReadonlyArray<string>}
|
||||
*/
|
||||
export const REQUIRED_ESXI_ENV = ['ESXI_HOST', 'ESXI_USER', 'ESXI_PASSWORD', 'ESXI_VM_ID']
|
||||
|
||||
/**
|
||||
* Tells whether the ESXi migration tests can run.
|
||||
*
|
||||
* Returned in the shape node:test expects for its `skip` option, so the suite is skipped
|
||||
* with an actionable message rather than failing on an unconfigured environment.
|
||||
*
|
||||
* @returns {string|false} Skip reason, or false when everything needed is set
|
||||
*/
|
||||
export function getEsxiSkipReason() {
|
||||
const missing = REQUIRED_ESXI_ENV.filter(name => (process.env[name] ?? '') === '')
|
||||
return missing.length === 0 ? false : `ESXi migration tests need ${missing.join(', ')} to be set in .env`
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the ESXi source configuration from the environment.
|
||||
*
|
||||
* Only call this once `getEsxiSkipReason()` returned false.
|
||||
*
|
||||
* @returns {{ host: string, user: string, password: string, vmId: string, sslVerify: boolean, timeout: number }}
|
||||
*/
|
||||
export function getEsxiConfig() {
|
||||
return {
|
||||
host: process.env.ESXI_HOST,
|
||||
user: process.env.ESXI_USER,
|
||||
password: process.env.ESXI_PASSWORD,
|
||||
vmId: process.env.ESXI_VM_ID,
|
||||
// lab ESXi hosts serve a self-signed certificate, so this defaults to off
|
||||
sslVerify: process.env.ESXI_SSL_VERIFY === 'true',
|
||||
timeout: millisecondsFromEnv('ESXI_TEST_TIMEOUT_MS', 4 * 3600_000),
|
||||
// how long the guest is given to boot and flush after the reset that churns its disk
|
||||
resetSettleMs: millisecondsFromEnv('ESXI_RESET_SETTLE_MS', 90_000),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads an optional environment variable, treating a blank value as unset.
|
||||
*
|
||||
* A key present but left empty in a .env file reads as an empty string, not undefined, so
|
||||
* `??` does not fall back to the default. That matters most for the numeric options:
|
||||
* `Number('')` is 0, which silently turns a timeout into "abort immediately".
|
||||
*
|
||||
* @param {string} name - Environment variable name
|
||||
* @returns {string|undefined} The value, or undefined when unset or empty
|
||||
*/
|
||||
export function optionalEnv(name) {
|
||||
const value = process.env[name]
|
||||
return value === undefined || value === '' ? undefined : value
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads an optional duration from the environment, in milliseconds.
|
||||
*
|
||||
* @param {string} name - Environment variable name
|
||||
* @param {number} fallback - Value to use when unset or empty
|
||||
* @returns {number} A positive, finite number of milliseconds
|
||||
* @throws {Error} If the variable is set to something that is not a positive number
|
||||
*/
|
||||
function millisecondsFromEnv(name, fallback) {
|
||||
const raw = optionalEnv(name)
|
||||
if (raw === undefined) {
|
||||
return fallback
|
||||
}
|
||||
|
||||
const value = Number(raw)
|
||||
if (!Number.isFinite(value) || value <= 0) {
|
||||
throw new Error(`${name} must be a positive number of milliseconds, got ${JSON.stringify(raw)}`)
|
||||
}
|
||||
return value
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits for a VM's blocked operations to reach an expected state.
|
||||
*
|
||||
* XO's object cache is fed by XAPI events, so a field written during an API call is not
|
||||
* necessarily visible on the very next read — polling here rather than asserting once avoids
|
||||
* failing on that lag, while still failing if the value never changes.
|
||||
*
|
||||
* @param {import('../client/dispatchClient.js').DispatchClient} dispatchClient
|
||||
* @param {string} vmUuid - UUID of the VM
|
||||
* @param {{ blocked: boolean }} expected - Whether `start`/`start_on` must be blocked
|
||||
* @param {number} [timeout=30000] - How long to wait, in milliseconds
|
||||
* @returns {Promise<Object>} The VM record once it matches
|
||||
* @throws {Error} If the expected state is not reached in time
|
||||
*/
|
||||
export async function waitForBlockedOperations(dispatchClient, vmUuid, { blocked }, timeout = 30_000) {
|
||||
let lastSeen
|
||||
try {
|
||||
return await waitUntil(
|
||||
async () => {
|
||||
const vm = await dispatchClient.vm.details(vmUuid)
|
||||
lastSeen = vm.blockedOperations
|
||||
const isBlocked = lastSeen?.start !== undefined && lastSeen?.start_on !== undefined
|
||||
const isUnblocked = lastSeen?.start === undefined && lastSeen?.start_on === undefined
|
||||
return (blocked ? isBlocked : isUnblocked) ? vm : false
|
||||
},
|
||||
1000,
|
||||
timeout
|
||||
)
|
||||
} catch (cause) {
|
||||
const error = new Error(
|
||||
`VM ${vmUuid} should have had start and start_on ${blocked ? 'blocked' : 'unblocked'} within ${timeout} ms, ` +
|
||||
`last seen blockedOperations: ${JSON.stringify(lastSeen)}`
|
||||
)
|
||||
error.cause = cause
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// ESXI SOURCE INSPECTION
|
||||
// =============================================================================
|
||||
|
||||
/**
|
||||
* Opens a connection to the source ESXi host.
|
||||
*
|
||||
* Used to assert the state of the *source* VM, which XO's API does not expose in full
|
||||
* (`esxi.listVms` reports the power state but not the snapshots).
|
||||
*
|
||||
* @param {{ host: string, user: string, password: string, sslVerify: boolean }} config
|
||||
* @returns {Promise<Esxi>} A connected client
|
||||
*/
|
||||
export async function connectToEsxi({ host, user, password, sslVerify }) {
|
||||
const esxi = new Esxi(host, user, password, sslVerify)
|
||||
try {
|
||||
await once(esxi, 'ready')
|
||||
} catch (cause) {
|
||||
const error = new Error(
|
||||
`could not connect to ESXi ${host} as ${user}: ${cause.message}. Check ESXI_HOST, ESXI_USER and ` +
|
||||
`ESXI_PASSWORD — in .env a value containing # or a trailing space must be wrapped in double quotes`
|
||||
)
|
||||
error.cause = cause
|
||||
throw error
|
||||
}
|
||||
log.debug('Connected to ESXi', { host })
|
||||
return esxi
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts the source VM is in the state the migration scenario starts from: running, and
|
||||
* without any snapshot so that XO has to take its own.
|
||||
*
|
||||
* @param {Esxi} esxi - Connected ESXi client
|
||||
* @param {string} vmId - ESXi VM id (the numeric MoRef, e.g. '34')
|
||||
* @returns {Promise<Object>} The source VM metadata
|
||||
* @throws {assert.AssertionError} If the VM is halted or already has a snapshot
|
||||
*/
|
||||
export async function assertSourceIsRunningWithoutSnapshot(esxi, vmId) {
|
||||
const metadata = await esxi.getTransferableVmMetadata(vmId)
|
||||
logSourceState(metadata, 'before the first migration')
|
||||
|
||||
assert.notEqual(
|
||||
metadata.powerState,
|
||||
'poweredOff',
|
||||
`source VM ${vmId} (${metadata.name_label}) must be running: the scenario migrates a live VM`
|
||||
)
|
||||
assert.equal(
|
||||
metadata.snapshots?.current,
|
||||
undefined,
|
||||
`source VM ${vmId} (${metadata.name_label}) must have no snapshot so that XO takes its own — ` +
|
||||
`remove its snapshots on the ESXi side before running this test`
|
||||
)
|
||||
|
||||
return metadata
|
||||
}
|
||||
|
||||
/**
|
||||
* Reboots the guest of the source VM so it writes to its active disk, and waits for those
|
||||
* writes to land.
|
||||
*
|
||||
* A hard reset is used rather than a powerOff/powerOn pair on purpose: the latter closes the
|
||||
* vmdk files, which makes VMware rewrite the delta's CID. That would hide the very situation
|
||||
* this suite exists to cover — a delta still carrying its parent's CID.
|
||||
*
|
||||
* How much a boot writes is guest dependent, hence the settle delay rather than a byte
|
||||
* target; nothing here asserts a minimum, the caller reports what was actually transferred.
|
||||
*
|
||||
* @param {Esxi} esxi - Connected ESXi client
|
||||
* @param {string} vmId - ESXi VM id, must be powered on
|
||||
* @param {{ settleMs: number }} options - How long to let the guest boot and flush
|
||||
*/
|
||||
export async function churnSourceByReset(esxi, vmId, { settleMs }) {
|
||||
log.debug('Resetting the source VM to make its guest write', { vmId, settleMs })
|
||||
await esxi.reset(vmId)
|
||||
await new Promise(resolve => setTimeout(resolve, settleMs))
|
||||
log.debug('Source VM had time to boot and flush', { vmId })
|
||||
}
|
||||
|
||||
/**
|
||||
* Waits until the source VM has a current snapshot.
|
||||
*
|
||||
* Used to know when XO has taken its snapshot during a migration: from that point on
|
||||
* everything the guest writes lands in the active disk, which is what the delta pass moves.
|
||||
*
|
||||
* @param {Esxi} esxi - Connected ESXi client
|
||||
* @param {string} vmId - ESXi VM id
|
||||
* @param {number} [timeout=120000] - How long to wait, in milliseconds
|
||||
* @returns {Promise<string>} uid of the current snapshot
|
||||
*/
|
||||
export async function waitForSourceSnapshot(esxi, vmId, timeout = 120_000) {
|
||||
const uid = await waitUntil(
|
||||
async () => {
|
||||
const { snapshots } = await esxi.getTransferableVmMetadata(vmId)
|
||||
return snapshots?.current ?? false
|
||||
},
|
||||
2000,
|
||||
timeout
|
||||
)
|
||||
log.debug('Source VM has been snapshotted by XO', { vmId, snapshotUid: uid })
|
||||
return uid
|
||||
}
|
||||
|
||||
/**
|
||||
* Brings the source VM back to the state the scenarios start from: running, without any
|
||||
* snapshot.
|
||||
*
|
||||
* The snapshots are removed while the VM is halted so the consolidation does not compete with
|
||||
* a live guest. Note `#waitForTaskEnd` gives a task 60 s, so a very large delta to consolidate
|
||||
* would time out.
|
||||
*
|
||||
* @param {Esxi} esxi - Connected ESXi client
|
||||
* @param {string} vmId - ESXi VM id
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
export async function resetSourceState(esxi, vmId) {
|
||||
const { powerState, snapshots } = await esxi.getTransferableVmMetadata(vmId)
|
||||
|
||||
if (snapshots?.current !== undefined) {
|
||||
log.debug('Removing the snapshots left on the source VM', { vmId, current: snapshots.current })
|
||||
await esxi.removeAllSnapshots(vmId)
|
||||
}
|
||||
|
||||
if (powerState === 'poweredOff') {
|
||||
log.debug('Starting the source VM back up', { vmId })
|
||||
await esxi.powerOn(vmId)
|
||||
await waitUntil(async () => (await esxi.getTransferableVmMetadata(vmId)).powerState !== 'poweredOff', 2000, 120_000)
|
||||
}
|
||||
|
||||
log.debug('Source VM is back to its initial state', { vmId })
|
||||
}
|
||||
|
||||
/**
|
||||
* Records the state of the source VM: power state, snapshots, and the identity of every disk
|
||||
* of every chain.
|
||||
*
|
||||
* `uid` is the vmdk CID and `parentId` its parentCID. VMware creates a snapshot delta with
|
||||
* `CID = parentCID` and only rewrites it once the disk is closed, so seeing a delta whose
|
||||
* `uid` equals its `parentId` — and equals its parent's `uid` — is expected right after XO
|
||||
* snapshots the source. It is also the state that used to make the delta look already
|
||||
* imported, so it is worth having in the log whenever a comparison fails later on.
|
||||
*
|
||||
* @param {Object} metadata - Result of `getTransferableVmMetadata`
|
||||
* @param {string} label - When this snapshot of the state was taken
|
||||
*/
|
||||
export function logSourceState(metadata, label) {
|
||||
const describeDisk = (disk, snapshotUid) => ({
|
||||
snapshotUid,
|
||||
node: disk.node,
|
||||
diskPath: disk.diskPath,
|
||||
uid: disk.uid,
|
||||
parentId: disk.parentId,
|
||||
isFull: disk.isFull,
|
||||
vmdkFormat: disk.vmdkFormat,
|
||||
capacity: disk.capacity !== undefined ? formatBytes(disk.capacity) : undefined,
|
||||
})
|
||||
|
||||
const snapshots = metadata.snapshots?.snapshots ?? []
|
||||
|
||||
// the disks are listed flat rather than nested under their snapshot: logSetup.js inspects
|
||||
// at depth 3, and nesting them would print the interesting part as `[Object]`
|
||||
log.debug(`Source VM state ${label}`, {
|
||||
name: metadata.name_label,
|
||||
powerState: metadata.powerState,
|
||||
currentSnapshot: metadata.snapshots?.current,
|
||||
snapshots: snapshots.map(({ uid, parent, displayName, numDisks }) => ({
|
||||
uid,
|
||||
parent,
|
||||
displayName,
|
||||
numDisks,
|
||||
})),
|
||||
snapshotDisks: snapshots.flatMap(snapshot => (snapshot.disks ?? []).map(disk => describeDisk(disk, snapshot.uid))),
|
||||
activeDisks: metadata.disks.map(disk => describeDisk(disk, undefined)),
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetches and logs the current state of the source VM.
|
||||
*
|
||||
* @param {Esxi} esxi - Connected ESXi client
|
||||
* @param {string} vmId - ESXi VM id
|
||||
* @param {string} label - When this snapshot of the state was taken
|
||||
* @returns {Promise<Object>} The source VM metadata
|
||||
*/
|
||||
export async function getAndLogSourceState(esxi, vmId, label) {
|
||||
const metadata = await esxi.getTransferableVmMetadata(vmId)
|
||||
logSourceState(metadata, label)
|
||||
return metadata
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// TRANSFER ACCOUNTING
|
||||
// =============================================================================
|
||||
|
||||
/**
|
||||
* Parses the transfer report XO appends to a VDI's description on every import pass.
|
||||
*
|
||||
* importDiskChain() writes one line per transfer, ending with the disk of the chain it
|
||||
* started from — `base` for a full import, `snapshot` for a delta on top of a previous
|
||||
* one. That makes it the only *persisted* record of what each migration actually moved.
|
||||
*
|
||||
* @param {string} [nameDescription] - `name_description` of the VDI
|
||||
* @returns {Array<{ megabytes: number, seconds: number, from: 'base' | 'snapshot' }>} One entry per transfer, oldest first
|
||||
*/
|
||||
export function parseTransferReports(nameDescription = '') {
|
||||
const reports = []
|
||||
const regex = /([\d.]+) MB in (\d+) s \([^)]*\) from\s+(base|snapshot)/g
|
||||
|
||||
let match
|
||||
while ((match = regex.exec(nameDescription)) !== null) {
|
||||
reports.push({ megabytes: Number(match[1]), seconds: Number(match[2]), from: match[3] })
|
||||
}
|
||||
return reports
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts a VDI was imported by exactly the expected sequence of transfers.
|
||||
*
|
||||
* @param {{ uuid: string, name_description: string }} vdi - VDI record
|
||||
* @param {ReadonlyArray<'base' | 'snapshot'>} expected - Expected origins, oldest transfer first
|
||||
* @throws {assert.AssertionError} If the sequence does not match
|
||||
*/
|
||||
export function assertTransferSequence(vdi, expected) {
|
||||
const reports = parseTransferReports(vdi.name_description)
|
||||
|
||||
log.debug('Transfers reported by the VDI', {
|
||||
vdi: vdi.uuid,
|
||||
expected: [...expected],
|
||||
reports,
|
||||
nameDescription: vdi.name_description,
|
||||
})
|
||||
|
||||
assert.deepEqual(
|
||||
reports.map(({ from }) => from),
|
||||
[...expected],
|
||||
`VDI ${vdi.uuid} should have been imported by ${expected.length} transfer(s) (${expected.join(' then ')}), ` +
|
||||
`its description reads: ${JSON.stringify(vdi.name_description)}`
|
||||
)
|
||||
return reports
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// DISK INTROSPECTION
|
||||
// =============================================================================
|
||||
|
||||
/**
|
||||
* Lists the disks of a VM, ordered by their position on the bus.
|
||||
*
|
||||
* The VDI name is not usable to pair the disks of two separately migrated VMs — it is
|
||||
* derived from the vmdk extent that was read, which differs between a base import and a
|
||||
* whole-chain import — so the bus position is what makes the pairing meaningful.
|
||||
*
|
||||
* @param {import('../client/dispatchClient.js').DispatchClient} dispatchClient
|
||||
* @param {string} vmUuid - UUID of the VM
|
||||
* @returns {Promise<Array<{ uuid: string, name_label: string, name_description: string, size: number, other_config: Record<string, string>, position: number, device: string }>>}
|
||||
*/
|
||||
export async function getOrderedDisks(dispatchClient, vmUuid) {
|
||||
const { restApiClient } = dispatchClient
|
||||
const vm = await dispatchClient.vm.details(vmUuid)
|
||||
|
||||
const vbds = await Promise.all(
|
||||
(vm.$VBDs ?? []).map(vbdId => restApiClient.get(`/rest/v0/vbds/${vbdId}?fields=device,position,is_cd_drive,VDI`))
|
||||
)
|
||||
|
||||
const disks = []
|
||||
for (const vbd of vbds) {
|
||||
if (vbd.is_cd_drive || vbd.VDI === undefined || vbd.VDI === null) {
|
||||
continue
|
||||
}
|
||||
const vdi = await restApiClient.get(
|
||||
`/rest/v0/vdis/${vbd.VDI}?fields=uuid,name_label,name_description,size,other_config`
|
||||
)
|
||||
disks.push({ ...vdi, position: Number(vbd.position), device: vbd.device })
|
||||
}
|
||||
|
||||
disks.sort((a, b) => a.position - b.position)
|
||||
|
||||
log.debug('Disks of the migrated VM', {
|
||||
vm: vmUuid,
|
||||
disks: disks.map(disk => ({
|
||||
device: disk.device,
|
||||
position: disk.position,
|
||||
vdi: disk.uuid,
|
||||
nameLabel: disk.name_label,
|
||||
size: formatBytes(disk.size),
|
||||
// which source disk XO considers this VDI to hold — the reference the next pass
|
||||
// resumes from
|
||||
esxiDiskPath: disk.other_config?.esxi_diskPath,
|
||||
esxiUuid: disk.other_config?.esxi_uuid,
|
||||
})),
|
||||
})
|
||||
|
||||
return disks
|
||||
}
|
||||
|
||||
// =============================================================================
|
||||
// RAW EXPORT COMPARISON
|
||||
// =============================================================================
|
||||
|
||||
/**
|
||||
* Opens the raw (flat) export of a VDI as a Node stream.
|
||||
*
|
||||
* @param {import('../client/restApiClient.js').RestApiClient} restApiClient
|
||||
* @param {string} vdiUuid - UUID of the VDI to export
|
||||
* @param {{ timeout: number }} options
|
||||
* @returns {Promise<Readable>} The response body
|
||||
* @throws {Error} If the export request is rejected
|
||||
*/
|
||||
async function openRawExport(restApiClient, vdiUuid, { timeout }) {
|
||||
const response = await fetch(`${restApiClient.baseUrl}/rest/v0/vdis/${vdiUuid}.raw`, {
|
||||
method: 'GET',
|
||||
headers: restApiClient.headers,
|
||||
signal: AbortSignal.timeout(timeout),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const error = new Error(`raw export of VDI ${vdiUuid} failed: HTTP ${response.status} - ${response.statusText}`)
|
||||
error.code = 'RAW_EXPORT_HTTP_ERROR'
|
||||
error.cause = new Error(await response.text())
|
||||
throw error
|
||||
}
|
||||
|
||||
return Readable.fromWeb(response.body)
|
||||
}
|
||||
|
||||
/**
|
||||
* Offset of the first byte that differs between two buffers.
|
||||
* @private
|
||||
*/
|
||||
function firstDifferingByte(a, b) {
|
||||
const length = Math.min(a.length, b.length)
|
||||
for (let i = 0; i < length; i++) {
|
||||
if (a[i] !== b[i]) {
|
||||
return i
|
||||
}
|
||||
}
|
||||
return length
|
||||
}
|
||||
|
||||
/**
|
||||
* Asserts that two VDIs export byte for byte identical raw content.
|
||||
*
|
||||
* Both exports are streamed and compared chunk by chunk — nothing is written to disk, so
|
||||
* this works on disks far larger than the runner's storage. The two reads are issued
|
||||
* concurrently so neither HTTP response sits idle while the other is being consumed.
|
||||
*
|
||||
* @param {import('../client/restApiClient.js').RestApiClient} restApiClient
|
||||
* @param {Object} options
|
||||
* @param {string} options.referenceVdi - UUID of the VDI taken as reference
|
||||
* @param {string} options.candidateVdi - UUID of the VDI to check against it
|
||||
* @param {number} options.size - Virtual size of both VDIs, in bytes
|
||||
* @param {number} [options.chunkSize=4194304] - Comparison granularity
|
||||
* @param {number} [options.timeout] - Per-request timeout in milliseconds
|
||||
* @throws {assert.AssertionError} If the contents differ, with the offset of the first difference
|
||||
*/
|
||||
export async function assertRawExportsAreIdentical(
|
||||
restApiClient,
|
||||
{ referenceVdi, candidateVdi, size, chunkSize = 4 * 1024 * 1024, timeout = 4 * 3600_000 }
|
||||
) {
|
||||
log.debug('Comparing raw exports', {
|
||||
referenceVdi,
|
||||
candidateVdi,
|
||||
size: formatBytes(size),
|
||||
chunkSize: formatBytes(chunkSize),
|
||||
timeoutMinutes: Math.round(timeout / 60_000),
|
||||
})
|
||||
|
||||
const [reference, candidate] = await Promise.all([
|
||||
openRawExport(restApiClient, referenceVdi, { timeout }),
|
||||
openRawExport(restApiClient, candidateVdi, { timeout }),
|
||||
])
|
||||
|
||||
const startTime = Date.now()
|
||||
try {
|
||||
let offset = 0
|
||||
let nextProgressLog = 1024 * 1024 * 1024
|
||||
|
||||
while (offset < size) {
|
||||
const length = Math.min(chunkSize, size - offset)
|
||||
|
||||
// readChunkStrict so that a stream ending early fails here, instead of being read as
|
||||
// a difference in content
|
||||
const [referenceChunk, candidateChunk] = await Promise.all([
|
||||
readChunkStrict(reference, length),
|
||||
readChunkStrict(candidate, length),
|
||||
])
|
||||
|
||||
if (!referenceChunk.equals(candidateChunk)) {
|
||||
assert.fail(
|
||||
`raw exports differ at byte ${offset + firstDifferingByte(referenceChunk, candidateChunk)} of ${size}: ` +
|
||||
`reference VDI ${referenceVdi}, candidate VDI ${candidateVdi}`
|
||||
)
|
||||
}
|
||||
|
||||
offset += length
|
||||
if (offset >= nextProgressLog) {
|
||||
const elapsedSeconds = (Date.now() - startTime) / 1000
|
||||
log.debug('Raw exports identical so far', {
|
||||
compared: formatBytes(offset),
|
||||
total: formatBytes(size),
|
||||
percent: Math.round((offset / size) * 100),
|
||||
throughput: `${formatBytes(offset / elapsedSeconds)}/s`,
|
||||
elapsedSeconds: Math.round(elapsedSeconds),
|
||||
})
|
||||
nextProgressLog += 1024 * 1024 * 1024
|
||||
}
|
||||
}
|
||||
|
||||
const [referenceTail, candidateTail] = await Promise.all([readChunk(reference), readChunk(candidate)])
|
||||
assert.equal(referenceTail, null, `reference VDI ${referenceVdi} exported more than its ${size} bytes`)
|
||||
assert.equal(candidateTail, null, `candidate VDI ${candidateVdi} exported more than its ${size} bytes`)
|
||||
|
||||
log.debug('Raw exports are identical', {
|
||||
size: formatBytes(size),
|
||||
durationSeconds: Math.round((Date.now() - startTime) / 1000),
|
||||
})
|
||||
} finally {
|
||||
reference.destroy()
|
||||
candidate.destroy()
|
||||
}
|
||||
}
|
||||
@@ -36,6 +36,6 @@
|
||||
"typescript-eslint": "^8.61.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@xen-orchestra/disk-transform": "^1.3.2"
|
||||
"@xen-orchestra/disk-transform": "^1.3.3"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
"main": "./dist/index.mjs",
|
||||
"name": "@xen-orchestra/rest-api",
|
||||
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/@xen-orchestra/rest-api",
|
||||
"version": "0.36.0",
|
||||
"version": "0.37.0",
|
||||
"description": "REST API to manage your XOA",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"private": false,
|
||||
@@ -36,11 +36,11 @@
|
||||
"dependencies": {
|
||||
"@vates/async-each": "^1.0.3",
|
||||
"@vates/task": "^0.7.0",
|
||||
"@vates/types": "^1.29.0",
|
||||
"@vates/types": "^1.30.1",
|
||||
"@xen-orchestra/acl": "^1.5.0",
|
||||
"@xen-orchestra/backups": "^0.73.8",
|
||||
"@xen-orchestra/backups": "^0.73.10",
|
||||
"@xen-orchestra/log": "^0.7.2",
|
||||
"@xen-orchestra/xapi": "^8.10.0",
|
||||
"@xen-orchestra/xapi": "^8.10.2",
|
||||
"complex-matcher": "^1.1.1",
|
||||
"golike-defer": "^0.5.1",
|
||||
"inversify": "^6.2.2",
|
||||
|
||||
@@ -909,11 +909,11 @@ export class HostController extends XapiXoController<XoHost> {
|
||||
const host = this.getObject(hostId)
|
||||
if (host.power_state === HOST_POWER_STATE.RUNNING) {
|
||||
throw incorrectState({
|
||||
actual: host.power_state,
|
||||
expected: HOST_POWER_STATE.HALTED,
|
||||
object: host.id,
|
||||
property: 'power_state',
|
||||
})
|
||||
actual: host.power_state,
|
||||
expected: HOST_POWER_STATE.HALTED,
|
||||
object: host.id,
|
||||
property: 'power_state',
|
||||
})
|
||||
}
|
||||
await this.getXapiObject(hostId).$xapi.forgetHost(hostId)
|
||||
}
|
||||
@@ -927,4 +927,51 @@ export class HostController extends XapiXoController<XoHost> {
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Required privilege:
|
||||
* - resource: host, action: scan-pifs
|
||||
*
|
||||
* Scan for physical interfaces on a host and create PIF objects to represent them. Host must be running.
|
||||
*
|
||||
* @example id "b61a5c92-700e-4966-a13b-00633f03eea8"
|
||||
*/
|
||||
@Example(taskLocation)
|
||||
@Extension('x-mcp-exposure', 'confirm')
|
||||
@Post('{id}/actions/scan_pifs')
|
||||
@Middlewares(acl({ resource: 'host', action: 'scan-pifs', objectId: 'params.id' }))
|
||||
@Tags('pifs')
|
||||
@SuccessResponse(asynchronousActionResp.status, asynchronousActionResp.description)
|
||||
@Response(noContentResp.status, noContentResp.description)
|
||||
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
|
||||
@Response(notFoundResp.status, notFoundResp.description)
|
||||
@Response(incorrectStateResp.status, incorrectStateResp.description)
|
||||
hostScanPifs(@Path() id: string, @Query() sync?: boolean): CreateActionReturnType<void> {
|
||||
const hostId = id as XoHost['id']
|
||||
|
||||
const action = async () => {
|
||||
const host = this.getObject(hostId)
|
||||
|
||||
if (host.power_state !== HOST_POWER_STATE.RUNNING) {
|
||||
throw incorrectState({
|
||||
actual: host.power_state,
|
||||
expected: HOST_POWER_STATE.RUNNING,
|
||||
object: host.id,
|
||||
property: 'power_state',
|
||||
})
|
||||
}
|
||||
|
||||
await this.getXapi(host).callAsync('PIF.scan', host._xapiRef)
|
||||
}
|
||||
|
||||
return this.createAction<void>(action, {
|
||||
sync,
|
||||
statusCode: noContentResp.status,
|
||||
taskProperties: {
|
||||
name: 'scan pifs',
|
||||
objectId: hostId,
|
||||
objectType: 'host',
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -61,8 +61,8 @@ export function createExternalRouter(swaggerOpenApiSpec: OpenAPIV3.Document): {
|
||||
if (route.security === undefined) route.security = '*'
|
||||
await expressAuthentication(req as AuthenticatedRequest, route.security, route.scope === 'acl' ? ['acl'] : [])
|
||||
|
||||
// Coerces query boolean from string to boolean
|
||||
coerceBooleanQueryParams(req.query, route.query)
|
||||
// Coerces query strings to the types declared by the route
|
||||
coerceQueryParams(req.query, route.query)
|
||||
|
||||
// Validate inputs, throws if invalid
|
||||
paramsSchema?.parse(req.params)
|
||||
@@ -337,11 +337,23 @@ function extractParametersFromZod(schema: z.ZodType, location: 'path' | 'query')
|
||||
return []
|
||||
}
|
||||
|
||||
function coerceBooleanQueryParams(query: Record<string, unknown>, def: RouteDefinition['query']): void {
|
||||
// Express query params are always strings, coerce them to the types declared by the route
|
||||
// Exported for testing
|
||||
export function coerceQueryParams(query: Record<string, unknown>, def: RouteDefinition['query']): void {
|
||||
if (!def) return
|
||||
for (const [key, field] of Object.entries(def)) {
|
||||
if (field.type === 'boolean' && typeof query[key] === 'string') {
|
||||
query[key] = query[key] === 'true'
|
||||
const value = query[key]
|
||||
if (typeof value !== 'string') continue
|
||||
|
||||
if (field.type === 'boolean') {
|
||||
if (value.toLowerCase() === 'true') {
|
||||
query[key] = true
|
||||
} else if (value.toLowerCase() === 'false') {
|
||||
query[key] = false
|
||||
}
|
||||
} else if (field.type === 'number') {
|
||||
// a non-numeric value becomes NaN, which is rejected by the zod validation
|
||||
query[key] = value.trim() === '' ? NaN : Number(value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
49
@xen-orchestra/rest-api/src/router/external-router.test.mts
Normal file
49
@xen-orchestra/rest-api/src/router/external-router.test.mts
Normal file
@@ -0,0 +1,49 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { describe, it } from 'node:test'
|
||||
|
||||
// this module depends on the IoC container, which cannot be initialized on its own
|
||||
// because of circular imports between the services: load the generated routes first,
|
||||
// like `index.mts` does
|
||||
import '../open-api/routes/routes.js'
|
||||
|
||||
import { coerceQueryParams } from './external-router.mjs'
|
||||
import type { RouteDefinition } from './types.mjs'
|
||||
|
||||
const def: RouteDefinition['query'] = {
|
||||
bool: { type: 'boolean', optional: true },
|
||||
num: { type: 'number', optional: true },
|
||||
str: { type: 'string', optional: true },
|
||||
}
|
||||
|
||||
const coerce = (query: Record<string, unknown>) => {
|
||||
coerceQueryParams(query, def)
|
||||
return query
|
||||
}
|
||||
|
||||
describe('coerceQueryParams', () => {
|
||||
it('coerces booleans', () => {
|
||||
assert.deepEqual(coerce({ bool: 'true' }), { bool: true })
|
||||
assert.deepEqual(coerce({ bool: 'false' }), { bool: false })
|
||||
assert.deepEqual(coerce({ bool: 'TRUE' }), { bool: true })
|
||||
assert.deepEqual(coerce({ bool: 'FALSE' }), { bool: false })
|
||||
})
|
||||
it('keeps non-boolean values as strings', () => {
|
||||
assert.deepEqual(coerce({ bool: 'abc' }), { bool: 'abc' })
|
||||
})
|
||||
|
||||
it('coerces numbers', () => {
|
||||
assert.deepEqual(coerce({ num: '42' }), { num: 42 })
|
||||
assert.deepEqual(coerce({ num: '-4.2' }), { num: -4.2 })
|
||||
})
|
||||
|
||||
it('coerces a non-numeric value to NaN, which fails the validation', () => {
|
||||
assert.ok(Number.isNaN(coerce({ num: 'abc' }).num))
|
||||
})
|
||||
it('coerces empty strings to NaN, which fails the validation', () => {
|
||||
assert.ok(Number.isNaN(coerce({ num: '' }).num))
|
||||
})
|
||||
|
||||
it('leaves strings and undeclared params untouched', () => {
|
||||
assert.deepEqual(coerce({ str: '42', other: 'true' }), { str: '42', other: 'true' })
|
||||
})
|
||||
})
|
||||
@@ -450,6 +450,43 @@ export default class Esxi extends EventEmitter {
|
||||
return this.#exec('PowerOnVM_Task', { _this: vmId })
|
||||
}
|
||||
|
||||
/**
|
||||
* Hard resets a running VM, making its guest reboot.
|
||||
*
|
||||
* Unlike a powerOff/powerOn pair this keeps the VM powered on as far as the hypervisor is
|
||||
* concerned, so the vmdk files are never closed: a snapshot delta keeps the CID it was
|
||||
* created with. Useful to make a guest write to its active disk without altering the
|
||||
* identity of the disks of the chain.
|
||||
*
|
||||
* @param {string} vmId - id of the VM, must be powered on
|
||||
*/
|
||||
async reset(vmId) {
|
||||
const res = await this.#exec('ResetVM_Task', { _this: vmId })
|
||||
const taskId = res.returnval.$value
|
||||
try {
|
||||
return await this.#waitForTaskEnd(taskId)
|
||||
} catch (error) {
|
||||
warn('Fail to reset VM', { vmId, error })
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes every snapshot of a VM, consolidating their content into the base disks.
|
||||
*
|
||||
* @param {string} vmId - id of the VM
|
||||
*/
|
||||
async removeAllSnapshots(vmId) {
|
||||
const res = await this.#exec('RemoveAllSnapshots_Task', { _this: vmId, consolidate: true })
|
||||
const taskId = res.returnval.$value
|
||||
try {
|
||||
return await this.#waitForTaskEnd(taskId)
|
||||
} catch (error) {
|
||||
warn('Fail to remove the snapshots of VM', { vmId, error })
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
async snapshot(vmId, name, description) {
|
||||
const res = await this.#exec('CreateSnapshotEx_Task', { _this: vmId, name, description, memory: false })
|
||||
const taskId = res.returnval.$value
|
||||
|
||||
@@ -1,10 +1,10 @@
|
||||
{
|
||||
"license": "ISC",
|
||||
"private": false,
|
||||
"version": "0.14.0",
|
||||
"version": "0.15.0",
|
||||
"name": "@xen-orchestra/vmware-explorer",
|
||||
"dependencies": {
|
||||
"@vates/nbd-client": "^3.4.0",
|
||||
"@vates/nbd-client": "^3.5.0",
|
||||
"@vates/node-vsphere-soap": "^2.1.3",
|
||||
"@vates/read-chunk": "^1.2.1",
|
||||
"@vates/task": "^0.7.0",
|
||||
@@ -31,6 +31,7 @@
|
||||
"url": "https://vates.fr"
|
||||
},
|
||||
"scripts": {
|
||||
"postversion": "npm publish --access public"
|
||||
"postversion": "npm publish --access public",
|
||||
"test": "node --test"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,11 +2,12 @@
|
||||
|
||||
function set(obj, keyPath, val) {
|
||||
const [key, ...other] = keyPath
|
||||
// key like snapshot0->snapshot9 are grouped in an array snapshots[]
|
||||
const match = key.match(/^(.+)([0-9])$/)
|
||||
|
||||
const match = key.match(/^(.+?)([0-9]+)$/)
|
||||
if (match) {
|
||||
// an array
|
||||
let [, label, index] = match
|
||||
index = parseInt(index)
|
||||
// I like my array names in plural form
|
||||
label += 's'
|
||||
if (!obj[label]) {
|
||||
@@ -17,7 +18,7 @@ function set(obj, keyPath, val) {
|
||||
// it contains objects
|
||||
if (!obj[label][index]) {
|
||||
// and this object is not already initialized
|
||||
obj[label][parseInt(index)] = {}
|
||||
obj[label][index] = {}
|
||||
}
|
||||
set(obj[label][index], other, val)
|
||||
} else {
|
||||
|
||||
133
@xen-orchestra/vmware-explorer/parsers/vmsd.test.mjs
Normal file
133
@xen-orchestra/vmware-explorer/parsers/vmsd.test.mjs
Normal file
@@ -0,0 +1,133 @@
|
||||
import { strict as assert } from 'node:assert'
|
||||
import test from 'node:test'
|
||||
|
||||
import parseVmsd from './vmsd.mjs'
|
||||
|
||||
const { describe, it } = test
|
||||
|
||||
// a real .vmsd, as written by ESXi for a VM with 4 snapshots
|
||||
const VMSD_4_SNAPSHOTS = `.encoding = "UTF-8"
|
||||
snapshot.lastUID = "4"
|
||||
snapshot.current = "4"
|
||||
snapshot0.uid = "1"
|
||||
snapshot0.filename = "test flo-Snapshot1.vmsn"
|
||||
snapshot0.displayName = "SNAPSHOT POST INSTALL"
|
||||
snapshot0.description = "blablabla"
|
||||
snapshot0.createTimeHigh = "388745"
|
||||
snapshot0.createTimeLow = "1991180826"
|
||||
snapshot0.numDisks = "1"
|
||||
snapshot0.disk0.fileName = "test flo_0.vmdk"
|
||||
snapshot0.disk0.node = "scsi0:0"
|
||||
snapshot.numSnapshots = "4"
|
||||
snapshot1.uid = "2"
|
||||
snapshot1.filename = "test flo-Snapshot2.vmsn"
|
||||
snapshot1.parent = "1"
|
||||
snapshot1.displayName = "SECOND"
|
||||
snapshot1.description = "small"
|
||||
snapshot1.numDisks = "1"
|
||||
snapshot1.disk0.fileName = "test flo_0-000001.vmdk"
|
||||
snapshot1.disk0.node = "scsi0:0"
|
||||
snapshot2.uid = "3"
|
||||
snapshot2.filename = "test flo-Snapshot3.vmsn"
|
||||
snapshot2.parent = "2"
|
||||
snapshot2.displayName = "third"
|
||||
snapshot2.numDisks = "1"
|
||||
snapshot2.disk0.fileName = "test flo_0-000002.vmdk"
|
||||
snapshot2.disk0.node = "scsi0:0"
|
||||
snapshot3.uid = "4"
|
||||
snapshot3.filename = "test flo-Snapshot4.vmsn"
|
||||
snapshot3.parent = "3"
|
||||
snapshot3.displayName = "from cli"
|
||||
snapshot3.numDisks = "1"
|
||||
snapshot3.disk0.fileName = "test flo_0-000003.vmdk"
|
||||
snapshot3.disk0.node = "scsi0:0"
|
||||
`
|
||||
|
||||
// VMware allows up to 32 snapshots per VM, so the `snapshotN` index is not limited to one digit
|
||||
function buildVmsd(nSnapshots, nDisksPerSnapshot = 1) {
|
||||
const lines = ['.encoding = "UTF-8"', `snapshot.lastUID = "${nSnapshots}"`, `snapshot.current = "${nSnapshots}"`]
|
||||
for (let index = 0; index < nSnapshots; index++) {
|
||||
const uid = index + 1
|
||||
lines.push(
|
||||
`snapshot${index}.uid = "${uid}"`,
|
||||
`snapshot${index}.filename = "vm-Snapshot${uid}.vmsn"`,
|
||||
`snapshot${index}.displayName = "snapshot ${uid}"`,
|
||||
`snapshot${index}.numDisks = "${nDisksPerSnapshot}"`
|
||||
)
|
||||
if (index > 0) {
|
||||
lines.push(`snapshot${index}.parent = "${index}"`)
|
||||
}
|
||||
for (let diskIndex = 0; diskIndex < nDisksPerSnapshot; diskIndex++) {
|
||||
lines.push(
|
||||
`snapshot${index}.disk${diskIndex}.fileName = "vm_${diskIndex}-${String(uid).padStart(6, '0')}.vmdk"`,
|
||||
`snapshot${index}.disk${diskIndex}.node = "scsi0:${diskIndex}"`
|
||||
)
|
||||
}
|
||||
}
|
||||
lines.push(`snapshot.numSnapshots = "${nSnapshots}"`)
|
||||
return lines.join('\n') + '\n'
|
||||
}
|
||||
|
||||
describe('parseVmsd', function () {
|
||||
it('returns undefined when the VM has no current snapshot', function () {
|
||||
assert.equal(parseVmsd('.encoding = "UTF-8"\nsnapshot.lastUID = "0"\nsnapshot.numSnapshots = "0"\n'), undefined)
|
||||
})
|
||||
|
||||
it('parses a VM with less than 10 snapshots', function () {
|
||||
const { current, lastUID, numSnapshots, snapshots } = parseVmsd(VMSD_4_SNAPSHOTS)
|
||||
|
||||
assert.equal(current, '4')
|
||||
assert.equal(lastUID, '4')
|
||||
assert.equal(numSnapshots, '4')
|
||||
assert.deepEqual(
|
||||
snapshots.map(({ uid }) => uid),
|
||||
['1', '2', '3', '4']
|
||||
)
|
||||
assert.deepEqual(snapshots[3], {
|
||||
uid: '4',
|
||||
filename: 'test flo-Snapshot4.vmsn',
|
||||
parent: '3',
|
||||
displayName: 'from cli',
|
||||
numDisks: '1',
|
||||
disks: [{ fileName: 'test flo_0-000003.vmdk', node: 'scsi0:0' }],
|
||||
})
|
||||
})
|
||||
|
||||
it('parses a VM with 10 snapshots or more', function () {
|
||||
const { current, snapshots } = parseVmsd(buildVmsd(12))
|
||||
|
||||
assert.equal(current, '12')
|
||||
assert.equal(snapshots.length, 12)
|
||||
// snapshot10 and snapshot11 must not be mistaken for an index of snapshot1
|
||||
assert.deepEqual(
|
||||
snapshots.map(({ uid }) => uid),
|
||||
['1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12']
|
||||
)
|
||||
assert.deepEqual(snapshots[10], {
|
||||
uid: '11',
|
||||
filename: 'vm-Snapshot11.vmsn',
|
||||
parent: '10',
|
||||
displayName: 'snapshot 11',
|
||||
numDisks: '1',
|
||||
disks: [{ fileName: 'vm_0-000011.vmdk', node: 'scsi0:0' }],
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps the snapshot referenced by `current` findable by its uid', function () {
|
||||
// buildDiskChainByNode() looks the current snapshot up by uid, and dereferences its disks
|
||||
const { current, snapshots } = parseVmsd(buildVmsd(12))
|
||||
const currentSnapshot = snapshots.find(({ uid }) => uid === current)
|
||||
|
||||
assert.notEqual(currentSnapshot, undefined)
|
||||
assert.equal(currentSnapshot.disks.length, 1)
|
||||
})
|
||||
|
||||
it('parses a snapshot with 10 disks or more', function () {
|
||||
const { snapshots } = parseVmsd(buildVmsd(1, 11))
|
||||
|
||||
assert.equal(snapshots.length, 1)
|
||||
assert.equal(snapshots[0].disks.length, 11)
|
||||
// disk10 must not be mistaken for an index of disk1
|
||||
assert.deepEqual(snapshots[0].disks[10], { fileName: 'vm_10-000001.vmdk', node: 'scsi0:10' })
|
||||
})
|
||||
})
|
||||
@@ -6,7 +6,7 @@
|
||||
- [Icons](./icons.md)
|
||||
- [Stores](./stores.md)
|
||||
- [Subscribable stores](./subscribable-stores.md)
|
||||
- [Modals](./modals.md)
|
||||
- [Overlays (modals & drawers)](./overlays.md)
|
||||
|
||||
# Composables
|
||||
|
||||
@@ -28,4 +28,4 @@
|
||||
|
||||
- [Job System](../lib/packages/job/README.md)
|
||||
- [Menu System](../lib/packages/menu/README.md)
|
||||
- [Modal System](../lib/packages/modal/README.md)
|
||||
- [Overlay System](../lib/packages/overlay/README.md)
|
||||
|
||||
@@ -1,115 +0,0 @@
|
||||
# Modals
|
||||
|
||||
## `useModal` hook
|
||||
|
||||
You can read the [useModal](../lib/packages/modal/README.md#opening-a-modal-usemodal-composable) documentation to learn more about how to open a modal.
|
||||
|
||||
A modal component should not contain any logic. It should only display the content of the modal and emit a `confirm` or `cancel` event.
|
||||
|
||||
## Create a modal with `VtsModal` component
|
||||
|
||||
### Basic dismissible modal
|
||||
|
||||
A dismissible modal can be closed by clicking on the close button or by clicking outside the modal.
|
||||
|
||||
```html
|
||||
<template>
|
||||
<VtsModal accent="info" dismissible>
|
||||
<template #content> Hello World </template>
|
||||
</VtsModal>
|
||||
</template>
|
||||
```
|
||||
|
||||
#### Custom dismiss event
|
||||
|
||||
By default, a `dismissible` modal will call the `onCancel` handler of `useModal`, if any. Else it will just close the modal.
|
||||
|
||||
If you want to use a custom event, you can pass the `dismiss` event to the `VtsModal` component.
|
||||
|
||||
```html
|
||||
<VtsModal accent="info" dismissible @dismiss="handleDismiss()"></VtsModal>
|
||||
```
|
||||
|
||||
### Modal with buttons
|
||||
|
||||
To confirm or cancel the modal, you can use `VtsModalConfirmButton` and `VtsModalCancelButton`.
|
||||
|
||||
For other actions, you can use `VtsModalButton`.
|
||||
|
||||
By default, these buttons will be the same color as the modal's accent color.
|
||||
|
||||
They also will be disabled with a spinner when the modal is busy.
|
||||
|
||||
```html
|
||||
<template>
|
||||
<VtsModal accent="info">
|
||||
<template #content> You are about to delete this item. </template>
|
||||
|
||||
<template #buttons>
|
||||
<VtsModalCancelButton />
|
||||
<VtsModalConfirmButton>Delete</VtsModalConfirmButton>
|
||||
</template>
|
||||
</VtsModal>
|
||||
</template>
|
||||
```
|
||||
|
||||
### Custom `confirm` and `cancel` events
|
||||
|
||||
If you need to pass arguments to the `confirm` or `cancel` event, you can define and emit them manually.
|
||||
|
||||
```html
|
||||
<template>
|
||||
<VtsModal accent="info" @confirm="emit('confirm', name)">
|
||||
<template #content>
|
||||
What's your name?
|
||||
|
||||
<input v-model="name" />
|
||||
</template>
|
||||
|
||||
<template #buttons>
|
||||
<VtsModalCancelButton @click="emit('cancel', false)">Cancel</VtsModalCancelButton>
|
||||
<VtsModalCancelButton @click="emit('cancel', true)">CANCEL!!!</VtsModalCancelButton>
|
||||
<VtsModalConfirmButton>Submit</VtsModalConfirmButton>
|
||||
</template>
|
||||
</VtsModal>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
const emit = defineEmits<{
|
||||
confirm: [name: string]
|
||||
cancel: [angry: boolean]
|
||||
}>()
|
||||
|
||||
const name = ref('')
|
||||
</script>
|
||||
```
|
||||
|
||||
### Multiple confirm buttons
|
||||
|
||||
`VtsModal` is a form, and, by default, `VtsModalConfirmButton` will be a "submit" button.
|
||||
|
||||
When the form is submitted, it will emit a `confirm` event, if any. Otherwise, it will close the modal.
|
||||
|
||||
If you want to have multiple confirm buttons, to pass different payloads to the `confirm` event, you can pass a `@click` event.
|
||||
|
||||
In this case, the button will no longer be a "submit" button.
|
||||
|
||||
```html
|
||||
<template>
|
||||
<VtsModal accent="info">
|
||||
<template #content> How many do you want? </template>
|
||||
|
||||
<template #buttons>
|
||||
<VtsModalCancelButton>None</VtsModalCancelButton>
|
||||
<VtsModalConfirmButton @click="emit('confirm', 1)">1</VtsModalConfirmButton>
|
||||
<VtsModalConfirmButton @click="emit('confirm', 10)">10</VtsModalConfirmButton>
|
||||
</template>
|
||||
</VtsModal>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
const emit = defineEmits<{
|
||||
confirm: [count: number]
|
||||
}>()
|
||||
</script>
|
||||
```
|
||||
144
@xen-orchestra/web-core/docs/overlays.md
Normal file
144
@xen-orchestra/web-core/docs/overlays.md
Normal file
@@ -0,0 +1,144 @@
|
||||
# Overlays (modals & drawers)
|
||||
|
||||
## Opening an overlay
|
||||
|
||||
Overlays are opened with the `useOverlay` composable. Read the [Overlay System](../lib/packages/overlay/README.md) documentation to learn how to define an overlay, open it, and await the user's decision.
|
||||
|
||||
An overlay component should not contain any business logic. It should only display the content of the overlay and emit events (typically `confirm` and `cancel`); the logic lives in the composables that open it.
|
||||
|
||||
## Create a modal with the `UiModal` component
|
||||
|
||||
### Basic dismissible modal
|
||||
|
||||
`UiModal` emits a `dismiss` event when the user clicks outside the modal or presses Escape. When a `dismiss` listener is attached, a close button is also displayed.
|
||||
|
||||
```html
|
||||
<template>
|
||||
<UiModal accent="info" @dismiss="emit('cancel')">
|
||||
<template #content> Hello World </template>
|
||||
</UiModal>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
const emit = defineEmits<{
|
||||
cancel: []
|
||||
}>()
|
||||
</script>
|
||||
```
|
||||
|
||||
A modal without a `dismiss` listener is not dismissible: the close button is hidden, and clicking outside or pressing Escape does nothing.
|
||||
|
||||
### Modal with buttons
|
||||
|
||||
To confirm or cancel the modal, use `VtsOverlayConfirmButton` and `VtsOverlayCancelButton` in the `buttons` slot.
|
||||
|
||||
For other actions, use `VtsOverlayButton`.
|
||||
|
||||
These buttons take the modal's accent color, and are automatically disabled while the overlay is handling an event — with a spinner on the button that triggered it.
|
||||
|
||||
`UiModal` is a form: `VtsOverlayConfirmButton` is a submit button by default, and submitting the form emits the `confirm` event.
|
||||
|
||||
```html
|
||||
<template>
|
||||
<UiModal accent="danger" @confirm="emit('confirm')" @dismiss="emit('cancel')">
|
||||
<template #content> You are about to delete this item. </template>
|
||||
|
||||
<template #buttons>
|
||||
<VtsOverlayCancelButton @click="emit('cancel')" />
|
||||
<VtsOverlayConfirmButton>Delete</VtsOverlayConfirmButton>
|
||||
</template>
|
||||
</UiModal>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
const emit = defineEmits<{
|
||||
confirm: []
|
||||
cancel: []
|
||||
}>()
|
||||
</script>
|
||||
```
|
||||
|
||||
### Event payloads
|
||||
|
||||
If you need to pass a payload to the `confirm` or `cancel` events, emit it from the corresponding handler:
|
||||
|
||||
```html
|
||||
<template>
|
||||
<UiModal accent="info" @confirm="emit('confirm', name)" @dismiss="emit('cancel')">
|
||||
<template #content>
|
||||
What's your name?
|
||||
|
||||
<input v-model="name" />
|
||||
</template>
|
||||
|
||||
<template #buttons>
|
||||
<VtsOverlayCancelButton @click="emit('cancel')" />
|
||||
<VtsOverlayConfirmButton>Submit</VtsOverlayConfirmButton>
|
||||
</template>
|
||||
</UiModal>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
const emit = defineEmits<{
|
||||
confirm: [name: string]
|
||||
cancel: []
|
||||
}>()
|
||||
|
||||
const name = ref('')
|
||||
</script>
|
||||
```
|
||||
|
||||
### Multiple confirm buttons
|
||||
|
||||
If you want multiple confirm buttons passing different payloads to the `confirm` event, give each one a `@click` handler.
|
||||
|
||||
A `VtsOverlayConfirmButton` with a `@click` handler is no longer a submit button.
|
||||
|
||||
```html
|
||||
<template>
|
||||
<UiModal accent="info">
|
||||
<template #content> How many do you want? </template>
|
||||
|
||||
<template #buttons>
|
||||
<VtsOverlayCancelButton @click="emit('cancel')">None</VtsOverlayCancelButton>
|
||||
<VtsOverlayConfirmButton @click="emit('confirm', 1)">1</VtsOverlayConfirmButton>
|
||||
<VtsOverlayConfirmButton @click="emit('confirm', 10)">10</VtsOverlayConfirmButton>
|
||||
</template>
|
||||
</UiModal>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
const emit = defineEmits<{
|
||||
confirm: [count: number]
|
||||
cancel: []
|
||||
}>()
|
||||
</script>
|
||||
```
|
||||
|
||||
## Create a drawer with the `UiDrawer` component
|
||||
|
||||
`UiDrawer` works the same way: it is a form emitting `confirm` on submit and `dismiss` on outside click or Escape, with `title`, `content`, and `buttons` slots.
|
||||
|
||||
```html
|
||||
<template>
|
||||
<UiDrawer :title="t('settings')" @confirm="emit('confirm')" @dismiss="emit('cancel')">
|
||||
<template #content>
|
||||
<!-- Drawer content -->
|
||||
</template>
|
||||
|
||||
<template #buttons>
|
||||
<VtsOverlayCancelButton @click="emit('cancel')" />
|
||||
<VtsOverlayConfirmButton>Save</VtsOverlayConfirmButton>
|
||||
</template>
|
||||
</UiDrawer>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
const emit = defineEmits<{
|
||||
confirm: []
|
||||
cancel: []
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
</script>
|
||||
```
|
||||
@@ -1,89 +0,0 @@
|
||||
<template>
|
||||
<UiDrawer
|
||||
:is-open="effectiveIsOpen"
|
||||
:is-dismissible="dismissible"
|
||||
v-on="{ dismiss: handleDismiss, afterLeave: onAfterLeave }"
|
||||
>
|
||||
<template v-if="slots.title" #title>
|
||||
<slot name="title" />
|
||||
</template>
|
||||
|
||||
<template #content>
|
||||
<slot name="content" />
|
||||
</template>
|
||||
|
||||
<template v-if="slots.buttons" #buttons>
|
||||
<slot name="buttons" />
|
||||
</template>
|
||||
</UiDrawer>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import UiDrawer from '@core/components/ui/drawer/UiDrawer.vue'
|
||||
import { IK_DRAWER } from '@core/packages/drawer/types.ts'
|
||||
import { useMagicKeys, whenever } from '@vueuse/core'
|
||||
import { computed, inject, onMounted, ref } from 'vue'
|
||||
|
||||
const {
|
||||
dismissible,
|
||||
isOpen = undefined,
|
||||
current,
|
||||
} = defineProps<{
|
||||
dismissible?: boolean
|
||||
isOpen?: boolean
|
||||
current?: boolean
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
dismiss: []
|
||||
}>()
|
||||
|
||||
const slots = defineSlots<{
|
||||
content(): any
|
||||
title?(): any
|
||||
buttons?(): any
|
||||
}>()
|
||||
|
||||
const drawer = inject(IK_DRAWER, undefined)
|
||||
|
||||
const internalVisible = ref(false)
|
||||
|
||||
onMounted(() => {
|
||||
if (isOpen === undefined) {
|
||||
internalVisible.value = true
|
||||
}
|
||||
})
|
||||
|
||||
const effectiveIsOpen = computed(() => isOpen ?? internalVisible.value)
|
||||
|
||||
let afterLeaveCallback: (() => void) | undefined
|
||||
|
||||
function onAfterLeave() {
|
||||
afterLeaveCallback?.()
|
||||
afterLeaveCallback = undefined
|
||||
}
|
||||
|
||||
const handleDismiss = computed(() => {
|
||||
if (!dismissible) {
|
||||
return undefined
|
||||
}
|
||||
|
||||
return () => {
|
||||
if (isOpen !== undefined) {
|
||||
emit('dismiss')
|
||||
return
|
||||
}
|
||||
|
||||
afterLeaveCallback = () => drawer?.value.onCancel()
|
||||
internalVisible.value = false
|
||||
}
|
||||
})
|
||||
|
||||
const { escape } = useMagicKeys()
|
||||
|
||||
whenever(escape, () => {
|
||||
if (dismissible && current) {
|
||||
handleDismiss.value?.()
|
||||
}
|
||||
})
|
||||
</script>
|
||||
@@ -1,22 +0,0 @@
|
||||
<template>
|
||||
<UiButton :accent :busy="drawer?.isBusy.value" :variant size="medium">
|
||||
<slot />
|
||||
</UiButton>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import UiButton, { type ButtonAccent, type ButtonVariant } from '@core/components/ui/button/UiButton.vue'
|
||||
import { IK_DRAWER } from '@core/packages/drawer/types.ts'
|
||||
import { inject } from 'vue'
|
||||
|
||||
const { accent = 'brand' } = defineProps<{
|
||||
variant: ButtonVariant
|
||||
accent?: ButtonAccent
|
||||
}>()
|
||||
|
||||
defineSlots<{
|
||||
default(): any
|
||||
}>()
|
||||
|
||||
const drawer = inject(IK_DRAWER)
|
||||
</script>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user