mirror of
https://github.com/vatesfr/xen-orchestra.git
synced 2026-11-30 02:37:27 -06:00
Compare commits
7 Commits
docs/body-
...
feat_task_
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
42dd10babd | ||
|
|
8be88ba22b | ||
|
|
8bb26f1c48 | ||
|
|
28c7514b81 | ||
|
|
939496a72d | ||
|
|
0537257b12 | ||
|
|
4158daabe5 |
@@ -19,12 +19,12 @@
|
||||
},
|
||||
"main": "./index.mjs",
|
||||
"dependencies": {
|
||||
"@xen-orchestra/fs": "^4.10.0",
|
||||
"@xen-orchestra/fs": "^4.9.5",
|
||||
"@xen-orchestra/log": "^0.7.2",
|
||||
"fuse-native": "^2.2.6",
|
||||
"lru-cache": "^7.14.0",
|
||||
"promise-toolbox": "^0.21.0",
|
||||
"vhd-lib": "^4.17.0"
|
||||
"vhd-lib": "^4.16.2"
|
||||
},
|
||||
"bin": {
|
||||
"xo-fuse-vhd": "./cli.mjs"
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@vates/iscsi",
|
||||
"version": "0.4.0",
|
||||
"version": "0.2.0",
|
||||
"main": "dist/index.mjs",
|
||||
"types": "dist/index.d.mts",
|
||||
"bin": {
|
||||
@@ -23,7 +23,7 @@
|
||||
"dependencies": {
|
||||
"@vates/async-each": "^1.0.3",
|
||||
"@vates/read-chunk": "^1.2.1",
|
||||
"@xen-orchestra/disk-transform": "^1.3.4",
|
||||
"@xen-orchestra/disk-transform": "^1.3.0",
|
||||
"@xen-orchestra/log": "^0.7.2",
|
||||
"promise-toolbox": "^0.21.0"
|
||||
},
|
||||
|
||||
@@ -1,129 +0,0 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { execFile, execFileSync } from 'node:child_process'
|
||||
import { mkdtemp, rm, truncate, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { promisify } from 'node:util'
|
||||
import { after, before, describe, it } from 'node:test'
|
||||
|
||||
import { FileBlockDevice } from './index.mjs'
|
||||
|
||||
const execFileP = promisify(execFile)
|
||||
|
||||
const BLOCK_SIZE = 512
|
||||
const SIZE = 4 * 1024 * 1024 // 4 MiB
|
||||
|
||||
/**
|
||||
* Why this cannot run here, or `false` if it can. A real block device is the
|
||||
* whole point, and the cheapest one to make is a loop device — which needs root
|
||||
* and `losetup`.
|
||||
*/
|
||||
function skipReason(): string | false {
|
||||
if (process.getuid === undefined || process.getuid() !== 0) {
|
||||
return 'requires root to attach a loop device'
|
||||
}
|
||||
try {
|
||||
execFileSync('losetup', ['--version'], { stdio: 'ignore' })
|
||||
} catch {
|
||||
return 'requires util-linux (losetup not found)'
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
const bytePattern = (i: number) => (i * 31 + 11) & 0xff
|
||||
|
||||
describe('FileBlockDevice on a loop device', { skip: skipReason() }, () => {
|
||||
let dir: string
|
||||
let devicePath: string
|
||||
|
||||
before(async () => {
|
||||
dir = await mkdtemp(join(tmpdir(), 'vates-iscsi-loop-'))
|
||||
const backing = join(dir, 'backing.img')
|
||||
await writeFile(backing, '')
|
||||
await truncate(backing, SIZE)
|
||||
const { stdout } = await execFileP('losetup', ['--find', '--show', backing])
|
||||
devicePath = stdout.trim()
|
||||
})
|
||||
|
||||
after(async () => {
|
||||
if (devicePath !== undefined) {
|
||||
await execFileP('losetup', ['--detach', devicePath])
|
||||
}
|
||||
await rm(dir, { force: true, recursive: true })
|
||||
})
|
||||
|
||||
const withDevice = async (fn: (device: FileBlockDevice) => Promise<void>): Promise<void> => {
|
||||
const device = new FileBlockDevice({ path: devicePath, size: SIZE })
|
||||
await device.open()
|
||||
try {
|
||||
await fn(device)
|
||||
} finally {
|
||||
await device.close()
|
||||
}
|
||||
}
|
||||
|
||||
it('accepts the device node and reports the capacity it was given', async () => {
|
||||
await withDevice(async device => {
|
||||
assert.equal(device.getSize(), SIZE)
|
||||
assert.equal(device.getBlockSize(), BLOCK_SIZE)
|
||||
})
|
||||
})
|
||||
|
||||
it('round-trips block-aligned data', async () => {
|
||||
await withDevice(async device => {
|
||||
const payload = Buffer.alloc(8 * BLOCK_SIZE)
|
||||
for (let i = 0; i < payload.length; i++) {
|
||||
payload[i] = bytePattern(i)
|
||||
}
|
||||
await device.write(16 * BLOCK_SIZE, payload)
|
||||
assert.deepEqual(await device.read(16 * BLOCK_SIZE, payload.length), payload)
|
||||
})
|
||||
})
|
||||
|
||||
it('round-trips data straddling block boundaries, at an unaligned offset', async () => {
|
||||
await withDevice(async device => {
|
||||
const payload = Buffer.from('a payload that is not a whole number of sectors long')
|
||||
const offset = 3 * BLOCK_SIZE + 17
|
||||
await device.write(offset, payload)
|
||||
assert.deepEqual(await device.read(offset, payload.length), payload)
|
||||
// the surrounding sector was read-modify-written by the kernel, not clobbered
|
||||
assert.deepEqual(await device.read(3 * BLOCK_SIZE, 17), Buffer.alloc(17))
|
||||
})
|
||||
})
|
||||
|
||||
it('survives a reopen, which is what makes it a cache', async () => {
|
||||
const payload = Buffer.alloc(BLOCK_SIZE, 0x5a)
|
||||
await withDevice(device => device.write(2 * BLOCK_SIZE, payload))
|
||||
await withDevice(async device => {
|
||||
await device.flush()
|
||||
assert.deepEqual(await device.read(2 * BLOCK_SIZE, BLOCK_SIZE), payload)
|
||||
})
|
||||
})
|
||||
|
||||
it('reads a large range in one call', async () => {
|
||||
await withDevice(async device => {
|
||||
const payload = Buffer.alloc(SIZE / 2)
|
||||
for (let i = 0; i < payload.length; i++) {
|
||||
payload[i] = bytePattern(i + 7)
|
||||
}
|
||||
await device.write(0, payload)
|
||||
assert.deepEqual(await device.read(0, payload.length), payload)
|
||||
})
|
||||
})
|
||||
|
||||
it('throws on a read running past the end, instead of zero-filling it', async () => {
|
||||
// the behaviour that sets the block device mode apart: a short read on a
|
||||
// device of a known size is an I/O error, never a sparse tail
|
||||
await withDevice(async device => {
|
||||
await assert.rejects(device.read(SIZE, BLOCK_SIZE), /ended after 0 bytes/)
|
||||
await assert.rejects(device.read(SIZE - BLOCK_SIZE, 2 * BLOCK_SIZE), /ended after 512 bytes/)
|
||||
})
|
||||
})
|
||||
|
||||
it('flushes without error', async () => {
|
||||
await withDevice(async device => {
|
||||
await device.write(0, Buffer.alloc(BLOCK_SIZE, 0xff))
|
||||
await device.flush()
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -34,60 +34,31 @@ export interface BlockDevice {
|
||||
const DEFAULT_BLOCK_SIZE = 512
|
||||
|
||||
export interface FileBlockDeviceOptions {
|
||||
/**
|
||||
* Path to the backing file. It must already exist and be sized to capacity —
|
||||
* or be a block device node, see {@link FileBlockDeviceOptions.size}.
|
||||
*/
|
||||
/** Path to the backing file. It must already exist and be sized to capacity. */
|
||||
readonly path: string
|
||||
/** Logical block size in bytes. Defaults to 512. */
|
||||
readonly blockSize?: number
|
||||
/**
|
||||
* Capacity in bytes, for a block device node (e.g. a VDI hot-plugged onto the
|
||||
* appliance's VM, `/dev/xvdX`), whose inode reports a size of 0.
|
||||
*
|
||||
* Setting it switches to the block device mode:
|
||||
* - `path` must be a block device: a typo naming the wrong node is the
|
||||
* difference between a cache and a destroyed disk;
|
||||
* - a short read is an I/O error, not a sparse tail: zero-filling it would hand
|
||||
* the initiator fabricated data.
|
||||
*/
|
||||
readonly size?: number
|
||||
}
|
||||
|
||||
/**
|
||||
* A {@link BlockDevice} backed by a regular (sparse) file, or a block device
|
||||
* node, opened read/write.
|
||||
* A {@link BlockDevice} backed by a regular (sparse) file opened read/write.
|
||||
*
|
||||
* The file must already exist and be sized to the desired capacity (e.g. via
|
||||
* `fs.truncate`); this keeps the device a pure data store with no provisioning
|
||||
* policy of its own.
|
||||
*
|
||||
* I/O is buffered, never `O_DIRECT`, which would need buffers aligned to the
|
||||
* logical block size that Node cannot allocate.
|
||||
*/
|
||||
export class FileBlockDevice implements BlockDevice {
|
||||
readonly #path: string
|
||||
readonly #blockSize: number
|
||||
readonly #isBlockDevice: boolean
|
||||
#handle?: FileHandle
|
||||
#size = 0
|
||||
|
||||
constructor({ path, blockSize = DEFAULT_BLOCK_SIZE, size }: FileBlockDeviceOptions) {
|
||||
constructor({ path, blockSize = DEFAULT_BLOCK_SIZE }: FileBlockDeviceOptions) {
|
||||
if (!Number.isInteger(blockSize) || blockSize <= 0) {
|
||||
throw new Error(`blockSize must be a positive integer, got ${blockSize}`)
|
||||
}
|
||||
if (size !== undefined) {
|
||||
if (!Number.isInteger(size) || size <= 0) {
|
||||
throw new Error(`size must be a positive integer, got ${size}`)
|
||||
}
|
||||
if (size % blockSize !== 0) {
|
||||
throw new Error(`size (${size}) is not a multiple of block size (${blockSize})`)
|
||||
}
|
||||
this.#size = size
|
||||
}
|
||||
this.#path = path
|
||||
this.#blockSize = blockSize
|
||||
this.#isBlockDevice = size !== undefined
|
||||
}
|
||||
|
||||
/** Open the backing file and read its current size. Must be called before any I/O. */
|
||||
@@ -97,18 +68,12 @@ export class FileBlockDevice implements BlockDevice {
|
||||
}
|
||||
const handle = await open(this.#path, 'r+')
|
||||
try {
|
||||
const stats = await handle.stat()
|
||||
if (this.#isBlockDevice) {
|
||||
if (!stats.isBlockDevice()) {
|
||||
throw new Error(`${this.#path} is not a block device`)
|
||||
}
|
||||
} else {
|
||||
if (stats.size % this.#blockSize !== 0) {
|
||||
throw new Error(`backing file size (${stats.size}) is not a multiple of block size (${this.#blockSize})`)
|
||||
}
|
||||
this.#size = stats.size
|
||||
const { size } = await handle.stat()
|
||||
if (size % this.#blockSize !== 0) {
|
||||
throw new Error(`backing file size (${size}) is not a multiple of block size (${this.#blockSize})`)
|
||||
}
|
||||
this.#handle = handle
|
||||
this.#size = size
|
||||
} catch (error) {
|
||||
await handle.close()
|
||||
throw error
|
||||
@@ -139,10 +104,6 @@ export class FileBlockDevice implements BlockDevice {
|
||||
while (read < length) {
|
||||
const { bytesRead } = await handle.read(buffer, read, length - read, offset + read)
|
||||
if (bytesRead === 0) {
|
||||
if (this.#isBlockDevice) {
|
||||
// the device is exactly as long as the caller said: the I/O failed
|
||||
throw new Error(`read of ${length} bytes at ${offset} on ${this.#path} ended after ${read} bytes`)
|
||||
}
|
||||
// Reading past EOF (sparse tail): zero-fill the remainder.
|
||||
buffer.fill(0, read)
|
||||
break
|
||||
|
||||
@@ -1,173 +0,0 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { describe, it } from 'node:test'
|
||||
import { mkdtemp, rm, truncate, writeFile } from 'node:fs/promises'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
|
||||
import { FileBlockDevice } from './backend.mjs'
|
||||
|
||||
const BLOCK_SIZE = 512
|
||||
|
||||
/** A temporary directory removed whatever the test does. */
|
||||
const withTmpDir = async (fn: (dir: string) => Promise<void>): Promise<void> => {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'vates-iscsi-backend-'))
|
||||
try {
|
||||
await fn(dir)
|
||||
} finally {
|
||||
await rm(dir, { force: true, recursive: true })
|
||||
}
|
||||
}
|
||||
|
||||
/** A sparse file of `size` bytes, as the class requires: existing and pre-sized. */
|
||||
const makeFile = async (dir: string, size: number, name = 'lun.img'): Promise<string> => {
|
||||
const path = join(dir, name)
|
||||
await writeFile(path, '')
|
||||
await truncate(path, size)
|
||||
return path
|
||||
}
|
||||
|
||||
describe('FileBlockDevice', () => {
|
||||
it('rejects a non-positive-integer block size', () => {
|
||||
assert.throws(() => new FileBlockDevice({ path: '/nope', blockSize: 0 }), /positive integer/)
|
||||
assert.throws(() => new FileBlockDevice({ path: '/nope', blockSize: -1 }), /positive integer/)
|
||||
assert.throws(() => new FileBlockDevice({ path: '/nope', blockSize: 1.5 }), /positive integer/)
|
||||
})
|
||||
|
||||
it('reads the capacity from the backing file', async () => {
|
||||
await withTmpDir(async dir => {
|
||||
const device = new FileBlockDevice({ path: await makeFile(dir, 4 * BLOCK_SIZE) })
|
||||
await device.open()
|
||||
try {
|
||||
assert.equal(device.getSize(), 4 * BLOCK_SIZE)
|
||||
assert.equal(device.getBlockSize(), BLOCK_SIZE)
|
||||
} finally {
|
||||
await device.close()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
it('refuses a file whose size is not a multiple of the block size', async () => {
|
||||
await withTmpDir(async dir => {
|
||||
const device = new FileBlockDevice({ path: await makeFile(dir, BLOCK_SIZE + 1) })
|
||||
await assert.rejects(device.open(), /not a multiple of block size/)
|
||||
})
|
||||
})
|
||||
|
||||
it('throws on I/O before open()', async () => {
|
||||
const device = new FileBlockDevice({ path: '/nope' })
|
||||
await assert.rejects(device.read(0, BLOCK_SIZE), /must be called before I\/O/)
|
||||
await assert.rejects(device.write(0, Buffer.alloc(BLOCK_SIZE)), /must be called before I\/O/)
|
||||
await assert.rejects(device.flush(), /must be called before I\/O/)
|
||||
})
|
||||
|
||||
it('round-trips a write, at an offset and unaligned', async () => {
|
||||
await withTmpDir(async dir => {
|
||||
const device = new FileBlockDevice({ path: await makeFile(dir, 4 * BLOCK_SIZE) })
|
||||
await device.open()
|
||||
try {
|
||||
const payload = Buffer.from('hello, lun')
|
||||
await device.write(BLOCK_SIZE + 3, payload)
|
||||
assert.deepEqual(await device.read(BLOCK_SIZE + 3, payload.length), payload)
|
||||
|
||||
// the bytes around it are untouched
|
||||
assert.deepEqual(await device.read(BLOCK_SIZE, 3), Buffer.alloc(3))
|
||||
} finally {
|
||||
await device.close()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
it('zero-fills the sparse tail of a read past EOF', async () => {
|
||||
await withTmpDir(async dir => {
|
||||
// a hole: nothing was ever written, so the whole file reads as zeroes
|
||||
const device = new FileBlockDevice({ path: await makeFile(dir, 2 * BLOCK_SIZE) })
|
||||
await device.open()
|
||||
try {
|
||||
assert.deepEqual(await device.read(0, 2 * BLOCK_SIZE), Buffer.alloc(2 * BLOCK_SIZE))
|
||||
|
||||
// past the end of the file, `fh.read` reports 0 bytes read: the remainder is
|
||||
// zero-filled rather than being reported as an error
|
||||
assert.deepEqual(await device.read(2 * BLOCK_SIZE, BLOCK_SIZE), Buffer.alloc(BLOCK_SIZE))
|
||||
} finally {
|
||||
await device.close()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
it('reads back a large buffer in full', async () => {
|
||||
await withTmpDir(async dir => {
|
||||
const size = 1024 * BLOCK_SIZE
|
||||
const device = new FileBlockDevice({ path: await makeFile(dir, size) })
|
||||
await device.open()
|
||||
try {
|
||||
const payload = Buffer.alloc(size)
|
||||
for (let i = 0; i < payload.length; i++) {
|
||||
payload[i] = (i * 31 + 11) & 0xff
|
||||
}
|
||||
await device.write(0, payload)
|
||||
assert.deepEqual(await device.read(0, size), payload)
|
||||
} finally {
|
||||
await device.close()
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
it('flushes and closes, and tolerates being opened or closed twice', async () => {
|
||||
await withTmpDir(async dir => {
|
||||
const device = new FileBlockDevice({ path: await makeFile(dir, BLOCK_SIZE) })
|
||||
await device.open()
|
||||
await device.open() // no-op
|
||||
await device.write(0, Buffer.alloc(BLOCK_SIZE, 0xaa))
|
||||
await device.flush()
|
||||
await device.close()
|
||||
await device.close() // no-op
|
||||
await assert.rejects(device.read(0, BLOCK_SIZE), /must be called before I\/O/)
|
||||
})
|
||||
})
|
||||
|
||||
it('leaves no handle behind when open() fails', async () => {
|
||||
await withTmpDir(async dir => {
|
||||
const device = new FileBlockDevice({ path: await makeFile(dir, BLOCK_SIZE + 1) })
|
||||
await assert.rejects(device.open())
|
||||
// the handle opened before the size check was closed again
|
||||
await assert.rejects(device.read(0, BLOCK_SIZE), /must be called before I\/O/)
|
||||
})
|
||||
})
|
||||
})
|
||||
|
||||
// A real device node cannot be created without root, so what is covered here is
|
||||
// everything around the I/O: the guards, the capacity, and the lifecycle. The
|
||||
// I/O itself is covered by `backend.integ.mts`, against a loop device.
|
||||
describe('FileBlockDevice with a size, over a block device', () => {
|
||||
it('rejects a non-positive-integer size', () => {
|
||||
for (const size of [0, -BLOCK_SIZE, 1.5]) {
|
||||
assert.throws(() => new FileBlockDevice({ path: '/dev/null', size }), /size must be a positive integer/)
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects a size that is not a multiple of the block size', () => {
|
||||
assert.throws(
|
||||
() => new FileBlockDevice({ path: '/dev/null', size: BLOCK_SIZE + 1 }),
|
||||
/is not a multiple of block size/
|
||||
)
|
||||
})
|
||||
|
||||
it('reports the capacity it was given, never the inode', () => {
|
||||
// nothing may be read from the inode, which for a real device node reports 0
|
||||
const device = new FileBlockDevice({ path: '/dev/null', size: 4 * BLOCK_SIZE })
|
||||
assert.equal(device.getSize(), 4 * BLOCK_SIZE)
|
||||
assert.equal(device.getBlockSize(), BLOCK_SIZE)
|
||||
})
|
||||
|
||||
it('refuses to open a path that is not a block device', async () => {
|
||||
await withTmpDir(async dir => {
|
||||
const path = await makeFile(dir, 4 * BLOCK_SIZE)
|
||||
const device = new FileBlockDevice({ path, size: 4 * BLOCK_SIZE })
|
||||
// the guard against a misconfigured path naming, say, a real disk's
|
||||
// filesystem instead of the cache device
|
||||
await assert.rejects(device.open(), new RegExp(`${path} is not a block device`))
|
||||
// and the handle it opened to check was closed again
|
||||
await assert.rejects(device.read(0, BLOCK_SIZE), /must be called before I\/O/)
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -13,7 +13,7 @@
|
||||
"url": "https://vates.fr"
|
||||
},
|
||||
"license": "ISC",
|
||||
"version": "3.7.0",
|
||||
"version": "3.6.0",
|
||||
"engines": {
|
||||
"node": ">=14.0"
|
||||
},
|
||||
@@ -22,10 +22,10 @@
|
||||
"@vates/async-each": "^1.0.3",
|
||||
"@vates/read-chunk": "^1.2.1",
|
||||
"@xen-orchestra/async-map": "^0.1.5",
|
||||
"@xen-orchestra/disk-transform": "^1.3.4",
|
||||
"@xen-orchestra/disk-transform": "^1.3.3",
|
||||
"@xen-orchestra/log": "^0.7.2",
|
||||
"promise-toolbox": "^0.21.0",
|
||||
"xen-api": "^5.1.0"
|
||||
"xen-api": "^5.0.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"tap": "^18.7.0",
|
||||
|
||||
@@ -102,6 +102,69 @@ await Task.run.call(object, 'method')
|
||||
await Task.run.call(object, 'method', 'foo', 'bar')
|
||||
```
|
||||
|
||||
### `TaskMetrics`
|
||||
|
||||
Metrics of a task (bytes read, bytes written, queue depth…), with a bounded history to draw charts.
|
||||
|
||||
The metrics are bound to an explicit task, not to the current one, so they can be updated from any async context (e.g. a source read by multiple consumers). The task must be started before the first update.
|
||||
|
||||
```js
|
||||
import { TaskMetrics } from '@vates/task/metrics'
|
||||
|
||||
const metrics = new TaskMetrics(task, {
|
||||
// maximum number of samples in the history, covering the whole duration of the task
|
||||
historySize: 20,
|
||||
|
||||
// minimum duration between two emits, in milliseconds
|
||||
minEmitInterval: 5e3,
|
||||
|
||||
// number of recent samples, one per emit
|
||||
recentSize: 5,
|
||||
})
|
||||
|
||||
// optional declaration, before the first update
|
||||
metrics.define('bytesRead', {
|
||||
// emitted as is, for the clients to format the values
|
||||
unit: 'bytes',
|
||||
})
|
||||
|
||||
// expected final value, if known
|
||||
metrics.setTotal('bytesRead', bytesToRead)
|
||||
|
||||
// adds to a cumulative metric
|
||||
metrics.add('bytesRead', block.length)
|
||||
|
||||
// emits the latest values whatever the throttling, to call before ending the task
|
||||
metrics.flush()
|
||||
```
|
||||
|
||||
The metrics are emitted in the `metrics` property of the task:
|
||||
|
||||
```js
|
||||
{
|
||||
bytesRead: {
|
||||
// latest value
|
||||
value: 1234567890,
|
||||
|
||||
// expected final value, if known
|
||||
total: 3072327680,
|
||||
|
||||
// if defined
|
||||
unit: 'bytes',
|
||||
|
||||
// latest samples ([timestamp, value]), one per emit: current speed
|
||||
recent: [[1729000000000, 1200000000], …],
|
||||
|
||||
// at most `historySize` samples covering the whole duration of the task: chart
|
||||
history: [[1728999000000, 0], …],
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
The history interval starts at the emit interval and is doubled when the history is full: every other sample is dropped, which loses resolution, not volume, as the values are cumulative.
|
||||
|
||||
A client watching the task can draw the history as the skeleton of the chart, then append the recent samples it receives to get a finer curve.
|
||||
|
||||
### `combineEvents`
|
||||
|
||||
Create a consolidated log from individual events.
|
||||
|
||||
@@ -118,6 +118,69 @@ await Task.run.call(object, 'method')
|
||||
await Task.run.call(object, 'method', 'foo', 'bar')
|
||||
```
|
||||
|
||||
### `TaskMetrics`
|
||||
|
||||
Metrics of a task (bytes read, bytes written, queue depth…), with a bounded history to draw charts.
|
||||
|
||||
The metrics are bound to an explicit task, not to the current one, so they can be updated from any async context (e.g. a source read by multiple consumers). The task must be started before the first update.
|
||||
|
||||
```js
|
||||
import { TaskMetrics } from '@vates/task/metrics'
|
||||
|
||||
const metrics = new TaskMetrics(task, {
|
||||
// maximum number of samples in the history, covering the whole duration of the task
|
||||
historySize: 20,
|
||||
|
||||
// minimum duration between two emits, in milliseconds
|
||||
minEmitInterval: 5e3,
|
||||
|
||||
// number of recent samples, one per emit
|
||||
recentSize: 5,
|
||||
})
|
||||
|
||||
// optional declaration, before the first update
|
||||
metrics.define('bytesRead', {
|
||||
// emitted as is, for the clients to format the values
|
||||
unit: 'bytes',
|
||||
})
|
||||
|
||||
// expected final value, if known
|
||||
metrics.setTotal('bytesRead', bytesToRead)
|
||||
|
||||
// adds to a cumulative metric
|
||||
metrics.add('bytesRead', block.length)
|
||||
|
||||
// emits the latest values whatever the throttling, to call before ending the task
|
||||
metrics.flush()
|
||||
```
|
||||
|
||||
The metrics are emitted in the `metrics` property of the task:
|
||||
|
||||
```js
|
||||
{
|
||||
bytesRead: {
|
||||
// latest value
|
||||
value: 1234567890,
|
||||
|
||||
// expected final value, if known
|
||||
total: 3072327680,
|
||||
|
||||
// if defined
|
||||
unit: 'bytes',
|
||||
|
||||
// latest samples ([timestamp, value]), one per emit: current speed
|
||||
recent: [[1729000000000, 1200000000], …],
|
||||
|
||||
// at most `historySize` samples covering the whole duration of the task: chart
|
||||
history: [[1728999000000, 0], …],
|
||||
},
|
||||
}
|
||||
```
|
||||
|
||||
The history interval starts at the emit interval and is doubled when the history is full: every other sample is dropped, which loses resolution, not volume, as the values are cumulative.
|
||||
|
||||
A client watching the task can draw the history as the skeleton of the chart, then append the recent samples it receives to get a finer curve.
|
||||
|
||||
### `combineEvents`
|
||||
|
||||
Create a consolidated log from individual events.
|
||||
|
||||
180
@vates/task/metrics.js
Normal file
180
@vates/task/metrics.js
Normal file
@@ -0,0 +1,180 @@
|
||||
'use strict'
|
||||
|
||||
const assert = require('node:assert').strict
|
||||
|
||||
class Metric {
|
||||
constructor({ historyInterval, unit }) {
|
||||
// samples (`[timestamp, value]`)
|
||||
this.history = []
|
||||
// only grows, see TaskMetrics
|
||||
this.historyInterval = historyInterval
|
||||
this.recent = []
|
||||
this.total = undefined
|
||||
this.unit = unit
|
||||
this.value = 0
|
||||
}
|
||||
|
||||
toJSON() {
|
||||
const { history, recent, total, unit, value } = this
|
||||
const json = { value, recent: recent.slice(), history: history.slice() }
|
||||
if (total !== undefined) {
|
||||
json.total = total
|
||||
}
|
||||
if (unit !== undefined) {
|
||||
json.unit = unit
|
||||
}
|
||||
return json
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Cumulative metrics of a task (bytes read, bytes written…), with a bounded history to draw charts
|
||||
*
|
||||
* The metrics are emitted in the `metrics` property of the task, throttled. Each metric is:
|
||||
*
|
||||
* - `value`: the latest value
|
||||
* - `total`: the expected final value, if known
|
||||
* - `unit`: the unit of the values, if defined (`bytes`, `blocks`…)
|
||||
* - `recent`: the latest samples (`[timestamp, value]`), one per emit, to compute the current speed
|
||||
* - `history`: samples covering the whole duration of the task, at most `historySize`
|
||||
*
|
||||
* The history interval starts at the emit interval and is doubled when the history is full: every other sample is
|
||||
* dropped, which loses resolution, not volume, as the values are cumulative.
|
||||
*
|
||||
* The metrics are bound to an explicit task, not to the current one: they can be updated from any async context. The
|
||||
* task must be started before the first update.
|
||||
*/
|
||||
class TaskMetrics {
|
||||
#historySize
|
||||
#lastEmitDate
|
||||
#metrics = new Map()
|
||||
#minEmitInterval
|
||||
#recentSize
|
||||
#task
|
||||
|
||||
/**
|
||||
* @param {import('./index.js').Task} task
|
||||
* @param {object} [opts]
|
||||
* @param {number} [opts.historySize] maximum number of samples in the history
|
||||
* @param {number} [opts.minEmitInterval] minimum duration between two emits, in milliseconds
|
||||
* @param {number} [opts.recentSize] number of recent samples
|
||||
*/
|
||||
constructor(task, { historySize = 20, minEmitInterval = 5e3, recentSize = 5 } = {}) {
|
||||
assert(historySize >= 2, 'historySize must be at least 2')
|
||||
assert(recentSize >= 2, 'recentSize must be at least 2')
|
||||
|
||||
this.#historySize = historySize
|
||||
this.#minEmitInterval = minEmitInterval
|
||||
this.#recentSize = recentSize
|
||||
this.#task = task
|
||||
}
|
||||
|
||||
/**
|
||||
* Declares a metric, before its first update
|
||||
*
|
||||
* Optional: an undeclared metric has no unit
|
||||
*
|
||||
* @param {string} name
|
||||
* @param {object} [opts]
|
||||
* @param {string} [opts.unit]
|
||||
*/
|
||||
define(name, { unit } = {}) {
|
||||
assert(!this.#metrics.has(name), `metric ${name} is already defined`)
|
||||
|
||||
this.#metrics.set(name, new Metric({ historyInterval: this.#minEmitInterval, unit }))
|
||||
}
|
||||
|
||||
#getMetric(name) {
|
||||
let metric = this.#metrics.get(name)
|
||||
if (metric === undefined) {
|
||||
metric = new Metric({ historyInterval: this.#minEmitInterval })
|
||||
this.#metrics.set(name, metric)
|
||||
}
|
||||
return metric
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds `delta` to a metric
|
||||
*
|
||||
* @param {string} name
|
||||
* @param {number} delta
|
||||
*/
|
||||
add(name, delta) {
|
||||
this.#getMetric(name).value += delta
|
||||
this.#maybeEmit()
|
||||
}
|
||||
|
||||
/**
|
||||
* Sets the expected final value of a metric
|
||||
*
|
||||
* @param {string} name
|
||||
* @param {number | undefined} total
|
||||
*/
|
||||
setTotal(name, total) {
|
||||
this.#getMetric(name).total = total
|
||||
}
|
||||
|
||||
/**
|
||||
* Emits the metrics now, whatever the throttling, the latest values are always in the history
|
||||
*
|
||||
* To call once the task is done, before ending it
|
||||
*/
|
||||
flush() {
|
||||
this.#emit({ isFinal: true })
|
||||
}
|
||||
|
||||
#maybeEmit() {
|
||||
if (this.#lastEmitDate === undefined || Date.now() - this.#lastEmitDate >= this.#minEmitInterval) {
|
||||
this.#emit({ isFinal: false })
|
||||
}
|
||||
}
|
||||
|
||||
#emit({ isFinal }) {
|
||||
const task = this.#task
|
||||
// ended task: late updates are ignored
|
||||
if (task.status !== 'pending') {
|
||||
return
|
||||
}
|
||||
|
||||
const now = Date.now()
|
||||
this.#lastEmitDate = now
|
||||
|
||||
const metrics = {}
|
||||
for (const [name, metric] of this.#metrics) {
|
||||
this.#sample(metric, now, isFinal)
|
||||
metrics[name] = metric.toJSON()
|
||||
}
|
||||
task.set('metrics', metrics)
|
||||
}
|
||||
|
||||
#sample(metric, now, isFinal) {
|
||||
const sample = [now, metric.value]
|
||||
|
||||
const { recent } = metric
|
||||
recent.push(sample)
|
||||
if (recent.length > this.#recentSize) {
|
||||
recent.shift()
|
||||
}
|
||||
|
||||
const { history } = metric
|
||||
const last = history[history.length - 1]
|
||||
if (last === undefined || now - last[0] >= metric.historyInterval) {
|
||||
history.push(sample)
|
||||
} else if (isFinal) {
|
||||
if (history.length > 1) {
|
||||
// the final value replaces the latest sample to keep the spacing
|
||||
history[history.length - 1] = sample
|
||||
} else {
|
||||
// but never the first one
|
||||
history.push(sample)
|
||||
}
|
||||
}
|
||||
|
||||
if (history.length > this.#historySize) {
|
||||
// keep every other sample, and always the latest one
|
||||
metric.history = history.filter((_, i) => i % 2 === 0 || i === history.length - 1)
|
||||
metric.historyInterval *= 2
|
||||
}
|
||||
}
|
||||
}
|
||||
exports.TaskMetrics = TaskMetrics
|
||||
175
@vates/task/metrics.test.js
Normal file
175
@vates/task/metrics.test.js
Normal file
@@ -0,0 +1,175 @@
|
||||
'use strict'
|
||||
|
||||
const assert = require('node:assert').strict
|
||||
const { afterEach, beforeEach, describe, it, mock } = require('node:test')
|
||||
|
||||
const { Task } = require('./index.js')
|
||||
const { TaskMetrics } = require('./metrics.js')
|
||||
|
||||
const EMIT_INTERVAL = 5e3
|
||||
|
||||
// started task recording its `metrics` property
|
||||
function createTask() {
|
||||
const emitted = []
|
||||
const task = new Task({
|
||||
onProgress(event) {
|
||||
if (event.type === 'property' && event.name === 'metrics') {
|
||||
emitted.push(event.value)
|
||||
}
|
||||
},
|
||||
})
|
||||
task.start()
|
||||
task.emitted = emitted
|
||||
return task
|
||||
}
|
||||
|
||||
describe('TaskMetrics', () => {
|
||||
beforeEach(() => {
|
||||
mock.timers.enable({ apis: ['Date'], now: 0 })
|
||||
})
|
||||
afterEach(() => {
|
||||
mock.timers.reset()
|
||||
})
|
||||
|
||||
it('emits the cumulative values, throttled', () => {
|
||||
const task = createTask()
|
||||
const metrics = new TaskMetrics(task)
|
||||
|
||||
metrics.add('bytesRead', 10)
|
||||
metrics.add('bytesRead', 10) // throttled
|
||||
mock.timers.tick(EMIT_INTERVAL)
|
||||
metrics.add('bytesRead', 10)
|
||||
|
||||
assert.deepEqual(
|
||||
task.emitted.map(_ => _.bytesRead.value),
|
||||
[10, 30]
|
||||
)
|
||||
})
|
||||
|
||||
it('always emits the final value', () => {
|
||||
const task = createTask()
|
||||
const metrics = new TaskMetrics(task)
|
||||
|
||||
metrics.add('bytesRead', 10)
|
||||
mock.timers.tick(1e3)
|
||||
metrics.add('bytesRead', 10) // throttled
|
||||
metrics.flush()
|
||||
|
||||
const last = task.emitted.at(-1).bytesRead
|
||||
assert.equal(last.value, 20)
|
||||
assert.deepEqual(last.history.at(-1), [1e3, 20])
|
||||
// the first sample is kept
|
||||
assert.deepEqual(last.history[0], [0, 10])
|
||||
})
|
||||
|
||||
it('keeps a bounded number of recent samples', () => {
|
||||
const task = createTask()
|
||||
const metrics = new TaskMetrics(task, { recentSize: 3 })
|
||||
|
||||
for (let i = 1; i <= 10; i++) {
|
||||
metrics.add('bytesRead', 1)
|
||||
mock.timers.tick(EMIT_INTERVAL)
|
||||
}
|
||||
|
||||
assert.deepEqual(task.emitted.at(-1).bytesRead.recent, [
|
||||
[7 * EMIT_INTERVAL, 8],
|
||||
[8 * EMIT_INTERVAL, 9],
|
||||
[9 * EMIT_INTERVAL, 10],
|
||||
])
|
||||
})
|
||||
|
||||
it('keeps a bounded history covering the whole duration, without total', () => {
|
||||
const task = createTask()
|
||||
const historySize = 10
|
||||
const metrics = new TaskMetrics(task, { historySize })
|
||||
|
||||
const nbEmits = 1000
|
||||
for (let i = 1; i <= nbEmits; i++) {
|
||||
metrics.add('bytesRead', 1)
|
||||
mock.timers.tick(EMIT_INTERVAL)
|
||||
}
|
||||
metrics.flush()
|
||||
|
||||
const { history } = task.emitted.at(-1).bytesRead
|
||||
assert.ok(history.length <= historySize, `${history.length} samples`)
|
||||
assert.ok(history.length >= historySize / 2, `${history.length} samples`)
|
||||
// covers the whole duration
|
||||
assert.deepEqual(history[0], [0, 1])
|
||||
assert.deepEqual(history.at(-1), [nbEmits * EMIT_INTERVAL, nbEmits])
|
||||
// sorted, and the values are cumulative
|
||||
for (let i = 1; i < history.length; i++) {
|
||||
assert.ok(history[i][0] > history[i - 1][0])
|
||||
assert.ok(history[i][1] >= history[i - 1][1])
|
||||
}
|
||||
})
|
||||
|
||||
it('handles several metrics independently', () => {
|
||||
const task = createTask()
|
||||
const metrics = new TaskMetrics(task, { historySize: 4 })
|
||||
|
||||
for (let i = 1; i <= 100; i++) {
|
||||
metrics.add('bytesRead', 2)
|
||||
metrics.add('bytesWritten', 1)
|
||||
mock.timers.tick(EMIT_INTERVAL)
|
||||
}
|
||||
metrics.flush()
|
||||
|
||||
const { bytesRead, bytesWritten } = task.emitted.at(-1)
|
||||
assert.equal(bytesRead.value, 200)
|
||||
assert.equal(bytesWritten.value, 100)
|
||||
for (const { history } of [bytesRead, bytesWritten]) {
|
||||
assert.ok(history.length >= 2 && history.length <= 4, `${history.length} samples`)
|
||||
assert.equal(history.at(-1)[0], 100 * EMIT_INTERVAL)
|
||||
}
|
||||
})
|
||||
|
||||
it('emits copies, not the internal state', () => {
|
||||
const task = createTask()
|
||||
const metrics = new TaskMetrics(task)
|
||||
|
||||
metrics.add('bytesRead', 1)
|
||||
const first = task.emitted[0].bytesRead
|
||||
mock.timers.tick(EMIT_INTERVAL)
|
||||
metrics.add('bytesRead', 1)
|
||||
|
||||
assert.equal(first.value, 1)
|
||||
assert.equal(first.recent.length, 1)
|
||||
})
|
||||
|
||||
it('ignores the updates once the task has ended', () => {
|
||||
const task = createTask()
|
||||
const metrics = new TaskMetrics(task)
|
||||
|
||||
metrics.add('bytesRead', 1)
|
||||
task.success()
|
||||
mock.timers.tick(EMIT_INTERVAL)
|
||||
metrics.add('bytesRead', 1)
|
||||
metrics.flush()
|
||||
|
||||
assert.equal(task.emitted.length, 1)
|
||||
})
|
||||
|
||||
it('emits the total and the unit', () => {
|
||||
const task = createTask()
|
||||
const metrics = new TaskMetrics(task)
|
||||
metrics.define('bytesRead', { unit: 'bytes' })
|
||||
metrics.setTotal('bytesRead', 10)
|
||||
|
||||
metrics.add('bytesRead', 1)
|
||||
metrics.add('other', 1)
|
||||
metrics.flush()
|
||||
|
||||
const { bytesRead, other } = task.emitted.at(-1)
|
||||
assert.equal(bytesRead.total, 10)
|
||||
assert.equal(bytesRead.unit, 'bytes')
|
||||
assert.equal(other.total, undefined)
|
||||
assert.equal(other.unit, undefined)
|
||||
})
|
||||
|
||||
it('rejects a metric defined twice', () => {
|
||||
const metrics = new TaskMetrics(createTask())
|
||||
|
||||
metrics.define('a')
|
||||
assert.throws(() => metrics.define('a'), /already defined/)
|
||||
})
|
||||
})
|
||||
@@ -23,6 +23,7 @@
|
||||
},
|
||||
"exports": {
|
||||
".": "./index.js",
|
||||
"./combineEvents": "./combineEvents.js"
|
||||
"./combineEvents": "./combineEvents.js",
|
||||
"./metrics": "./metrics.js"
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"name": "@vates/types",
|
||||
"private": false,
|
||||
"version": "2.5.0",
|
||||
"version": "2.3.0",
|
||||
"main": "./dist/index.mjs",
|
||||
"exports": {
|
||||
".": {
|
||||
@@ -11,10 +11,6 @@
|
||||
"./xo": "./dist/xo.d.mts",
|
||||
"./xo-app": "./dist/xo-app.d.mts",
|
||||
"./xen-api": "./dist/xen-api.d.mts",
|
||||
"./backup-expression-context": {
|
||||
"default": "./dist/backup-expression-context.mjs",
|
||||
"types": "./dist/backup-expression-context.d.mts"
|
||||
},
|
||||
"./common": {
|
||||
"default": "./dist/common.mjs",
|
||||
"types": "./dist/common.d.mts"
|
||||
@@ -38,7 +34,7 @@
|
||||
"typescript": "~5.6.3",
|
||||
"typescript-eslint": "^8.61.0",
|
||||
"@types/express": "^5.0.0",
|
||||
"@xen-orchestra/disk-transform": "^1.3.4"
|
||||
"@xen-orchestra/disk-transform": "^1.3.3"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
|
||||
@@ -1,38 +0,0 @@
|
||||
export const BACKUP_EXPRESSION_CONTEXT = {
|
||||
run: {
|
||||
dayOfWeek: { type: 'number' },
|
||||
dayOfMonth: { type: 'number' },
|
||||
hour: { type: 'number' },
|
||||
month: { type: 'number' },
|
||||
year: { type: 'number' },
|
||||
},
|
||||
sr: {
|
||||
name_label: { type: 'string' },
|
||||
type: { type: 'string' },
|
||||
description: { type: 'string' },
|
||||
tags: { type: 'string[]' },
|
||||
},
|
||||
backupRepository: {
|
||||
name: { type: 'string' },
|
||||
type: { type: 'string' },
|
||||
tags: { type: 'string[]' },
|
||||
},
|
||||
vm: {
|
||||
name_label: { type: 'string' },
|
||||
tags: { type: 'string[]' },
|
||||
power_state: { type: 'string' },
|
||||
},
|
||||
chainLength: { type: 'number' },
|
||||
} as const
|
||||
|
||||
export type BACKUP_EXPRESSION_CONTEXT = (typeof BACKUP_EXPRESSION_CONTEXT)[keyof typeof BACKUP_EXPRESSION_CONTEXT]
|
||||
|
||||
export const BACKUP_SETTING_CONTEXT = {
|
||||
healthCheckVmsWithTags: ['vm', 'run'],
|
||||
fullInterval: ['vm', 'run', 'chainLength'],
|
||||
vmFilter: ['vm', 'run'],
|
||||
srs: ['sr', 'run'],
|
||||
remotes: ['backupRepository', 'run'],
|
||||
} as const
|
||||
|
||||
export type BACKUP_SETTING_CONTEXT = (typeof BACKUP_SETTING_CONTEXT)[keyof typeof BACKUP_SETTING_CONTEXT]
|
||||
@@ -772,7 +772,6 @@ export type RawTrafficRule = {
|
||||
ipRange: string
|
||||
direction: TrafficRuleDirection
|
||||
port?: string
|
||||
priority?: number
|
||||
}
|
||||
|
||||
type BaseTrafficRule = RawTrafficRule & {
|
||||
|
||||
@@ -4,8 +4,5 @@ export * from './xo.mjs'
|
||||
export * from './xo-app.mjs'
|
||||
export * from './lib/xen-orchestra-xapi.mjs'
|
||||
export * from './lib/xen-orchestra-acl.mjs'
|
||||
export * from './lib/xen-orchestra-plugins.mjs'
|
||||
export * from './lib/xen-orchestra-v2v.mjs'
|
||||
export * from './lib/complex-matcher.mjs'
|
||||
export * from './lib/rest-api.mjs'
|
||||
export * from './lib/xen-orchestra-vmware-explorer.mjs'
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,219 +0,0 @@
|
||||
import type { Branded } from '../common.mjs'
|
||||
import type { XoNetwork, XoSr, XoVmTemplate } from '../xo.mjs'
|
||||
|
||||
// Stateless API: requests needing the source carry the connection in a POST body (never in URLs or access logs) and
|
||||
// xo-server stores nothing it reads from the source.
|
||||
|
||||
export const V2V_PLATFORM = {
|
||||
VMWARE: 'vmware',
|
||||
} as const
|
||||
|
||||
export type V2V_PLATFORM = (typeof V2V_PLATFORM)[keyof typeof V2V_PLATFORM]
|
||||
|
||||
// 422 rather than 401 for invalid source credentials: a 401 would open the browser Basic authentication prompt
|
||||
export const V2V_ERROR_CODE = {
|
||||
INVALID_CREDENTIALS: 'V2V_INVALID_CREDENTIALS',
|
||||
} as const
|
||||
|
||||
export type V2V_ERROR_CODE = (typeof V2V_ERROR_CODE)[keyof typeof V2V_ERROR_CODE]
|
||||
|
||||
// Clones, restores and replicas inherit `other_config`: the imported VM records its own UUID to be told apart from
|
||||
// them, and the source identity because a moref is only unique within one vCenter. The source identity is the
|
||||
// inventory `instanceUuid`, or `<lowercased host>:<port>` for a standalone ESXi which has none.
|
||||
export const V2V_VM_OTHER_CONFIG = {
|
||||
SOURCE_VM_ID: 'sourceVmId',
|
||||
SOURCE_SNAPSHOT_ID: 'sourceSnapshotId',
|
||||
IMPORTED_VM_UUID: 'xo:v2v:importedVmUuid',
|
||||
SOURCE_ID: 'xo:v2v:sourceId',
|
||||
SOURCE_VM_INSTANCE_UUID: 'xo:v2v:sourceVmInstanceUuid',
|
||||
} as const
|
||||
|
||||
export type V2V_VM_OTHER_CONFIG = (typeof V2V_VM_OTHER_CONFIG)[keyof typeof V2V_VM_OTHER_CONFIG]
|
||||
|
||||
export type XoV2vVmOtherConfig = Partial<Record<V2V_VM_OTHER_CONFIG, string>>
|
||||
|
||||
// The disk of the source chain an imported VDI last received, one of the `chainPaths` of its source disk: the CID
|
||||
// cannot tell a fresh snapshot delta from its parent, the path can
|
||||
export const V2V_VDI_OTHER_CONFIG = {
|
||||
DISK_PATH: 'esxi_diskPath',
|
||||
} as const
|
||||
|
||||
export type V2V_VDI_OTHER_CONFIG = (typeof V2V_VDI_OTHER_CONFIG)[keyof typeof V2V_VDI_OTHER_CONFIG]
|
||||
|
||||
export const V2V_START_BLOCKED_REASON = 'Esxi migration in progress...'
|
||||
|
||||
export const V2V_PARTIAL_IMPORT_TAG = 'xo:no-bak=V2V partial import'
|
||||
|
||||
export const V2V_SNAPSHOT_NAME = {
|
||||
AFTER_PARTIAL_IMPORT: 'after partial import from V2V',
|
||||
AFTER_COMPLETE_IMPORT: 'after complete import from V2V',
|
||||
COMPLETE_IMPORT: 'complete import from V2V',
|
||||
} as const
|
||||
|
||||
export type V2V_SNAPSHOT_NAME = (typeof V2V_SNAPSHOT_NAME)[keyof typeof V2V_SNAPSHOT_NAME]
|
||||
|
||||
// Set on the task of a start so the front can tell which source VMs are being imported
|
||||
export const V2V_TASK_PROPERTY = {
|
||||
SOURCE_VM_IDS: 'sourceVmIds',
|
||||
} as const
|
||||
|
||||
export type XoV2vConnection = {
|
||||
host: string
|
||||
port: number
|
||||
username: string
|
||||
password: string
|
||||
skipSslCheck: boolean
|
||||
}
|
||||
|
||||
export type XoV2vStatus = {
|
||||
vectura: { status: 'success' } | { status: 'error'; error: string }
|
||||
}
|
||||
|
||||
export type XoV2vInventoryPayload = {
|
||||
platform: V2V_PLATFORM
|
||||
connection: XoV2vConnection
|
||||
}
|
||||
|
||||
export type XoV2vDatacenter = {
|
||||
id: Branded<'v2v-datacenter'>
|
||||
name: string
|
||||
}
|
||||
|
||||
export type XoV2vCluster = {
|
||||
id: Branded<'v2v-cluster'>
|
||||
name: string
|
||||
datacenterId: XoV2vDatacenter['id']
|
||||
}
|
||||
|
||||
export type XoV2vHost = {
|
||||
id: Branded<'v2v-host'>
|
||||
name: string
|
||||
clusterId?: XoV2vCluster['id']
|
||||
datacenterId: XoV2vDatacenter['id']
|
||||
}
|
||||
|
||||
// Sizes are in bytes, as in the rest of XO, not in the KB/MB VMware returns
|
||||
export type XoV2vDatastore = {
|
||||
id: Branded<'v2v-datastore'>
|
||||
name: string
|
||||
type: string
|
||||
capacity: number
|
||||
free: number
|
||||
hostIds: XoV2vHost['id'][]
|
||||
}
|
||||
|
||||
export type XoV2vPortGroup = {
|
||||
id: Branded<'v2v-port-group'>
|
||||
name: string
|
||||
vlan?: number
|
||||
}
|
||||
|
||||
export const V2V_DISK_MODE = {
|
||||
PERSISTENT: 'persistent',
|
||||
NON_PERSISTENT: 'nonpersistent',
|
||||
INDEPENDENT_PERSISTENT: 'independent_persistent',
|
||||
INDEPENDENT_NON_PERSISTENT: 'independent_nonpersistent',
|
||||
UNDOABLE: 'undoable',
|
||||
APPEND: 'append',
|
||||
} as const
|
||||
|
||||
export type V2V_DISK_MODE = (typeof V2V_DISK_MODE)[keyof typeof V2V_DISK_MODE]
|
||||
|
||||
// `key` is the vmx device node (`scsi0:0`, `ethernet0`…), the identifier the import matches the start maps against
|
||||
export type XoV2vDisk = {
|
||||
key: Branded<'v2v-disk'>
|
||||
label: string
|
||||
datastoreId: XoV2vDatastore['id']
|
||||
capacity: number
|
||||
mode: V2V_DISK_MODE
|
||||
isRdm: boolean
|
||||
isEncrypted: boolean
|
||||
// `dir/disk.vmdk` in its datastore (no `[datastore]` prefix) of the base disk, then of each snapshot delta down to
|
||||
// the active disk: the chain the import walks for this vmx node
|
||||
chainPaths: string[]
|
||||
}
|
||||
|
||||
// No port group for opaque (NSX) or missing backings
|
||||
export type XoV2vNic = {
|
||||
key: Branded<'v2v-nic'>
|
||||
label: string
|
||||
portGroupId?: XoV2vPortGroup['id']
|
||||
macAddress: string
|
||||
}
|
||||
|
||||
export const V2V_VM_POWER_STATE = {
|
||||
POWERED_ON: 'poweredOn',
|
||||
POWERED_OFF: 'poweredOff',
|
||||
SUSPENDED: 'suspended',
|
||||
} as const
|
||||
|
||||
export type V2V_VM_POWER_STATE = (typeof V2V_VM_POWER_STATE)[keyof typeof V2V_VM_POWER_STATE]
|
||||
|
||||
export const V2V_FIRMWARE = {
|
||||
BIOS: 'bios',
|
||||
UEFI: 'uefi',
|
||||
} as const
|
||||
|
||||
export type V2V_FIRMWARE = (typeof V2V_FIRMWARE)[keyof typeof V2V_FIRMWARE]
|
||||
|
||||
export type XoV2vVm = {
|
||||
id: Branded<'v2v-vm'>
|
||||
instanceUuid: string
|
||||
name: string
|
||||
description: string
|
||||
powerState: V2V_VM_POWER_STATE
|
||||
hostId: XoV2vHost['id']
|
||||
nCpus: number
|
||||
memory: number
|
||||
firmware: V2V_FIRMWARE
|
||||
secureBoot: boolean
|
||||
datastoreIds: XoV2vDatastore['id'][]
|
||||
snapshotCount: number
|
||||
// Compared with `other_config.sourceSnapshotId` of a partial import: a delta is only possible while they match
|
||||
currentSnapshotId?: string
|
||||
disks: XoV2vDisk[]
|
||||
nics: XoV2vNic[]
|
||||
}
|
||||
|
||||
export type XoV2vInventory = {
|
||||
product: string
|
||||
version: string
|
||||
// Absent on a standalone ESXi, identified by its connection address instead
|
||||
instanceUuid?: string
|
||||
datacenters: XoV2vDatacenter[]
|
||||
clusters: XoV2vCluster[]
|
||||
hosts: XoV2vHost[]
|
||||
datastores: XoV2vDatastore[]
|
||||
portGroups: XoV2vPortGroup[]
|
||||
vms: XoV2vVm[]
|
||||
}
|
||||
|
||||
export type XoV2vStartOptions = {
|
||||
stopSource: boolean
|
||||
startVm: boolean
|
||||
cleanup: boolean
|
||||
}
|
||||
|
||||
// A resumed import sends no disk or NIC map: the back end reads its mapping from the existing XCP-ng VM
|
||||
export type XoV2vStartPayloadVm = Partial<XoV2vStartOptions> & {
|
||||
id: XoV2vVm['id']
|
||||
disks?: Record<XoV2vDisk['key'], XoSr['id']>
|
||||
nics?: Record<XoV2vNic['key'], XoNetwork['id']>
|
||||
template?: XoVmTemplate['id']
|
||||
tags: string[]
|
||||
keepMac: boolean
|
||||
}
|
||||
|
||||
// Body of `POST /pools/{id}/actions/import_vms_from_vmware`: the pool is in the path. Checked against the body of the
|
||||
// route when the REST API is built, which refuses any extra key
|
||||
export type XoV2vStartPayload = {
|
||||
connection: XoV2vConnection
|
||||
defaults: XoV2vStartOptions & {
|
||||
sr: XoSr['id']
|
||||
network: XoNetwork['id']
|
||||
template: XoVmTemplate['id']
|
||||
}
|
||||
vms: XoV2vStartPayloadVm[]
|
||||
stopOnError: boolean
|
||||
concurrency: number
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
// shape of `Esxi#getInventory()` in `@xen-orchestra/vmware-explorer`
|
||||
// the objects reference each other through their VMware managed object references (moref)
|
||||
|
||||
export type VmwareDatacenter = {
|
||||
id: string
|
||||
name: string
|
||||
}
|
||||
|
||||
export type VmwareCluster = {
|
||||
id: string
|
||||
name: string
|
||||
datacenter?: string
|
||||
}
|
||||
|
||||
export type VmwareHost = {
|
||||
id: string
|
||||
name: string
|
||||
/** a cluster, or the compute resource of a standalone host */
|
||||
parent?: string
|
||||
datacenter?: string
|
||||
}
|
||||
|
||||
export type VmwareDatastore = {
|
||||
id: string
|
||||
name?: string
|
||||
type?: string
|
||||
capacity?: number
|
||||
freeSpace?: number
|
||||
/** the hosts which mount the datastore and can reach it */
|
||||
hosts: string[]
|
||||
}
|
||||
|
||||
export type VmwareVlan = number | { start: number; end: number }[]
|
||||
|
||||
export type VmwareStandardNetwork = {
|
||||
id: string
|
||||
name: string
|
||||
distributed: false
|
||||
}
|
||||
|
||||
export type VmwareDistributedPortgroup = {
|
||||
id: string
|
||||
name: string
|
||||
distributed: true
|
||||
vlan?: VmwareVlan
|
||||
}
|
||||
|
||||
export type VmwareNetwork = VmwareStandardNetwork | VmwareDistributedPortgroup
|
||||
|
||||
export type VmwareVmDisk = {
|
||||
/** node of the disk, as the vmx names it, e.g. `scsi0:0` */
|
||||
key: string
|
||||
label: string
|
||||
capacity: number
|
||||
datastore?: string
|
||||
diskMode?: string
|
||||
rdm: boolean
|
||||
encrypted: boolean
|
||||
/** `dir/disk.vmdk` in its datastore of the base disk, then of each snapshot delta down to the active disk */
|
||||
chainPaths: string[]
|
||||
}
|
||||
|
||||
export type VmwareVmNic = {
|
||||
/** device key of the card */
|
||||
key: string
|
||||
label: string
|
||||
macAddress?: string
|
||||
addressType?: string
|
||||
network?: string
|
||||
}
|
||||
|
||||
export type VmwareVm = {
|
||||
id: string
|
||||
name?: string
|
||||
annotation?: string
|
||||
instanceUuid?: string
|
||||
firmware?: string
|
||||
secureBoot: boolean
|
||||
isTemplate: boolean
|
||||
cpus?: number
|
||||
memory?: number
|
||||
powerState?: 'poweredOff' | 'poweredOn' | 'suspended'
|
||||
host?: string
|
||||
datastores: string[]
|
||||
currentSnapshot?: string
|
||||
snapshotCount: number
|
||||
disks: VmwareVmDisk[]
|
||||
nics: VmwareVmNic[]
|
||||
}
|
||||
|
||||
export type VmwareInventory = {
|
||||
/** e.g. `VMware vCenter Server`, `VMware ESXi` */
|
||||
product?: string
|
||||
version?: string
|
||||
/** only set by a vCenter */
|
||||
instanceUuid?: string
|
||||
datacenters: VmwareDatacenter[]
|
||||
clusters: VmwareCluster[]
|
||||
hosts: VmwareHost[]
|
||||
datastores: VmwareDatastore[]
|
||||
networks: VmwareNetwork[]
|
||||
vms: VmwareVm[]
|
||||
}
|
||||
@@ -130,8 +130,6 @@ export type XsPatches = {
|
||||
uuid?: string
|
||||
}
|
||||
|
||||
type WrappedRecordOfType<Type extends WrappedXenApiRecord['$type']> = Extract<WrappedXenApiRecord, { $type: Type }>
|
||||
|
||||
export interface Xapi {
|
||||
status: string
|
||||
pool?: { uuid: string }
|
||||
@@ -149,14 +147,6 @@ export interface Xapi {
|
||||
ref: T['$ref'],
|
||||
field: K
|
||||
): Promise<T[K]>
|
||||
// the record is inferred from `type`, for a JS caller which cannot spell it out as a type argument
|
||||
getField<Type extends WrappedXenApiRecord['$type'], Field extends keyof WrappedRecordOfType<Type>>(
|
||||
type: Type,
|
||||
ref: WrappedRecordOfType<Type>['$ref'],
|
||||
field: Field
|
||||
): Promise<WrappedRecordOfType<Type>[Field]>
|
||||
/** Synchronous: the record as the object cache currently holds it. */
|
||||
getObjectByRef<Ref extends WrappedXenApiRecord['$ref']>(ref: Ref): Extract<WrappedXenApiRecord, { $ref: Ref }>
|
||||
getObject: <
|
||||
XoRecord extends XapiXoRecord,
|
||||
WrappedRecord extends WrappedXenApiRecord = Extract<WrappedXenApiRecord, { $type: XoRecord['type'] }>,
|
||||
@@ -293,42 +283,6 @@ export interface Xapi {
|
||||
}
|
||||
): Promise<XenApiVdi['$ref']>
|
||||
SR_reclaimSpace(ref: XenApiSr['$ref']): Promise<void>
|
||||
VBD_create(params: {
|
||||
bootable?: boolean
|
||||
currently_attached?: boolean
|
||||
device?: string
|
||||
empty?: boolean
|
||||
mode?: VBD_MODE
|
||||
other_config?: Record<string, string>
|
||||
qos_algorithm_params?: Record<string, string>
|
||||
qos_algorithm_type?: string
|
||||
/** a plug failure, only logged otherwise, is thrown: the VBD exists all the same */
|
||||
throwVbdPlug?: boolean
|
||||
type?: VBD_TYPE
|
||||
unpluggable?: boolean
|
||||
userdevice?: string
|
||||
VDI?: XenApiVdi['$ref']
|
||||
VM: XenApiVm['$ref']
|
||||
}): Promise<XenApiVbd['$ref']>
|
||||
/** unplugs the VBD first, if needed */
|
||||
VBD_destroy(ref: XenApiVbd['$ref']): Promise<void>
|
||||
VDI_create(
|
||||
params: {
|
||||
name_description?: string
|
||||
name_label: string
|
||||
other_config?: Record<string, string>
|
||||
read_only?: boolean
|
||||
sharable?: boolean
|
||||
SR?: XenApiSr['$ref']
|
||||
tags?: string[]
|
||||
type?: VDI_TYPE
|
||||
virtual_size: number
|
||||
xenstore_data?: Record<string, string>
|
||||
},
|
||||
opts?: { sm_config?: Record<string, string> }
|
||||
): Promise<XenApiVdi['$ref']>
|
||||
/** a VDI which no longer exists counts as destroyed */
|
||||
VDI_destroy(ref: XenApiVdi['$ref']): Promise<void>
|
||||
editVm(
|
||||
id: XoVm['id'],
|
||||
props: EditVmProps,
|
||||
|
||||
@@ -824,10 +824,7 @@ export interface XenApiSr {
|
||||
VDIs: XenApiVdi['$ref'][]
|
||||
virtual_allocation: number
|
||||
}
|
||||
export type XenApiSrWrapped = WrapperXenApi<XenApiSr, 'SR', XenApiSrCallMethods> & {
|
||||
// resolved by xen-api from `PBDs`
|
||||
$PBDs: XenApiPbdWrapped[]
|
||||
}
|
||||
export type XenApiSrWrapped = WrapperXenApi<XenApiSr, 'SR', XenApiSrCallMethods>
|
||||
|
||||
export interface XenApiSrStat {
|
||||
$ref: Branded<'sr_stat'>
|
||||
|
||||
@@ -3,35 +3,25 @@ import type {
|
||||
AnyXoJob,
|
||||
AnyXoLog,
|
||||
NonXapiXoRecord,
|
||||
XoBackupDiskPartition,
|
||||
XapiXoRecord,
|
||||
XoAuthenticationToken,
|
||||
XoBackupRepository,
|
||||
XoConfigBackupArchive,
|
||||
XoGroup,
|
||||
XoHost,
|
||||
XoMetadataBackupJob,
|
||||
XoMirrorBackupJob,
|
||||
XoNetwork,
|
||||
XoPlugin,
|
||||
XoPool,
|
||||
XoPoolBackupArchive,
|
||||
XoProxy,
|
||||
XoSchedule,
|
||||
XoServer,
|
||||
XoSr,
|
||||
XoTask,
|
||||
XoUser,
|
||||
XoVif,
|
||||
XoVm,
|
||||
XoVmBackupArchive,
|
||||
XoVmBackupJob,
|
||||
XoVmTemplate,
|
||||
} from './xo.mjs'
|
||||
import { VatesTask } from './lib/vates-task.mjs'
|
||||
import type { PluginRestRouteDefinition } from './lib/rest-api.mjs'
|
||||
import type { VmwareInventory } from './lib/xen-orchestra-vmware-explorer.mjs'
|
||||
import type { XoV2vStatus } from './lib/xen-orchestra-v2v.mjs'
|
||||
import type { RPU_RECOVERY_STEP_NAME } from './common.mjs'
|
||||
import {
|
||||
Xapi,
|
||||
@@ -185,13 +175,13 @@ export type PoolRollingUpdateRecoveryBlocked = {
|
||||
|
||||
export type PoolRollingUpdateRecovery = PoolRollingUpdateRecoveryRun | PoolRollingUpdateRecoveryBlocked
|
||||
|
||||
/** A disk of a backup archive currently served as an iSCSI LUN */
|
||||
/** A disk of a backup archive currently served as a read-only iSCSI LUN */
|
||||
export type BackupArchiveDiskMount = {
|
||||
/** Handle to pass to `unmountBackupArchiveDisk` */
|
||||
id: string
|
||||
/** UUID of the SR introduced on the host */
|
||||
srUuid: string
|
||||
/** UUID of the VDI exposing the backup disk, read-only unless it is cached */
|
||||
/** UUID of the read-only VDI exposing the backup disk */
|
||||
vdiUuid: string
|
||||
/** IQN of the target serving the disk */
|
||||
iqn: string
|
||||
@@ -210,15 +200,6 @@ type XoStoreRangeOptions = {
|
||||
reverse?: boolean
|
||||
}
|
||||
|
||||
// `@xen-orchestra/vmware-explorer` is not typed
|
||||
export type EsxiConnectionParams = {
|
||||
/** `host` or `host:port` */
|
||||
host: string
|
||||
user: string
|
||||
password: string
|
||||
sslVerify: boolean
|
||||
}
|
||||
|
||||
export type XoApp = EventEmitter & {
|
||||
hooks: EventEmitter
|
||||
_redis: {
|
||||
@@ -261,6 +242,12 @@ export type XoApp = EventEmitter & {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* the VM backup archives of the backup repositories, as a collection: `add`, `update` and
|
||||
* `remove` events carrying the archive and its previous value
|
||||
*/
|
||||
vmBackupArchives: EventEmitter
|
||||
|
||||
tasks: EventEmitter & {
|
||||
abort(id: XoTask['id'], reason?: string): Promise<void>
|
||||
clearLogs(): Promise<void>
|
||||
@@ -299,8 +286,6 @@ export type XoApp = EventEmitter & {
|
||||
backupGuard(objectId: XapiXoRecord['id'], opts?: { bypassBackupCheck?: boolean; operation: string }): Promise<void>
|
||||
/* Throw if no authorization */
|
||||
checkFeatureAuthorization(featureCode: FeatureCode): Promise<void>
|
||||
/* whether this machine can run the tools of an import from VMware */
|
||||
checkEsxiDependencies(): Promise<XoV2vStatus>
|
||||
/* validate, apply and persist the configuration of a plugin */
|
||||
configurePlugin(id: string, configuration: unknown, mergeWithExisting?: boolean): Promise<void>
|
||||
/* connect a server (XCP-ng/XenServer) */
|
||||
@@ -328,17 +313,6 @@ export type XoApp = EventEmitter & {
|
||||
set(key: string, value: unknown): void
|
||||
unset(key: string): void
|
||||
}
|
||||
createBackupNgJob<T extends XoVmBackupJob | XoMirrorBackupJob>(
|
||||
type: T['type'],
|
||||
props: Omit<T, 'id' | 'type'>,
|
||||
/** keyed by temporary IDs, which can be used as keys in `props.settings` */
|
||||
schedules?: Record<string, Pick<XoSchedule, 'cron' | 'enabled' | 'name' | 'timezone'>>
|
||||
): Promise<T>
|
||||
createMetadataBackupJob(
|
||||
props: Omit<XoMetadataBackupJob, 'id' | 'type'>,
|
||||
/** keyed by temporary IDs, which can be used as keys in `props.settings` */
|
||||
schedules: Record<string, Pick<XoSchedule, 'cron' | 'enabled' | 'name' | 'timezone'>>
|
||||
): Promise<XoMetadataBackupJob>
|
||||
createAuthenticationToken(opts: {
|
||||
client?: {
|
||||
id?: string
|
||||
@@ -354,14 +328,6 @@ export type XoApp = EventEmitter & {
|
||||
proxy?: XoProxy['id']
|
||||
url: string
|
||||
}): Promise<XoBackupRepository>
|
||||
createSchedule(params: {
|
||||
cron: XoSchedule['cron']
|
||||
enabled: XoSchedule['enabled']
|
||||
jobId: XoSchedule['jobId']
|
||||
name?: XoSchedule['name']
|
||||
timezone?: XoSchedule['timezone']
|
||||
userId?: XoUser['id']
|
||||
}): Promise<XoSchedule>
|
||||
createUser(params: {
|
||||
firstname?: string
|
||||
lastname?: string
|
||||
@@ -378,14 +344,11 @@ export type XoApp = EventEmitter & {
|
||||
deleteAclV2Privilege(privilegeId: XoAclBasePrivilege['id'], options?: { force?: boolean }): Promise<boolean>
|
||||
deleteAclV2Role(roleId: XoAclRole['id'], options?: { force?: boolean }): Promise<boolean>
|
||||
deleteGroup(id: XoGroup['id']): Promise<void>
|
||||
deleteSchedule(id: XoSchedule['id']): Promise<void>
|
||||
deleteUser(id: XoUser['id']): Promise<void>
|
||||
detachHostFromPool(hostId: XoHost['id']): Promise<void>
|
||||
createGroup(params: { name: string; provider?: string; providerGroup?: string }): Promise<XoGroup>
|
||||
disablePluginAutoload(id: XoPlugin['id']): Promise<void>
|
||||
/* disconnect a server (XCP-ng/XenServer) */
|
||||
disconnectXenServer(id: XoServer['id']): Promise<void>
|
||||
enablePluginAutoload(id: XoPlugin['id']): Promise<void>
|
||||
findEnabledScheduleSequenceFromSchedule(id: XoSchedule['id']): Promise<XoSchedule | undefined>
|
||||
getAclV2Privilege(id: XoAclBasePrivilege['id']): Promise<XoAclBasePrivilege>
|
||||
getAclV2Privileges(): Promise<XoAclBasePrivilege[]>
|
||||
@@ -411,14 +374,10 @@ export type XoApp = EventEmitter & {
|
||||
getAllProxies(): Promise<XoProxy[]>
|
||||
getAllJobs<T extends AnyXoJob['type']>(type: T): Promise<Extract<AnyXoJob, { type: T }>[]>
|
||||
getAllJobs(type?: string): Promise<AnyXoJob[]>
|
||||
getPlugin(id: XoPlugin['id']): Promise<XoPlugin>
|
||||
getPlugins(): Promise<XoPlugin[]>
|
||||
getProxy(id: XoProxy['id']): Promise<XoProxy>
|
||||
getRemote(id: XoBackupRepository['id']): Promise<XoBackupRepository>
|
||||
getAllRemotes(): Promise<XoBackupRepository[]>
|
||||
removeRemote(id: XoBackupRepository['id']): Promise<void>
|
||||
/** Also deletes the schedules of the job */
|
||||
removeJob(id: AnyXoJob['id']): Promise<void>
|
||||
getAllRemotesInfo(): Promise<
|
||||
Record<
|
||||
XoBackupRepository['id'],
|
||||
@@ -482,7 +441,6 @@ export type XoApp = EventEmitter & {
|
||||
}>
|
||||
getUser: (id: XoUser['id'], opts?: { obfuscatePassword?: boolean }) => Promise<XoUser>
|
||||
getUserIdentityFields(): string[]
|
||||
getEsxiInventory(params: EsxiConnectionParams): Promise<VmwareInventory>
|
||||
getXapi(maybeId: XapiXoRecord['id'] | XapiXoRecord): Xapi
|
||||
getXapiHostStats: (hostId: XoHost['id'], granularity?: XapiStatsGranularity) => Promise<XapiHostStats>
|
||||
getXapiObject: <T extends XapiXoRecord>(
|
||||
@@ -492,29 +450,9 @@ export type XoApp = EventEmitter & {
|
||||
getXapiPoolStats(poolId: XoPool['id'], granularity?: XapiStatsGranularity): Promise<XapiPoolStats>
|
||||
getXapiVmStats: (vmId: XoVm['id'], granularity?: XapiStatsGranularity) => Promise<XapiVmStats>
|
||||
getXenServer(id: XoServer['id']): Promise<XoServer>
|
||||
/** the connection of the pool holding this object, which may not be connected */
|
||||
getXenServerIdByObject<T extends XapiXoRecord>(maybeId: T['id'] | T, type?: T['type'] | T['type'][]): XoServer['id']
|
||||
getXenServerWithCredentials(id: XoServer['id']): Promise<XoServer & { password: string }>
|
||||
getXoEventEmitterByType(type: string): EventEmitter
|
||||
hasFeatureAuthorization(featureCode: string): Promise<boolean>
|
||||
hasObject<T extends XapiXoRecord>(id: T['id'], type: T['type']): boolean
|
||||
listBackupNgDiskPartitions(remoteId: XoBackupRepository['id'], diskId: string): Promise<XoBackupDiskPartition[]>
|
||||
listBackupNgPartitionFiles(
|
||||
remoteId: XoBackupRepository['id'],
|
||||
diskId: string,
|
||||
partitionId: string | undefined,
|
||||
path: string
|
||||
// keys ending in "/" are directories; files carry size (bytes) and mtime (epoch ms).
|
||||
// Values may be empty ({}) for directories or when served by an older proxy.
|
||||
): Promise<Record<string, { size?: number; mtime?: number }>>
|
||||
fetchBackupNgPartitionFiles(
|
||||
remoteId: XoBackupRepository['id'],
|
||||
diskId: string,
|
||||
partitionId: string | undefined,
|
||||
paths: string[],
|
||||
format: string
|
||||
): Promise<Readable>
|
||||
loadPlugin(id: XoPlugin['id']): Promise<void>
|
||||
listMetadataBackups(backupRepositoryIds: XoBackupRepository['id'][]): Promise<{
|
||||
xo: Record<XoBackupRepository['id'], XoConfigBackupArchive[]>
|
||||
pool: Record<XoBackupRepository['id'], Record<XoPool['id'], XoPoolBackupArchive[]>>
|
||||
@@ -524,41 +462,19 @@ export type XoApp = EventEmitter & {
|
||||
backupRepositoryIds: XoBackupRepository['id'][],
|
||||
opts?: { _forceRefresh?: boolean; vmId?: XoVm['id'] }
|
||||
): Promise<Record<XoBackupRepository['id'], Record<XoVm['id'], XoVmBackupArchive[]> | null>>
|
||||
/** imports one VM from VMware, resuming a previous partial import when possible, returns the UUID of the XCP-ng VM */
|
||||
migrationfromEsxi(
|
||||
params: EsxiConnectionParams & {
|
||||
sr: XoSr['id']
|
||||
network: XoNetwork['id']
|
||||
/** overrides `sr`, by disk node (e.g. `scsi0:0`) */
|
||||
disks?: Record<string, XoSr['id']>
|
||||
/** overrides `network`, by NIC device key (e.g. `4000`) */
|
||||
nics?: Record<string, XoNetwork['id']>
|
||||
template: XoVmTemplate['id']
|
||||
stopSource: boolean
|
||||
/** VMware moref of the VM */
|
||||
vm: string
|
||||
}
|
||||
): Promise<XoVm['uuid']>
|
||||
/**
|
||||
* Serve one disk of a backup archive as an iSCSI LUN and attach it to `host`
|
||||
* as an SR, read-only unless `cacheSrId` is set. Undone by `unmountBackupArchiveDisk`.
|
||||
* Serve one disk of a backup archive as a read-only iSCSI LUN and attach it to
|
||||
* `host` as an SR. Undone by `unmountBackupArchiveDisk`.
|
||||
*
|
||||
* The LUN is served by whoever can read the backup repository: this appliance, or the proxy the
|
||||
* repository is linked to.
|
||||
*/
|
||||
mountBackupArchiveDisk(params: {
|
||||
archiveId: XoVmBackupArchive['id']
|
||||
/**
|
||||
* SR of a VDI of the serving appliance, which the disk is materialized into as it is read and
|
||||
* which holds the writes; unset, nothing is cached and the mount is read-only. On a local SR,
|
||||
* the serving appliance must not be migrated while the mount lasts: the VDI cannot follow it
|
||||
*/
|
||||
cacheSrId?: XoSr['id']
|
||||
/** One of the archive's `disks[].id` */
|
||||
diskId: string
|
||||
hostId: XoHost['id']
|
||||
}): Promise<BackupArchiveDiskMount>
|
||||
purgePluginConfiguration(id: XoPlugin['id']): Promise<void>
|
||||
pingRemote(id: XoBackupRepository['id']): Promise<{ success: true }>
|
||||
/**
|
||||
* Record the live mounts a proxy created by itself, while running a restore: they never went
|
||||
@@ -599,7 +515,6 @@ export type XoApp = EventEmitter & {
|
||||
removeUserFromGroup(userId: XoUser['id'], id: XoGroup['id']): Promise<void>
|
||||
runJob(job: AnyXoJob, schedule: XoSchedule): void
|
||||
runWithApiContext: (user: XoUser | undefined, fn: () => void) => Promise<unknown>
|
||||
testPlugin(id: XoPlugin['id'], data?: unknown): Promise<void>
|
||||
testRemote(
|
||||
id: XoBackupRepository['id']
|
||||
): Promise<
|
||||
@@ -609,26 +524,12 @@ export type XoApp = EventEmitter & {
|
||||
touchXoObject(type: string, id: NonXapiXoRecord['id']): Promise<void>
|
||||
/** Detach a disk mounted by `mountBackupArchiveDisk` and stop serving it */
|
||||
unmountBackupArchiveDisk(id: BackupArchiveDiskMount['id']): Promise<void>
|
||||
unloadPlugin(id: XoPlugin['id']): Promise<void>
|
||||
reclaimSpace(
|
||||
remoteId: XoBackupRepository['id'],
|
||||
opts?: { vmUuid?: XoVm['id']; merge?: boolean; remove?: boolean }
|
||||
): Promise<{ vmUuid: string; success: boolean; merge?: boolean; size?: number; error?: string }[]>
|
||||
/** Remove a server from the DB (XCP-ng/XenServer) */
|
||||
unregisterXenServer(id: XoServer['id']): Promise<void>
|
||||
/**
|
||||
* Shallow merge of the properties into the existing job, a `null` value removes the property.
|
||||
*/
|
||||
updateJob(job: { id: AnyXoJob['id']; [key: string]: unknown }, merge?: boolean): Promise<void>
|
||||
updateSchedule(params: {
|
||||
id: XoSchedule['id']
|
||||
cron?: XoSchedule['cron']
|
||||
enabled?: XoSchedule['enabled']
|
||||
jobId?: XoSchedule['jobId']
|
||||
name?: XoSchedule['name']
|
||||
timezone?: XoSchedule['timezone']
|
||||
userId?: XoUser['id']
|
||||
}): Promise<void>
|
||||
updateUser(
|
||||
id: XoUser['id'],
|
||||
updates: {
|
||||
|
||||
@@ -21,29 +21,6 @@ import type {
|
||||
import type * as CMType from './lib/complex-matcher.mjs'
|
||||
import { XoAclBasePrivilege, XoAclRole } from './lib/xen-orchestra-acl.mjs'
|
||||
import type { XenApiHost, XenApiPool } from './xen-api.mjs'
|
||||
import type {
|
||||
XoAuditPlugin,
|
||||
XoAuthGithubPlugin,
|
||||
XoAuthGooglePlugin,
|
||||
XoAuthLdapPlugin,
|
||||
XoAuthOidcPlugin,
|
||||
XoAuthSamlPlugin,
|
||||
XoBackupReportsPlugin,
|
||||
XoIpmiSensorsPlugin,
|
||||
XoLoadBalancerPlugin,
|
||||
XoNetboxPlugin,
|
||||
XoOpenmetricsPlugin,
|
||||
XoPerfAlertPlugin,
|
||||
XoSdnControllerPlugin,
|
||||
XoTestPluginPlugin,
|
||||
XoTransportEmailPlugin,
|
||||
XoTransportIcinga2Plugin,
|
||||
XoTransportNagiosPlugin,
|
||||
XoTransportSlackPlugin,
|
||||
XoTransportXmppPlugin,
|
||||
XoUsageReportPlugin,
|
||||
XoWebHooksPlugin,
|
||||
} from './lib/xen-orchestra-plugins.mjs'
|
||||
|
||||
type BaseXapiXo = {
|
||||
$pool: XoPool['id']
|
||||
@@ -180,15 +157,6 @@ export type XoBackupLog = BaseXoLog & {
|
||||
export type XoRestoreLog = BaseXoLog & {
|
||||
message: 'restore'
|
||||
}
|
||||
export type XoBackupDiskPartition = {
|
||||
id: Branded<'xo-backup-disk-partition'>
|
||||
name?: string
|
||||
size: number
|
||||
start: number
|
||||
/** number for MBR, string for GPT partition */
|
||||
type: string | number
|
||||
}
|
||||
|
||||
export type XoVmBackupArchive = {
|
||||
id: Branded<'vm-backup-archive'>
|
||||
type: 'xo-vm-backup'
|
||||
@@ -240,7 +208,6 @@ export type XoBackupRepositoryBenchmark = {
|
||||
}
|
||||
|
||||
export type XoBackupRepository = {
|
||||
available?: number
|
||||
benchmarks?: XoBackupRepositoryBenchmark[]
|
||||
enabled: boolean
|
||||
error?: Record<string, unknown>
|
||||
@@ -248,9 +215,7 @@ export type XoBackupRepository = {
|
||||
name: string
|
||||
options?: string
|
||||
proxy?: XoProxy['id']
|
||||
size?: number
|
||||
url: string
|
||||
used?: number
|
||||
}
|
||||
|
||||
export type XoGpuGroup = BaseXapiXo & {
|
||||
@@ -492,29 +457,6 @@ export type XoPool = BaseXapiXo & {
|
||||
zstdSupported: boolean
|
||||
}
|
||||
|
||||
export type XoPlugin =
|
||||
| XoAuditPlugin
|
||||
| XoAuthGithubPlugin
|
||||
| XoAuthGooglePlugin
|
||||
| XoAuthLdapPlugin
|
||||
| XoAuthOidcPlugin
|
||||
| XoAuthSamlPlugin
|
||||
| XoBackupReportsPlugin
|
||||
| XoIpmiSensorsPlugin
|
||||
| XoLoadBalancerPlugin
|
||||
| XoNetboxPlugin
|
||||
| XoOpenmetricsPlugin
|
||||
| XoPerfAlertPlugin
|
||||
| XoSdnControllerPlugin
|
||||
| XoTestPluginPlugin
|
||||
| XoTransportEmailPlugin
|
||||
| XoTransportIcinga2Plugin
|
||||
| XoTransportNagiosPlugin
|
||||
| XoTransportSlackPlugin
|
||||
| XoTransportXmppPlugin
|
||||
| XoUsageReportPlugin
|
||||
| XoWebHooksPlugin
|
||||
|
||||
export type XoProxy = {
|
||||
id: Branded<'proxy'>
|
||||
url: string
|
||||
@@ -539,22 +481,15 @@ type XoBackupJobGeneralSettings = {
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps the last backup of each of the last `retention` days/weeks/months/years, in addition to `exportRetention`.
|
||||
*
|
||||
* Requires the `timezone` setting.
|
||||
*/
|
||||
export type XoBackupJobLongTermRetention = {
|
||||
daily?: { retention: number; settings: Record<string, unknown> }
|
||||
weekly?: { retention: number; settings: Record<string, unknown> }
|
||||
monthly?: { retention: number; settings: Record<string, unknown> }
|
||||
yearly?: { retention: number; settings: Record<string, unknown> }
|
||||
}
|
||||
|
||||
export type XoVmBackupJobGeneralSettings = XoBackupJobGeneralSettings & {
|
||||
cbtDestroySnapshotData?: boolean
|
||||
concurrency?: number
|
||||
longTermRetention?: XoBackupJobLongTermRetention
|
||||
longTermRetention?: {
|
||||
daily?: { retention: number; settings: Record<string, unknown> }
|
||||
weekly?: { retention: number; settings: Record<string, unknown> }
|
||||
monthly?: { retention: number; settings: Record<string, unknown> }
|
||||
yearly?: { retention: number; settings: Record<string, unknown> }
|
||||
}
|
||||
checkpointSnapshot?: boolean
|
||||
offlineSnapshot?: boolean
|
||||
maxExportRate?: number
|
||||
@@ -568,8 +503,8 @@ export type XoVmBackupJobGeneralSettings = XoBackupJobGeneralSettings & {
|
||||
}
|
||||
export type XoVmBackupJobScheduleSettings = {
|
||||
exportRetention?: number
|
||||
healthCheckVmsWithTags?: XoVm['tags'] | string
|
||||
fullInterval?: number | string
|
||||
healthCheckVmsWithTags?: XoVm['tags']
|
||||
fullInterval?: number
|
||||
copyRetention?: number
|
||||
snapshotRetention?: number
|
||||
cbtDestroySnapshotData?: boolean
|
||||
@@ -580,9 +515,9 @@ export type XoVmBackupJob = BaseXoJob & {
|
||||
compression?: 'native' | 'zstd' | ''
|
||||
proxy?: XoProxy['id']
|
||||
mode: 'full' | 'delta'
|
||||
remotes?: CMType.IdOr<XoBackupRepository['id']> | string
|
||||
remotes?: CMType.IdOr<XoBackupRepository['id']>
|
||||
vms: CMType.IdOr<XoVm['id']> | Record<string, unknown>
|
||||
srs?: CMType.IdOr<XoSr['id']> | string
|
||||
srs?: CMType.IdOr<XoSr['id']>
|
||||
type: 'backup'
|
||||
settings: {
|
||||
'': XoVmBackupJobGeneralSettings
|
||||
@@ -611,17 +546,16 @@ export type XoMetadataBackupJob = BaseXoJob & {
|
||||
|
||||
export type XoMirrorBackupGeneralSettings = XoBackupJobGeneralSettings & {
|
||||
concurrency?: number
|
||||
longTermRetention?: XoBackupJobLongTermRetention
|
||||
nRetriesVmBackupFailures?: number
|
||||
mergeBackupsSynchronously?: boolean
|
||||
timeout?: number
|
||||
timezone?: string
|
||||
maxExportRate?: number
|
||||
backupReportTpl?: 'compactMjml'
|
||||
reportWhen: 'failure'
|
||||
}
|
||||
export type XoMirrorBackupScheduleSettings = {
|
||||
exportRetention?: number
|
||||
healthCheckVmsWithTags?: XoVm['tags'] | string
|
||||
vmFilter?: string
|
||||
healthCheckVmsWithTags?: XoVm['tags']
|
||||
healthCheckSr?: XoSr['id']
|
||||
[key: string]: unknown
|
||||
}
|
||||
@@ -764,7 +698,6 @@ export type XoTask = {
|
||||
| 'backup-log'
|
||||
| 'backup-repository'
|
||||
| 'group'
|
||||
| 'plugin'
|
||||
| 'proxy'
|
||||
| 'restore'
|
||||
| 'restore-log'
|
||||
@@ -980,7 +913,6 @@ export type NonXapiXoRecord =
|
||||
| AnyXoLog
|
||||
| XoAuthenticationToken
|
||||
| XoGroup
|
||||
| XoPlugin
|
||||
| XoProxy
|
||||
| XoJob
|
||||
| XoBackupRepository
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
"main": "dist/index.mjs",
|
||||
"name": "@xen-orchestra/acl",
|
||||
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/@xen-orchestra/acl",
|
||||
"version": "1.8.0",
|
||||
"version": "1.7.0",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"private": false,
|
||||
"type": "module",
|
||||
@@ -30,7 +30,7 @@
|
||||
},
|
||||
"devDependencies": {
|
||||
"@eslint/js": "^9.19.0",
|
||||
"@vates/types": "^2.5.0",
|
||||
"@vates/types": "^2.3.0",
|
||||
"rimraf": "^6.0.1",
|
||||
"typescript": "~5.6",
|
||||
"typescript-eslint": "^8.61.0"
|
||||
|
||||
@@ -1,5 +1,3 @@
|
||||
export default {
|
||||
export: true, // can export the content ( full or file by file )
|
||||
read: true, // can read the metadata of an archive
|
||||
mount: true, // can mount the archive for file level restore
|
||||
read: true,
|
||||
}
|
||||
|
||||
@@ -14,7 +14,6 @@ import { default as pbd } from './pbd.mjs'
|
||||
import { default as pci } from './pci.mjs'
|
||||
import { default as pgpu } from './pgpu.mjs'
|
||||
import { default as pif } from './pif.mjs'
|
||||
import { default as plugin } from './plugin.mjs'
|
||||
import { default as pool } from './pool.mjs'
|
||||
import { default as proxy } from './proxy.mjs'
|
||||
import { default as restoreLog } from './restore-log.mjs'
|
||||
@@ -57,7 +56,6 @@ export const SUPPORTED_ACTIONS_BY_RESOURCE = {
|
||||
pci,
|
||||
pgpu,
|
||||
pif,
|
||||
plugin,
|
||||
pool,
|
||||
proxy,
|
||||
'restore-log': restoreLog,
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
export default {
|
||||
load: true,
|
||||
read: true,
|
||||
test: true,
|
||||
unload: true,
|
||||
update: {
|
||||
autoload: true,
|
||||
configuration: true,
|
||||
},
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@xen-orchestra/backup-archive",
|
||||
"version": "1.2.0",
|
||||
"version": "1.1.3",
|
||||
"description": "Helper to handle generic backup archives",
|
||||
"license": "ISC",
|
||||
"author": "",
|
||||
@@ -21,18 +21,18 @@
|
||||
"tar-stream": "^3.1.8",
|
||||
"@types/tar-stream": "^3.1.4",
|
||||
"tmp": "^0.2.1",
|
||||
"@vates/types": "^2.5.0"
|
||||
"@vates/types": "^2.3.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@xen-orchestra/log": "^0.7.1",
|
||||
"@xen-orchestra/fs": "^4.10.0",
|
||||
"@xen-orchestra/disk-transform": "^1.3.4",
|
||||
"@xen-orchestra/fs": "^4.9.5",
|
||||
"@xen-orchestra/disk-transform": "^1.3.3",
|
||||
"@vates/task": "0.7.0",
|
||||
"golike-defer": "0.5.1",
|
||||
"uuid": "^9.0.0",
|
||||
"promise-toolbox": "^0.21.0",
|
||||
"@vates/async-each": "^1.0.1",
|
||||
"vhd-lib": "^4.17.0"
|
||||
"vhd-lib": "^4.16.2"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "yarn run clean && tsc",
|
||||
|
||||
@@ -5,7 +5,6 @@
|
||||
* @typedef {import('vhd-lib/Vhd/VhdFile.js').VhdFile} VhdFile
|
||||
* @typedef {import('vhd-lib/_createFooterHeader.js').VhdFooter} VhdFooter
|
||||
* @typedef {import('@xen-orchestra/disk-transform').DiskBlock} DiskBlock
|
||||
* @typedef {import('vhd-lib/disk-consumer/compressedBlock.mjs').CompressedDiskBlock} CompressedDiskBlock
|
||||
* @typedef {import('@xen-orchestra/fs').RemoteHandlerAbstract} RemoteHandlerAbstract
|
||||
*
|
||||
|
||||
@@ -51,31 +50,16 @@ export class RemoteVhdDisk extends RemoteDisk {
|
||||
*/
|
||||
#dispose = () => {}
|
||||
|
||||
/**
|
||||
* @type {string | undefined}
|
||||
*/
|
||||
#rawBlocksCompression
|
||||
|
||||
/**
|
||||
* set in init(): this disk is a VHD directory using #rawBlocksCompression
|
||||
* @type {boolean}
|
||||
*/
|
||||
#rawBlocks = false
|
||||
|
||||
/**
|
||||
* @param {Object} params
|
||||
* @param {RemoteHandlerAbstract} params.handler
|
||||
* @param {string} params.path
|
||||
* @param {string} [params.rawBlocksCompression] if this disk is a VHD directory using this compression, its blocks
|
||||
* are read as stored (see CompressedDiskBlock), to be written as is in a VHD directory using the same compression.
|
||||
* Otherwise (plain VHD, other compression), they are read normally
|
||||
*/
|
||||
constructor({ handler, path, rawBlocksCompression }) {
|
||||
constructor({ handler, path }) {
|
||||
super()
|
||||
// @todo : ensure this is the full path from the root of the remote
|
||||
this.#path = path
|
||||
this.#handler = handler
|
||||
this.#rawBlocksCompression = rawBlocksCompression
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -98,9 +82,6 @@ export class RemoteVhdDisk extends RemoteDisk {
|
||||
this.#vhd = undefined
|
||||
throw Object.assign(new Error("Can't init vhd directory without using alias"), { code: 'NOT_SUPPORTED' })
|
||||
}
|
||||
// the disk may predate a change of the remote configuration: only use its raw blocks if they match
|
||||
this.#rawBlocks =
|
||||
this.#rawBlocksCompression !== undefined && this.#getCompressionType() === this.#rawBlocksCompression
|
||||
|
||||
if (!options.ignoreBlockIndexes) {
|
||||
await this.#vhd.readBlockAllocationTable()
|
||||
@@ -285,22 +266,12 @@ export class RemoteVhdDisk extends RemoteDisk {
|
||||
/**
|
||||
* Reads a specific block from the VHD.
|
||||
* @param {number} index
|
||||
* @returns {Promise<DiskBlock | CompressedDiskBlock>} diskBlock
|
||||
* @returns {Promise<DiskBlock>} diskBlock
|
||||
*/
|
||||
async readBlock(index) {
|
||||
if (this.#vhd === undefined) {
|
||||
throw new Error(`can't call readBlock of a RemoteVhdDisk before init`)
|
||||
}
|
||||
if (this.#rawBlocks) {
|
||||
/** @type {CompressedDiskBlock} */
|
||||
const block = {
|
||||
index,
|
||||
// only a VHD directory has a compression, checked in init()
|
||||
data: await /** @type {VhdDirectory} */ (this.#vhd).readCompressedBlock(index),
|
||||
compression: /** @type {string} */ (this.#rawBlocksCompression),
|
||||
}
|
||||
return block
|
||||
}
|
||||
const { data } = await this.#vhd.readBlock(index)
|
||||
return {
|
||||
index,
|
||||
|
||||
@@ -8,8 +8,8 @@
|
||||
"dependencies": {
|
||||
"@vates/async-each": "^1.0.3",
|
||||
"@xen-orchestra/async-map": "^0.1.5",
|
||||
"@xen-orchestra/backups": "^0.78.0",
|
||||
"@xen-orchestra/fs": "^4.10.0",
|
||||
"@xen-orchestra/backups": "^0.76.1",
|
||||
"@xen-orchestra/fs": "^4.9.5",
|
||||
"filenamify": "^6.0.0",
|
||||
"getopts": "^2.2.5",
|
||||
"lodash": "^4.18.0",
|
||||
@@ -28,7 +28,7 @@
|
||||
"scripts": {
|
||||
"postversion": "npm publish --access public"
|
||||
},
|
||||
"version": "1.1.18",
|
||||
"version": "1.1.16",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"author": {
|
||||
"name": "Vates SAS",
|
||||
|
||||
@@ -2,8 +2,8 @@ import assert from 'node:assert'
|
||||
|
||||
import { formatFilenameDate } from './_filenameDate.mjs'
|
||||
import { importIncrementalVm } from './_incrementalVm.mjs'
|
||||
import { liveMountXapiLabels } from './liveMountXapiLabels.mjs'
|
||||
import { watchStreamSize } from './_watchStreamSize.mjs'
|
||||
import { meterIncrementalExport, SourceReadTask } from './_SourceReadTask.mjs'
|
||||
import { decorateClass } from '@vates/decorate-with'
|
||||
import { Task } from '@vates/task'
|
||||
import { createLogger } from '@xen-orchestra/log'
|
||||
@@ -43,8 +43,7 @@ export class ImportVmBackup {
|
||||
* @param {object} [params.liveMount] - how to serve a disk from the backup repository instead of
|
||||
* copying it, injected by the caller since a live mount outlives the restore and cannot be run
|
||||
* from this package
|
||||
* @param {({ cacheSrUuid, diskPath, hostId, xapiLabels }) => Promise<{ id: string, vdiUuid: string }>} params.liveMount.mountDisk
|
||||
* `xapiLabels` are those of {@link liveMountXapiLabels}, `cacheSrUuid` makes the mount read/write
|
||||
* @param {({ diskPath, hostId }) => Promise<{ id: string, vdiUuid: string }>} params.liveMount.mountDisk
|
||||
* @param {(id: string) => Promise<void>} params.liveMount.unmountDisk
|
||||
* @param {object} [params.settings]
|
||||
*/
|
||||
@@ -358,23 +357,11 @@ export class ImportVmBackup {
|
||||
}
|
||||
|
||||
const diskPath = join(metadataDir, metadata.vhds[vdiRef])
|
||||
const cacheSrUuid = this._vdiRestoreTargets.get(vdi.uuid).cacheSr
|
||||
const readWrite = cacheSrUuid !== undefined
|
||||
const xapiLabels = liveMountXapiLabels({
|
||||
readWrite,
|
||||
timestamp: metadata.timestamp,
|
||||
vdiNameLabel: vdi.name_label,
|
||||
vmNameLabel: metadata.vm.name_label,
|
||||
})
|
||||
const mount = await liveMount.mountDisk({ cacheSrUuid, diskPath, hostId, xapiLabels })
|
||||
const mount = await liveMount.mountDisk({ diskPath, hostId })
|
||||
this.#liveMounts.push({ ...mount, hostId })
|
||||
info('disk live mounted', { cacheSrUuid, diskPath, hostId, mountId: mount.id, vdiUuid: vdi.uuid })
|
||||
info('disk live mounted', { diskPath, hostId, mountId: mount.id, vdiUuid: vdi.uuid })
|
||||
|
||||
const record = {
|
||||
...vdi,
|
||||
liveMountedVdiRef: await xapi.call('VDI.get_by_uuid', mount.vdiUuid),
|
||||
liveMountedReadOnly: !readWrite,
|
||||
}
|
||||
const record = { ...vdi, liveMountedVdiRef: await xapi.call('VDI.get_by_uuid', mount.vdiUuid) }
|
||||
// it is attached as is: there is nothing to clone it from, nothing to transfer into it, and
|
||||
// no SR to create it on — `SR` still holds the ref it had on the backed up pool
|
||||
delete record.baseVdi
|
||||
@@ -424,6 +411,7 @@ export class ImportVmBackup {
|
||||
throw new Error('live mounting a disk is only supported when restoring an incremental backup')
|
||||
}
|
||||
backup = await adapter.readFullVmBackup(metadata)
|
||||
sizeContainer.readTask = new SourceReadTask({ name: 'read' })
|
||||
watchStreamSize(backup, sizeContainer)
|
||||
} else {
|
||||
assert.strictEqual(metadata.mode, 'delta')
|
||||
@@ -432,6 +420,7 @@ export class ImportVmBackup {
|
||||
// releases them, a successful one hands their ids back to the caller
|
||||
$defer.onFailure(() => this.#releaseLiveMounts())
|
||||
backup = await this._decorateIncrementalVmMetadata()
|
||||
meterIncrementalExport(backup)
|
||||
}
|
||||
|
||||
return Task.run(
|
||||
|
||||
@@ -141,20 +141,7 @@ describe('ImportVmBackup#_decorateIncrementalVmMetadata()', () => {
|
||||
|
||||
const backup = await importer._decorateIncrementalVmMetadata()
|
||||
|
||||
assert.deepEqual(liveMount.mounted, [
|
||||
{
|
||||
// not cached: read only
|
||||
cacheSrUuid: undefined,
|
||||
diskPath: `/xo-vm-backups/${VM_UUID}/${vhdPath(DATA)}`,
|
||||
hostId: HOST,
|
||||
// named after the backed up VM and disk, not after the file on the backup repository
|
||||
xapiLabels: {
|
||||
srNameLabel: '[XO live mount] a vm (20250801T080832Z)',
|
||||
vdiNameLabel: 'data',
|
||||
vdiNameDescription: 'Read-only live mount of a vm (20250801T080832Z), removed on unmount.',
|
||||
},
|
||||
},
|
||||
])
|
||||
assert.deepEqual(liveMount.mounted, [{ diskPath: `/xo-vm-backups/${VM_UUID}/${vhdPath(DATA)}`, hostId: HOST }])
|
||||
// no data is transferred for it
|
||||
assert.deepEqual(Object.keys(backup.disks), [SYSTEM.ref])
|
||||
})
|
||||
@@ -166,7 +153,6 @@ describe('ImportVmBackup#_decorateIncrementalVmMetadata()', () => {
|
||||
|
||||
const vdi = backup.vdis[DATA.ref]
|
||||
assert.equal(vdi.liveMountedVdiRef, 'VDI_REF:mounted-vdi-1')
|
||||
assert.equal(vdi.liveMountedReadOnly, true)
|
||||
assert.equal(vdi.SR, undefined)
|
||||
assert.equal(vdi.uuid, DATA.uuid)
|
||||
// the other disk is restored as usual
|
||||
@@ -174,19 +160,6 @@ describe('ImportVmBackup#_decorateIncrementalVmMetadata()', () => {
|
||||
assert.equal(backup.vdis[SYSTEM.ref].liveMountedVdiRef, undefined)
|
||||
})
|
||||
|
||||
it('mounts a cached disk read/write, and says so in its names', async () => {
|
||||
const { importer, liveMount } = makeImporter({
|
||||
mapVdisSrs: { [DATA.uuid]: { type: 'live-mount', host: HOST, cacheSr: OTHER_SR } },
|
||||
})
|
||||
|
||||
const backup = await importer._decorateIncrementalVmMetadata()
|
||||
|
||||
const [mounted] = liveMount.mounted
|
||||
assert.equal(mounted.cacheSrUuid, OTHER_SR)
|
||||
assert.equal(mounted.xapiLabels.srNameLabel, '[XO live restore] a vm (20250801T080832Z)')
|
||||
assert.equal(backup.vdis[DATA.ref].liveMountedReadOnly, false)
|
||||
})
|
||||
|
||||
it('rejects live mounts spread over several hosts', async () => {
|
||||
const { importer } = makeImporter({
|
||||
mapVdisSrs: {
|
||||
|
||||
@@ -40,10 +40,10 @@ afterEach(async () => {
|
||||
const uniqueId = () => uuid.v1()
|
||||
const uniqueIdBuffer = () => uuid.v1({}, Buffer.alloc(16))
|
||||
|
||||
async function getAdapter({ useVhdDirectory = false, remoteCompressionType } = {}) {
|
||||
async function getAdapter({ useVhdDirectory = false, vhdDirectoryCompression, remoteCompressionType } = {}) {
|
||||
handler = getHandler({ url: `file://${tempDir}`, useVhdDirectory, compressionType: remoteCompressionType })
|
||||
await handler.sync()
|
||||
return new RemoteAdapter(handler)
|
||||
return new RemoteAdapter(handler, { vhdDirectoryCompression })
|
||||
}
|
||||
|
||||
const listVmDir = () => handler.list(rootPath, { ignoreMissing: true })
|
||||
@@ -145,8 +145,7 @@ describe('RemoteAdapter#isMergeableParent', { concurrency: 1 }, () => {
|
||||
|
||||
test(`diskIsDirectory=${diskIsDirectory} useVhdDirectory=${useVhdDirectory} compressionMatches=${compressionMatches} uuidMatches=${uuidMatches} -> ${expected}`, async () => {
|
||||
const targetCompression = 'brotli'
|
||||
// no compressionType on the remote: brotli
|
||||
const adapter = await getAdapter({ useVhdDirectory })
|
||||
const adapter = await getAdapter({ useVhdDirectory, vhdDirectoryCompression: targetCompression })
|
||||
const targetUuid = uniqueIdBuffer()
|
||||
|
||||
await generateVhd(`${basePath}/disk.vhd`, {
|
||||
@@ -165,32 +164,37 @@ describe('RemoteAdapter#isMergeableParent', { concurrency: 1 }, () => {
|
||||
})
|
||||
|
||||
describe('RemoteAdapter#isMergeableParent compression resolution', { concurrency: 1 }, () => {
|
||||
test('the compressionType of the remote is the one compared against', async () => {
|
||||
const adapter = await getAdapter({ useVhdDirectory: true, remoteCompressionType: 'gzip' })
|
||||
test('the per-remote compressionType override wins over the adapter default', async () => {
|
||||
const adapter = await getAdapter({
|
||||
useVhdDirectory: true,
|
||||
vhdDirectoryCompression: 'gzip', // config.toml-style default
|
||||
remoteCompressionType: 'brotli', // per-remote override, should be the one actually compared against
|
||||
})
|
||||
const targetUuid = uniqueIdBuffer()
|
||||
await generateVhd(`${basePath}/disk.vhd`, { mode: 'directory', compression: 'gzip', uuid: targetUuid })
|
||||
await generateVhd(`${basePath}/disk.vhd`, { mode: 'directory', compression: 'brotli', uuid: targetUuid })
|
||||
|
||||
assert.equal(await adapter.isMergeableParent(targetUuid, `${basePath}/disk.vhd.alias.vhd`), true)
|
||||
})
|
||||
|
||||
test('a disk compressed with another codec than the remote is rejected', async () => {
|
||||
const adapter = await getAdapter({ useVhdDirectory: true, remoteCompressionType: 'gzip' })
|
||||
test('a disk compressed with the adapter default (not the override) is rejected', async () => {
|
||||
const adapter = await getAdapter({
|
||||
useVhdDirectory: true,
|
||||
vhdDirectoryCompression: 'gzip',
|
||||
remoteCompressionType: 'brotli',
|
||||
})
|
||||
const targetUuid = uniqueIdBuffer()
|
||||
await generateVhd(`${basePath}/disk.vhd`, { mode: 'directory', compression: 'brotli', uuid: targetUuid })
|
||||
// disk uses the config default, not the remote override that's actually in effect
|
||||
await generateVhd(`${basePath}/disk.vhd`, { mode: 'directory', compression: 'gzip', uuid: targetUuid })
|
||||
|
||||
assert.equal(await adapter.isMergeableParent(targetUuid, `${basePath}/disk.vhd.alias.vhd`), false)
|
||||
})
|
||||
|
||||
test('a remote without compressionType uses brotli', async () => {
|
||||
const adapter = await getAdapter({ useVhdDirectory: true })
|
||||
const targetUuid = uniqueIdBuffer()
|
||||
await generateVhd(`${basePath}/disk.vhd`, { mode: 'directory', compression: 'brotli', uuid: targetUuid })
|
||||
|
||||
assert.equal(await adapter.isMergeableParent(targetUuid, `${basePath}/disk.vhd.alias.vhd`), true)
|
||||
})
|
||||
|
||||
test("a remote-level 'none' means no compression", async () => {
|
||||
const adapter = await getAdapter({ useVhdDirectory: true, remoteCompressionType: 'none' })
|
||||
test("a remote-level 'none' override means no compression, ignoring the adapter default", async () => {
|
||||
const adapter = await getAdapter({
|
||||
useVhdDirectory: true,
|
||||
vhdDirectoryCompression: 'brotli',
|
||||
remoteCompressionType: 'none',
|
||||
})
|
||||
const targetUuid = uniqueIdBuffer()
|
||||
// no compression option => VhdDirectory's own getCompressionType() is undefined, matching 'none'
|
||||
await generateVhd(`${basePath}/disk.vhd`, { mode: 'directory', uuid: targetUuid })
|
||||
@@ -319,105 +323,3 @@ describe('RemoteAdapter#writeVhd validated by checkDisk', { concurrency: 1 }, ()
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
// IncrementalRemote runner when source and targets use the same compression: the blocks are copied as stored
|
||||
describe('RemoteAdapter raw blocks copy', { concurrency: 1 }, () => {
|
||||
// copy a disk the way the IncrementalRemote runner does, and check the target content
|
||||
async function copyAndCheck(adapter, sourcePath, { rawBlocksCompression, expectedCompression }) {
|
||||
const targetPath = `${basePath}/${adapter.getVhdFileName('target')}`
|
||||
const source = await adapter._createVhdDisk(handler, sourcePath, { useChain: false, rawBlocksCompression })
|
||||
await adapter.writeVhd(targetPath, source, {
|
||||
validator: tmpPath => checkDisk(handler, tmpPath),
|
||||
uuid: uniqueIdBuffer(),
|
||||
})
|
||||
|
||||
await Disposable.use(openVhd(handler, targetPath), async vhd => {
|
||||
assert.equal(vhd.compressionType, expectedCompression)
|
||||
await vhd.readBlockAllocationTable()
|
||||
assert.ok(vhd.containsBlock(0))
|
||||
assert.ok(!vhd.containsBlock(1))
|
||||
const { data } = await vhd.readBlock(2)
|
||||
assert.ok(
|
||||
data.every(byte => byte === 0x42),
|
||||
'block 2 should contain the source disk data'
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
for (const compression of ['brotli', 'gzip', 'none']) {
|
||||
test(`${compression}: a disk read with the same compression is copied as stored, readable and identical`, async () => {
|
||||
const adapter = await getAdapter({ useVhdDirectory: true, remoteCompressionType: compression })
|
||||
const sourcePath = `${basePath}/${adapter.getVhdFileName('source')}`
|
||||
await adapter.writeVhd(sourcePath, new MockDisk(3, [0, 2], 0x42), { uuid: uniqueIdBuffer() })
|
||||
|
||||
const source = await adapter._createVhdDisk(handler, sourcePath, {
|
||||
useChain: false,
|
||||
rawBlocksCompression: compression,
|
||||
})
|
||||
const block = await source.readBlock(2)
|
||||
await source.close()
|
||||
assert.equal(block.compression, compression)
|
||||
if (compression !== 'none') {
|
||||
assert.ok(block.data.length < 2 * 1024 * 1024, 'the block should be read compressed')
|
||||
}
|
||||
|
||||
await copyAndCheck(adapter, sourcePath, { rawBlocksCompression: compression, expectedCompression: compression })
|
||||
})
|
||||
}
|
||||
|
||||
test('a disk written before a compression change is read normally and copied', async () => {
|
||||
const gzipAdapter = await getAdapter({ useVhdDirectory: true, remoteCompressionType: 'gzip' })
|
||||
const sourcePath = `${basePath}/${gzipAdapter.getVhdFileName('source')}`
|
||||
await gzipAdapter.writeVhd(sourcePath, new MockDisk(3, [0, 2], 0x42), { uuid: uniqueIdBuffer() })
|
||||
await handler.forget()
|
||||
|
||||
const brotliAdapter = await getAdapter({ useVhdDirectory: true, remoteCompressionType: 'brotli' })
|
||||
const source = await brotliAdapter._createVhdDisk(handler, sourcePath, {
|
||||
useChain: false,
|
||||
rawBlocksCompression: 'brotli',
|
||||
})
|
||||
const block = await source.readBlock(2)
|
||||
await source.close()
|
||||
assert.equal(block.compression, undefined)
|
||||
assert.equal(block.data.length, 2 * 1024 * 1024)
|
||||
|
||||
await copyAndCheck(brotliAdapter, sourcePath, { rawBlocksCompression: 'brotli', expectedCompression: 'brotli' })
|
||||
})
|
||||
|
||||
test('a VHD file written before the switch to VHD directories is read normally and copied', async () => {
|
||||
const fileAdapter = await getAdapter({ useVhdDirectory: false })
|
||||
const sourcePath = `${basePath}/${fileAdapter.getVhdFileName('source')}`
|
||||
await fileAdapter.writeVhd(sourcePath, new MockDisk(3, [0, 2], 0x42), { uuid: uniqueIdBuffer() })
|
||||
await handler.forget()
|
||||
|
||||
const directoryAdapter = await getAdapter({ useVhdDirectory: true, remoteCompressionType: 'brotli' })
|
||||
await copyAndCheck(directoryAdapter, sourcePath, { rawBlocksCompression: 'brotli', expectedCompression: 'brotli' })
|
||||
})
|
||||
|
||||
// blocks as read from a VHD directory using `compression`, without their real content: only the checks are tested
|
||||
class MockCompressedDisk extends MockDisk {
|
||||
#compression
|
||||
constructor(compression, ...args) {
|
||||
super(...args)
|
||||
this.#compression = compression
|
||||
}
|
||||
|
||||
async readBlock(index) {
|
||||
return { ...(await super.readBlock(index)), compression: this.#compression }
|
||||
}
|
||||
}
|
||||
|
||||
test('a VHD directory target refuses blocks compressed differently', async () => {
|
||||
const adapter = await getAdapter({ useVhdDirectory: true, remoteCompressionType: 'brotli' })
|
||||
await assert.rejects(
|
||||
adapter.writeVhd(
|
||||
`${basePath}/${adapter.getVhdFileName('target')}`,
|
||||
new MockCompressedDisk('gzip', 1, [0], 0x42),
|
||||
{
|
||||
uuid: uniqueIdBuffer(),
|
||||
}
|
||||
),
|
||||
/can't write a gzip compressed block 0/
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -3,7 +3,6 @@ import { asyncMap, asyncMapSettled } from '@xen-orchestra/async-map'
|
||||
import { createLogger } from '@xen-orchestra/log'
|
||||
import { stringify } from 'uuid'
|
||||
import { decorateMethodsWith } from '@vates/decorate-with'
|
||||
import assert from 'node:assert'
|
||||
import { basename, dirname, join, resolve } from 'node:path'
|
||||
import { normalize } from '@xen-orchestra/fs/path'
|
||||
import { synchronized } from 'decorator-synchronized'
|
||||
@@ -27,7 +26,6 @@ import { formatFilenameDate } from './_filenameDate.mjs'
|
||||
import { isMetadataFile } from './_backupType.mjs'
|
||||
import {
|
||||
isKnownJournalEvent,
|
||||
purgeBackupJournal,
|
||||
readBackupJournal,
|
||||
writeBackupJournalEntries,
|
||||
writeBackupJournalEntry,
|
||||
@@ -66,10 +64,6 @@ export class RemoteAdapter {
|
||||
this._handler = handler
|
||||
this._readCacheListVmBackups = synchronized.withKey()(this._readCacheListVmBackups)
|
||||
this._useGetDiskLegacy = useGetDiskLegacy
|
||||
|
||||
// Cache of the partition list per diskId, populated by listPartitions and evicted by
|
||||
// getDisk when the disk is unmounted
|
||||
this._partitionsCache = new Map()
|
||||
}
|
||||
|
||||
get handler() {
|
||||
@@ -323,14 +317,6 @@ export class RemoteAdapter {
|
||||
return this.handler.getConfig('useVhdDirectory')
|
||||
}
|
||||
|
||||
/**
|
||||
* @returns {string | undefined} the compression of the VHD directories written on this remote ('none' if not
|
||||
* compressed), undefined if this remote writes plain VHD files
|
||||
*/
|
||||
getVhdDirectoryCompression() {
|
||||
return this.useVhdDirectory() ? (this.handler.getConfig('compressionType') ?? 'brotli') : undefined // compatibility layer
|
||||
}
|
||||
|
||||
#useAlias() {
|
||||
return this.useVhdDirectory()
|
||||
}
|
||||
@@ -560,14 +546,6 @@ export class RemoteAdapter {
|
||||
return readBackupJournal(this._handler, cursor, opts)
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} before timestamp in ms, the journal days before its own are removed
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async purgeBackupJournal(before) {
|
||||
return purgeBackupJournal(this._handler, before)
|
||||
}
|
||||
|
||||
// Same as `readBackupJournal()`, with the current metadata of the added and changed backups
|
||||
// attached, so that a listing can be brought up to date from the result alone, in a single
|
||||
// round-trip for a caller which is not on this host.
|
||||
@@ -698,7 +676,7 @@ export class RemoteAdapter {
|
||||
path,
|
||||
concurrency: writeBlockConcurrency,
|
||||
validator,
|
||||
compression: this.getVhdDirectoryCompression(),
|
||||
compression: handler.getConfig('compressionType') ?? 'brotli', // compatibility layer
|
||||
uuid,
|
||||
parentUuid,
|
||||
parentPath,
|
||||
@@ -738,24 +716,19 @@ export class RemoteAdapter {
|
||||
}
|
||||
|
||||
// open the hierarchy of ancestors until we find a full one
|
||||
async _createVhdDisk(handler, path, { useChain, rawBlocksCompression }) {
|
||||
async _createVhdDisk(handler, path, { useChain }) {
|
||||
let disk
|
||||
if (useChain) {
|
||||
assert.strictEqual(rawBlocksCompression, undefined, `can't read raw blocks of a disk chain`)
|
||||
disk = await openDiskChain({ handler, path })
|
||||
} else {
|
||||
disk = new RemoteVhdDisk({ handler, path, rawBlocksCompression })
|
||||
disk = new RemoteVhdDisk({ handler, path })
|
||||
await disk.init()
|
||||
}
|
||||
disk = new ReadAhead(disk)
|
||||
return disk
|
||||
}
|
||||
|
||||
/**
|
||||
* `rawBlocksCompression`: the blocks of the VHD directories using this compression are read as stored (see
|
||||
* RemoteVhdDisk), to be written as is in a remote using the same compression
|
||||
*/
|
||||
async readIncrementalVmBackup(metadata, ignoredVdis, { useChain = true, rawBlocksCompression } = {}) {
|
||||
async readIncrementalVmBackup(metadata, ignoredVdis, { useChain = true } = {}) {
|
||||
const handler = this._handler
|
||||
const { vbds, vhds, vifs, vm, vmSnapshot, vtpms } = metadata
|
||||
const dir = dirname(metadata._filename)
|
||||
@@ -763,7 +736,7 @@ export class RemoteAdapter {
|
||||
const disks = {}
|
||||
await asyncMapSettled(Object.keys(vdis), async ref => {
|
||||
delete vdis[ref].baseVdi
|
||||
disks[ref] = await this._createVhdDisk(handler, join(dir, vhds[ref]), { useChain, rawBlocksCompression })
|
||||
disks[ref] = await this._createVhdDisk(handler, join(dir, vhds[ref]), { useChain })
|
||||
})
|
||||
|
||||
return {
|
||||
|
||||
116
@xen-orchestra/backups/_SourceReadTask.mjs
Normal file
116
@xen-orchestra/backups/_SourceReadTask.mjs
Normal file
@@ -0,0 +1,116 @@
|
||||
import { Task } from '@vates/task'
|
||||
import { TaskMetrics } from '@vates/task/metrics'
|
||||
import { MeteredDisk } from '@xen-orchestra/disk-transform'
|
||||
|
||||
const MAX_DURATION_BETWEEN_EMIT = 5e3
|
||||
|
||||
/**
|
||||
* Reports the reading of a source (a disk, a XVA) in its own task, child of the current task
|
||||
*
|
||||
* A source is read once, even when it is consumed by multiple writers, but from the async context of the writer
|
||||
* pulling the next block: the task is held here instead of relying on the current task
|
||||
*
|
||||
* Its lifecycle follows the source: started before the first read, ended when the source is exhausted, fails or is
|
||||
* closed early. A source never read (a step failing before the transfer, a disk without blocks) leaves no task
|
||||
*
|
||||
* The bytes read are reported in the `bytesRead` metric (`metrics` property, see `@vates/task/metrics`), with the
|
||||
* number of bytes to read as total, and the `progress` property when this number is known
|
||||
*
|
||||
* Implements `ReadMeter` from `@xen-orchestra/disk-transform`
|
||||
*/
|
||||
export class SourceReadTask {
|
||||
#isStarted = false
|
||||
#lastProgressDate = 0
|
||||
#bytesToRead
|
||||
#bytesRead = 0
|
||||
#metrics
|
||||
#task
|
||||
|
||||
/**
|
||||
* @param {Record<string, unknown>} properties of the task, must not contain `type` or `id`: xo-web would display it
|
||||
* as a VM/SR/remote task
|
||||
*/
|
||||
constructor(properties) {
|
||||
// created here to be a child of the current task, only started on the first read
|
||||
this.#task = new Task({ properties })
|
||||
this.#metrics = new TaskMetrics(this.#task, { minEmitInterval: MAX_DURATION_BETWEEN_EMIT })
|
||||
this.#metrics.define('bytesRead', { unit: 'bytes' })
|
||||
}
|
||||
|
||||
get bytesRead() {
|
||||
return this.#bytesRead
|
||||
}
|
||||
|
||||
#setProgress() {
|
||||
this.#lastProgressDate = Date.now()
|
||||
if (this.#bytesToRead > 0) {
|
||||
this.#task.set('progress', Math.min(100, Math.round((this.#bytesRead * 100) / this.#bytesToRead)))
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* No-op once started
|
||||
*
|
||||
* @param {object} [opts]
|
||||
* @param {number} [opts.bytesToRead] number of bytes to read, if known
|
||||
*/
|
||||
onStart({ bytesToRead } = {}) {
|
||||
if (this.#isStarted) {
|
||||
return
|
||||
}
|
||||
this.#isStarted = true
|
||||
this.#bytesToRead = bytesToRead
|
||||
this.#task.start()
|
||||
this.#metrics.setTotal('bytesRead', bytesToRead)
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {number} length number of bytes read
|
||||
*/
|
||||
onRead(length) {
|
||||
this.onStart()
|
||||
if (this.#task.status !== 'pending') {
|
||||
// already ended, late reads are ignored
|
||||
return
|
||||
}
|
||||
this.#bytesRead += length
|
||||
this.#metrics.add('bytesRead', length)
|
||||
if (Date.now() - this.#lastProgressDate >= MAX_DURATION_BETWEEN_EMIT) {
|
||||
this.#setProgress()
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* A source closed early is not a failure: its consumers stopped, they report their own errors
|
||||
*
|
||||
* @param {{ isComplete: boolean, error?: unknown }} result
|
||||
*/
|
||||
onEnd({ isComplete, error }) {
|
||||
const task = this.#task
|
||||
if (!this.#isStarted || task.status !== 'pending') {
|
||||
return
|
||||
}
|
||||
this.#metrics.flush()
|
||||
this.#setProgress()
|
||||
if (error !== undefined) {
|
||||
task.failure(error)
|
||||
} else {
|
||||
task.success({ isComplete })
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports the reading of each disk of an incremental export in its own task, child of the current task
|
||||
*
|
||||
* Each disk is replaced by a `MeteredDisk`, which only exposes the generic `Disk` interface: source specific methods
|
||||
* (`useNbd()` for example) must be called before
|
||||
*
|
||||
* @param {{ disks: Record<string, import('@xen-orchestra/disk-transform').Disk>, vdis: Record<string, { name_label: string, uuid: string }> }} incrementalExport
|
||||
*/
|
||||
export function meterIncrementalExport({ disks, vdis }) {
|
||||
for (const [key, disk] of Object.entries(disks)) {
|
||||
const vdi = vdis[key]
|
||||
disks[key] = new MeteredDisk(disk, new SourceReadTask({ name: `read disk ${vdi.name_label}`, vdiUuid: vdi.uuid }))
|
||||
}
|
||||
}
|
||||
243
@xen-orchestra/backups/_SourceReadTask.test.mjs
Normal file
243
@xen-orchestra/backups/_SourceReadTask.test.mjs
Normal file
@@ -0,0 +1,243 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { Readable, Writable } from 'node:stream'
|
||||
import { pipeline } from 'node:stream/promises'
|
||||
import { describe, it } from 'node:test'
|
||||
import { setTimeout as delay } from 'node:timers/promises'
|
||||
import { Task } from '@vates/task'
|
||||
import { MeteredDisk, RandomAccessDisk, SynchronizedDisk } from '@xen-orchestra/disk-transform'
|
||||
|
||||
import { forkStreamUnpipe } from './_runners/_forkStreamUnpipe.mjs'
|
||||
import { meterIncrementalExport, SourceReadTask } from './_SourceReadTask.mjs'
|
||||
import { watchStreamSize } from './_watchStreamSize.mjs'
|
||||
|
||||
const BLOCK_SIZE = 1024
|
||||
const NB_BLOCKS = 20
|
||||
|
||||
class MemoryDisk extends RandomAccessDisk {
|
||||
getVirtualSize() {
|
||||
return NB_BLOCKS * BLOCK_SIZE
|
||||
}
|
||||
getBlockSize() {
|
||||
return BLOCK_SIZE
|
||||
}
|
||||
async init() {}
|
||||
async close() {}
|
||||
isDifferencing() {
|
||||
return false
|
||||
}
|
||||
getBlockIndexes() {
|
||||
return Array.from({ length: NB_BLOCKS }, (_, index) => index)
|
||||
}
|
||||
hasBlock() {
|
||||
return true
|
||||
}
|
||||
async readBlock(index) {
|
||||
return { index, data: Buffer.alloc(BLOCK_SIZE) }
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs `fn` in a root task, and returns the tasks created inside, by name
|
||||
*/
|
||||
async function collectTasks(fn) {
|
||||
const tasksById = new Map()
|
||||
const root = new Task({
|
||||
properties: { name: 'root' },
|
||||
onProgress(event) {
|
||||
if (event.type === 'start') {
|
||||
const { name, ...properties } = event.properties
|
||||
tasksById.set(event.id, { id: event.id, name, parentId: event.parentId, properties })
|
||||
return
|
||||
}
|
||||
const task = tasksById.get(event.id)
|
||||
if (task === undefined) {
|
||||
return
|
||||
}
|
||||
if (event.type === 'property') {
|
||||
task.properties[event.name] = event.value
|
||||
} else if (event.type === 'end') {
|
||||
task.status = event.status
|
||||
task.result = event.result
|
||||
}
|
||||
},
|
||||
})
|
||||
await root.run(fn).catch(() => {})
|
||||
const tasksByName = {}
|
||||
for (const task of tasksById.values()) {
|
||||
task.isRootChild = task.parentId === root.id
|
||||
tasksByName[task.name] = task
|
||||
}
|
||||
return tasksByName
|
||||
}
|
||||
|
||||
// each writer consumes its fork at its own pace, in its own task
|
||||
function runWriters(consumers) {
|
||||
return Promise.all(Object.entries(consumers).map(([name, consume]) => Task.run({ properties: { name } }, consume)))
|
||||
}
|
||||
|
||||
function createMeteredDisk(diskProperties = { name: 'read disk', vdiUuid: 'vdi-uuid' }) {
|
||||
return new MeteredDisk(new MemoryDisk(), new SourceReadTask(diskProperties))
|
||||
}
|
||||
|
||||
describe('SourceReadTask', () => {
|
||||
it('reports a disk read by multiple writers only in its own task', async () => {
|
||||
const tasks = await collectTasks(async () => {
|
||||
const synchronizedDisk = new SynchronizedDisk(createMeteredDisk())
|
||||
const forks = { backup: synchronizedDisk.fork('backup'), replication: synchronizedDisk.fork('replication') }
|
||||
|
||||
await runWriters({
|
||||
async backup() {
|
||||
for await (const block of forks.backup.diskBlocks()) {
|
||||
assert.equal(block.data.length, BLOCK_SIZE)
|
||||
await delay(1)
|
||||
}
|
||||
},
|
||||
async replication() {
|
||||
for await (const block of forks.replication.diskBlocks()) {
|
||||
assert.equal(block.data.length, BLOCK_SIZE)
|
||||
await delay(Math.random() * 3)
|
||||
}
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
const readTask = tasks['read disk']
|
||||
assert.equal(readTask.isRootChild, true)
|
||||
assert.equal(readTask.status, 'success')
|
||||
assert.deepEqual(readTask.result, { isComplete: true })
|
||||
assert.deepEqual(Object.keys(readTask.properties).sort(), ['metrics', 'progress', 'vdiUuid'])
|
||||
assert.equal(readTask.properties.vdiUuid, 'vdi-uuid')
|
||||
assert.equal(readTask.properties.progress, 100)
|
||||
const { bytesRead } = readTask.properties.metrics
|
||||
assert.equal(bytesRead.value, NB_BLOCKS * BLOCK_SIZE)
|
||||
assert.equal(bytesRead.total, NB_BLOCKS * BLOCK_SIZE)
|
||||
// the final value is always in the history
|
||||
assert.equal(bytesRead.history.at(-1)[1], NB_BLOCKS * BLOCK_SIZE)
|
||||
assert.deepEqual(tasks.backup.properties, {})
|
||||
assert.deepEqual(tasks.replication.properties, {})
|
||||
})
|
||||
|
||||
it('reports a forked stream of unknown length only in its own task', async () => {
|
||||
const chunks = Array.from({ length: NB_BLOCKS }, () => Buffer.alloc(BLOCK_SIZE))
|
||||
const tasks = await collectTasks(async () => {
|
||||
const stream = Readable.from(chunks)
|
||||
watchStreamSize(stream, { size: 0, readTask: new SourceReadTask({ name: 'read' }) })
|
||||
const forks = [forkStreamUnpipe(stream), forkStreamUnpipe(stream)]
|
||||
const sink = () =>
|
||||
new Writable({
|
||||
write(_chunk, _encoding, callback) {
|
||||
setTimeout(callback, 1)
|
||||
},
|
||||
})
|
||||
|
||||
await runWriters({
|
||||
remote: () => pipeline(forks[0], sink()),
|
||||
sr: () => pipeline(forks[1], sink()),
|
||||
})
|
||||
})
|
||||
|
||||
assert.equal(tasks.read.isRootChild, true)
|
||||
assert.equal(tasks.read.status, 'success')
|
||||
assert.deepEqual(tasks.read.result, { isComplete: true })
|
||||
assert.equal(tasks.read.properties.metrics.bytesRead.value, NB_BLOCKS * BLOCK_SIZE)
|
||||
assert.equal(tasks.read.properties.metrics.bytesRead.total, undefined)
|
||||
assert.equal(tasks.read.properties.progress, undefined)
|
||||
})
|
||||
|
||||
it('leaves no task when the source is never read', async () => {
|
||||
const tasks = await collectTasks(async () => {
|
||||
createMeteredDisk()
|
||||
})
|
||||
|
||||
assert.deepEqual(Object.keys(tasks), ['root'])
|
||||
})
|
||||
|
||||
it('succeeds as incomplete when its consumers stop early', async () => {
|
||||
const tasks = await collectTasks(async () => {
|
||||
let nbRead = 0
|
||||
for await (const block of createMeteredDisk().diskBlocks()) {
|
||||
assert.equal(block.data.length, BLOCK_SIZE)
|
||||
if (++nbRead === 5) {
|
||||
break
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
assert.equal(tasks['read disk'].status, 'success')
|
||||
assert.deepEqual(tasks['read disk'].result, { isComplete: false })
|
||||
assert.equal(tasks['read disk'].properties.metrics.bytesRead.value, 5 * BLOCK_SIZE)
|
||||
assert.equal(tasks['read disk'].properties.progress, 25)
|
||||
})
|
||||
|
||||
it('fails when the source fails', async () => {
|
||||
const tasks = await collectTasks(async () => {
|
||||
const disk = new MemoryDisk()
|
||||
disk.readBlock = async index => {
|
||||
if (index === 2) {
|
||||
throw new Error('NBD connection lost')
|
||||
}
|
||||
return { index, data: Buffer.alloc(BLOCK_SIZE) }
|
||||
}
|
||||
const meteredDisk = new MeteredDisk(disk, new SourceReadTask({ name: 'read disk' }))
|
||||
await assert.rejects(async () => {
|
||||
for await (const block of meteredDisk.diskBlocks()) {
|
||||
assert.equal(block.data.length, BLOCK_SIZE)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
assert.equal(tasks['read disk'].status, 'failure')
|
||||
assert.equal(tasks['read disk'].result.message, 'NBD connection lost')
|
||||
assert.equal(tasks['read disk'].properties.metrics.bytesRead.value, 2 * BLOCK_SIZE)
|
||||
})
|
||||
|
||||
it('reports each disk of an incremental export in its own task', async () => {
|
||||
const tasks = await collectTasks(async () => {
|
||||
const incrementalExport = {
|
||||
disks: { 'OpaqueRef:1': new MemoryDisk(), 'OpaqueRef:2': new MemoryDisk() },
|
||||
vdis: {
|
||||
'OpaqueRef:1': { name_label: 'system', uuid: 'vdi-1' },
|
||||
'OpaqueRef:2': { name_label: 'data', uuid: 'vdi-2' },
|
||||
},
|
||||
}
|
||||
meterIncrementalExport(incrementalExport)
|
||||
for (const disk of Object.values(incrementalExport.disks)) {
|
||||
assert.ok(disk instanceof MeteredDisk)
|
||||
for await (const block of disk.diskBlocks()) {
|
||||
assert.equal(block.data.length, BLOCK_SIZE)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
for (const [name, vdiUuid] of [
|
||||
['read disk system', 'vdi-1'],
|
||||
['read disk data', 'vdi-2'],
|
||||
]) {
|
||||
assert.equal(tasks[name].isRootChild, true)
|
||||
assert.equal(tasks[name].status, 'success')
|
||||
assert.equal(tasks[name].properties.vdiUuid, vdiUuid)
|
||||
assert.equal(tasks[name].properties.metrics.bytesRead.value, NB_BLOCKS * BLOCK_SIZE)
|
||||
}
|
||||
})
|
||||
|
||||
it('groups the reads of a restore point in the task it is metered in', async () => {
|
||||
const tasks = await collectTasks(async () => {
|
||||
const incrementalExport = {
|
||||
disks: { 'OpaqueRef:1': new MemoryDisk() },
|
||||
vdis: { 'OpaqueRef:1': { name_label: 'system', uuid: 'vdi-1' } },
|
||||
}
|
||||
const readTask = new Task({ properties: { name: 'read', timestamp: 1 } })
|
||||
await readTask.runInside(() => meterIncrementalExport(incrementalExport))
|
||||
for await (const block of incrementalExport.disks['OpaqueRef:1'].diskBlocks()) {
|
||||
assert.equal(block.data.length, BLOCK_SIZE)
|
||||
}
|
||||
readTask.success()
|
||||
})
|
||||
|
||||
assert.equal(tasks.read.isRootChild, true)
|
||||
assert.equal(tasks.read.status, 'success')
|
||||
assert.equal(tasks['read disk system'].isRootChild, false)
|
||||
assert.equal(tasks['read disk system'].parentId, tasks.read.id)
|
||||
assert.equal(tasks['read disk system'].status, 'success')
|
||||
})
|
||||
})
|
||||
@@ -393,47 +393,6 @@ describe('readBackupJournal()', { concurrency: 1 }, () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('purgeBackupJournal()', { concurrency: 1 }, () => {
|
||||
const DAY = 24 * 60 * 60 * 1e3
|
||||
const HOUR = 60 * 60 * 1e3
|
||||
|
||||
// midnight of the given number of days ago, so that the tests do not depend on the time they run at
|
||||
const daysAgo = n => (Math.floor(Date.now() / DAY) - n) * DAY
|
||||
|
||||
const writeEntryAt = timestamp =>
|
||||
writeJournalEntryAt(timestamp, { event: 'add', vmUuid, filename: `/${rootPath}/${timestamp}.json` })
|
||||
|
||||
test('removes the days before the one of `before`, and keeps that day whole', async () => {
|
||||
for (const n of [3, 2]) {
|
||||
await writeEntryAt(daysAgo(n) + HOUR)
|
||||
}
|
||||
|
||||
// after the entry of its own day: that entry is kept all the same
|
||||
await adapter.purgeBackupJournal(daysAgo(2) + 2 * HOUR)
|
||||
|
||||
assert.deepEqual(await listJournalDays(), [formatJournalDay(daysAgo(2))])
|
||||
})
|
||||
|
||||
test('skips a day which cannot be removed, and removes the next ones', async t => {
|
||||
for (const n of [3, 2]) {
|
||||
await writeEntryAt(daysAgo(n))
|
||||
}
|
||||
const lockedDay = formatJournalDay(daysAgo(3))
|
||||
|
||||
const rmtree = handler.rmtree.bind(handler)
|
||||
t.mock.method(handler, 'rmtree', async path => {
|
||||
if (path === `/${BACKUP_JOURNAL_DIR}/${lockedDay}`) {
|
||||
throw Object.assign(new Error('EPERM: operation not permitted'), { code: 'EPERM' })
|
||||
}
|
||||
return rmtree(path)
|
||||
})
|
||||
|
||||
await adapter.purgeBackupJournal(Date.now())
|
||||
|
||||
assert.deepEqual(await listJournalDays(), [lockedDay])
|
||||
})
|
||||
})
|
||||
|
||||
describe('readBackupJournalEvents()', { concurrency: 1 }, () => {
|
||||
// records the paths whose metadata is read from now on, to check a replay does not re-read the
|
||||
// same backup once per event
|
||||
|
||||
@@ -309,47 +309,3 @@ export async function readBackupJournal(handler, cursor, { mustExist = false } =
|
||||
|
||||
return entries
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes the journal entries of the days before the one of `before`.
|
||||
*
|
||||
* Whole days are removed, entries are never removed one by one: the day of `before` is kept entirely,
|
||||
* whatever the time of its entries.
|
||||
*
|
||||
* A day which cannot be removed is skipped, e.g. its files are immutable (`EPERM` on a local
|
||||
* repository, `AccessDenied` from the policy of a bucket): it must not keep the later days from being
|
||||
* removed, and the next purge tries it again. Only a failure to list the journal rejects.
|
||||
*
|
||||
* A purge warns once, with its first failure and their count: where deletes are refused, every day
|
||||
* before `before` fails again on each purge, one more each day.
|
||||
*
|
||||
* @param {RemoteHandler} handler
|
||||
* @param {number} before timestamp in ms
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
export async function purgeBackupJournal(handler, before) {
|
||||
const minDay = formatJournalDay(before)
|
||||
const days = await handler.list(`/${BACKUP_JOURNAL_DIR}`, {
|
||||
filter: name => isDayName(name) && name < minDay,
|
||||
ignoreMissing: true,
|
||||
})
|
||||
let firstFailure
|
||||
let nFailures = 0
|
||||
// one day at a time: this runs in the background, it must not compete with the backups for the
|
||||
// remote
|
||||
for (const day of days) {
|
||||
const path = `/${BACKUP_JOURNAL_DIR}/${day}`
|
||||
try {
|
||||
await handler.rmtree(path)
|
||||
debug('journal day purged', { path })
|
||||
} catch (error) {
|
||||
if (firstFailure === undefined) {
|
||||
firstFailure = { error, path }
|
||||
}
|
||||
++nFailures
|
||||
}
|
||||
}
|
||||
if (firstFailure !== undefined) {
|
||||
warn('failed to purge some journal days', { ...firstFailure, nFailures })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,6 +75,7 @@ class BackupWorker {
|
||||
yield new RemoteAdapter(handler, {
|
||||
debounceResource: this.debounceResource,
|
||||
dirMode: this.#config.dirMode,
|
||||
vhdDirectoryCompression: this.#config.vhdDirectoryCompression,
|
||||
})
|
||||
} finally {
|
||||
await handler.forget()
|
||||
|
||||
@@ -1,111 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
import { createLogger } from '@xen-orchestra/log'
|
||||
import moment from 'moment-timezone'
|
||||
import { parse } from 'xo-remote-parser'
|
||||
|
||||
const { warn } = createLogger('xo:backups:buildContext')
|
||||
|
||||
/**
|
||||
* @typedef {import('@vates/types/xen-api').XenApiVm} XenApiVm
|
||||
* @typedef {import('@vates/types/xo').XoSr} XoSr
|
||||
* @typedef {import('@vates/types/xo').XoBackupRepository} XoBackupRepository
|
||||
*
|
||||
* @typedef {object} RunContext
|
||||
* @property {number} dayOfWeek
|
||||
* @property {number} dayOfMonth
|
||||
* @property {number} hour
|
||||
* @property {number} month
|
||||
* @property {number} year
|
||||
*
|
||||
* @typedef {object} VmContext
|
||||
* @property {Record<string, unknown>} vm
|
||||
* @property {RunContext} run
|
||||
* @property {number} [chainLength]
|
||||
*
|
||||
* @typedef {object} SrContext
|
||||
* @property {{name_label: string, type: string, description: string, tags: string[]}} sr
|
||||
* @property {RunContext} run
|
||||
*
|
||||
* @typedef {object} BackupRepositoryContext
|
||||
* @property {{name: string, type: string | undefined, tags: string[]}} backupRepository
|
||||
* @property {RunContext} run
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {Date} date
|
||||
* @param {string | undefined} timezone
|
||||
* @returns {RunContext}
|
||||
*/
|
||||
export function buildRunContext(date, timezone) {
|
||||
const momentDate = timezone ? moment.tz(date, timezone) : moment(date)
|
||||
return {
|
||||
dayOfWeek: momentDate.day(),
|
||||
dayOfMonth: momentDate.date(),
|
||||
hour: momentDate.hour(),
|
||||
month: momentDate.month() + 1,
|
||||
year: momentDate.year(),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {XenApiVm} vm
|
||||
* @param {RunContext} run
|
||||
* @param {number} [chainLength]
|
||||
* @returns {VmContext}
|
||||
*/
|
||||
export function buildVmContext(vm, run, chainLength) {
|
||||
/** @type {Record<string, unknown>} */
|
||||
const vmObject = {}
|
||||
for (const [key, value] of Object.entries(vm)) {
|
||||
if (!key.startsWith('$') && typeof value !== 'function') {
|
||||
vmObject[key] = value
|
||||
}
|
||||
}
|
||||
|
||||
if (!Array.isArray(vmObject.tags)) {
|
||||
vmObject.tags = []
|
||||
}
|
||||
|
||||
return { vm: vmObject, run, chainLength }
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {XoSr} sr
|
||||
* @param {RunContext} run
|
||||
* @returns {SrContext}
|
||||
*/
|
||||
export function buildSrContext(sr, run) {
|
||||
return {
|
||||
sr: {
|
||||
name_label: sr.name_label,
|
||||
type: sr.SR_type,
|
||||
description: sr.name_description,
|
||||
tags: Array.isArray(sr.tags) ? sr.tags : [],
|
||||
},
|
||||
run,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {XoBackupRepository} backupRepository
|
||||
* @param {RunContext} run
|
||||
* @returns {BackupRepositoryContext}
|
||||
*/
|
||||
export function buildBackupRepositoryContext(backupRepository, run) {
|
||||
let type
|
||||
try {
|
||||
type = parse(backupRepository.url).type
|
||||
} catch (error) {
|
||||
warn('cannot parse backup repository URL', { backupRepositoryId: backupRepository.id, error })
|
||||
}
|
||||
|
||||
return {
|
||||
backupRepository: {
|
||||
name: backupRepository.name,
|
||||
type,
|
||||
tags: [], // Placeholder - Backup repositories don't have tags yet
|
||||
},
|
||||
run,
|
||||
}
|
||||
}
|
||||
@@ -1,147 +0,0 @@
|
||||
import { describe, it } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
|
||||
import { buildRunContext, buildVmContext, buildSrContext, buildBackupRepositoryContext } from './_buildContext.mjs'
|
||||
import { BACKUP_EXPRESSION_CONTEXT } from '@vates/types/backup-expression-context'
|
||||
|
||||
describe('buildContext', () => {
|
||||
const date = new Date('2025-01-05T03:00:00Z')
|
||||
const runContext = buildRunContext(date, 'America/New_York')
|
||||
const expectedRunContext = {
|
||||
dayOfWeek: 6,
|
||||
dayOfMonth: 4,
|
||||
hour: 22,
|
||||
month: 1,
|
||||
year: 2025,
|
||||
}
|
||||
|
||||
it('buildRunContext', () => {
|
||||
assert.deepEqual(runContext, expectedRunContext)
|
||||
})
|
||||
|
||||
it('buildVmContext', () => {
|
||||
const vm1 = { name: 'name', $value: '$value', func: () => {} }
|
||||
const vmContext1 = buildVmContext(vm1, runContext, 3)
|
||||
assert.deepEqual(vmContext1, {
|
||||
vm: {
|
||||
name: 'name',
|
||||
tags: [],
|
||||
},
|
||||
run: expectedRunContext,
|
||||
chainLength: 3,
|
||||
})
|
||||
|
||||
const vm2 = { name: 'name', $value: '$value', func: () => {}, tags: ['tag'] }
|
||||
const vmContext2 = buildVmContext(vm2, runContext, undefined)
|
||||
assert.deepEqual(vmContext2, {
|
||||
vm: {
|
||||
name: 'name',
|
||||
tags: ['tag'],
|
||||
},
|
||||
run: expectedRunContext,
|
||||
chainLength: undefined,
|
||||
})
|
||||
|
||||
const vm3 = { name: 'name', $value: '$value', func: () => {}, tags: 'tag' }
|
||||
const vmContext3 = buildVmContext(vm3, runContext, undefined)
|
||||
assert.deepEqual(vmContext3, {
|
||||
vm: {
|
||||
name: 'name',
|
||||
tags: [],
|
||||
},
|
||||
run: expectedRunContext,
|
||||
chainLength: undefined,
|
||||
})
|
||||
})
|
||||
|
||||
it('buildVmContext exposes every field advertised by the schema', () => {
|
||||
// vm is an open context (buildVmContext copies through all real VM fields),
|
||||
// so we assert the schema's curated fields are a subset of the output, not equality.
|
||||
const vm = { name_label: 'name', power_state: 'Running', tags: ['tag'], $ref: 'ref', func: () => {} }
|
||||
const { vm: vmContext } = buildVmContext(vm, runContext)
|
||||
|
||||
for (const field of Object.keys(BACKUP_EXPRESSION_CONTEXT.vm)) {
|
||||
assert.ok(field in vmContext, `vm context is missing schema field: ${field}`)
|
||||
}
|
||||
})
|
||||
|
||||
it('buildSrContext', () => {
|
||||
const sr1 = {
|
||||
name_label: 'name_label',
|
||||
SR_type: 'type',
|
||||
name_description: 'description',
|
||||
ignored: 'ignored',
|
||||
}
|
||||
const srContext1 = buildSrContext(sr1, runContext)
|
||||
assert.deepEqual(srContext1, {
|
||||
sr: {
|
||||
name_label: 'name_label',
|
||||
type: 'type',
|
||||
description: 'description',
|
||||
tags: [],
|
||||
},
|
||||
run: expectedRunContext,
|
||||
})
|
||||
assert.deepEqual(Object.keys(srContext1.sr).sort(), Object.keys(BACKUP_EXPRESSION_CONTEXT.sr).sort())
|
||||
|
||||
const sr2 = {
|
||||
name_label: 'name_label',
|
||||
SR_type: 'type',
|
||||
name_description: 'description',
|
||||
tags: ['tag'],
|
||||
ignored: 'ignored',
|
||||
}
|
||||
const srContext2 = buildSrContext(sr2, runContext)
|
||||
assert.deepEqual(srContext2, {
|
||||
sr: {
|
||||
name_label: 'name_label',
|
||||
type: 'type',
|
||||
description: 'description',
|
||||
tags: ['tag'],
|
||||
},
|
||||
run: expectedRunContext,
|
||||
})
|
||||
assert.deepEqual(Object.keys(srContext2.sr).sort(), Object.keys(BACKUP_EXPRESSION_CONTEXT.sr).sort())
|
||||
})
|
||||
|
||||
it('buildBackupRepositoryContext', () => {
|
||||
const backupRepository1 = {
|
||||
name: 'name',
|
||||
url: 'nfs://host/path',
|
||||
ignored: 'ignored',
|
||||
}
|
||||
const backupRepositoryContext1 = buildBackupRepositoryContext(backupRepository1, runContext)
|
||||
assert.deepEqual(backupRepositoryContext1, {
|
||||
backupRepository: {
|
||||
name: 'name',
|
||||
type: 'nfs',
|
||||
tags: [],
|
||||
},
|
||||
run: expectedRunContext,
|
||||
})
|
||||
assert.deepEqual(
|
||||
Object.keys(backupRepositoryContext1.backupRepository).sort(),
|
||||
Object.keys(BACKUP_EXPRESSION_CONTEXT.backupRepository).sort()
|
||||
)
|
||||
|
||||
const backupRepository2 = {
|
||||
name: 'name',
|
||||
url: 'nfs://host/path',
|
||||
tags: [],
|
||||
ignored: 'ignored',
|
||||
}
|
||||
const backupRepositoryContext2 = buildBackupRepositoryContext(backupRepository2, runContext)
|
||||
assert.deepEqual(backupRepositoryContext2, {
|
||||
backupRepository: {
|
||||
name: 'name',
|
||||
type: 'nfs',
|
||||
tags: [],
|
||||
},
|
||||
run: expectedRunContext,
|
||||
})
|
||||
assert.deepEqual(
|
||||
Object.keys(backupRepositoryContext2.backupRepository).sort(),
|
||||
Object.keys(BACKUP_EXPRESSION_CONTEXT.backupRepository).sort()
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -1,24 +0,0 @@
|
||||
// @ts-check
|
||||
|
||||
import * as CM from 'complex-matcher'
|
||||
|
||||
/**
|
||||
* Parse and compile a complex-matcher expression into a predicate function.
|
||||
* Throws synchronously if the expression is syntactically invalid.
|
||||
*
|
||||
* @param {string} expression
|
||||
* @returns {(context: object) => boolean}
|
||||
*/
|
||||
export function compileExpression(expression) {
|
||||
return CM.parse(expression).createPredicate()
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if value is a non-empty string — i.e. a complex-matcher expression.
|
||||
*
|
||||
* @param {unknown} value
|
||||
* @returns {value is string}
|
||||
*/
|
||||
export function isExpression(value) {
|
||||
return typeof value === 'string' && value.length > 0 && !Number.isFinite(Number(value))
|
||||
}
|
||||
@@ -1,95 +0,0 @@
|
||||
import { describe, it } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
|
||||
import { compileExpression, isExpression } from './_expressionPredicate.mjs'
|
||||
|
||||
describe('compileExpression', () => {
|
||||
it('run:dayOfWeek:0', () => {
|
||||
const predicate = compileExpression('run:dayOfWeek:0')
|
||||
|
||||
assert(predicate({ run: { dayOfWeek: 0 } }))
|
||||
assert(!predicate({ run: { dayOfWeek: 1 } }))
|
||||
})
|
||||
|
||||
it('chainLength:>5', () => {
|
||||
const predicate = compileExpression('chainLength:>5')
|
||||
|
||||
assert(predicate({ chainLength: 6 }))
|
||||
assert(!predicate({ chainLength: 5 }))
|
||||
})
|
||||
|
||||
it('vm:tags:prod', () => {
|
||||
const predicate = compileExpression('vm:tags:prod')
|
||||
|
||||
assert(predicate({ vm: { tags: ['prod'] } }))
|
||||
assert(predicate({ vm: { tags: ['prod', 'test'] } }))
|
||||
assert(!predicate({ vm: { tags: ['test'] } }))
|
||||
assert(!predicate({ vm: { tags: [] } }))
|
||||
})
|
||||
|
||||
it('run:dayOfWeek:0 chainLength:>3', () => {
|
||||
const predicate = compileExpression('run:dayOfWeek:0 chainLength:>3')
|
||||
|
||||
assert(predicate({ run: { dayOfWeek: 0 }, chainLength: 6 }))
|
||||
assert(!predicate({ run: { dayOfWeek: 0 }, chainLength: 2 }))
|
||||
assert(!predicate({ run: { dayOfWeek: 1 }, chainLength: 6 }))
|
||||
})
|
||||
|
||||
it('|(run:dayOfWeek:0 chainLength:>6)', () => {
|
||||
const predicate = compileExpression('|(run:dayOfWeek:0 chainLength:>6)')
|
||||
|
||||
assert(predicate({ run: { dayOfWeek: 0 }, chainLength: 7 }))
|
||||
assert(predicate({ run: { dayOfWeek: 1 }, chainLength: 7 }))
|
||||
assert(predicate({ run: { dayOfWeek: 0 }, chainLength: 6 }))
|
||||
assert(!predicate({ run: { dayOfWeek: 1 }, chainLength: 6 }))
|
||||
})
|
||||
|
||||
it('missing field', () => {
|
||||
const predicate = compileExpression('run:dayOfWeek:0')
|
||||
|
||||
assert(predicate({ run: { dayOfWeek: 0 }, chainLength: 6 }))
|
||||
assert(!predicate({ chainLength: 6 }))
|
||||
assert(!predicate({ run: {}, chainLength: 6 }))
|
||||
})
|
||||
|
||||
it('null-checking', () => {
|
||||
const predicate = compileExpression('!vm')
|
||||
|
||||
assert(predicate({}))
|
||||
assert(!predicate({ vm: [{ vm: 'vm' }] }))
|
||||
})
|
||||
|
||||
it('throws on invalid expression', () => {
|
||||
assert.throws(() => compileExpression('vm:('))
|
||||
})
|
||||
})
|
||||
|
||||
describe('isExpression', () => {
|
||||
it('non-empty string', () => {
|
||||
assert(isExpression('vm:tags:test'))
|
||||
})
|
||||
|
||||
it('number', () => {
|
||||
assert(!isExpression(0))
|
||||
})
|
||||
|
||||
it('string[]', () => {
|
||||
assert(!isExpression(['string']))
|
||||
})
|
||||
|
||||
it('undefined', () => {
|
||||
assert(!isExpression(undefined))
|
||||
})
|
||||
|
||||
it('empty string', () => {
|
||||
assert(!isExpression(''))
|
||||
})
|
||||
|
||||
it('number', () => {
|
||||
assert(!isExpression('3'))
|
||||
})
|
||||
|
||||
it('number with spaces', () => {
|
||||
assert(!isExpression(' 5 '))
|
||||
})
|
||||
})
|
||||
@@ -1,7 +1,7 @@
|
||||
import { strict as assert } from 'node:assert'
|
||||
import test from 'node:test'
|
||||
import { execFile } from 'node:child_process'
|
||||
import { copyFile, mkdir, mkdtemp, rm, symlink, writeFile } 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'
|
||||
@@ -9,7 +9,6 @@ import { promisify } from 'node:util'
|
||||
import { randomBytes } from 'node:crypto'
|
||||
|
||||
import Disposable from 'promise-toolbox/Disposable'
|
||||
import * as tar from 'tar'
|
||||
|
||||
import { RemoteAdapter } from './RemoteAdapter.mjs'
|
||||
|
||||
@@ -72,83 +71,6 @@ test('fetchPartitionFiles resolves with a node:stream for every format', async t
|
||||
}
|
||||
})
|
||||
|
||||
async function readAll(stream) {
|
||||
const chunks = []
|
||||
for await (const chunk of stream) {
|
||||
chunks.push(chunk)
|
||||
}
|
||||
return Buffer.concat(chunks)
|
||||
}
|
||||
|
||||
async function listTgzEntries(archive, tmp) {
|
||||
const file = join(tmp, 'archive.tgz')
|
||||
await writeFile(file, archive)
|
||||
const entries = []
|
||||
await tar.t({ file, onReadEntry: entry => entries.push(entry.path.replace(/\/$/, '')) })
|
||||
return entries
|
||||
}
|
||||
|
||||
// The partition is mounted on the XOA/proxy: a guest symlink is resolved against the host root,
|
||||
// so following one would expose host files. Paths through a symlink are refused, and symlinks
|
||||
// met while walking a directory are skipped.
|
||||
test('file restore never follows symbolic links', async t => {
|
||||
const tmp = await mkdtemp(join(tmpdir(), 'xo-flr-symlink-'))
|
||||
t.after(() => rm(tmp, { recursive: true, force: true }))
|
||||
|
||||
// `host` stands for the XOA filesystem, `root` for the mounted guest partition
|
||||
const host = join(tmp, 'host')
|
||||
const root = join(tmp, 'root')
|
||||
await mkdir(host)
|
||||
await writeFile(join(host, 'secret.txt'), 'host secret')
|
||||
await mkdir(join(root, 'dir'), { recursive: true })
|
||||
await writeFile(join(root, 'dir', 'file.txt'), 'guest file')
|
||||
await symlink(host, join(root, 'absolute')) // like `ln -s / foo` in the guest
|
||||
await symlink('../../host', join(root, 'dir', 'relative'))
|
||||
await symlink('file.txt', join(root, 'dir', 'in-tree'))
|
||||
|
||||
const adapter = new RemoteAdapter({})
|
||||
adapter.getPartition = Disposable.factory(async function* () {
|
||||
yield root
|
||||
})
|
||||
|
||||
const refusedPaths = ['/absolute', '/absolute/secret.txt', '/dir/relative', '/dir/relative/host/secret.txt']
|
||||
|
||||
await t.test('listing refuses a path through a symlink', async () => {
|
||||
for (const path of refusedPaths) {
|
||||
await assert.rejects(adapter.listPartitionFiles('disk', 'partition', path), { code: 'ELINK_NOT_SUPPORTED' }, path)
|
||||
}
|
||||
})
|
||||
|
||||
await t.test('listing skips symlinks', async () => {
|
||||
assert.deepEqual(await adapter.listPartitionFiles('disk', 'partition', '/'), { 'dir/': {} })
|
||||
assert.deepEqual(await adapter.listPartitionFiles('disk', 'partition', '/dir'), { 'file.txt': {} })
|
||||
})
|
||||
|
||||
for (const format of ['tgz', 'zip']) {
|
||||
await t.test(`${format}: download refuses a path through a symlink`, async () => {
|
||||
for (const path of refusedPaths) {
|
||||
await assert.rejects(
|
||||
adapter.fetchPartitionFiles('disk', 'partition', ['/dir/file.txt', path], format),
|
||||
{ code: 'ELINK_NOT_SUPPORTED' },
|
||||
path
|
||||
)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
await t.test('tgz: symlinks inside a selected directory are skipped', async () => {
|
||||
const archive = await readAll(await adapter.fetchPartitionFiles('disk', 'partition', ['/dir'], 'tgz'))
|
||||
assert.deepEqual((await listTgzEntries(archive, tmp)).sort(), ['dir', 'dir/file.txt'])
|
||||
})
|
||||
|
||||
await t.test('zip: symlinks inside a selected directory are skipped', async () => {
|
||||
const archive = await readAll(await adapter.fetchPartitionFiles('disk', 'partition', ['/dir'], 'zip'))
|
||||
assert.ok(archive.includes('dir/file.txt'))
|
||||
assert.equal(archive.includes('dir/relative'), false)
|
||||
assert.equal(archive.includes('dir/in-tree'), false)
|
||||
})
|
||||
})
|
||||
|
||||
test('LVM file-restore against real losetup/dmsetup/lvm', { skip }, async t => {
|
||||
const tmp = await mkdtemp(join(tmpdir(), 'xo-flr-'))
|
||||
const adapter = new RemoteAdapter({})
|
||||
|
||||
@@ -66,29 +66,7 @@ export const toLvPartitions = (partitionId, originalVgName, lvItems) =>
|
||||
}))
|
||||
|
||||
const makeRelative = path => resolve('/', path).slice(1)
|
||||
|
||||
// The partition is mounted on the XOA/proxy, so the kernel resolves a guest symlink against the
|
||||
// host root: following one (e.g. `ln -s / foo` in the VM, then `/foo/etc`) would read host files.
|
||||
// Symlinks are therefore not supported by file restore: a path going through one is refused,
|
||||
// checked component by component with lstat. The mount is read-only, so no check/use race.
|
||||
export async function resolveWithoutSymlinks(rootPath, path) {
|
||||
const relativePath = makeRelative(path)
|
||||
let currentPath = rootPath
|
||||
for (const name of relativePath.split('/')) {
|
||||
if (name === '') {
|
||||
continue
|
||||
}
|
||||
currentPath = join(currentPath, name)
|
||||
const stats = await lstat(currentPath)
|
||||
if (stats.isSymbolicLink()) {
|
||||
const error = new Error(`symbolic links are not supported by file restore: ${path}`)
|
||||
error.code = 'ELINK_NOT_SUPPORTED'
|
||||
error.path = path
|
||||
throw error
|
||||
}
|
||||
}
|
||||
return relativePath
|
||||
}
|
||||
const resolveSubpath = (root, path) => resolve(root, makeRelative(path))
|
||||
|
||||
async function addZipEntries(zip, realBasePath, virtualBasePath, relativePaths) {
|
||||
for (const relativePath of relativePaths) {
|
||||
@@ -312,12 +290,6 @@ export const fileRestoreMethods = {
|
||||
const self = this
|
||||
Disposable.use(async function* () {
|
||||
const path = yield self.getPartition(diskId, partitionId)
|
||||
// validated before resolving the promise, so a refused path rejects instead of
|
||||
// producing a truncated archive
|
||||
const relativePaths = []
|
||||
for (const requestedPath of paths) {
|
||||
relativePaths.push(await resolveWithoutSymlinks(path, requestedPath))
|
||||
}
|
||||
let outputStream
|
||||
|
||||
if (format === 'tgz') {
|
||||
@@ -326,13 +298,7 @@ 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.
|
||||
//
|
||||
// symlinks found while walking the selected directories are skipped, like in the zip
|
||||
// format and the file listing
|
||||
const pack = tar.c(
|
||||
{ cwd: path, gzip: true, jobs: 1, filter: (_, stats) => !stats.isSymbolicLink() },
|
||||
relativePaths
|
||||
)
|
||||
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
|
||||
@@ -350,7 +316,7 @@ export const fileRestoreMethods = {
|
||||
// appear as a freeze with no response sent.
|
||||
outputStream = zip.outputStream
|
||||
resolve(zip.outputStream)
|
||||
await addZipEntries(zip, path, '', relativePaths)
|
||||
await addZipEntries(zip, path, '', paths.map(makeRelative))
|
||||
zip.end()
|
||||
} else {
|
||||
throw new Error('unsupported format ' + format)
|
||||
@@ -365,23 +331,17 @@ export const fileRestoreMethods = {
|
||||
},
|
||||
|
||||
async *getDisk(diskId) {
|
||||
try {
|
||||
if (this._useGetDiskLegacy) {
|
||||
yield* getDiskLegacy(this._handler, diskId)
|
||||
return
|
||||
}
|
||||
const handler = this._handler
|
||||
// this is a disposable
|
||||
const mountDir = yield getTmpDir()
|
||||
// this is also a disposable
|
||||
yield mount(handler, diskId, mountDir)
|
||||
// this will yield disk path to caller
|
||||
yield `${mountDir}/vhd0`
|
||||
} finally {
|
||||
// Disposable.factory disposes by calling gen.return(), which runs this finally before
|
||||
// the mount/tmpdir disposers — i.e. exactly as the disk is unmounted.
|
||||
this._partitionsCache.delete(diskId)
|
||||
if (this._useGetDiskLegacy) {
|
||||
yield* getDiskLegacy(this._handler, diskId)
|
||||
return
|
||||
}
|
||||
const handler = this._handler
|
||||
// this is a disposable
|
||||
const mountDir = yield getTmpDir()
|
||||
// this is also a disposable
|
||||
yield mount(handler, diskId, mountDir)
|
||||
// this will yield disk path to caller
|
||||
yield `${mountDir}/vhd0`
|
||||
},
|
||||
|
||||
// partitionId values:
|
||||
@@ -411,7 +371,7 @@ export const fileRestoreMethods = {
|
||||
|
||||
listPartitionFiles(diskId, partitionId, path) {
|
||||
return Disposable.use(this.getPartition(diskId, partitionId), async rootPath => {
|
||||
path = join(rootPath, await resolveWithoutSymlinks(rootPath, path))
|
||||
path = resolveSubpath(rootPath, path)
|
||||
const entriesMap = {}
|
||||
await asyncEach(
|
||||
await readdir(path),
|
||||
@@ -437,13 +397,7 @@ export const fileRestoreMethods = {
|
||||
},
|
||||
|
||||
listPartitions(diskId) {
|
||||
const cache = this._partitionsCache
|
||||
const cached = cache.get(diskId)
|
||||
if (cached !== undefined) {
|
||||
return cached
|
||||
}
|
||||
|
||||
const pPartitions = Disposable.use(this.getDisk(diskId), async devicePath => {
|
||||
return Disposable.use(this.getDisk(diskId), async devicePath => {
|
||||
// partx may return empty on FUSE-backed files (vhd0); a loop device
|
||||
// presents proper block-device semantics that partx reads reliably.
|
||||
// losetup may itself fail if the FUSE mount isn't fully ready yet —
|
||||
@@ -461,14 +415,11 @@ export const fileRestoreMethods = {
|
||||
}
|
||||
}
|
||||
|
||||
// direct listing failed, try with lvm listing
|
||||
if (partitions.length === 0) {
|
||||
debug('direct listing of the volume partition failed, try to read through LVM')
|
||||
try {
|
||||
// handle potential raw LVM physical volume
|
||||
return await this._listLvmLogicalVolumes(devicePath, undefined, partitions)
|
||||
} catch (error) {
|
||||
warn('LVM listing of this volume failed ', error)
|
||||
return []
|
||||
}
|
||||
}
|
||||
@@ -504,16 +455,6 @@ export const fileRestoreMethods = {
|
||||
})
|
||||
return results
|
||||
})
|
||||
|
||||
// The entry is evicted on disk unmount (see getDisk)
|
||||
// a failed probe is not cached so the next call retries.
|
||||
cache.set(diskId, pPartitions)
|
||||
pPartitions.catch(() => {
|
||||
if (cache.get(diskId) === pPartitions) {
|
||||
cache.delete(diskId)
|
||||
}
|
||||
})
|
||||
return pPartitions
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -294,9 +294,9 @@ export const importIncrementalVm = defer(async function importIncrementalVm(
|
||||
await asyncMap(Object.values(vdiVbds), vbd =>
|
||||
xapi.VBD_create({
|
||||
...vbd,
|
||||
// an uncached live mount serves its disk read only: attach it as such, instead of letting
|
||||
// the guest discover it through I/O errors on its first write
|
||||
mode: isLiveMounted && vdi.liveMountedReadOnly ? 'RO' : vbd.mode,
|
||||
// a live mount serves its disk read only: attach it as such, instead of letting the
|
||||
// guest discover it through I/O errors on its first write
|
||||
mode: isLiveMounted ? 'RO' : vbd.mode,
|
||||
VDI: newVdi.$ref,
|
||||
VM: vmRef,
|
||||
})
|
||||
@@ -307,16 +307,9 @@ export const importIncrementalVm = defer(async function importIncrementalVm(
|
||||
})
|
||||
|
||||
// 3.5. Destroy old VDIs that are no longer attached to the VM.
|
||||
// Some storage backends refuse to destroy a VDI that still has snapshot children.
|
||||
// Log it and leave it for later cleanup.
|
||||
await asyncMap([...oldVdiRefs], ref =>
|
||||
xapi.call('VDI.destroy', ref).catch(error =>
|
||||
Task.warning('failed to destroy orphaned VDI', {
|
||||
vdi: xapi.getObject(ref, undefined)?.uuid ?? ref,
|
||||
error,
|
||||
})
|
||||
)
|
||||
)
|
||||
// Uses ignoreErrors because some storage backends refuse to destroy a VDI that still has snapshot children;
|
||||
// those VDIs will become truly orphaned once the old snapshot VMs are cleaned up by _deleteOldEntries.
|
||||
await asyncMap([...oldVdiRefs], ref => ignoreErrors.call(xapi.call('VDI.destroy', ref)))
|
||||
|
||||
// 4. For updates, destroy existing VIFs before recreating them.
|
||||
if (isUpdate) {
|
||||
|
||||
@@ -60,7 +60,7 @@ const parsePartxLine = createParser({
|
||||
export async function listPartitions(devicePath) {
|
||||
const parts = await fromCallback(execFile, 'partx', [
|
||||
'--bytes',
|
||||
'--output=START,SIZE,NAME,UUID,TYPE',
|
||||
'--output=NR,START,SIZE,NAME,UUID,TYPE',
|
||||
'--pairs',
|
||||
devicePath,
|
||||
]).catch(error => {
|
||||
|
||||
@@ -10,8 +10,6 @@ import { FullRemote } from './_vmRunners/FullRemote.mjs'
|
||||
import { IncrementalRemote } from './_vmRunners/IncrementalRemote.mjs'
|
||||
import { Throttle } from '@vates/generator-toolbox'
|
||||
import createStreamThrottle from './_createStreamThrottle.mjs'
|
||||
import { compileExpression, isExpression } from '../_expressionPredicate.mjs'
|
||||
import { buildRunContext, buildVmContext } from '../_buildContext.mjs'
|
||||
|
||||
const noop = Function.prototype
|
||||
|
||||
@@ -62,25 +60,21 @@ export const VmsRemote = class RemoteVmsBackupRunner extends Abstract {
|
||||
return
|
||||
}
|
||||
|
||||
const runContext = job.runContext ?? buildRunContext(new Date(), settings.timezone)
|
||||
const predicate = isExpression(settings.vmFilter) ? compileExpression(settings.vmFilter) : null
|
||||
|
||||
const vmsUuids = await sourceRemoteAdapter.listAllVms()
|
||||
|
||||
const queue = new Set(vmsUuids)
|
||||
|
||||
Task.info('vms', { vms: vmsUuids })
|
||||
let nbVms = vmsUuids.length
|
||||
const nbVms = vmsUuids.length
|
||||
let nbVmsDone = 0
|
||||
|
||||
remoteAdapters = getAdaptersByRemote(remoteAdapters)
|
||||
const allSettings = this._job.settings
|
||||
const baseSettings = this._baseSettings
|
||||
|
||||
const queue = new Set(vmsUuids)
|
||||
const taskByVmId = {}
|
||||
const nTriesByVmId = {}
|
||||
|
||||
const handleVm = async vmUuid => {
|
||||
const handleVm = vmUuid => {
|
||||
if (nTriesByVmId[vmUuid] === undefined) {
|
||||
nTriesByVmId[vmUuid] = 0
|
||||
}
|
||||
@@ -90,26 +84,12 @@ export const VmsRemote = class RemoteVmsBackupRunner extends Abstract {
|
||||
const vmSettings = { ...settings, ...allSettings[vmUuid] }
|
||||
const isLastRun = nTriesByVmId[vmUuid] === vmSettings.nRetriesVmBackupFailures + 1
|
||||
|
||||
const vmBackups = await sourceRemoteAdapter.listVmBackups(vmUuid, ({ mode }) => mode === job.mode)
|
||||
|
||||
// avoiding to create tasks for empty directories
|
||||
if (vmBackups.length === 0) {
|
||||
nbVms--
|
||||
return
|
||||
}
|
||||
|
||||
if (predicate !== null && !predicate(buildVmContext(vmBackups.at(-1).vm, runContext))) {
|
||||
nbVms--
|
||||
return
|
||||
}
|
||||
|
||||
const opts = {
|
||||
baseSettings,
|
||||
config,
|
||||
job,
|
||||
healthCheckSr,
|
||||
remoteAdapters,
|
||||
runContext,
|
||||
schedule,
|
||||
settings: vmSettings,
|
||||
sourceRemoteAdapter,
|
||||
@@ -126,39 +106,45 @@ export const VmsRemote = class RemoteVmsBackupRunner extends Abstract {
|
||||
throw new Error(`Job mode ${job.mode} not implemented for mirror backup`)
|
||||
}
|
||||
|
||||
if (taskByVmId[vmUuid] === undefined) {
|
||||
taskByVmId[vmUuid] = new Task(taskStart)
|
||||
}
|
||||
const task = taskByVmId[vmUuid]
|
||||
// error has to be caught in the task to prevent its failure, but handled outside the task to execute another task.run()
|
||||
let taskError
|
||||
return task
|
||||
.runInside(async () =>
|
||||
vmBackup.run().catch(error => {
|
||||
taskError = error
|
||||
})
|
||||
)
|
||||
.then(result => {
|
||||
if (taskError === undefined) {
|
||||
nbVmsDone++
|
||||
return task.success(result)
|
||||
return sourceRemoteAdapter
|
||||
.listVmBackups(vmUuid, ({ mode }) => mode === job.mode)
|
||||
.then(vmBackups => {
|
||||
// avoiding to create tasks for empty directories
|
||||
if (vmBackups.length > 0) {
|
||||
if (taskByVmId[vmUuid] === undefined) {
|
||||
taskByVmId[vmUuid] = new Task(taskStart)
|
||||
}
|
||||
const task = taskByVmId[vmUuid]
|
||||
// error has to be caught in the task to prevent its failure, but handled outside the task to execute another task.run()
|
||||
let taskError
|
||||
return task
|
||||
.runInside(async () =>
|
||||
vmBackup.run().catch(error => {
|
||||
taskError = error
|
||||
})
|
||||
)
|
||||
.then(result => {
|
||||
if (taskError === undefined) {
|
||||
nbVmsDone++
|
||||
return task.success(result)
|
||||
}
|
||||
if (isLastRun) {
|
||||
nbVmsDone++
|
||||
return task.failure(taskError)
|
||||
}
|
||||
Task.set('progress', Math.round((nbVmsDone * 100) / nbVms))
|
||||
// don't end the task
|
||||
task.warning(`Retry the VM mirror backup due to an error`, {
|
||||
attempt: nTriesByVmId[vmUuid],
|
||||
error: taskError.message,
|
||||
isRetry: true,
|
||||
})
|
||||
queue.add(vmUuid)
|
||||
})
|
||||
.catch(noop)
|
||||
}
|
||||
if (isLastRun) {
|
||||
nbVmsDone++
|
||||
return task.failure(taskError)
|
||||
}
|
||||
Task.set('progress', Math.round((nbVmsDone * 100) / nbVms))
|
||||
// don't end the task
|
||||
task.warning(`Retry the VM mirror backup due to an error`, {
|
||||
attempt: nTriesByVmId[vmUuid],
|
||||
error: taskError.message,
|
||||
isRetry: true,
|
||||
})
|
||||
queue.add(vmUuid)
|
||||
})
|
||||
.catch(noop)
|
||||
}
|
||||
|
||||
const { concurrency } = settings
|
||||
const _handleVm = !concurrency ? handleVm : limitConcurrency(concurrency)(handleVm)
|
||||
|
||||
|
||||
@@ -12,7 +12,6 @@ import { Throttle } from '@vates/generator-toolbox'
|
||||
import { asyncEach } from '@vates/async-each'
|
||||
import createStreamThrottle from './_createStreamThrottle.mjs'
|
||||
import { selectSynchronizedSnapshotVms } from './_selectSynchronizedSnapshotVms.mjs'
|
||||
import { buildRunContext } from '../_buildContext.mjs'
|
||||
|
||||
const noop = Function.prototype
|
||||
|
||||
@@ -69,7 +68,6 @@ export const VmsXapi = class VmsXapiBackupRunner extends Abstract {
|
||||
const getSnapshotNameLabel = this._getSnapshotNameLabel
|
||||
const schedule = this._schedule
|
||||
const settings = this._settings
|
||||
const runContext = job.runContext ?? buildRunContext(new Date(), settings.timezone)
|
||||
|
||||
const throttleGenerator = new Throttle(settings.maxExportRate)
|
||||
const throttleStream = createStreamThrottle(settings.maxExportRate)
|
||||
@@ -153,7 +151,6 @@ export const VmsXapi = class VmsXapiBackupRunner extends Abstract {
|
||||
healthCheckSr,
|
||||
job,
|
||||
remoteAdapters,
|
||||
runContext,
|
||||
schedule,
|
||||
settings: vmSettings,
|
||||
srs,
|
||||
@@ -252,7 +249,6 @@ export const VmsXapi = class VmsXapiBackupRunner extends Abstract {
|
||||
throttleGenerator,
|
||||
throttleStream,
|
||||
vm,
|
||||
runContext,
|
||||
}
|
||||
|
||||
const vmBackup = this._getVmBackup(job.mode, opts)
|
||||
|
||||
@@ -4,6 +4,7 @@ import { AbstractRemote } from './_AbstractRemote.mjs'
|
||||
import { FullRemoteWriter } from '../_writers/FullRemoteWriter.mjs'
|
||||
import { forkStreamUnpipe } from '../_forkStreamUnpipe.mjs'
|
||||
import { watchStreamSize } from '../../_watchStreamSize.mjs'
|
||||
import { SourceReadTask } from '../../_SourceReadTask.mjs'
|
||||
import { AggregatedFullRemoteWriter } from '../_writers/AggregatedFullRemoteWriter.mjs'
|
||||
import { Task } from '@vates/task'
|
||||
|
||||
@@ -24,7 +25,8 @@ export const FullRemote = class FullRemoteVmBackupRunner extends AbstractRemote
|
||||
let nbTransferredVms = 0
|
||||
for (const metadata of transferList) {
|
||||
const stream = this._throttleStream(await this._sourceRemoteAdapter.readFullVmBackup(metadata))
|
||||
const sizeContainer = watchStreamSize(stream)
|
||||
// the backup is read once, whatever the number of writers
|
||||
const sizeContainer = watchStreamSize(stream, { size: 0, readTask: new SourceReadTask({ name: 'read' }) })
|
||||
let checksum
|
||||
try {
|
||||
// the unencrypted destinations store the same data as the source: no need to compute their checksum again
|
||||
@@ -53,7 +55,7 @@ export const FullRemote = class FullRemoteVmBackupRunner extends AbstractRemote
|
||||
'writer.run()'
|
||||
)
|
||||
// for healthcheck
|
||||
this._vm = metadata.vm
|
||||
this._tags = metadata.vm.tags
|
||||
nbTransferredVms++
|
||||
Task.set('progress', Math.round((nbTransferredVms * 100) / nbTransferrableVms))
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import { forkStreamUnpipe } from '../_forkStreamUnpipe.mjs'
|
||||
import { FullRemoteWriter } from '../_writers/FullRemoteWriter.mjs'
|
||||
import { FullXapiWriter } from '../_writers/FullXapiWriter.mjs'
|
||||
import { watchStreamSize } from '../../_watchStreamSize.mjs'
|
||||
import { SourceReadTask } from '../../_SourceReadTask.mjs'
|
||||
import { AbstractXapi } from './_AbstractXapi.mjs'
|
||||
import { AggregatedFullRemoteWriter } from '../_writers/AggregatedFullRemoteWriter.mjs'
|
||||
import { AggregatedFullXapiWriter } from '../_writers/AggregatedFullXapiWriter.mjs'
|
||||
@@ -78,7 +79,8 @@ export const FullXapi = class FullXapiVmBackupRunner extends AbstractXapi {
|
||||
maxStreamLength += XVA_BLOCK_SIZE * nbBlocks + headersSize
|
||||
}
|
||||
|
||||
const sizeContainer = watchStreamSize(stream)
|
||||
// the export is read once, whatever the number of writers
|
||||
const sizeContainer = watchStreamSize(stream, { size: 0, readTask: new SourceReadTask({ name: 'read' }) })
|
||||
|
||||
const transferStart = Date.now()
|
||||
await this._callWriters(
|
||||
|
||||
@@ -13,6 +13,7 @@ import { SynchronizedDisk, ThrottledDisk } from '@xen-orchestra/disk-transform'
|
||||
import { AggregatedIncrementalRemoteWriter } from '../_writers/AggregatedIncrementalRemoteWriter.mjs'
|
||||
import { Task } from '@vates/task'
|
||||
import { TaskProgressHandler } from './_TaskProgressHandler.mjs'
|
||||
import { meterIncrementalExport } from '../../_SourceReadTask.mjs'
|
||||
|
||||
const { warn } = createLogger('xo:backups:Incrementalremote')
|
||||
class IncrementalRemoteVmBackupRunner extends AbstractRemote {
|
||||
@@ -62,33 +63,14 @@ class IncrementalRemoteVmBackupRunner extends AbstractRemote {
|
||||
})
|
||||
// yeah , let's go
|
||||
}
|
||||
|
||||
/**
|
||||
* the block files can be copied as stored, never decompressed nor recompressed, if all the writers write VHD
|
||||
* directories with the same compression (the source disks must also use it, checked per disk when reading)
|
||||
* @returns {string | undefined} the common compression, undefined if a writer writes plain VHD files or if they differ
|
||||
*/
|
||||
#getRawBlocksCompression() {
|
||||
const compressions = new Set([...this._writers].map(writer => writer.getVhdDirectoryCompression()))
|
||||
// a single undefined value means plain VHD files on every writer: no raw blocks either
|
||||
return compressions.size === 1 ? [...compressions][0] : undefined
|
||||
}
|
||||
|
||||
async _run() {
|
||||
const transferList = await this._computeTransferList(({ mode }) => mode === 'delta')
|
||||
// the source remote writes with the same compression as all the writers: the blocks can be copied as stored
|
||||
// this is based on the remote configurations, each source disk checks its own compression since it may predate a
|
||||
// configuration change, and falls back to a normal read
|
||||
const writersCompression = this.#getRawBlocksCompression()
|
||||
const rawBlocksCompression =
|
||||
writersCompression === this._sourceRemoteAdapter.getVhdDirectoryCompression() ? writersCompression : undefined
|
||||
const nbTransferrableVms = transferList.length
|
||||
let nbTransferredVms = 0
|
||||
for (const metadata of transferList) {
|
||||
assert.strictEqual(metadata.mode, 'delta')
|
||||
const incrementalExport = await this._sourceRemoteAdapter.readIncrementalVmBackup(metadata, undefined, {
|
||||
useChain: false,
|
||||
rawBlocksCompression,
|
||||
})
|
||||
// don't trust metadata too much
|
||||
// recompute if it's a base backup
|
||||
@@ -96,11 +78,7 @@ class IncrementalRemoteVmBackupRunner extends AbstractRemote {
|
||||
const isVhdDifferencing = {}
|
||||
|
||||
for (const key in incrementalExport.disks) {
|
||||
let disk = incrementalExport.disks[key]
|
||||
isVhdDifferencing[key] = disk.isDifferencing()
|
||||
disk.addProgressHandler(new TaskProgressHandler())
|
||||
disk = new ThrottledDisk(disk, this._throttleGenerator)
|
||||
incrementalExport.disks[key] = new SynchronizedDisk(disk)
|
||||
isVhdDifferencing[key] = incrementalExport.disks[key].isDifferencing()
|
||||
}
|
||||
|
||||
const hasDifferencingDisk = Object.values(isVhdDifferencing).includes(true)
|
||||
@@ -116,22 +94,41 @@ class IncrementalRemoteVmBackupRunner extends AbstractRemote {
|
||||
await this._selectBaseVm(metadata)
|
||||
await this._callWriters(writer => writer.prepare({ isBase: metadata.isBase }), 'writer.prepare()')
|
||||
|
||||
await this._callWriters(
|
||||
writer =>
|
||||
writer.transfer({
|
||||
deltaExport: forkDeltaExport(incrementalExport, writer.constructor.name),
|
||||
includeNonNbdQcow2Fix: metadata.includeNonNbdQcow2Fix,
|
||||
isVhdDifferencing,
|
||||
timestamp: metadata.timestamp,
|
||||
vm: metadata.vm,
|
||||
vmSnapshot: metadata.vmSnapshot,
|
||||
}),
|
||||
'writer.transfer()'
|
||||
)
|
||||
// one task per restore point, holding the reading of its disks from the source remote: each disk is read once,
|
||||
// whatever the number of writers
|
||||
// not `id` nor `type`: xo-web would display it as a remote task
|
||||
const readTask = new Task({
|
||||
properties: { name: 'read', remoteId: this.job.sourceRemote, timestamp: metadata.timestamp },
|
||||
})
|
||||
await readTask.runInside(() => meterIncrementalExport(incrementalExport))
|
||||
for (const key in incrementalExport.disks) {
|
||||
const disk = incrementalExport.disks[key]
|
||||
disk.addProgressHandler(new TaskProgressHandler())
|
||||
incrementalExport.disks[key] = new SynchronizedDisk(new ThrottledDisk(disk, this._throttleGenerator))
|
||||
}
|
||||
|
||||
try {
|
||||
await this._callWriters(
|
||||
writer =>
|
||||
writer.transfer({
|
||||
deltaExport: forkDeltaExport(incrementalExport, writer.constructor.name),
|
||||
includeNonNbdQcow2Fix: metadata.includeNonNbdQcow2Fix,
|
||||
isVhdDifferencing,
|
||||
timestamp: metadata.timestamp,
|
||||
vm: metadata.vm,
|
||||
vmSnapshot: metadata.vmSnapshot,
|
||||
}),
|
||||
'writer.transfer()'
|
||||
)
|
||||
} catch (error) {
|
||||
readTask.failure(error)
|
||||
throw error
|
||||
}
|
||||
readTask.success()
|
||||
|
||||
await this._callWriters(writer => writer.cleanup(), 'writer.cleanup()')
|
||||
// for healthcheck
|
||||
this._vm = metadata.vm
|
||||
this._tags = metadata.vm.tags
|
||||
nbTransferredVms++
|
||||
Task.set('progress', Math.round((nbTransferredVms * 100) / nbTransferrableVms))
|
||||
}
|
||||
|
||||
@@ -18,19 +18,11 @@ import { ThrottledDisk, SynchronizedDisk } from '@xen-orchestra/disk-transform'
|
||||
import { AggregatedIncrementalRemoteWriter } from '../_writers/AggregatedIncrementalRemoteWriter.mjs'
|
||||
import { AggregatedIncrementalXapiWriter } from '../_writers/AggregatedIncrementalXapiWriter.mjs'
|
||||
import { TaskProgressHandler } from './_TaskProgressHandler.mjs'
|
||||
import { compileExpression, isExpression } from '../../_expressionPredicate.mjs'
|
||||
import { buildVmContext } from '../../_buildContext.mjs'
|
||||
import { meterIncrementalExport } from '../../_SourceReadTask.mjs'
|
||||
|
||||
const { debug } = createLogger('xo:backups:IncrementalXapiVmBackup')
|
||||
|
||||
export const IncrementalXapi = class IncrementalXapiVmBackupRunner extends AbstractXapi {
|
||||
constructor(props) {
|
||||
super(props)
|
||||
|
||||
const fullInterval = this._settings.fullInterval
|
||||
this._fullIntervalPredicate = isExpression(fullInterval) ? compileExpression(fullInterval) : null
|
||||
}
|
||||
|
||||
_getWriters() {
|
||||
return [
|
||||
IncrementalRemoteWriter,
|
||||
@@ -57,8 +49,12 @@ export const IncrementalXapi = class IncrementalXapiVmBackupRunner extends Abstr
|
||||
preferNbd: this._settings.preferNbd,
|
||||
})
|
||||
|
||||
// specific to the XAPI disks: read before they are wrapped
|
||||
const useNbd = Object.values(deltaExport.disks).some(disk => disk.useNbd())
|
||||
// each disk is read once, whatever the number of writers
|
||||
meterIncrementalExport(deltaExport)
|
||||
|
||||
const isVhdDifferencing = {}
|
||||
let useNbd = false
|
||||
for (const key in deltaExport.disks) {
|
||||
let disk = deltaExport.disks[key]
|
||||
disk.addProgressHandler(new TaskProgressHandler())
|
||||
@@ -66,7 +62,6 @@ export const IncrementalXapi = class IncrementalXapiVmBackupRunner extends Abstr
|
||||
if (!isFull && !isVhdDifferencing[key] && key !== exportedVm.$suspend_VDI?.$ref) {
|
||||
Task.warning('Backup fell back to a full')
|
||||
}
|
||||
useNbd = useNbd || disk.useNbd()
|
||||
disk = new ThrottledDisk(disk, this._throttleGenerator)
|
||||
deltaExport.disks[key] = new SynchronizedDisk(disk)
|
||||
}
|
||||
@@ -238,17 +233,15 @@ export const IncrementalXapi = class IncrementalXapiVmBackupRunner extends Abstr
|
||||
}
|
||||
|
||||
// we do tafter checkbasevdis because we want the writer to know the target VM
|
||||
// especially on replication when we always update the same VM
|
||||
// especially on replication when we alwayr update the same VM
|
||||
const fullInterval = this._settings.fullInterval
|
||||
const chainLength = (deltaChainLength ?? 0) + 1
|
||||
if (isExpression(fullInterval)) {
|
||||
const context = buildVmContext(this._vm, this._runContext, chainLength)
|
||||
if (this._fullIntervalPredicate(context)) {
|
||||
debug('forcing full backup: fullInterval expression matched', { fullInterval })
|
||||
return
|
||||
}
|
||||
} else if (fullInterval !== 0 && fullInterval <= chainLength) {
|
||||
debug('not using base VM because fullInterval reached', { fullInterval, chainLength })
|
||||
if (fullInterval !== 0 && fullInterval <= deltaChainLength + 1) {
|
||||
debug('not using base VM because fullInterval reached', {
|
||||
fullInterval,
|
||||
deltaChainLength,
|
||||
eq: fullInterval < deltaChainLength + 1,
|
||||
dc1: deltaChainLength + 1,
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import { asyncMap } from '@xen-orchestra/async-map'
|
||||
import { createLogger } from '@xen-orchestra/log'
|
||||
import { Task } from '@vates/task'
|
||||
import { compileExpression, isExpression } from '../../_expressionPredicate.mjs'
|
||||
import { buildVmContext } from '../../_buildContext.mjs'
|
||||
|
||||
const { debug, warn } = createLogger('xo:backups:AbstractVmRunner')
|
||||
|
||||
@@ -75,58 +73,24 @@ export const Abstract = class AbstractVmBackupRunner {
|
||||
}
|
||||
|
||||
// check if current VM has tags
|
||||
const tags = this._vm.tags
|
||||
const tags = this._tags
|
||||
|
||||
// accept both 'xo:no-health-check' and 'xo:no-health-check=reason'
|
||||
if (tags.some(t => t.startsWith('xo:no-health-check'))) {
|
||||
const vmAlwaysIgnored = tags.some(t => t.startsWith('xo:no-health-check'))
|
||||
const intersect = !vmAlwaysIgnored && settings.healthCheckVmsWithTags.some(t => tags.includes(t))
|
||||
|
||||
if (vmAlwaysIgnored || (settings.healthCheckVmsWithTags.length !== 0 && !intersect)) {
|
||||
// create a task to have an info in the logs and reports
|
||||
return Task.run(
|
||||
{
|
||||
properties: {
|
||||
name: 'health check',
|
||||
},
|
||||
properties: { name: 'health check' },
|
||||
},
|
||||
() => {
|
||||
Task.info(`This VM is excluded from health checks via tag`)
|
||||
Task.info(`This VM doesn't match the health check's tags for this schedule`)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
if (isExpression(settings.healthCheckVmsWithTags)) {
|
||||
const context = buildVmContext(this._vm, this._runContext)
|
||||
if (!this._healthCheckPredicate(context)) {
|
||||
return Task.run(
|
||||
{
|
||||
properties: { name: 'health check' },
|
||||
},
|
||||
() => {
|
||||
Task.info(`VM did not match healthCheckVmsWithTags expression`)
|
||||
}
|
||||
)
|
||||
}
|
||||
} else {
|
||||
const intersect = settings.healthCheckVmsWithTags.some(t => tags.includes(t))
|
||||
if (settings.healthCheckVmsWithTags.length !== 0 && !intersect) {
|
||||
// create a task to have an info in the logs and reports
|
||||
return Task.run(
|
||||
{
|
||||
properties: { name: 'health check' },
|
||||
},
|
||||
() => {
|
||||
Task.info(`This VM doesn't match the health check's tags for this schedule`)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
await this._callWriters(writer => writer.healthCheck(), 'writer.healthCheck()')
|
||||
}
|
||||
|
||||
_compileHealthCheckPredicate() {
|
||||
const { healthCheckVmsWithTags } = this._settings
|
||||
if (isExpression(healthCheckVmsWithTags)) {
|
||||
this._healthCheckPredicate = compileExpression(healthCheckVmsWithTags)
|
||||
} else {
|
||||
this._healthCheckPredicate = undefined
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,7 +20,6 @@ export const AbstractRemote = class AbstractRemoteVmBackupRunner extends Abstrac
|
||||
job,
|
||||
healthCheckSr,
|
||||
remoteAdapters,
|
||||
runContext,
|
||||
schedule,
|
||||
settings,
|
||||
sourceRemoteAdapter,
|
||||
@@ -41,14 +40,11 @@ export const AbstractRemote = class AbstractRemoteVmBackupRunner extends Abstrac
|
||||
this._throttleGenerator = throttleGenerator
|
||||
this._throttleStream = throttleStream
|
||||
this._vmUuid = vmUuid
|
||||
this._runContext = runContext
|
||||
|
||||
const allSettings = job.settings
|
||||
const writers = new Set()
|
||||
this._writers = writers
|
||||
|
||||
this._compileHealthCheckPredicate()
|
||||
|
||||
const [BackupWriter, AggregratedBackupWriter] = this._getRemoteWriters()
|
||||
if (settings.distributeBackups) {
|
||||
writers.add(
|
||||
|
||||
@@ -36,7 +36,6 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
|
||||
job,
|
||||
remoteAdapters,
|
||||
remotes,
|
||||
runContext,
|
||||
schedule,
|
||||
settings,
|
||||
srs,
|
||||
@@ -64,13 +63,12 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
|
||||
this.timestamp = undefined
|
||||
|
||||
// VM currently backed up
|
||||
const tags = vm.tags
|
||||
const tags = (this._tags = vm.tags)
|
||||
|
||||
// VM (snapshot) that is really exported
|
||||
this._exportedVm = undefined
|
||||
this._synchronizedSnapshotTimestamp = synchronizedSnapshotTimestamp
|
||||
this._vm = vm
|
||||
this._runContext = runContext
|
||||
|
||||
this._getSnapshotNameLabel = getSnapshotNameLabel
|
||||
this._isIncremental = job.mode === 'delta'
|
||||
@@ -92,9 +90,6 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
|
||||
settings.offlineSnapshot = true
|
||||
}
|
||||
this._settings = settings
|
||||
|
||||
this._compileHealthCheckPredicate()
|
||||
|
||||
// Create writers
|
||||
{
|
||||
const writers = new Set()
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { describe, it } from 'node:test'
|
||||
import { Task } from '@vates/task'
|
||||
|
||||
import { TaskProgressHandler } from './_TaskProgressHandler.mjs'
|
||||
|
||||
async function collectProgress(fn) {
|
||||
const progress = []
|
||||
const task = new Task({
|
||||
properties: { name: 'transfer' },
|
||||
onProgress(event) {
|
||||
if (event.type === 'property' && event.name === 'progress') {
|
||||
progress.push(event.value)
|
||||
}
|
||||
},
|
||||
})
|
||||
await task.run(fn)
|
||||
return progress
|
||||
}
|
||||
|
||||
describe('TaskProgressHandler', () => {
|
||||
it('throttles the intermediate steps', async () => {
|
||||
const progress = await collectProgress(async () => {
|
||||
const progressHandler = new TaskProgressHandler()
|
||||
for (let i = 1; i < 1000; i++) {
|
||||
await progressHandler.setProgress(i / 1000)
|
||||
}
|
||||
})
|
||||
// initial value + at most one emit per percent
|
||||
assert.ok(progress.length <= 101, `${progress.length} emits`)
|
||||
})
|
||||
|
||||
it('always emits the end, even when the last step is under the threshold', async () => {
|
||||
const progress = await collectProgress(async () => {
|
||||
const progressHandler = new TaskProgressHandler()
|
||||
await progressHandler.setProgress(0.991)
|
||||
await progressHandler.setProgress(1)
|
||||
})
|
||||
assert.equal(progress.at(-1), 100)
|
||||
})
|
||||
})
|
||||
@@ -1,15 +1,5 @@
|
||||
import { AbstractAggregatedRemoteWriter } from './_AbstractAggregatedRemoteWriter.mjs'
|
||||
export class AggregatedIncrementalRemoteWriter extends AbstractAggregatedRemoteWriter {
|
||||
/**
|
||||
* the backup can land on any of the adapters, the compression is only known if they all use the same one
|
||||
* (based on the adapters since the child writers are only created in beforeBackup())
|
||||
* @returns {string | undefined} see RemoteAdapter#getVhdDirectoryCompression
|
||||
*/
|
||||
getVhdDirectoryCompression() {
|
||||
const compressions = new Set(Object.values(this.adapters).map(adapter => adapter.getVhdDirectoryCompression()))
|
||||
return compressions.size === 1 ? [...compressions][0] : undefined
|
||||
}
|
||||
|
||||
async deleteOldBackupsOnAdapter(adapter, backups) {
|
||||
await adapter.deleteDeltaVmBackups(backups)
|
||||
}
|
||||
|
||||
@@ -23,16 +23,9 @@ import { diskHasData } from './_diskHasData.mjs'
|
||||
const { warn } = createLogger('xo:backups:DeltaBackupWriter')
|
||||
|
||||
export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrementalWriter) {
|
||||
#exportTask
|
||||
#parentVdiPaths
|
||||
#parentUuids
|
||||
|
||||
/**
|
||||
* @returns {string | undefined} see RemoteAdapter#getVhdDirectoryCompression
|
||||
*/
|
||||
getVhdDirectoryCompression() {
|
||||
return this._adapter.getVhdDirectoryCompression()
|
||||
}
|
||||
|
||||
async checkBaseVdis(baseUuidToSrcVdi) {
|
||||
this.#parentVdiPaths = {}
|
||||
this.#parentUuids = {}
|
||||
@@ -149,20 +142,29 @@ export class IncrementalRemoteWriter extends MixinRemoteWriter(AbstractIncrement
|
||||
}
|
||||
|
||||
prepare({ isFull }) {
|
||||
// the mirror calls prepare() once per restore point: the previous export is over, unless it has already failed
|
||||
if (this.#exportTask?.status === 'pending') {
|
||||
this.#exportTask.success()
|
||||
}
|
||||
|
||||
// create the task related to this export and ensure all methods are called in this context
|
||||
const task = new Task({
|
||||
const task = (this.#exportTask = new Task({
|
||||
properties: {
|
||||
id: this._remoteId,
|
||||
isFull,
|
||||
name: 'export',
|
||||
type: 'remote',
|
||||
},
|
||||
})
|
||||
this._prepare = task.wrapInside(this._prepare)
|
||||
this.transfer = task.wrapInside(this.transfer)
|
||||
this.healthCheck = task.wrapInside(this.healthCheck)
|
||||
this.cleanup = task.wrapInside(this.cleanup)
|
||||
this.afterBackup = task.wrap(this.afterBackup)
|
||||
}))
|
||||
// wrap the methods of the class, not the ones wrapped by a previous call, which would run in all the previous
|
||||
// exports
|
||||
const methods = Object.getPrototypeOf(this)
|
||||
this._prepare = task.wrapInside(methods._prepare)
|
||||
this.transfer = task.wrapInside(methods.transfer)
|
||||
this.healthCheck = task.wrapInside(methods.healthCheck)
|
||||
this.cleanup = task.wrapInside(methods.cleanup)
|
||||
// ends the last export
|
||||
this.afterBackup = task.wrap(methods.afterBackup)
|
||||
|
||||
return this._prepare()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,93 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { describe, it } from 'node:test'
|
||||
import { Task } from '@vates/task'
|
||||
|
||||
import { IncrementalRemoteWriter } from './IncrementalRemoteWriter.mjs'
|
||||
|
||||
// only the task handling is tested: the remote operations are stubbed
|
||||
class TestWriter extends IncrementalRemoteWriter {
|
||||
constructor({ failingTimestamp } = {}) {
|
||||
super({ remoteId: 'remote-id', adapter: {}, vmUuid: 'vm-uuid', job: {}, settings: {}, config: {}, schedule: {} })
|
||||
this.failingTimestamp = failingTimestamp
|
||||
}
|
||||
|
||||
async _prepare() {}
|
||||
|
||||
async transfer({ timestamp }) {
|
||||
await Task.run({ properties: { name: 'transfer', timestamp } }, async () => {
|
||||
if (timestamp === this.failingTimestamp) {
|
||||
throw new Error('transfer failed')
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
async cleanup() {}
|
||||
|
||||
async healthCheck() {}
|
||||
|
||||
async afterBackup() {}
|
||||
}
|
||||
|
||||
/**
|
||||
* Runs `fn` in a root task, and returns the tasks created inside
|
||||
*/
|
||||
async function collectTasks(fn) {
|
||||
const tasksById = new Map()
|
||||
const root = new Task({
|
||||
properties: { name: 'root' },
|
||||
onProgress(event) {
|
||||
if (event.type === 'start') {
|
||||
tasksById.set(event.id, { id: event.id, parentId: event.parentId, properties: event.properties })
|
||||
} else if (event.type === 'end') {
|
||||
tasksById.get(event.id).status = event.status
|
||||
}
|
||||
},
|
||||
})
|
||||
await root.run(fn).catch(() => {})
|
||||
return [...tasksById.values()]
|
||||
}
|
||||
|
||||
// what the mirror runner does for each restore point to transfer
|
||||
async function transferRestorePoint(writer, timestamp) {
|
||||
await writer.prepare({ isFull: false })
|
||||
await writer.transfer({ timestamp })
|
||||
await writer.cleanup()
|
||||
}
|
||||
|
||||
describe('IncrementalRemoteWriter.prepare()', () => {
|
||||
it('creates one export per restore point, each holding its own transfer', async () => {
|
||||
const tasks = await collectTasks(async () => {
|
||||
const writer = new TestWriter()
|
||||
for (const timestamp of [1, 2, 3]) {
|
||||
await transferRestorePoint(writer, timestamp)
|
||||
}
|
||||
await writer.healthCheck()
|
||||
await writer.afterBackup()
|
||||
})
|
||||
|
||||
const exports = tasks.filter(task => task.properties.name === 'export')
|
||||
assert.equal(exports.length, 3)
|
||||
for (const [i, exportTask] of exports.entries()) {
|
||||
assert.equal(exportTask.status, 'success')
|
||||
const transfers = tasks.filter(task => task.parentId === exportTask.id)
|
||||
assert.deepEqual(
|
||||
transfers.map(task => task.properties.timestamp),
|
||||
[i + 1]
|
||||
)
|
||||
}
|
||||
})
|
||||
|
||||
it('only fails the export of the failing restore point', async () => {
|
||||
const tasks = await collectTasks(async () => {
|
||||
const writer = new TestWriter({ failingTimestamp: 2 })
|
||||
await transferRestorePoint(writer, 1)
|
||||
await transferRestorePoint(writer, 2)
|
||||
})
|
||||
|
||||
const exports = tasks.filter(task => task.properties.name === 'export')
|
||||
assert.deepEqual(
|
||||
exports.map(task => task.status),
|
||||
['success', 'failure']
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -65,11 +65,6 @@ export class IncrementalXapiWriter extends MixinXapiWriter(AbstractIncrementalWr
|
||||
|
||||
const snapshotCandidates = new Map()
|
||||
|
||||
// skip orphan snapshots (active VDI destroyed): they can't be validated against an active disk
|
||||
const replicaSnapshots = sr.$VDIs.filter(
|
||||
vdi => vdi?.managed && vdi?.is_a_snapshot && vdi.$snapshot_of !== undefined
|
||||
)
|
||||
|
||||
for (const [baseUuid, srcVdiuid] of baseUuidToSrcVdi) {
|
||||
let target
|
||||
|
||||
@@ -77,9 +72,11 @@ export class IncrementalXapiWriter extends MixinXapiWriter(AbstractIncrementalWr
|
||||
|
||||
if (contentKey !== undefined) {
|
||||
debug('got one content key, look for a candidate')
|
||||
target = replicaSnapshots.find(
|
||||
target = sr.$VDIs.find(
|
||||
vdi =>
|
||||
vdi.other_config[CONTENT_KEY] === contentKey &&
|
||||
vdi?.managed &&
|
||||
vdi?.is_a_snapshot &&
|
||||
vdi.other_config[CONTENT_KEY] === contentKey && // &&
|
||||
// ensure we don't replicate on ourself or any of the vdi in the source chain
|
||||
vdi.$snapshot_of.uuid !== srcVdiuid
|
||||
)
|
||||
@@ -88,11 +85,13 @@ export class IncrementalXapiWriter extends MixinXapiWriter(AbstractIncrementalWr
|
||||
// fall back for older snapshots
|
||||
if (target === undefined) {
|
||||
debug('content key not here or not found , look by jobid ')
|
||||
target = replicaSnapshots.find(
|
||||
target = sr.$VDIs.find(
|
||||
vdi =>
|
||||
vdi?.managed &&
|
||||
vdi?.is_a_snapshot &&
|
||||
vdi.other_config[JOB_ID] === this._job.id &&
|
||||
vdi.other_config[VM_UUID] === this._vmUuid &&
|
||||
vdi.other_config[COPY_OF] === baseUuid
|
||||
vdi?.other_config[COPY_OF] === baseUuid
|
||||
)
|
||||
}
|
||||
if (target !== undefined) {
|
||||
@@ -392,7 +391,6 @@ export class IncrementalXapiWriter extends MixinXapiWriter(AbstractIncrementalWr
|
||||
mostRecentEntry = this._oldEntries.pop()
|
||||
}
|
||||
await this._deleteOldEntries()
|
||||
await this._deleteOrphanVdis()
|
||||
this._oldEntries = mostRecentEntry !== undefined ? [mostRecentEntry] : []
|
||||
}
|
||||
}
|
||||
@@ -400,7 +398,6 @@ export class IncrementalXapiWriter extends MixinXapiWriter(AbstractIncrementalWr
|
||||
async cleanup() {
|
||||
if (!this._settings.skipDeleteOldEntries) {
|
||||
await this._deleteOldEntries()
|
||||
await this._deleteOrphanVdis()
|
||||
}
|
||||
}
|
||||
|
||||
@@ -408,35 +405,6 @@ export class IncrementalXapiWriter extends MixinXapiWriter(AbstractIncrementalWr
|
||||
return asyncMapSettled(this._oldEntries, vm => vm.$destroy({ bypassBlockedOperation: true }))
|
||||
}
|
||||
|
||||
// VDIs from this job/VM/SR that ended up detached from any VM, because a previous run
|
||||
// was interrupted or a storage backend refused to destroy a VDI at import time.
|
||||
// Destroying a VM only reaches the VDIs still attached to it, _deleteOldEntries never cleans them.
|
||||
async _deleteOrphanVdis() {
|
||||
const sr = this._sr
|
||||
const vmUuid = this._vmUuid
|
||||
const jobId = this._job.id
|
||||
|
||||
const orphanVdis = sr.$VDIs.filter(
|
||||
vdi =>
|
||||
vdi?.managed &&
|
||||
vdi.other_config[JOB_ID] === jobId &&
|
||||
vdi.other_config[VM_UUID] === vmUuid &&
|
||||
vdi.other_config[REPLICATED_TO_SR_UUID] === sr.uuid &&
|
||||
vdi.type !== 'suspend' &&
|
||||
// a VBD or VM missing from the cache (e.g. just destroyed) keeps the VDI, next run will handle it
|
||||
vdi.$VBDs.every(vbd => vbd?.$VM?.is_control_domain === true)
|
||||
)
|
||||
|
||||
await asyncEach(
|
||||
orphanVdis,
|
||||
vdi =>
|
||||
sr.$xapi
|
||||
.call('VDI.destroy', vdi.$ref)
|
||||
.catch(error => Task.warning('failed to delete orphan VDI', { vdi: vdi.uuid, error })),
|
||||
{ concurrency: 5 }
|
||||
)
|
||||
}
|
||||
|
||||
#decorateVmMetadata(backup, timestamp) {
|
||||
const { _warmMigration } = this._settings
|
||||
const sr = this._sr
|
||||
|
||||
@@ -12,14 +12,11 @@ const { warn } = createLogger('xo:backups:vdiRestoreTargets')
|
||||
*/
|
||||
|
||||
/**
|
||||
* Attach the backup disk itself to the restored VM, through a live mount: no copy, read only —
|
||||
* unless it is cached, which makes it read/write.
|
||||
* Attach the backup disk itself to the restored VM, through a live mount: no copy, read only.
|
||||
*
|
||||
* @typedef {object} LiveMountVdiTarget
|
||||
* @property {'live-mount'} type
|
||||
* @property {string} host - uuid of the host the disk is attached to
|
||||
* @property {string} [cacheSr] - uuid of the SR of the local VDI the disk is materialized into, which
|
||||
* also holds the writes, lost on unmount
|
||||
*/
|
||||
|
||||
/**
|
||||
@@ -136,20 +133,6 @@ export function hasLiveMountTarget(mapVdisSrs) {
|
||||
return Object.values(mapVdisSrs ?? {}).some(value => value?.type === 'live-mount')
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a raw `mapVdisSrs` setting asks for at least one cached, hence read/write, live mount.
|
||||
*
|
||||
* Such a mount needs the VM of the appliance serving it, which the caller has to look up. A `null`
|
||||
* cache SR does not ask for one: it is invalid, and left to {@link normalizeVdiRestoreTargets} to
|
||||
* reject, rather than failing on the lookup of a VM which was never needed.
|
||||
*
|
||||
* @param {object} [mapVdisSrs]
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function hasCachedLiveMountTarget(mapVdisSrs) {
|
||||
return Object.values(mapVdisSrs ?? {}).some(value => value?.type === 'live-mount' && value.cacheSr != null)
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalize the `mapVdisSrs` restore setting into per-VDI targets.
|
||||
*
|
||||
@@ -203,17 +186,10 @@ function normalizeTarget(vdiUuid, value, useDifferentialRestore) {
|
||||
}
|
||||
|
||||
if (type === 'live-mount') {
|
||||
const { cacheSr, host } = value
|
||||
if (!isNonEmptyString(host)) {
|
||||
if (!isNonEmptyString(value.host)) {
|
||||
throw invalidTarget(vdiUuid, 'a live mount requires the id of the host the disk is attached to')
|
||||
}
|
||||
if (cacheSr === undefined) {
|
||||
return { type: 'live-mount', host }
|
||||
}
|
||||
if (!isNonEmptyString(cacheSr)) {
|
||||
throw invalidTarget(vdiUuid, `expected the uuid of the cache SR, got ${typeof cacheSr}`)
|
||||
}
|
||||
return { type: 'live-mount', host, cacheSr }
|
||||
return { type: 'live-mount', host: value.host }
|
||||
}
|
||||
|
||||
if (type === 'restore') {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { describe, it } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
|
||||
import { hasCachedLiveMountTarget, hasLiveMountTarget, normalizeVdiRestoreTargets } from './_vdiRestoreTargets.mjs'
|
||||
import { hasLiveMountTarget, normalizeVdiRestoreTargets } from './_vdiRestoreTargets.mjs'
|
||||
|
||||
const VDI_1 = 'vdi-uuid-1'
|
||||
const VDI_2 = 'vdi-uuid-2'
|
||||
@@ -64,11 +64,6 @@ describe('normalizeVdiRestoreTargets()', () => {
|
||||
assert.equal(targets.getLiveMountHost(), HOST)
|
||||
})
|
||||
|
||||
it('keeps the cache SR of a live mount', () => {
|
||||
const targets = normalizeVdiRestoreTargets({ [VDI_1]: { type: 'live-mount', host: HOST, cacheSr: SR } })
|
||||
assert.deepEqual(targets.get(VDI_1), { type: 'live-mount', host: HOST, cacheSr: SR })
|
||||
})
|
||||
|
||||
it('accepts a restore without SR', () => {
|
||||
const targets = normalizeVdiRestoreTargets({ [VDI_1]: { type: 'restore' } })
|
||||
assert.deepEqual(targets.get(VDI_1), { type: 'restore', sr: undefined, useDifferential: false })
|
||||
@@ -102,13 +97,6 @@ describe('normalizeVdiRestoreTargets()', () => {
|
||||
)
|
||||
})
|
||||
|
||||
it('rejects a non string cache SR', () => {
|
||||
assert.throws(
|
||||
() => normalizeVdiRestoreTargets({ [VDI_1]: { type: 'live-mount', host: HOST, cacheSr: null } }),
|
||||
/expected the uuid of the cache SR/
|
||||
)
|
||||
})
|
||||
|
||||
it('rejects a non string SR', () => {
|
||||
assert.throws(() => normalizeVdiRestoreTargets({ [VDI_1]: { type: 'restore', sr: 42 } }), /expected an SR uuid/)
|
||||
})
|
||||
@@ -142,20 +130,3 @@ describe('hasLiveMountTarget()', () => {
|
||||
assert.equal(hasLiveMountTarget({ [VDI_1]: SR, [VDI_2]: null, [VDI_3]: { type: 'ignore' } }), false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('hasCachedLiveMountTarget()', () => {
|
||||
it('detects a cached live mount entry', () => {
|
||||
assert.equal(hasCachedLiveMountTarget({ [VDI_1]: { type: 'live-mount', host: HOST, cacheSr: SR } }), true)
|
||||
})
|
||||
|
||||
it('is false for an uncached live mount, and every other shape', () => {
|
||||
assert.equal(hasCachedLiveMountTarget(undefined), false)
|
||||
assert.equal(hasCachedLiveMountTarget({ [VDI_1]: { type: 'live-mount', host: HOST } }), false)
|
||||
assert.equal(hasCachedLiveMountTarget({ [VDI_1]: SR, [VDI_2]: null, [VDI_3]: { type: 'ignore' } }), false)
|
||||
})
|
||||
|
||||
// the normalization rejects it, which is the error worth reporting
|
||||
it('is false for a null cache SR', () => {
|
||||
assert.equal(hasCachedLiveMountTarget({ [VDI_1]: { type: 'live-mount', host: HOST, cacheSr: null } }), false)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,17 +1,41 @@
|
||||
import { TaskProgressHandler } from './_runners/_vmRunners/_TaskProgressHandler.mjs'
|
||||
|
||||
/**
|
||||
* @param {import('node:stream').Readable} stream
|
||||
* @param {{ size: number, progressHandler?: TaskProgressHandler, readTask?: import('./_SourceReadTask.mjs').SourceReadTask }} [container]
|
||||
* `readTask`: reports the reading of the stream in its own task
|
||||
*/
|
||||
export function watchStreamSize(stream, container = { size: 0 }) {
|
||||
const progressHandler = container.progressHandler ?? new TaskProgressHandler()
|
||||
const { progressHandler = new TaskProgressHandler(), readTask } = container
|
||||
stream.on('data', data => {
|
||||
if (container.size === 0) {
|
||||
// empty for xva exported by xapi
|
||||
readTask?.onStart({ bytesToRead: stream.length || undefined })
|
||||
}
|
||||
container.size += data.length
|
||||
if (stream.length) {
|
||||
// empty for xva exported by xapi
|
||||
progressHandler.setProgress(container.size / stream.length)
|
||||
}
|
||||
readTask?.onRead(data.length)
|
||||
})
|
||||
|
||||
stream.on('finish', () => {
|
||||
progressHandler.setProgress(1)
|
||||
})
|
||||
// a readable only emits 'end', a duplex (throttled stream) emits both
|
||||
let isComplete = false
|
||||
const complete = () => {
|
||||
if (!isComplete) {
|
||||
isComplete = true
|
||||
progressHandler.setProgress(1)
|
||||
readTask?.onEnd({ isComplete })
|
||||
}
|
||||
}
|
||||
stream.on('end', complete)
|
||||
stream.on('finish', complete)
|
||||
if (readTask !== undefined) {
|
||||
// no-op once the read task has ended
|
||||
stream.on('error', error => readTask.onEnd({ isComplete, error }))
|
||||
stream.on('close', () => readTask.onEnd({ isComplete }))
|
||||
}
|
||||
stream.pause()
|
||||
return container
|
||||
}
|
||||
|
||||
@@ -1,26 +0,0 @@
|
||||
import { isExpression, compileExpression } from './_expressionPredicate.mjs'
|
||||
import { invalidParameters } from 'xo-common/api-errors.js'
|
||||
|
||||
export function assertValidSettingsExpression(settings, keys) {
|
||||
for (const [scheduleId, scheduleSettings] of Object.entries(settings ?? {})) {
|
||||
for (const key of keys) {
|
||||
assertValidExpression(`settings/${scheduleId === '' ? 'general' : scheduleId}/${key}`, scheduleSettings?.[key])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function assertValidExpression(name, value) {
|
||||
if (isExpression(value)) {
|
||||
try {
|
||||
compileExpression(value)
|
||||
} catch (error) {
|
||||
throw invalidParameters(`Invalid ${name} expression: ${error.message}`, [
|
||||
{ instancePath: `/${name}`, message: error.message },
|
||||
])
|
||||
}
|
||||
} else if (typeof value === 'string' && value.trim() === '') {
|
||||
throw invalidParameters(`Invalid ${name} expression: must be a non-empty expression`, [
|
||||
{ instancePath: `/${name}`, message: 'must be a non-empty expression' },
|
||||
])
|
||||
}
|
||||
}
|
||||
@@ -1,77 +0,0 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { describe, it } from 'node:test'
|
||||
import { invalidParameters } from 'xo-common/api-errors.js'
|
||||
|
||||
import { assertValidExpression, assertValidSettingsExpression } from './backupExpressions.mjs'
|
||||
|
||||
const VALID = 'vm:tags:prod'
|
||||
const INVALID = 'vm:('
|
||||
|
||||
// checks that the error is `invalidParameters` and points to the expected field
|
||||
const isInvalidAt = instancePath => error =>
|
||||
invalidParameters.is(error) && error.data.errors[0].instancePath === instancePath
|
||||
|
||||
describe('assertValidExpression', function () {
|
||||
it('accepts a valid expression', function () {
|
||||
assert.doesNotThrow(() => assertValidExpression('srs', VALID))
|
||||
})
|
||||
|
||||
it('rejects an invalid expression with invalidParameters', function () {
|
||||
assert.throws(() => assertValidExpression('srs', INVALID), isInvalidAt('/srs'))
|
||||
})
|
||||
|
||||
it('ignores values which are not expressions', function () {
|
||||
for (const value of [undefined, '3', { id: 'sr-1' }, { id: { __or: ['sr-1', 'sr-2'] } }]) {
|
||||
assert.doesNotThrow(() => assertValidExpression('srs', value))
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects blank strings', function () {
|
||||
for (const value of ['', ' ']) {
|
||||
assert.throws(() => assertValidExpression('srs', value), isInvalidAt('/srs'))
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('assertValidSettingsExpression', function () {
|
||||
const KEYS = ['healthCheckVmsWithTags', 'fullInterval']
|
||||
|
||||
it('accepts valid expressions in the general and the schedule settings', function () {
|
||||
assert.doesNotThrow(() =>
|
||||
assertValidSettingsExpression(
|
||||
{ '': { fullInterval: VALID }, 'schedule-1': { healthCheckVmsWithTags: VALID } },
|
||||
KEYS
|
||||
)
|
||||
)
|
||||
})
|
||||
|
||||
it('rejects an invalid expression in the schedule settings and points to it', function () {
|
||||
assert.throws(
|
||||
() => assertValidSettingsExpression({ '': {}, 'schedule-1': { fullInterval: INVALID } }, KEYS),
|
||||
isInvalidAt('/settings/schedule-1/fullInterval')
|
||||
)
|
||||
})
|
||||
|
||||
it('rejects an invalid expression in the general settings', function () {
|
||||
// the general settings are keyed by '', named "general" in the path.
|
||||
assert.throws(
|
||||
() => assertValidSettingsExpression({ '': { healthCheckVmsWithTags: INVALID } }, KEYS),
|
||||
isInvalidAt('/settings/general/healthCheckVmsWithTags')
|
||||
)
|
||||
})
|
||||
|
||||
it('ignores the legacy array and number values', function () {
|
||||
assert.doesNotThrow(() =>
|
||||
assertValidSettingsExpression({ 'schedule-1': { healthCheckVmsWithTags: ['tag'], fullInterval: 3 } }, KEYS)
|
||||
)
|
||||
})
|
||||
|
||||
it('ignores the keys it has not been asked to check', function () {
|
||||
assert.doesNotThrow(() => assertValidSettingsExpression({ 'schedule-1': { vmFilter: INVALID } }, KEYS))
|
||||
})
|
||||
|
||||
it('handles missing settings and undefined entries', function () {
|
||||
assert.doesNotThrow(() => assertValidSettingsExpression(undefined, KEYS))
|
||||
assert.doesNotThrow(() => assertValidSettingsExpression({ 'schedule-1': undefined }, KEYS))
|
||||
})
|
||||
})
|
||||
@@ -43,7 +43,7 @@ A VM directory holds **both** the full and the incremental backups of that VM: t
|
||||
|
||||
Transient entries, not listed in the trees below:
|
||||
|
||||
- `xo-vm-backups/<VM UUID>.lock`, held while a job writes to that VM's folder and while `cleanVm` cleans or merges it (after a job, after a deletion, or in the merge worker on local remotes). It is effective on S3 (an object rewritten every 30 seconds) and Azure (blob lease) too. When listing VMs, entries starting with `.` and entries ending with `.lock` are ignored.
|
||||
- `xo-vm-backups/<VM UUID>.lock`, held for the duration of a job run on that VM. When listing VMs, entries starting with `.` and entries ending with `.lock` are ignored.
|
||||
- `xo-vm-backups/.queue/clean-vm/<YYYYMMDD>T<HHmmss>-<random>`, the merge worker queue
|
||||
- `.<VHD file name>.merge.json`, in a VDI directory, interrupted merge states.
|
||||
|
||||
@@ -167,7 +167,6 @@ Append-only log of what happened to the VM backup metadata.
|
||||
- entries are never modified nor overwritten, so it works on an immutable remote
|
||||
- written unencrypted, so it stays readable without the encryption key
|
||||
- one directory per day: a reader lists only the days it misses, a purge drops whole directories
|
||||
- xo-server removes the days older than `backups.journalRetention` from every enabled remote when it starts, then once a day; it always keeps the `fullListingInterval` of the remote, during which it reads the journal back; a day which cannot be removed is skipped, and the next purge tries it again
|
||||
- the time part has a fixed width, so sorting the names by name sorts them by date
|
||||
- `event` is `add`, `change` or `del`, and the file content also has a `reason` field
|
||||
- the name of the file is only there to be read by a human: XO reads every field from the file content
|
||||
|
||||
@@ -1,28 +0,0 @@
|
||||
import { formatFilenameDate } from './_filenameDate.mjs'
|
||||
|
||||
/**
|
||||
* XAPI names of what a live mount of a backed up disk shows the user, so the ones created by the REST
|
||||
* API and by a restore read the same.
|
||||
*
|
||||
* The VDI attached to the host keeps the name of the backed up disk: that is the disk of the VM as
|
||||
* the user knows it. The SR says what it is, and which restore point it serves, the same way as a
|
||||
* restored VM is named.
|
||||
*
|
||||
* @param {object} params
|
||||
* @param {string} params.vmNameLabel - name of the backed up VM
|
||||
* @param {string} params.vdiNameLabel - name of the backed up disk
|
||||
* @param {number} params.timestamp - of the restore point, in ms
|
||||
* @param {boolean} [params.readWrite] - whether the mount is a live restore rather than a live mount
|
||||
* @returns {{ srNameLabel: string, vdiNameLabel: string, vdiNameDescription: string }} - the `xapiLabels` of the live mount mixin
|
||||
*/
|
||||
export function liveMountXapiLabels({ vmNameLabel, vdiNameLabel, timestamp, readWrite = false }) {
|
||||
const what = readWrite ? 'live restore' : 'live mount'
|
||||
const restorePoint = `${vmNameLabel} (${formatFilenameDate(new Date(timestamp))})`
|
||||
return {
|
||||
srNameLabel: `[XO ${what}] ${restorePoint}`,
|
||||
vdiNameLabel,
|
||||
vdiNameDescription: readWrite
|
||||
? `Live restore of ${restorePoint}: what is written to it is lost on unmount.`
|
||||
: `Read-only live mount of ${restorePoint}, removed on unmount.`,
|
||||
}
|
||||
}
|
||||
@@ -1,27 +0,0 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { describe, it } from 'node:test'
|
||||
|
||||
import { liveMountXapiLabels } from './liveMountXapiLabels.mjs'
|
||||
|
||||
const TIMESTAMP = 1754035712000 // 2025-08-01T08:08:32Z
|
||||
|
||||
describe('liveMountXapiLabels', () => {
|
||||
it('keeps the name of the disk and names the SR after the restore point', () => {
|
||||
assert.deepEqual(liveMountXapiLabels({ timestamp: TIMESTAMP, vdiNameLabel: 'system', vmNameLabel: 'web01' }), {
|
||||
srNameLabel: '[XO live mount] web01 (20250801T080832Z)',
|
||||
vdiNameLabel: 'system',
|
||||
vdiNameDescription: 'Read-only live mount of web01 (20250801T080832Z), removed on unmount.',
|
||||
})
|
||||
})
|
||||
|
||||
it('says a live restore loses what is written to it', () => {
|
||||
const xapiLabels = liveMountXapiLabels({
|
||||
readWrite: true,
|
||||
timestamp: TIMESTAMP,
|
||||
vdiNameLabel: 'system',
|
||||
vmNameLabel: 'web01',
|
||||
})
|
||||
assert.equal(xapiLabels.srNameLabel, '[XO live restore] web01 (20250801T080832Z)')
|
||||
assert.match(xapiLabels.vdiNameDescription, /lost on unmount/)
|
||||
})
|
||||
})
|
||||
@@ -8,7 +8,7 @@
|
||||
"type": "git",
|
||||
"url": "https://github.com/vatesfr/xen-orchestra.git"
|
||||
},
|
||||
"version": "0.78.0",
|
||||
"version": "0.76.1",
|
||||
"engines": {
|
||||
"node": ">=14.18"
|
||||
},
|
||||
@@ -27,20 +27,19 @@
|
||||
"@vates/disposable": "^0.1.6",
|
||||
"@vates/fuse-vhd": "^2.1.3",
|
||||
"@vates/generator-toolbox": "^1.1.3",
|
||||
"@vates/nbd-client": "^3.7.0",
|
||||
"@vates/nbd-client": "^3.6.0",
|
||||
"@vates/parse-duration": "^0.1.1",
|
||||
"@vates/task": "^0.7.0",
|
||||
"@vates/types": "^2.5.0",
|
||||
"@vates/types": "^2.3.0",
|
||||
"@xen-orchestra/async-map": "^0.1.5",
|
||||
"@xen-orchestra/disk-transform": "^1.3.4",
|
||||
"@xen-orchestra/fs": "^4.10.0",
|
||||
"@xen-orchestra/disk-transform": "^1.3.3",
|
||||
"@xen-orchestra/fs": "^4.9.5",
|
||||
"@xen-orchestra/log": "^0.7.2",
|
||||
"@xen-orchestra/qcow2": "^1.4.1",
|
||||
"@xen-orchestra/qcow2": "^1.4.0",
|
||||
"@xen-orchestra/template": "^0.1.1",
|
||||
"@xen-orchestra/backup-archive": "^1.2.0",
|
||||
"@xen-orchestra/backup-archive": "^1.1.3",
|
||||
"app-conf": "^3.0.0",
|
||||
"compare-versions": "^6.0.0",
|
||||
"complex-matcher": "^1.1.1",
|
||||
"d3-time-format": "^4.1.0",
|
||||
"decorator-synchronized": "^0.6.0",
|
||||
"golike-defer": "^0.5.1",
|
||||
@@ -56,10 +55,8 @@
|
||||
"tar": "^7.5.19",
|
||||
"uuid": "^9.0.0",
|
||||
"value-matcher": "^0.2.0",
|
||||
"vhd-lib": "^4.17.0",
|
||||
"xen-api": "^5.1.0",
|
||||
"xo-common": "^0.11.0",
|
||||
"xo-remote-parser": "^2.0.0",
|
||||
"vhd-lib": "^4.16.2",
|
||||
"xen-api": "^5.0.2",
|
||||
"yazl": "^2.5.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
@@ -70,7 +67,7 @@
|
||||
"typescript": "^5.9.3"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@xen-orchestra/xapi": "^9.1.0"
|
||||
"@xen-orchestra/xapi": "^9.0.1"
|
||||
},
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"author": {
|
||||
|
||||
@@ -18,7 +18,7 @@
|
||||
"preferGlobal": true,
|
||||
"dependencies": {
|
||||
"golike-defer": "^0.5.1",
|
||||
"xen-api": "^5.1.0"
|
||||
"xen-api": "^5.0.2"
|
||||
},
|
||||
"scripts": {
|
||||
"postversion": "npm publish"
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"private": false,
|
||||
"name": "@xen-orchestra/disk-cli",
|
||||
"version": "2.2.5",
|
||||
"version": "2.2.3",
|
||||
"description": "CLI tool to inspect and manage disks in backup repositories",
|
||||
"type": "module",
|
||||
"bin": {
|
||||
@@ -20,13 +20,13 @@
|
||||
},
|
||||
"dependencies": {
|
||||
"@vates/async-each": "^1.0.3",
|
||||
"@xen-orchestra/backups": "^0.78.0",
|
||||
"@xen-orchestra/backup-archive": "^1.2.0",
|
||||
"@xen-orchestra/disk-transform": "^1.3.4",
|
||||
"@xen-orchestra/fs": "^4.10.0",
|
||||
"@xen-orchestra/qcow2": "^1.4.1",
|
||||
"@xen-orchestra/backups": "^0.76.1",
|
||||
"@xen-orchestra/backup-archive": "^1.1.3",
|
||||
"@xen-orchestra/disk-transform": "^1.3.3",
|
||||
"@xen-orchestra/fs": "^4.9.5",
|
||||
"@xen-orchestra/qcow2": "^1.4.0",
|
||||
"promise-toolbox": "^0.21.0",
|
||||
"vhd-lib": "^4.17.0"
|
||||
"vhd-lib": "^4.16.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^22.3.0",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@xen-orchestra/disk-transform",
|
||||
"version": "1.3.4",
|
||||
"version": "1.3.3",
|
||||
"main": "./dist/index.mjs",
|
||||
"license": "MIT",
|
||||
"private": false,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { Disk, DiskBlock, RandomAccessDisk } from './Disk.mjs'
|
||||
import type { ProgressHandler } from './ProgressHandler.mjs'
|
||||
|
||||
export class DiskPassthrough extends Disk {
|
||||
#source: Disk | undefined
|
||||
@@ -51,6 +52,10 @@ export class DiskPassthrough extends Disk {
|
||||
async buildDiskBlockGenerator(): Promise<AsyncGenerator<DiskBlock>> {
|
||||
return this.source.buildDiskBlockGenerator()
|
||||
}
|
||||
// the blocks are generated by the source, which is the one reporting the progress
|
||||
addProgressHandler(progressHandler: ProgressHandler) {
|
||||
this.source.addProgressHandler(progressHandler)
|
||||
}
|
||||
}
|
||||
|
||||
export abstract class RandomDiskPassthrough extends RandomAccessDisk {
|
||||
|
||||
55
@xen-orchestra/disk-transform/src/MeteredDisk.mts
Normal file
55
@xen-orchestra/disk-transform/src/MeteredDisk.mts
Normal file
@@ -0,0 +1,55 @@
|
||||
import { Disk, DiskBlock } from './Disk.mjs'
|
||||
import { DiskPassthrough } from './DiskPassthrough.mjs'
|
||||
|
||||
export type ReadMeter = {
|
||||
/** called once, before the first block, with the number of bytes the source will generate */
|
||||
onStart(result: { bytesToRead: number }): void
|
||||
/** called for each block read from the source */
|
||||
onRead(length: number): void
|
||||
/** called once, when the source is exhausted (`isComplete`), closed early by its consumer or failed (`error`) */
|
||||
onEnd(result: { isComplete: boolean; error?: unknown }): void
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports the bytes read from the source, and the end of its reading
|
||||
*
|
||||
* The meter is called from the async context of the consumer pulling the next block, which may be any of the
|
||||
* forks of a SynchronizedDisk: it must not rely on this context
|
||||
*/
|
||||
export class MeteredDisk extends DiskPassthrough {
|
||||
#meter: ReadMeter
|
||||
|
||||
constructor(source: Disk, meter: ReadMeter) {
|
||||
super(source)
|
||||
this.#meter = meter
|
||||
}
|
||||
|
||||
async buildDiskBlockGenerator(): Promise<AsyncGenerator<DiskBlock>> {
|
||||
const generator = await this.source.buildDiskBlockGenerator()
|
||||
const meter = this.#meter
|
||||
// the last block may be truncated to the virtual size
|
||||
const bytesToRead = Math.min(this.getBlockIndexesCount() * this.getBlockSize(), this.getVirtualSize())
|
||||
async function* meteredGenerator(): AsyncGenerator<DiskBlock> {
|
||||
let isComplete = false
|
||||
let isStarted = false
|
||||
let error: unknown
|
||||
try {
|
||||
for await (const block of generator) {
|
||||
if (!isStarted) {
|
||||
isStarted = true
|
||||
meter.onStart({ bytesToRead })
|
||||
}
|
||||
meter.onRead(block.data.length)
|
||||
yield block
|
||||
}
|
||||
isComplete = true
|
||||
} catch (err) {
|
||||
error = err
|
||||
throw err
|
||||
} finally {
|
||||
meter.onEnd({ isComplete, error })
|
||||
}
|
||||
}
|
||||
return meteredGenerator()
|
||||
}
|
||||
}
|
||||
120
@xen-orchestra/disk-transform/src/MeteredDisk.test.mts
Normal file
120
@xen-orchestra/disk-transform/src/MeteredDisk.test.mts
Normal file
@@ -0,0 +1,120 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert'
|
||||
import { DebugDisk } from './utils/DebugDisk.mjs'
|
||||
import { MeteredDisk, ReadMeter } from './MeteredDisk.mjs'
|
||||
import { SynchronizedDisk } from './SynchronizedDisk.mjs'
|
||||
import { DiskBlock } from './Disk.mjs'
|
||||
|
||||
const blockSize = 1024
|
||||
const nbBlocks = 20
|
||||
|
||||
function createMeter() {
|
||||
const meter = {
|
||||
readSize: 0,
|
||||
bytesToRead: [] as number[],
|
||||
ends: [] as Array<{ isComplete: boolean; error?: unknown }>,
|
||||
onStart({ bytesToRead }: { bytesToRead: number }) {
|
||||
meter.bytesToRead.push(bytesToRead)
|
||||
},
|
||||
onRead(length: number) {
|
||||
meter.readSize += length
|
||||
},
|
||||
onEnd(result: { isComplete: boolean; error?: unknown }) {
|
||||
meter.ends.push(result)
|
||||
},
|
||||
} satisfies ReadMeter & Record<string, unknown>
|
||||
return meter
|
||||
}
|
||||
|
||||
async function createDisk() {
|
||||
const disk = new DebugDisk({ nbBlocks, blockSize, fillRate: 100 })
|
||||
await disk.init()
|
||||
return disk
|
||||
}
|
||||
|
||||
test('MeteredDisk', async t => {
|
||||
await t.test('reports the bytes read and the completion', async () => {
|
||||
const disk = await createDisk()
|
||||
const meter = createMeter()
|
||||
const metered = new MeteredDisk(disk, meter)
|
||||
for await (const block of metered.diskBlocks()) {
|
||||
assert.strictEqual(block.data.length, blockSize)
|
||||
}
|
||||
assert.deepStrictEqual(meter.bytesToRead, [nbBlocks * blockSize])
|
||||
assert.strictEqual(meter.readSize, nbBlocks * blockSize)
|
||||
assert.deepStrictEqual(meter.ends, [{ isComplete: true, error: undefined }])
|
||||
assert.strictEqual(disk.closeDone, true)
|
||||
})
|
||||
|
||||
await t.test('reports an early stop of the consumer as incomplete', async () => {
|
||||
const meter = createMeter()
|
||||
const metered = new MeteredDisk(await createDisk(), meter)
|
||||
let nbRead = 0
|
||||
for await (const block of metered.diskBlocks()) {
|
||||
assert.strictEqual(block.data.length, blockSize)
|
||||
if (++nbRead === 3) {
|
||||
break
|
||||
}
|
||||
}
|
||||
assert.strictEqual(meter.readSize, 3 * blockSize)
|
||||
assert.deepStrictEqual(meter.ends, [{ isComplete: false, error: undefined }])
|
||||
})
|
||||
|
||||
await t.test('reports the error of the source', async () => {
|
||||
const disk = await createDisk()
|
||||
const error = new Error('read failed')
|
||||
disk.readBlock = async (index: number): Promise<DiskBlock> => {
|
||||
if (index === 5) {
|
||||
throw error
|
||||
}
|
||||
return { index, data: Buffer.alloc(blockSize) }
|
||||
}
|
||||
const meter = createMeter()
|
||||
const metered = new MeteredDisk(disk, meter)
|
||||
await assert.rejects(async () => {
|
||||
for await (const block of metered.diskBlocks()) {
|
||||
assert.strictEqual(block.data.length, blockSize)
|
||||
}
|
||||
}, error)
|
||||
assert.strictEqual(meter.readSize, 5 * blockSize)
|
||||
assert.deepStrictEqual(meter.ends, [{ isComplete: false, error }])
|
||||
})
|
||||
|
||||
await t.test('counts a source read once by multiple forks', async () => {
|
||||
const meter = createMeter()
|
||||
const synchronized = new SynchronizedDisk(new MeteredDisk(await createDisk(), meter))
|
||||
const forks = [synchronized.fork('first'), synchronized.fork('second')]
|
||||
await Promise.all(
|
||||
forks.map(async fork => {
|
||||
for await (const block of fork.diskBlocks()) {
|
||||
assert.strictEqual(block.data.length, blockSize)
|
||||
await new Promise(resolve => setTimeout(resolve, Math.random() * 3))
|
||||
}
|
||||
})
|
||||
)
|
||||
assert.strictEqual(meter.readSize, nbBlocks * blockSize)
|
||||
assert.deepStrictEqual(meter.ends, [{ isComplete: true, error: undefined }])
|
||||
})
|
||||
|
||||
await t.test('reports the size of the blocks present in the source', async () => {
|
||||
const disk = new DebugDisk({ nbBlocks, blockSize, fillRate: 50 })
|
||||
await disk.init()
|
||||
const meter = createMeter()
|
||||
for await (const block of new MeteredDisk(disk, meter).diskBlocks()) {
|
||||
assert.strictEqual(block.data.length, blockSize)
|
||||
}
|
||||
assert.deepStrictEqual(meter.bytesToRead, [disk.getBlockIndexesCount() * blockSize])
|
||||
assert.strictEqual(meter.readSize, disk.getBlockIndexesCount() * blockSize)
|
||||
})
|
||||
|
||||
await t.test('does not start on a source without blocks', async () => {
|
||||
const disk = new DebugDisk({ nbBlocks, blockSize, fillRate: 0 })
|
||||
await disk.init()
|
||||
const meter = createMeter()
|
||||
for await (const block of new MeteredDisk(disk, meter).diskBlocks()) {
|
||||
assert.strictEqual(block.data.length, blockSize)
|
||||
}
|
||||
assert.deepStrictEqual(meter.bytesToRead, [])
|
||||
assert.deepStrictEqual(meter.ends, [{ isComplete: true, error: undefined }])
|
||||
})
|
||||
})
|
||||
@@ -9,7 +9,7 @@ async function consumeGenerator(source: AsyncGenerator) {
|
||||
return 'finished'
|
||||
}
|
||||
test('Disk class', async t => {
|
||||
const testRes = await t.test('synchronized fork disk ', async () => {
|
||||
const testRes = await t.test('synchronised fork disk ', async () => {
|
||||
const blockSize = 1024
|
||||
const nbBlocks = 20
|
||||
const source = new DebugDisk({ nbBlocks, blockSize, fillRate: 100 })
|
||||
|
||||
@@ -12,11 +12,11 @@ export class ThrottledDisk extends DiskPassthrough {
|
||||
const generator = await this.source.buildDiskBlockGenerator()
|
||||
//throttle want to be able to know the length of the data
|
||||
async function* generatorWithLength() {
|
||||
for await (const block of generator) {
|
||||
// keep the other properties of the block (like the compression of a raw VHD directory block)
|
||||
for await (const { index, data } of generator) {
|
||||
yield {
|
||||
...block,
|
||||
length: block.data.length,
|
||||
index,
|
||||
data,
|
||||
length: data.length,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,32 +0,0 @@
|
||||
import { test } from 'node:test'
|
||||
import assert from 'node:assert'
|
||||
import { Throttle } from '@vates/generator-toolbox'
|
||||
import { DiskBlock } from './Disk.mjs'
|
||||
import { DebugDisk } from './utils/DebugDisk.mjs'
|
||||
import { ThrottledDisk } from './Throttled.mjs'
|
||||
|
||||
type TaggedDiskBlock = DiskBlock & { compression: string }
|
||||
|
||||
// a disk yielding blocks with an additional property, like the raw blocks of a VHD directory
|
||||
class TaggedDebugDisk extends DebugDisk {
|
||||
async readBlock(index: number): Promise<TaggedDiskBlock> {
|
||||
return { ...(await super.readBlock(index)), compression: 'brotli' }
|
||||
}
|
||||
}
|
||||
|
||||
test('ThrottledDisk keeps the other properties of the blocks', async () => {
|
||||
const blockSize = 1024
|
||||
const nbBlocks = 5
|
||||
const source = new TaggedDebugDisk({ nbBlocks, blockSize, fillRate: 100 })
|
||||
await source.init()
|
||||
// speed 0 disables the throttling
|
||||
const disk = new ThrottledDisk(source, new Throttle(0))
|
||||
|
||||
let nbBlocksRead = 0
|
||||
for await (const block of disk.diskBlocks()) {
|
||||
assert.strictEqual((block as TaggedDiskBlock).compression, 'brotli')
|
||||
assert.strictEqual(block.data.length, blockSize)
|
||||
nbBlocksRead++
|
||||
}
|
||||
assert.strictEqual(nbBlocksRead, nbBlocks)
|
||||
})
|
||||
@@ -9,5 +9,7 @@ export { RawDisk } from './RawDisk.mjs'
|
||||
export { ReadAhead } from './ReadAhead.mjs'
|
||||
export { SynchronizedDisk } from './SynchronizedDisk.mjs'
|
||||
export { TimeoutDisk } from './Timeout.mjs'
|
||||
export { MeteredDisk } from './MeteredDisk.mjs'
|
||||
export type { ReadMeter } from './MeteredDisk.mjs'
|
||||
export { ThrottledDisk } from './Throttled.mjs'
|
||||
export { ProgressHandler } from './ProgressHandler.mjs'
|
||||
|
||||
@@ -18,7 +18,7 @@ ee.on('start', async function () {
|
||||
// listeners have settled
|
||||
await ee.emitAsync('start')
|
||||
|
||||
// by default, it will rejects as soon as one listener reject, you can customize
|
||||
// by default, it will rejects as soon as one listener reject, you can customise
|
||||
// error handling though:
|
||||
await ee.emitAsync(
|
||||
{
|
||||
|
||||
@@ -36,7 +36,7 @@ ee.on('start', async function () {
|
||||
// listeners have settled
|
||||
await ee.emitAsync('start')
|
||||
|
||||
// by default, it will rejects as soon as one listener reject, you can customize
|
||||
// by default, it will rejects as soon as one listener reject, you can customise
|
||||
// error handling though:
|
||||
await ee.emitAsync(
|
||||
{
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
{
|
||||
"private": false,
|
||||
"name": "@xen-orchestra/fs",
|
||||
"version": "4.10.0",
|
||||
"version": "4.9.5",
|
||||
"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",
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
// the error of proper-lockfile, which LocalHandler uses: callers and the documentation know this one
|
||||
export default function lockedError(path) {
|
||||
return Object.assign(new Error('Lock file is already being held'), { code: 'ELOCKED', file: path })
|
||||
}
|
||||
@@ -1,12 +1,9 @@
|
||||
import { BlobServiceClient, StorageSharedKeyCredential } from '@azure/storage-blob'
|
||||
import { createLogger } from '@xen-orchestra/log'
|
||||
import { pTimeout } from 'promise-toolbox'
|
||||
import { parse } from 'xo-remote-parser'
|
||||
import { join, split } from './path'
|
||||
import RemoteHandlerAbstract from './abstract'
|
||||
import copyStreamToBuffer from './_copyStreamToBuffer'
|
||||
import lockedError from './_lockedError.js'
|
||||
import { randomUUID } from 'node:crypto'
|
||||
import { PassThrough, Transform, pipeline } from 'stream'
|
||||
|
||||
createLogger('xo:fs:azure')
|
||||
@@ -14,52 +11,7 @@ const MAX_BLOCK_SIZE = 1024 * 1024 * 4000 // 4000 MiB
|
||||
const MIN_BLOCK_SIZE = 1024 * 1024 * 4 // 4 MiB, default max block size
|
||||
const MAX_BLOCK_COUNT = 50000
|
||||
const AZURE_BATCH_MAX_REQUEST = 256 // BATCH_MAX_REQUEST constant from Azure
|
||||
const { debug, warn, info } = createLogger('xo:fs:azure')
|
||||
|
||||
// how long the lease of a lock lasts without being renewed, in seconds: the longest finite lease Azure allows, as an
|
||||
// infinite one would outlive a holder which crashed, and block the path until someone breaks it by hand
|
||||
export const LEASE_DURATION = 60
|
||||
|
||||
// how often a holder renews the lease of its lock: 4 renewals per lease, so that a holder survives a few slow or
|
||||
// failed requests without losing its lock
|
||||
export const RENEW_INTERVAL = 15e3
|
||||
|
||||
// how long a renewal, or a reacquisition, waits for its requests: a hung one counts as a failed one, and the next
|
||||
// renewal must still run before the lease expires, so RENEW_INTERVAL + RENEW_TIMEOUT + RENEW_INTERVAL < LEASE_DURATION
|
||||
// (15 s + 20 s + 15 s < 60 s)
|
||||
export const RENEW_TIMEOUT = 20e3
|
||||
|
||||
// leases the blob, creating it first, or throws `lockedError(path)`
|
||||
//
|
||||
// The holder of the lock deletes the blob when it releases it: when that happens between the upload and the
|
||||
// acquisition, one more attempt. Losing a second race means another contender got it.
|
||||
async function takeLease(blobClient, leaseClient, path) {
|
||||
for (let attempt = 0; attempt < 2; ++attempt) {
|
||||
try {
|
||||
await blobClient.upload('', 0, { conditions: { ifNoneMatch: '*' } })
|
||||
} catch (error) {
|
||||
// 409: the blob exists; 412: it exists and is leased, and a write without the lease ID is refused
|
||||
if (error.statusCode !== 409 && error.statusCode !== 412) {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
try {
|
||||
await leaseClient.acquireLease(LEASE_DURATION)
|
||||
return
|
||||
} catch (error) {
|
||||
// 409: another lease is active
|
||||
if (error.statusCode === 409) {
|
||||
throw lockedError(path)
|
||||
}
|
||||
// 404: the blob was deleted since the upload
|
||||
if (error.statusCode !== 404) {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
throw lockedError(path)
|
||||
}
|
||||
const { warn, info } = createLogger('xo:fs:azure')
|
||||
|
||||
export default class AzureHandler extends RemoteHandlerAbstract {
|
||||
#container
|
||||
@@ -378,89 +330,4 @@ export default class AzureHandler extends RemoteHandlerAbstract {
|
||||
await blobBatchClient.submitBatch(batch)
|
||||
}
|
||||
}
|
||||
|
||||
// Locks with a blob lease, Azure's own lock on a blob: Azure enforces its expiry, so there is no clock to compare,
|
||||
// and a renewal writes nothing, where rewriting the blob would leave a copy every time on accounts with versioning
|
||||
// or soft delete. An acquisition does leave one copy per lock taken, as the blob is created then deleted on release:
|
||||
// a lease needs a blob to hold it.
|
||||
//
|
||||
// The requests are sent with the blob client directly, not through the handler's methods: those go through the
|
||||
// handler's concurrency limit, and a renewal queued behind long uploads would let the lease expire.
|
||||
//
|
||||
// As with `LocalHandler#_lock()`, losing the lock while holding it is only logged, and the release function never
|
||||
// rejects. A renewal which finds the lease gone takes the lock back, and the lock is given up only when another
|
||||
// holder has it: any other error is a failed request, and the next renewal tries again.
|
||||
async _lock(path) {
|
||||
// `<path>.lock`, the name of the local lock directory: the listings skip it already
|
||||
const blobClient = this.#containerClient.getBlockBlobClient(this.#makeFullPath(`${path}.lock`))
|
||||
|
||||
// Azure requires a GUID. Proposing it, rather than letting Azure pick one, makes the retry of the SDK harmless
|
||||
// when the response of an acquisition is lost: acquiring with the ID of the active lease succeeds
|
||||
const leaseId = randomUUID()
|
||||
const leaseClient = blobClient.getBlobLeaseClient(leaseId)
|
||||
|
||||
await takeLease(blobClient, leaseClient, path)
|
||||
|
||||
let lastRenewal = Date.now()
|
||||
let lost = false
|
||||
let released = false
|
||||
let renewing = Promise.resolve()
|
||||
let timeout
|
||||
|
||||
async function renew() {
|
||||
try {
|
||||
await pTimeout.call(leaseClient.renewLease(), RENEW_TIMEOUT)
|
||||
lastRenewal = Date.now()
|
||||
return
|
||||
} catch (error) {
|
||||
// 404: the blob is gone; 409: it is leased to someone else
|
||||
if (error.statusCode !== 404 && error.statusCode !== 409) {
|
||||
// a failed request is not a lost lock: it is lost only if the lease expires and someone takes it, which the
|
||||
// next successful request finds out; it repeats every interval while Azure fails, hence debug
|
||||
debug('lock could not be renewed', { error, path, sinceLastRenewal: Date.now() - lastRenewal })
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
warn('lock compromised', { path })
|
||||
try {
|
||||
await pTimeout.call(takeLease(blobClient, leaseClient, path), RENEW_TIMEOUT)
|
||||
lastRenewal = Date.now()
|
||||
info('compromised lock was reacquired', { path })
|
||||
} catch (error) {
|
||||
lost = error.code === 'ELOCKED'
|
||||
warn('compromised lock could not be reacquired', { error, path })
|
||||
}
|
||||
}
|
||||
|
||||
function schedule() {
|
||||
timeout = setTimeout(() => {
|
||||
renewing = renew().then(() => {
|
||||
if (!released && !lost) {
|
||||
schedule()
|
||||
}
|
||||
})
|
||||
}, RENEW_INTERVAL)
|
||||
timeout.unref()
|
||||
}
|
||||
|
||||
schedule()
|
||||
|
||||
return async () => {
|
||||
released = true
|
||||
clearTimeout(timeout)
|
||||
|
||||
try {
|
||||
// a renewal in flight which found the blob deleted would take the lock again
|
||||
await renewing
|
||||
// only deletes the blob while the lease is ours: after a lost lock, it is someone else's
|
||||
await blobClient.delete({ conditions: { leaseId } })
|
||||
} catch (error) {
|
||||
// 404: the blob is gone; 412: it is not leased to `leaseId`
|
||||
if (error.statusCode !== 404 && error.statusCode !== 412) {
|
||||
warn('lock could not be released', { error, path })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,252 +0,0 @@
|
||||
import { after, afterEach, before, beforeEach, describe, it, mock } from 'node:test'
|
||||
import { strict as assert } from 'assert'
|
||||
|
||||
import 'dotenv/config'
|
||||
import sinon from 'sinon'
|
||||
import { ContainerClient } from '@azure/storage-blob'
|
||||
import { getHandler } from '.'
|
||||
import AzureHandler, { LEASE_DURATION, RENEW_INTERVAL, RENEW_TIMEOUT } from './azure.js'
|
||||
|
||||
// needs a real container, on Azure or Azurite
|
||||
//
|
||||
// xo_fs_azure='azure://<account>:<key>@<host>/<container>/<dir>' yarn workspace @xen-orchestra/fs test
|
||||
const url = process.env.xo_fs_azure
|
||||
|
||||
describe('AzureHandler#lock()', { skip: url === undefined }, () => {
|
||||
let handler
|
||||
|
||||
before(async () => {
|
||||
handler = getHandler({ url }).addPrefix(`xo-fs-tests-${Date.now()}`)
|
||||
await handler.sync()
|
||||
})
|
||||
|
||||
after(async () => {
|
||||
await handler?.forget()
|
||||
})
|
||||
|
||||
it('refuses a held lock until it is released', async () => {
|
||||
const lock = await handler.lock('vm')
|
||||
try {
|
||||
await assert.rejects(handler.lock('vm'), { code: 'ELOCKED' })
|
||||
} finally {
|
||||
await lock.dispose()
|
||||
}
|
||||
|
||||
const again = await handler.lock('vm')
|
||||
await again.dispose()
|
||||
})
|
||||
})
|
||||
|
||||
// `AzureHandler#_lock()` against a stubbed blob client: each status code it maps is checked through the lock it takes
|
||||
describe('AzureHandler#_lock with stubbed blob client', () => {
|
||||
let blob
|
||||
let leaseClient
|
||||
let getBlockBlobClientStub
|
||||
let handler
|
||||
|
||||
const httpError = statusCode => Object.assign(new Error(`HTTP ${statusCode}`), { statusCode })
|
||||
|
||||
// one renewal, after `RENEW_INTERVAL`
|
||||
async function renewOnce() {
|
||||
mock.timers.tick(RENEW_INTERVAL)
|
||||
await new Promise(resolve => setImmediate(resolve))
|
||||
}
|
||||
|
||||
// a request which hangs until `RENEW_TIMEOUT` gives up on it
|
||||
async function timeOut() {
|
||||
mock.timers.tick(RENEW_TIMEOUT)
|
||||
await new Promise(resolve => setImmediate(resolve))
|
||||
}
|
||||
|
||||
beforeEach(() => {
|
||||
mock.timers.enable({ apis: ['setTimeout', 'Date'] })
|
||||
|
||||
leaseClient = {
|
||||
acquireLease: sinon.stub().resolves(),
|
||||
renewLease: sinon.stub().resolves(),
|
||||
}
|
||||
blob = {
|
||||
upload: sinon.stub().resolves(),
|
||||
delete: sinon.stub().resolves(),
|
||||
getBlobLeaseClient: sinon.stub().returns(leaseClient),
|
||||
}
|
||||
getBlockBlobClientStub = sinon.stub(ContainerClient.prototype, 'getBlockBlobClient').returns(blob)
|
||||
|
||||
handler = new AzureHandler({ url: 'azure://account:a2V5@account.blob.core.windows.net/container/dir' })
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
getBlockBlobClientStub.restore()
|
||||
mock.timers.reset()
|
||||
})
|
||||
|
||||
it('leases the blob next to the path, under the directory of the handler, with a GUID of its own', async () => {
|
||||
const release = await handler._lock('vm')
|
||||
assert.deepEqual(getBlockBlobClientStub.firstCall.args, ['dir/vm.lock'])
|
||||
assert.match(
|
||||
blob.getBlobLeaseClient.firstCall.args[0],
|
||||
/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
|
||||
)
|
||||
assert.deepEqual(leaseClient.acquireLease.firstCall.args, [LEASE_DURATION])
|
||||
await release()
|
||||
})
|
||||
|
||||
describe('create', () => {
|
||||
// 409: the blob exists; 412: it exists and is leased
|
||||
for (const statusCode of [409, 412]) {
|
||||
it(`goes on to acquire the lease when create fails with ${statusCode}`, async () => {
|
||||
blob.upload.rejects(httpError(statusCode))
|
||||
|
||||
const release = await handler._lock('vm')
|
||||
assert.deepEqual(blob.upload.firstCall.args, ['', 0, { conditions: { ifNoneMatch: '*' } }])
|
||||
assert.equal(leaseClient.acquireLease.callCount, 1)
|
||||
await release()
|
||||
})
|
||||
}
|
||||
|
||||
it('rethrows an unexpected create error', async () => {
|
||||
blob.upload.rejects(httpError(500))
|
||||
|
||||
await assert.rejects(handler._lock('vm'), { statusCode: 500 })
|
||||
assert.equal(leaseClient.acquireLease.callCount, 0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('acquire', () => {
|
||||
it('reports a lease held by another as ELOCKED', async () => {
|
||||
leaseClient.acquireLease.rejects(httpError(409))
|
||||
|
||||
await assert.rejects(handler._lock('vm'), { code: 'ELOCKED' })
|
||||
})
|
||||
|
||||
it('retries once when the blob is gone, then gives up as ELOCKED', async () => {
|
||||
leaseClient.acquireLease.rejects(httpError(404))
|
||||
|
||||
await assert.rejects(handler._lock('vm'), { code: 'ELOCKED' })
|
||||
assert.equal(blob.upload.callCount, 2)
|
||||
assert.equal(leaseClient.acquireLease.callCount, 2)
|
||||
})
|
||||
|
||||
it('takes the lock when the blob is back on the retry', async () => {
|
||||
leaseClient.acquireLease.onFirstCall().rejects(httpError(404))
|
||||
|
||||
const release = await handler._lock('vm')
|
||||
assert.equal(blob.upload.callCount, 2)
|
||||
await release()
|
||||
})
|
||||
|
||||
it('rethrows an unexpected acquire error', async () => {
|
||||
leaseClient.acquireLease.rejects(httpError(500))
|
||||
|
||||
await assert.rejects(handler._lock('vm'), { statusCode: 500 })
|
||||
})
|
||||
})
|
||||
|
||||
describe('renew', () => {
|
||||
// 404: the blob is gone; 409: it is leased to someone else. Either way the lock is taken again
|
||||
for (const statusCode of [404, 409]) {
|
||||
it(`takes the lock again when renewal fails with ${statusCode}`, async () => {
|
||||
const release = await handler._lock('vm')
|
||||
leaseClient.renewLease.rejects(httpError(statusCode))
|
||||
|
||||
await renewOnce()
|
||||
assert.equal(leaseClient.renewLease.callCount, 1)
|
||||
assert.equal(leaseClient.acquireLease.callCount, 2)
|
||||
await release()
|
||||
})
|
||||
}
|
||||
|
||||
it('keeps the lock and renews again when renewal fails with another error', async () => {
|
||||
const release = await handler._lock('vm')
|
||||
leaseClient.renewLease.rejects(httpError(500))
|
||||
|
||||
await renewOnce()
|
||||
await renewOnce()
|
||||
assert.equal(leaseClient.renewLease.callCount, 2)
|
||||
assert.equal(leaseClient.acquireLease.callCount, 1)
|
||||
await release()
|
||||
})
|
||||
|
||||
it('gives up on a renewal which hangs, and renews again', async () => {
|
||||
const release = await handler._lock('vm')
|
||||
leaseClient.renewLease.onFirstCall().returns(new Promise(() => {}))
|
||||
|
||||
await renewOnce()
|
||||
await timeOut()
|
||||
await renewOnce()
|
||||
assert.equal(leaseClient.renewLease.callCount, 2)
|
||||
assert.equal(leaseClient.acquireLease.callCount, 1)
|
||||
await release()
|
||||
})
|
||||
|
||||
it('gives up on a reacquisition which hangs, and renews again', async () => {
|
||||
const release = await handler._lock('vm')
|
||||
leaseClient.renewLease.onFirstCall().rejects(httpError(409))
|
||||
leaseClient.acquireLease.onSecondCall().returns(new Promise(() => {}))
|
||||
|
||||
await renewOnce()
|
||||
await timeOut()
|
||||
await renewOnce()
|
||||
assert.equal(leaseClient.renewLease.callCount, 2)
|
||||
assert.equal(leaseClient.acquireLease.callCount, 2)
|
||||
await release()
|
||||
})
|
||||
|
||||
it('stops renewing once released', async () => {
|
||||
const release = await handler._lock('vm')
|
||||
await renewOnce()
|
||||
await release()
|
||||
|
||||
await renewOnce()
|
||||
assert.equal(leaseClient.renewLease.callCount, 1)
|
||||
})
|
||||
|
||||
it('gives up the lock when another holder has the lease', async () => {
|
||||
const release = await handler._lock('vm')
|
||||
leaseClient.renewLease.rejects(httpError(409))
|
||||
leaseClient.acquireLease.rejects(httpError(409))
|
||||
|
||||
await renewOnce()
|
||||
await renewOnce()
|
||||
assert.equal(leaseClient.renewLease.callCount, 1)
|
||||
assert.equal(leaseClient.acquireLease.callCount, 2)
|
||||
await release()
|
||||
})
|
||||
|
||||
it('waits for a renewal in flight before releasing', async () => {
|
||||
const release = await handler._lock('vm')
|
||||
let renewed
|
||||
leaseClient.renewLease.returns(new Promise(resolve => (renewed = resolve)))
|
||||
|
||||
await renewOnce()
|
||||
const releasing = release()
|
||||
await new Promise(resolve => setImmediate(resolve))
|
||||
assert.equal(blob.delete.callCount, 0)
|
||||
|
||||
renewed()
|
||||
await releasing
|
||||
assert.equal(blob.delete.callCount, 1)
|
||||
})
|
||||
})
|
||||
|
||||
describe('remove', () => {
|
||||
it('deletes the blob only while the lease is ours', async () => {
|
||||
const release = await handler._lock('vm')
|
||||
await release()
|
||||
|
||||
const [leaseId] = blob.getBlobLeaseClient.firstCall.args
|
||||
assert.deepEqual(blob.delete.firstCall.args, [{ conditions: { leaseId } }])
|
||||
})
|
||||
|
||||
// 404: the blob is gone; 412: it is not leased to us. Both are fine, and release never rejects anyway
|
||||
for (const statusCode of [404, 412, 500]) {
|
||||
it(`releases without rejecting when delete fails with ${statusCode}`, async () => {
|
||||
const release = await handler._lock('vm')
|
||||
blob.delete.rejects(httpError(statusCode))
|
||||
|
||||
await release()
|
||||
assert.equal(blob.delete.callCount, 1)
|
||||
})
|
||||
}
|
||||
})
|
||||
})
|
||||
@@ -19,7 +19,6 @@ import { getApplyMd5BodyChecksumPlugin } from '@aws-sdk/middleware-apply-body-ch
|
||||
import { Agent as HttpAgent } from 'http'
|
||||
import { Agent as HttpsAgent } from 'https'
|
||||
import { createLogger } from '@xen-orchestra/log'
|
||||
import lockedError from './_lockedError.js'
|
||||
import { PassThrough, Transform, pipeline } from 'stream'
|
||||
import { parse } from 'xo-remote-parser'
|
||||
import copyStreamToBuffer from './_copyStreamToBuffer.js'
|
||||
@@ -37,13 +36,6 @@ const MAX_PART_NUMBER = 10000
|
||||
const MIN_PART_SIZE = 5 * 1024 * 1024
|
||||
const { debug, info, warn } = createLogger('xo:fs:s3')
|
||||
|
||||
// how often a holder rewrites its lock object
|
||||
export const REFRESH_INTERVAL = 30e3
|
||||
|
||||
// how long a lock object may go without being rewritten before a contender takes it over: a holder survives a few
|
||||
// failed refreshes, and one which crashed blocks the path for 3 minutes at most
|
||||
export const STALE_AFTER = 180e3
|
||||
|
||||
export default class S3Handler extends RemoteHandlerAbstract {
|
||||
#bucket
|
||||
#dir
|
||||
@@ -51,8 +43,6 @@ export default class S3Handler extends RemoteHandlerAbstract {
|
||||
#httpAgent
|
||||
#httpsAgent
|
||||
#immutable = false
|
||||
// the S3 user may not read the bucket's Object Lock configuration: whether it is enabled is unknown
|
||||
#objectLockUnknown = false
|
||||
#maxPartSize
|
||||
#maxPartNumber
|
||||
#minPartSize
|
||||
@@ -524,12 +514,6 @@ export default class S3Handler extends RemoteHandlerAbstract {
|
||||
if (error.$metadata.httpStatusCode === 403) {
|
||||
info(`s3 user doesnt have enough privilege to check for Object Lock, enable content MD5 header`)
|
||||
this.#s3.middlewareStack.use(getApplyMd5BodyChecksumPlugin(this.#s3.config))
|
||||
if (!this.#objectLockUnknown) {
|
||||
warn(
|
||||
'the S3 user cannot read the Object Lock configuration of the bucket (s3:GetBucketObjectLockConfiguration), nothing is locked on this remote'
|
||||
)
|
||||
}
|
||||
this.#objectLockUnknown = true
|
||||
} else if (error.Code === 'ObjectLockConfigurationNotFoundError' || error.$metadata.httpStatusCode === 501) {
|
||||
info(`Object lock is not available or not configured, don't add the content MD5 header`)
|
||||
} else {
|
||||
@@ -537,77 +521,4 @@ export default class S3Handler extends RemoteHandlerAbstract {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Object Lock buckets keep the no-op lock of `RemoteHandlerAbstract`: every write of the lock object would leave
|
||||
// a version retained for the whole retention period. So do the buckets whose Object Lock configuration the S3
|
||||
// user cannot read (see `_sync()`).
|
||||
//
|
||||
// The lock is an object rewritten with plain writes, which every S3 provider supports: it is held while it is
|
||||
// fresher than STALE_AFTER. It is not atomic: two contenders which find it free at the same time both take it, and
|
||||
// a holder whose refreshes failed for STALE_AFTER keeps writing in a folder someone else took over.
|
||||
//
|
||||
// Its age is read on the provider's clock alone, `Last-Modified` against the `Date` of the response: XO's clock may
|
||||
// not agree with the provider's, and one more than 2.5 minutes ahead would take over a lock its holder keeps
|
||||
// refreshing (the SDK corrects its own clock only from 5 minutes off).
|
||||
async _lock(path) {
|
||||
if (this.isImmutable() || this.#objectLockUnknown) {
|
||||
return super._lock(path)
|
||||
}
|
||||
|
||||
// `<path>.lock`, the name of the local lock directory: the listings skip it already
|
||||
const params = this.#createParams(`${path}.lock`)
|
||||
|
||||
// the requests are sent with the S3 client directly, not through the handler's methods: those go through the
|
||||
// handler's concurrency limit, and a refresh queued behind long uploads would let the lock go stale
|
||||
const write = () => this.#s3.send(new PutObjectCommand({ ...params, Body: '' }))
|
||||
|
||||
// the output of a HEAD has no `Date`: it is read from the response
|
||||
let date
|
||||
const head = new HeadObjectCommand(params)
|
||||
head.middlewareStack.add(
|
||||
next => async args => {
|
||||
const result = await next(args)
|
||||
date = result.response.headers.date
|
||||
return result
|
||||
},
|
||||
{ step: 'deserialize' }
|
||||
)
|
||||
|
||||
let current
|
||||
try {
|
||||
current = await this.#s3.send(head)
|
||||
} catch (error) {
|
||||
if (error.name !== 'NotFound') {
|
||||
throw error
|
||||
}
|
||||
}
|
||||
// a provider which omits `Last-Modified` or `Date` never lets a lock be taken over: it stays held until released
|
||||
const age = Date.parse(date) - current?.LastModified?.getTime()
|
||||
if (current !== undefined && (Number.isNaN(age) || age <= STALE_AFTER)) {
|
||||
throw lockedError(path)
|
||||
}
|
||||
|
||||
await write()
|
||||
|
||||
let refreshing = Promise.resolve()
|
||||
const interval = setInterval(() => {
|
||||
refreshing = write().then(
|
||||
() => {},
|
||||
// a failed refresh is not a lost lock: the next one tries again
|
||||
error => debug('lock could not be refreshed', { error, path })
|
||||
)
|
||||
}, REFRESH_INTERVAL)
|
||||
interval.unref()
|
||||
|
||||
return async () => {
|
||||
clearInterval(interval)
|
||||
try {
|
||||
// a refresh landing after the delete would write the lock again
|
||||
await refreshing
|
||||
await this.#s3.send(new DeleteObjectCommand(params))
|
||||
} catch (error) {
|
||||
warn('lock could not be released', { error, path })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,216 +0,0 @@
|
||||
import { after, before, describe, it, beforeEach, afterEach, mock } from 'node:test'
|
||||
import { strict as assert } from 'assert'
|
||||
|
||||
import 'dotenv/config'
|
||||
import sinon from 'sinon'
|
||||
import {
|
||||
DeleteObjectCommand,
|
||||
GetObjectLockConfigurationCommand,
|
||||
HeadObjectCommand,
|
||||
PutObjectCommand,
|
||||
S3Client,
|
||||
} from '@aws-sdk/client-s3'
|
||||
import { getHandler } from '.'
|
||||
import S3Handler, { REFRESH_INTERVAL, STALE_AFTER } from './s3.js'
|
||||
|
||||
// needs a real bucket without Object Lock: on an Object Lock bucket the lock is the no-op one, the second
|
||||
// `lock()` succeeds, and this test fails
|
||||
//
|
||||
// xo_fs_s3='s3://<key>:<secret>@<host>/<bucket>/<dir>' yarn workspace @xen-orchestra/fs test
|
||||
const url = process.env.xo_fs_s3
|
||||
|
||||
describe('S3Handler#lock()', { skip: url === undefined }, () => {
|
||||
let handler
|
||||
|
||||
before(async () => {
|
||||
handler = getHandler({ url }).addPrefix(`xo-fs-tests-${Date.now()}`)
|
||||
await handler.sync()
|
||||
})
|
||||
|
||||
after(async () => {
|
||||
await handler?.forget()
|
||||
})
|
||||
|
||||
it('refuses a held lock until it is released', async () => {
|
||||
const lock = await handler.lock('vm')
|
||||
try {
|
||||
await assert.rejects(handler.lock('vm'), { code: 'ELOCKED' })
|
||||
} finally {
|
||||
await lock.dispose()
|
||||
}
|
||||
|
||||
const again = await handler.lock('vm')
|
||||
await again.dispose()
|
||||
})
|
||||
})
|
||||
|
||||
const createHandler = () => new S3Handler({ url: 's3://key:secret@localhost/bucket/dir' })
|
||||
|
||||
const s3Error = (name, httpStatusCode) => Object.assign(new Error(name), { name, $metadata: { httpStatusCode } })
|
||||
|
||||
// lets the async callback of a timer which just fired run to its end
|
||||
const flush = () => new Promise(resolve => setImmediate(resolve))
|
||||
|
||||
const KEY = 'dir/vm.lock'
|
||||
|
||||
// `S3Handler#_lock()` against a stubbed `S3Client#send()`
|
||||
describe('S3Handler#_lock() with a stubbed S3Client', () => {
|
||||
// by key
|
||||
let objects
|
||||
// what the provider does wrong, which each test sets
|
||||
let faults
|
||||
// how far the provider's clock is ahead of XO's
|
||||
let clockOffset
|
||||
let send
|
||||
|
||||
const providerDate = () => new Date(Date.now() + clockOffset)
|
||||
|
||||
beforeEach(() => {
|
||||
mock.timers.enable({ apis: ['setInterval', 'Date'] })
|
||||
objects = new Map()
|
||||
faults = {}
|
||||
clockOffset = 0
|
||||
|
||||
send = sinon.stub(S3Client.prototype, 'send').callsFake(async command => {
|
||||
const { Key } = command.input
|
||||
const current = objects.get(Key)
|
||||
|
||||
if (command instanceof PutObjectCommand) {
|
||||
if (faults.putStatus !== undefined) {
|
||||
throw s3Error('InternalError', faults.putStatus)
|
||||
}
|
||||
// resolved by the test
|
||||
if (faults.pendingPut !== undefined) {
|
||||
await faults.pendingPut
|
||||
}
|
||||
objects.set(Key, { lastModified: providerDate() })
|
||||
return {}
|
||||
}
|
||||
|
||||
if (command instanceof HeadObjectCommand) {
|
||||
if (current === undefined) {
|
||||
throw s3Error('NotFound', 404)
|
||||
}
|
||||
// the lock reads the `Date` of the response in a middleware of the command, which this stub bypasses: run it
|
||||
// on a response of its own
|
||||
await command.middlewareStack.resolve(
|
||||
async () => ({ response: { headers: { date: providerDate().toUTCString() } } }),
|
||||
{}
|
||||
)({ input: command.input })
|
||||
return { LastModified: current.lastModified }
|
||||
}
|
||||
|
||||
if (command instanceof DeleteObjectCommand) {
|
||||
objects.delete(Key)
|
||||
return {}
|
||||
}
|
||||
|
||||
if (command instanceof GetObjectLockConfigurationCommand) {
|
||||
if (faults.objectLock) {
|
||||
return { ObjectLockConfiguration: { ObjectLockEnabled: 'Enabled' } }
|
||||
}
|
||||
throw s3Error('AccessDenied', 403)
|
||||
}
|
||||
|
||||
throw new Error(`unexpected ${command.constructor.name}`)
|
||||
})
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
send.restore()
|
||||
mock.timers.reset()
|
||||
})
|
||||
|
||||
const writes = () => send.getCalls().filter(call => call.args[0] instanceof PutObjectCommand).length
|
||||
|
||||
for (const [what, objectLock] of [
|
||||
['on an Object Lock bucket', true],
|
||||
['when the S3 user cannot read the Object Lock configuration', false],
|
||||
]) {
|
||||
it(`takes no lock ${what}`, async () => {
|
||||
faults.objectLock = objectLock
|
||||
const handler = createHandler()
|
||||
await handler._sync()
|
||||
assert.equal(handler.isImmutable(), objectLock)
|
||||
|
||||
const release = await handler._lock('vm')
|
||||
await release()
|
||||
// the only request read the Object Lock configuration
|
||||
assert.equal(send.callCount, 1)
|
||||
})
|
||||
}
|
||||
|
||||
it('takes <path>.lock in the directory of the remote, rewrites it every REFRESH_INTERVAL, and deletes it', async () => {
|
||||
const release = await createHandler()._lock('vm')
|
||||
assert.equal(objects.get(KEY).lastModified.getTime(), Date.now())
|
||||
|
||||
mock.timers.tick(REFRESH_INTERVAL)
|
||||
await flush()
|
||||
assert.equal(writes(), 2)
|
||||
assert.equal(objects.get(KEY).lastModified.getTime(), Date.now())
|
||||
|
||||
await release()
|
||||
assert.equal(objects.has(KEY), false)
|
||||
})
|
||||
|
||||
it('refuses a held lock, and leaves it untouched', async () => {
|
||||
const handler = createHandler()
|
||||
const release = await handler._lock('vm')
|
||||
try {
|
||||
await assert.rejects(handler._lock('vm'), { code: 'ELOCKED' })
|
||||
assert.equal(writes(), 1)
|
||||
} finally {
|
||||
await release()
|
||||
}
|
||||
})
|
||||
|
||||
it("takes over a stale lock, not a fresh one, on the provider's clock", async () => {
|
||||
// XO's clock 2 minutes ahead: on it, the lock would look stale after 1 minute
|
||||
clockOffset = -120e3
|
||||
objects.set(KEY, { lastModified: providerDate() })
|
||||
|
||||
mock.timers.tick(STALE_AFTER)
|
||||
await assert.rejects(createHandler()._lock('vm'), { code: 'ELOCKED' })
|
||||
|
||||
// the resolution of `Date`
|
||||
mock.timers.tick(1e3)
|
||||
const release = await createHandler()._lock('vm')
|
||||
assert.equal(objects.get(KEY).lastModified.getTime(), providerDate().getTime())
|
||||
await release()
|
||||
})
|
||||
|
||||
it('keeps the lock when a refresh fails, and refreshes again', async () => {
|
||||
const release = await createHandler()._lock('vm')
|
||||
|
||||
faults.putStatus = 500
|
||||
mock.timers.tick(REFRESH_INTERVAL)
|
||||
await flush()
|
||||
assert.equal(objects.get(KEY).lastModified.getTime(), Date.now() - REFRESH_INTERVAL)
|
||||
|
||||
faults.putStatus = undefined
|
||||
mock.timers.tick(REFRESH_INTERVAL)
|
||||
await flush()
|
||||
assert.equal(objects.get(KEY).lastModified.getTime(), Date.now())
|
||||
|
||||
await release()
|
||||
assert.equal(objects.has(KEY), false)
|
||||
})
|
||||
|
||||
it('waits for a refresh in flight before deleting the lock', async () => {
|
||||
const release = await createHandler()._lock('vm')
|
||||
|
||||
let resolvePut
|
||||
faults.pendingPut = new Promise(resolve => {
|
||||
resolvePut = resolve
|
||||
})
|
||||
mock.timers.tick(REFRESH_INTERVAL)
|
||||
|
||||
const released = release()
|
||||
await flush()
|
||||
assert.equal(objects.has(KEY), true)
|
||||
|
||||
resolvePut()
|
||||
await released
|
||||
assert.equal(objects.has(KEY), false)
|
||||
})
|
||||
})
|
||||
@@ -16,13 +16,13 @@
|
||||
"xo-immutable-remote": "./dist/protectRemotes.mjs"
|
||||
},
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"version": "3.0.9",
|
||||
"version": "3.0.7",
|
||||
"engines": {
|
||||
"node": ">=20.0.0"
|
||||
},
|
||||
"dependencies": {
|
||||
"@vates/async-each": "^1.0.3",
|
||||
"@xen-orchestra/backups": "^0.78.0",
|
||||
"@xen-orchestra/backups": "^0.76.1",
|
||||
"@xen-orchestra/log": "^0.7.2",
|
||||
"app-conf": "^3.0.0",
|
||||
"execa": "^5.0.0",
|
||||
|
||||
@@ -2,16 +2,6 @@
|
||||
|
||||
## **next**
|
||||
|
||||
- [Web-Core/UiButtonIcon] Update icon buttons design, with a counter replacing the notification dot (PR [#10799](https://github.com/vatesfr/xen-orchestra/pull/10799))
|
||||
- [Mobile/Side panels] Full-page menus on mobile with "Change state" in "More actions", side panel actions shown as buttons when there is room, and fixes for long names in headers and menu placement (PR [#10745](https://github.com/vatesfr/xen-orchestra/pull/10745))
|
||||
- [Side panels] Side panels can be resized like the treeview, whose default width now adapts to the screen size (PR [#10725](https://github.com/vatesfr/xen-orchestra/pull/10725))
|
||||
- [Side panels] Values stay next to their label when they fit and move below it otherwise, fields with several values (IP addresses, bond devices) get a copy button per value and a "Copy all" action, and rows, links and statuses are more evenly spaced and sized (PR [#10733](https://github.com/vatesfr/xen-orchestra/pull/10733))
|
||||
- [Treeview] Fix translations of the tooltip for VM and host statuses in treeview (PR [#10643](https://github.com/vatesfr/xen-orchestra/pull/10643))
|
||||
- [Web-Core/UiDropdownButton] Update dropdown buttons design (PR [#9850](https://github.com/vatesfr/xen-orchestra/pull/9850))
|
||||
- [Tables] Tables are filtered as you type, half a second after the last keystroke, or right away with Enter; the "Search" button is removed (PR [#10797](https://github.com/vatesfr/xen-orchestra/pull/10797))
|
||||
|
||||
## **0.27.0** (2026-10-29)
|
||||
|
||||
- [New network] Choose between no NBD, secure NBD and insecure NBD (not encrypted) when creating a network (PR [#10540](https://github.com/vatesfr/xen-orchestra/pull/10540))
|
||||
- [VM/System] Fix video RAM displayed in bytes instead of MiB (PR [#10486](https://github.com/vatesfr/xen-orchestra/pull/10486))
|
||||
- [Treeview] Add a search bar and virtualize the tree (PR [#10414](https://github.com/vatesfr/xen-orchestra/pull/10414))
|
||||
@@ -24,12 +14,6 @@
|
||||
- [Treeview] Press Ctrl+K (Cmd+K on macOS) to focus the treeview search (PR [#10492](https://github.com/vatesfr/xen-orchestra/pull/10492))
|
||||
- [Pool] Fix connection, stats and consoles when overriding the pool master with `?master=`: use HTTPS by default instead of the protocol and port of the page (PR [#9955](https://github.com/vatesfr/xen-orchestra/pull/9955))
|
||||
- [Pool/Host/VM] Add copy button for multiple information on Host/VM Dashboard and Pool/Host/VM System tabs (PR [#9976](https://github.com/vatesfr/xen-orchestra/pull/9976))
|
||||
- [New/VM] Fix `MAP_DUPLICATE_KEY` error that could randomly prevent the VM creation (PR [#10552](https://github.com/vatesfr/xen-orchestra/pull/10552))
|
||||
- [Host/Network] Add the possibility to forget a PIF (PR [#10239](https://github.com/vatesfr/xen-orchestra/pull/10239))
|
||||
- [Lite] Display dates and times as `YYYY-MM-DD HH:mm:ss` (PR [#10547](https://github.com/vatesfr/xen-orchestra/pull/10547))
|
||||
- [Pool/Hosts] Add a side panel displaying the selected host's details, and a search bar to filter the hosts table (PR [#10580](https://github.com/vatesfr/xen-orchestra/pull/10580))
|
||||
- [VM/Host] Add console clipboard management (PR [#10625](https://github.com/vatesfr/xen-orchestra/pull/10625))
|
||||
- [VM/Network] Add the possibility to edit a VIF (PR [#10505](https://github.com/vatesfr/xen-orchestra/pull/10505))
|
||||
|
||||
## **0.26.0** (2026-10-01)
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@xen-orchestra/lite",
|
||||
"version": "0.27.0",
|
||||
"version": "0.26.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "GIT_HEAD=$(git rev-parse HEAD) vite",
|
||||
@@ -27,13 +27,13 @@
|
||||
"@types/file-saver": "^2.0.7",
|
||||
"@types/lodash-es": "^4.17.12",
|
||||
"@types/node": "^18.19.80",
|
||||
"@vates/types": "^2.5.0",
|
||||
"@vates/types": "^2.3.0",
|
||||
"@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.65.0",
|
||||
"@xen-orchestra/web-core": "^0.63.1",
|
||||
"complex-matcher": "^1.1.1",
|
||||
"d3-time-format": "^4.1.0",
|
||||
"decorator-synchronized": "^0.6.0",
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<VtsResponsiveMenu :title="t('account')" :section-title="t('menu')" placement="bottom-end">
|
||||
<MenuList placement="bottom-end">
|
||||
<template #trigger="{ open, isOpen }">
|
||||
<UiAccountMenuButton
|
||||
v-tooltip="isOpen ? false : { content: t('settings'), placement: 'left' }"
|
||||
@@ -33,13 +33,13 @@
|
||||
<MenuItem accent="brand" icon="fa:arrow-right-from-bracket" @click="logout">
|
||||
{{ t('action:log-out') }}
|
||||
</MenuItem>
|
||||
</VtsResponsiveMenu>
|
||||
</MenuList>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { useXenApiStore } from '@/stores/xen-api.store.ts'
|
||||
import MenuItem from '@core/components/menu/MenuItem.vue'
|
||||
import VtsResponsiveMenu from '@core/components/menu/VtsResponsiveMenu.vue'
|
||||
import MenuList from '@core/components/menu/MenuList.vue'
|
||||
import UiAccountMenuButton from '@core/components/ui/account-menu-button/UiAccountMenuButton.vue'
|
||||
import { vTooltip } from '@core/directives/tooltip.directive.ts'
|
||||
import { nextTick } from 'vue'
|
||||
|
||||
@@ -38,7 +38,7 @@
|
||||
Ctx
|
||||
</sup>
|
||||
</th>
|
||||
<td class="type">
|
||||
<td>
|
||||
<CodeHighlight :code="param.getTypeLabel()" />
|
||||
</td>
|
||||
<td class="reset-param">
|
||||
@@ -161,10 +161,6 @@ function openRawValueModal(code: string) {
|
||||
}
|
||||
}
|
||||
|
||||
.type :deep(.code-highlight) {
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.help {
|
||||
font-style: italic;
|
||||
color: var(--color-neutral-txt-secondary);
|
||||
|
||||
@@ -14,12 +14,27 @@
|
||||
<VtsIcon v-tooltip="t('master')" name="status:primary-circle" size="medium" />
|
||||
</template>
|
||||
<template #actions>
|
||||
<VtsChangeStateMenu v-if="!uiStore.isSmall">
|
||||
<MenuList placement="bottom-end">
|
||||
<template #trigger="{ open }">
|
||||
<UiDropdownButton @click="open($event)">{{ t('action:change-state') }}</UiDropdownButton>
|
||||
</template>
|
||||
<HostPowerStateActions :host />
|
||||
</VtsChangeStateMenu>
|
||||
<VtsActionsMenu :label="t('more-actions')" size="medium">
|
||||
<HostMoreActions :host :show-change-state="uiStore.isSmall" />
|
||||
</VtsActionsMenu>
|
||||
</MenuList>
|
||||
<MenuList placement="bottom-end">
|
||||
<template #trigger="{ open }">
|
||||
<UiButtonIcon
|
||||
v-tooltip="{
|
||||
placement: 'left',
|
||||
content: t('more-actions'),
|
||||
}"
|
||||
icon="action:more-actions"
|
||||
accent="brand"
|
||||
size="medium"
|
||||
@click="open($event)"
|
||||
/>
|
||||
</template>
|
||||
<HostMoreActions :host />
|
||||
</MenuList>
|
||||
</template>
|
||||
</UiHeadBar>
|
||||
</template>
|
||||
@@ -31,12 +46,12 @@ import HostMoreActions from '@/modules/host/components/HostMoreActions.vue'
|
||||
import { useHostUtils } from '@/modules/host/composables/host-utils.composable.ts'
|
||||
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
|
||||
import VtsIcon from '@core/components/icon/VtsIcon.vue'
|
||||
import VtsActionsMenu from '@core/components/menu/VtsActionsMenu.vue'
|
||||
import VtsChangeStateMenu from '@core/components/menu/VtsChangeStateMenu.vue'
|
||||
import MenuList from '@core/components/menu/MenuList.vue'
|
||||
import VtsObjectIcon from '@core/components/object-icon/VtsObjectIcon.vue'
|
||||
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
|
||||
import UiDropdownButton from '@core/components/ui/dropdown-button/UiDropdownButton.vue'
|
||||
import UiHeadBar from '@core/components/ui/head-bar/UiHeadBar.vue'
|
||||
import { vTooltip } from '@core/directives/tooltip.directive.ts'
|
||||
import { useUiStore } from '@core/stores/ui.store.ts'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
@@ -46,8 +61,6 @@ const { host } = defineProps<{
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const uiStore = useUiStore()
|
||||
|
||||
const { isMasterHost } = usePoolStore().subscribe()
|
||||
const isMaster = computed(() => isMasterHost(host.$ref))
|
||||
|
||||
|
||||
@@ -30,10 +30,16 @@
|
||||
<VtsKeyValueRow :label="t('uuid')" :value="host.uuid" copy />
|
||||
<VtsKeyValueRow :label="t('description')" :value="host.name_description" />
|
||||
<VtsKeyValueRow :label="t('version')" :value="host.software_version.product_version" />
|
||||
<VtsKeyValueRow :label="t('hardware')" :value="manufacturerInfo" />
|
||||
<VtsKeyValueRow
|
||||
:label="t('hardware')"
|
||||
:value="`${host.bios_strings['system-manufacturer']} (${host.bios_strings['system-product-name']})`"
|
||||
/>
|
||||
</VtsKeyValueList>
|
||||
<VtsKeyValueList>
|
||||
<VtsKeyValueRow :label="t('cores-with-sockets')" :value="coreSocketInfo" />
|
||||
<VtsKeyValueRow
|
||||
:label="t('cores-with-sockets')"
|
||||
:value="`${host.cpu_info.cpu_count} (${host.cpu_info.socket_count})`"
|
||||
/>
|
||||
<VtsKeyValueRow :label="t('ram')" :value="`${ram?.value} ${ram?.prefix}`" />
|
||||
<VtsKeyValueRow :label="t('tags')">
|
||||
<template #value>
|
||||
@@ -48,11 +54,10 @@
|
||||
|
||||
<script lang="ts" setup>
|
||||
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { useHostUtils } from '@/modules/host/composables/host-utils.composable.ts'
|
||||
import { getHostCoreSocketInfo, getHostManufacturerInfo } from '@/modules/host/utils/host.util.ts'
|
||||
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
|
||||
import { useHostStore } from '@/stores/xen-api/host.store.ts'
|
||||
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
|
||||
import type { IconName } from '@core/icons'
|
||||
import VtsIcon from '@core/components/icon/VtsIcon.vue'
|
||||
import VtsKeyValueList from '@core/components/key-value-list/VtsKeyValueList.vue'
|
||||
import VtsKeyValueRow from '@core/components/key-value-row/VtsKeyValueRow.vue'
|
||||
@@ -60,8 +65,10 @@ import VtsQuickInfoCard from '@core/components/quick-info-card/VtsQuickInfoCard.
|
||||
import VtsTag from '@core/components/tag/VtsTag.vue'
|
||||
import UiLink from '@core/components/ui/link/UiLink.vue'
|
||||
import UiTagsList from '@core/components/ui/tag/UiTagsList.vue'
|
||||
import useRelativeTime from '@core/composables/relative-time.composable.ts'
|
||||
import { vTooltip } from '@core/directives/tooltip.directive.ts'
|
||||
import { formatSizeRaw } from '@core/utils/size.util.ts'
|
||||
import { parseDateTime } from '@core/utils/time.util.ts'
|
||||
import { logicAnd } from '@vueuse/math'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
@@ -72,17 +79,24 @@ const { host } = defineProps<{
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const { masterHost, isReady: isPoolReady } = usePoolStore().subscribe()
|
||||
const { isMasterHost, masterHost, isReady: isPoolReady } = usePoolStore().subscribe()
|
||||
const { isReady: isHostReady } = useHostStore().subscribe()
|
||||
const { getHostMemory, isReady: isHostMetricsReady } = useHostMetricsStore().subscribe()
|
||||
|
||||
const { isMaster, isRunning, powerState, relativeStartTime } = useHostUtils(() => host)
|
||||
const { isHostRunning, getHostMemory, isReady: isHostMetricsReady } = useHostMetricsStore().subscribe()
|
||||
|
||||
const isReady = logicAnd(isPoolReady, isHostReady, isHostMetricsReady)
|
||||
|
||||
const manufacturerInfo = computed(() => getHostManufacturerInfo(host))
|
||||
const isRunning = computed(() => isHostRunning(host))
|
||||
|
||||
const coreSocketInfo = computed(() => getHostCoreSocketInfo(host))
|
||||
const powerState = computed<{ text: string; icon: IconName }>(() => ({
|
||||
text: isRunning.value ? t(`host:status:running`) : t('host:status:halted'),
|
||||
icon: isRunning.value ? 'status:running-circle' : 'status:halted-circle',
|
||||
}))
|
||||
|
||||
const date = computed(() => new Date(parseDateTime(Number(host.other_config.boot_time) * 1000)))
|
||||
|
||||
const relativeStartTime = useRelativeTime(date)
|
||||
|
||||
const isMaster = computed(() => isMasterHost(host.$ref))
|
||||
|
||||
const ram = computed(() => {
|
||||
const memory = getHostMemory(host)
|
||||
|
||||
@@ -1,18 +1,10 @@
|
||||
<template>
|
||||
<VtsSidePanel :has-selection="!!pif" class="host-pif-side-panel" @close="emit('close')">
|
||||
<template v-if="pif" #actions>
|
||||
<VtsForgetButton
|
||||
:busy="isForgettingPifs"
|
||||
:disabled="!canForgetPifs"
|
||||
:hint="forgetPifsErrorMessage"
|
||||
@click="forgetPifs()"
|
||||
/>
|
||||
</template>
|
||||
<template v-if="pif" #default>
|
||||
<!-- PIF -->
|
||||
<UiPanelCard>
|
||||
<UiPanelCardTitle :id="pif.uuid" size="medium" :label="isBond ? t('bond') : t('pif')" />
|
||||
<VtsCardRowList>
|
||||
<div class="content">
|
||||
<!-- NETWORK -->
|
||||
<VtsCardRowKeyValue>
|
||||
<template #key>
|
||||
@@ -82,15 +74,34 @@
|
||||
</UiTagsList>
|
||||
</template>
|
||||
</VtsCardRowKeyValue>
|
||||
</VtsCardRowList>
|
||||
</div>
|
||||
</UiPanelCard>
|
||||
<!-- NETWORK INFORMATION -->
|
||||
<UiPanelCard>
|
||||
<UiPanelCardTitle size="medium" :label="t('network-information')" />
|
||||
<VtsCardRowList>
|
||||
<div class="content">
|
||||
<!-- IP ADDRESSES -->
|
||||
<VtsCardRowKeyValue :values="ipAddresses">
|
||||
<template #key>{{ t('ip-addresses') }}</template>
|
||||
<div v-if="ipAddresses.length">
|
||||
<VtsCardRowKeyValue v-for="(ip, index) in ipAddresses" :key="ip">
|
||||
<template #key>
|
||||
<div v-if="index === 0">{{ t('ip-addresses') }}</div>
|
||||
</template>
|
||||
<template #value>
|
||||
<span v-tooltip class="text-ellipsis">{{ ip }}</span>
|
||||
</template>
|
||||
<template #addons>
|
||||
<VtsCopyButton :value="ip" />
|
||||
<VtsCopyAllMenuItem v-if="index === 0 && ipAddresses.length > 1" :values="ipAddresses" />
|
||||
</template>
|
||||
</VtsCardRowKeyValue>
|
||||
</div>
|
||||
<VtsCardRowKeyValue v-else>
|
||||
<template #key>
|
||||
{{ t('ip-addresses') }}
|
||||
</template>
|
||||
<template #value>
|
||||
<span class="value" />
|
||||
</template>
|
||||
</VtsCardRowKeyValue>
|
||||
<!-- MAC ADDRESSES -->
|
||||
<VtsCardRowKeyValue>
|
||||
@@ -154,15 +165,26 @@
|
||||
</template>
|
||||
</VtsCardRowKeyValue>
|
||||
<!-- BOND DEVICES -->
|
||||
<VtsCardRowKeyValue v-if="bondDevicesFiltered.length > 0" :values="bondDevicesFiltered">
|
||||
<template #key>{{ t('bond-devices') }}</template>
|
||||
</VtsCardRowKeyValue>
|
||||
</VtsCardRowList>
|
||||
<div>
|
||||
<VtsCardRowKeyValue v-for="(device, index) in bondDevices" :key="device">
|
||||
<template #key>
|
||||
<div v-if="index === 0">{{ t('bond-devices') }}</div>
|
||||
</template>
|
||||
<template #value>
|
||||
<span v-tooltip class="text-ellipsis">{{ device }}</span>
|
||||
</template>
|
||||
<template v-if="device" #addons>
|
||||
<VtsCopyButton :value="device" />
|
||||
<VtsCopyAllMenuItem v-if="index === 0 && bondDevices.length > 1" :values="bondDevicesFiltered" />
|
||||
</template>
|
||||
</VtsCardRowKeyValue>
|
||||
</div>
|
||||
</div>
|
||||
</UiPanelCard>
|
||||
<!-- PROPERTIES -->
|
||||
<UiPanelCard>
|
||||
<UiPanelCardTitle size="medium" :label="t('properties')" />
|
||||
<VtsCardRowList>
|
||||
<div class="content">
|
||||
<!-- MTU -->
|
||||
<VtsCardRowKeyValue>
|
||||
<template #key>
|
||||
@@ -196,7 +218,7 @@
|
||||
<VtsCopyButton :value="networkPurpose" />
|
||||
</template>
|
||||
</VtsCardRowKeyValue>
|
||||
</VtsCardRowList>
|
||||
</div>
|
||||
</UiPanelCard>
|
||||
</template>
|
||||
</VtsSidePanel>
|
||||
@@ -204,14 +226,12 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { XenApiPif } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { usePifForget } from '@/modules/pif/composables/use-pif-forget.composable.ts'
|
||||
import { useNetworkStore } from '@/stores/xen-api/network.store.ts'
|
||||
import { usePifMetricsStore } from '@/stores/xen-api/pif-metrics.store.ts'
|
||||
import { usePifStore } from '@/stores/xen-api/pif.store.ts'
|
||||
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
|
||||
import VtsCardRowList from '@core/components/card/VtsCardRowList.vue'
|
||||
import VtsCopyAllMenuItem from '@core/components/copy-all-menu-item/VtsCopyAllMenuItem.vue'
|
||||
import VtsCopyButton from '@core/components/copy-button/VtsCopyButton.vue'
|
||||
import VtsForgetButton from '@core/components/forget-button/VtsForgetButton.vue'
|
||||
import VtsIcon from '@core/components/icon/VtsIcon.vue'
|
||||
import VtsSidePanel from '@core/components/panel/VtsSidePanel.vue'
|
||||
import VtsStatus from '@core/components/status/VtsStatus.vue'
|
||||
@@ -238,10 +258,6 @@ const { getBondsDevices, isBondMaster } = usePifStore().subscribe()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const { forgetPifs, canForgetPifs, isForgettingPifs, forgetPifsErrorMessage } = usePifForget(() =>
|
||||
pif !== undefined ? [pif] : []
|
||||
)
|
||||
|
||||
const ipAddresses = computed(() => {
|
||||
if (pif === undefined) {
|
||||
return []
|
||||
@@ -301,6 +317,12 @@ const speed = computed(() => {
|
||||
|
||||
<style scoped lang="postcss">
|
||||
.host-pif-side-panel {
|
||||
.content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.8rem;
|
||||
}
|
||||
|
||||
.network {
|
||||
display: flex;
|
||||
gap: 0.8rem;
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
</template>
|
||||
</UiTitle>
|
||||
<div class="container">
|
||||
<UiQuerySearchBar v-bind="searchBindings" />
|
||||
<UiQuerySearchBar @search="(value: string) => (searchQuery = value)" />
|
||||
<VtsTable :state :pagination-bindings sticky="right">
|
||||
<thead>
|
||||
<tr>
|
||||
@@ -26,7 +26,6 @@
|
||||
|
||||
<script lang="ts" setup>
|
||||
import type { XenApiNetwork, XenApiPif } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { usePifForget } from '@/modules/pif/composables/use-pif-forget.composable.ts'
|
||||
import { useNetworkStore } from '@/stores/xen-api/network.store.ts'
|
||||
import { usePifStore } from '@/stores/xen-api/pif.store.ts'
|
||||
import VtsRow from '@core/components/table/VtsRow.vue'
|
||||
@@ -35,12 +34,11 @@ import UiQuerySearchBar from '@core/components/ui/query-search-bar/UiQuerySearch
|
||||
import UiTitle from '@core/components/ui/title/UiTitle.vue'
|
||||
import { usePagination } from '@core/composables/pagination.composable.ts'
|
||||
import { useRouteQuery } from '@core/composables/route-query.composable.ts'
|
||||
import { useSearchFilter } from '@core/composables/search-filter.composable.ts'
|
||||
import { useTableState } from '@core/composables/table-state.composable.ts'
|
||||
import { icon } from '@core/icons'
|
||||
import { usePifColumns } from '@core/tables/column-sets/pif-columns.ts'
|
||||
import { logicNot } from '@vueuse/math'
|
||||
import { computed } from 'vue'
|
||||
import { computed, ref } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const { pifs } = defineProps<{
|
||||
@@ -76,10 +74,21 @@ const getIpConfigurationMode = (ipMode: string) => {
|
||||
}
|
||||
}
|
||||
|
||||
const { items: filteredPifs, searchBindings } = useSearchFilter(
|
||||
() => pifs,
|
||||
pif => [...Object.values(pif), getNetworkName(pif.network)]
|
||||
)
|
||||
const searchQuery = ref('')
|
||||
|
||||
const filteredPifs = computed(() => {
|
||||
const searchTerm = searchQuery.value.trim().toLocaleLowerCase()
|
||||
|
||||
if (!searchTerm) {
|
||||
return pifs
|
||||
}
|
||||
|
||||
return pifs.filter(pif =>
|
||||
[...Object.values(pif), getNetworkName(pif.network)].some(value =>
|
||||
String(value).toLocaleLowerCase().includes(searchTerm)
|
||||
)
|
||||
)
|
||||
})
|
||||
|
||||
const state = useTableState({
|
||||
busy: logicNot(isReady),
|
||||
@@ -102,7 +111,7 @@ function getManagementIcon(pif: XenApiPif) {
|
||||
}
|
||||
|
||||
const { HeadCells, BodyCells } = usePifColumns({
|
||||
exclude: ['selectItem'],
|
||||
exclude: ['actions'],
|
||||
body: (pif: XenApiPif) => {
|
||||
const name = computed(() => getNetworkName(pif.network))
|
||||
const status = computed(() => getPifStatus(pif))
|
||||
@@ -111,8 +120,6 @@ const { HeadCells, BodyCells } = usePifColumns({
|
||||
const ipMode = computed(() => getIpConfigurationMode(pif.ip_configuration_mode))
|
||||
const rightIcon = computed(() => getManagementIcon(pif))
|
||||
|
||||
const { forgetPifs, canForgetPifs, isForgettingPifs, forgetPifsErrorMessage } = usePifForget(() => [pif])
|
||||
|
||||
return {
|
||||
network: r => r({ label: name.value }),
|
||||
device: r => r(pif.device, { rightIcon: rightIcon.value }),
|
||||
@@ -121,21 +128,7 @@ const { HeadCells, BodyCells } = usePifColumns({
|
||||
ip: r => r(ipAddresses.value),
|
||||
mac: r => r(pif.MAC),
|
||||
mode: r => r(ipMode.value),
|
||||
actions: r =>
|
||||
r({
|
||||
onClick: () => (selectedPifId.value = pif.uuid),
|
||||
actions: [
|
||||
{
|
||||
label: t('action:forget'),
|
||||
icon: 'action:forget',
|
||||
onClick: () => forgetPifs(),
|
||||
busy: isForgettingPifs.value,
|
||||
disabled: !canForgetPifs.value,
|
||||
hint: forgetPifsErrorMessage.value,
|
||||
accent: 'danger',
|
||||
},
|
||||
],
|
||||
}),
|
||||
selectItem: r => r(() => (selectedPifId.value = pif.uuid)),
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
@@ -58,7 +58,7 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { useHostUtils } from '@/modules/host/composables/host-utils.composable.ts'
|
||||
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
|
||||
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
|
||||
import VtsIcon from '@core/components/icon/VtsIcon.vue'
|
||||
import VtsRelativeTime from '@core/components/relative-time/VtsRelativeTime.vue'
|
||||
@@ -71,6 +71,7 @@ import UiLink from '@core/components/ui/link/UiLink.vue'
|
||||
import UiTagsList from '@core/components/ui/tag/UiTagsList.vue'
|
||||
import UiTitle from '@core/components/ui/title/UiTitle.vue'
|
||||
import { vTooltip } from '@core/directives/tooltip.directive.ts'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const { host } = defineProps<{
|
||||
@@ -79,7 +80,9 @@ const { host } = defineProps<{
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const { pool, masterHost } = usePoolStore().subscribe()
|
||||
const { pool, isMasterHost, masterHost } = usePoolStore().subscribe()
|
||||
const { isHostRunning } = useHostMetricsStore().subscribe()
|
||||
|
||||
const { isMaster, isRunning } = useHostUtils(() => host)
|
||||
const isMaster = computed(() => isMasterHost(host.$ref))
|
||||
const isRunning = computed(() => isHostRunning(host))
|
||||
</script>
|
||||
|
||||
@@ -4,13 +4,19 @@
|
||||
{{ t('hardware-specifications') }}
|
||||
</UiTitle>
|
||||
<VtsTabularKeyValueList>
|
||||
<VtsTabularKeyValueRow :label="t('manufacturer-info')" :value="manufacturerInfo" />
|
||||
<VtsTabularKeyValueRow
|
||||
:label="t('manufacturer-info')"
|
||||
:value="`${host.bios_strings['system-manufacturer']} (${host.bios_strings['system-product-name']})`"
|
||||
/>
|
||||
<VtsTabularKeyValueRow
|
||||
:label="t('bios-info')"
|
||||
:value="`${host.bios_strings['bios-vendor']} (${host.bios_strings['bios-version']})`"
|
||||
/>
|
||||
<VtsTabularKeyValueRow :label="t('cpu-model')" :value="host.cpu_info.modelname" />
|
||||
<VtsTabularKeyValueRow :label="t('core-socket')" :value="coreSocketInfo" />
|
||||
<VtsTabularKeyValueRow
|
||||
:label="t('core-socket')"
|
||||
:value="`${host.cpu_info.cpu_count} (${host.cpu_info.socket_count})`"
|
||||
/>
|
||||
<VtsTabularKeyValueRow :label="t('gpus')">
|
||||
<template v-if="isReady" #value>
|
||||
<template v-if="devicesNames">
|
||||
@@ -27,7 +33,6 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { getHostCoreSocketInfo, getHostManufacturerInfo } from '@/modules/host/utils/host.util.ts'
|
||||
import { usePciStore } from '@/stores/xen-api/pci.store.ts'
|
||||
import { usePgpuStore } from '@/stores/xen-api/pgpu.store.ts'
|
||||
import VtsTabularKeyValueList from '@core/components/tabular-key-value-list/VtsTabularKeyValueList.vue'
|
||||
@@ -36,7 +41,6 @@ import UiCard from '@core/components/ui/card/UiCard.vue'
|
||||
import UiTitle from '@core/components/ui/title/UiTitle.vue'
|
||||
import { logicAnd } from '@vueuse/math'
|
||||
import { useArrayReduce } from '@vueuse/shared'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const { host } = defineProps<{
|
||||
@@ -50,10 +54,6 @@ const { getByOpaqueRef: getPciByOpaqueRef, isReady: isPciReady } = usePciStore()
|
||||
|
||||
const isReady = logicAnd(isPgpuReady, isPciReady)
|
||||
|
||||
const manufacturerInfo = computed(() => getHostManufacturerInfo(host))
|
||||
|
||||
const coreSocketInfo = computed(() => getHostCoreSocketInfo(host))
|
||||
|
||||
const devicesNames = useArrayReduce(
|
||||
() => pGpusByHost.value.get(host.$ref) ?? [],
|
||||
(acc, pGpu) => {
|
||||
|
||||
@@ -17,12 +17,13 @@
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { useHostUtils } from '@/modules/host/composables/host-utils.composable.ts'
|
||||
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
|
||||
import VtsRelativeTime from '@core/components/relative-time/VtsRelativeTime.vue'
|
||||
import VtsTabularKeyValueList from '@core/components/tabular-key-value-list/VtsTabularKeyValueList.vue'
|
||||
import VtsTabularKeyValueRow from '@core/components/tabular-key-value-row/VtsTabularKeyValueRow.vue'
|
||||
import UiCard from '@core/components/ui/card/UiCard.vue'
|
||||
import UiTitle from '@core/components/ui/title/UiTitle.vue'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const { host } = defineProps<{
|
||||
@@ -31,5 +32,7 @@ const { host } = defineProps<{
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const { isRunning } = useHostUtils(() => host)
|
||||
const { isHostRunning } = useHostMetricsStore().subscribe()
|
||||
|
||||
const isRunning = computed(() => isHostRunning(host))
|
||||
</script>
|
||||
|
||||
@@ -1,84 +1,110 @@
|
||||
<template>
|
||||
<tr class="pif-row" :class="{ compact }">
|
||||
<td class="typo-body-regular-small host">
|
||||
<UiLink
|
||||
v-if="host"
|
||||
:to="{ name: '/host/[uuid]/network', params: { uuid: host.uuid }, query: { id: pif.uuid } }"
|
||||
:icon="getHostIcon(host, getHostPowerState(host))"
|
||||
:is-primary="isMasterHost(host.$ref)"
|
||||
:primary-tooltip="t('master')"
|
||||
size="small"
|
||||
class="host-link"
|
||||
>
|
||||
<span v-tooltip class="text-ellipsis">{{ host.name_label }}</span>
|
||||
</UiLink>
|
||||
<span v-else>{{ t('host:status:unknown') }}</span>
|
||||
<tr class="pif-row" :class="{ clickable: pifHost }" @click="pifHost?.redirect()">
|
||||
<td v-tooltip class="typo-body-regular-small text-ellipsis host-container">
|
||||
<div v-if="pifHost" class="host">
|
||||
<VtsObjectIcon :state="pifHost.powerState" type="host" size="small" />
|
||||
<span v-tooltip class="typo-body-regular-small text-ellipsis host-name">
|
||||
{{ pifHost.label }}
|
||||
</span>
|
||||
</div>
|
||||
<div v-else>
|
||||
<span>{{ t('host:status:unknown') }}</span>
|
||||
</div>
|
||||
</td>
|
||||
<td v-tooltip class="typo-body-regular-small text-ellipsis device">{{ pif.device }}</td>
|
||||
<td class="typo-body-regular-small status">
|
||||
<VtsStatus :status :icon-only="compact" />
|
||||
<td v-tooltip class="typo-body-regular-small status">
|
||||
<VtsStatus :status />
|
||||
</td>
|
||||
<td>
|
||||
<UiButtonIcon size="small" accent="brand" icon="fa:angle-right" :disabled="!pifHost" />
|
||||
</td>
|
||||
</tr>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { XenApiPif } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { getHostIcon } from '@/modules/host/utils/host.util.ts'
|
||||
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
|
||||
import { useHostStore } from '@/stores/xen-api/host.store.ts'
|
||||
import { usePifStore } from '@/stores/xen-api/pif.store.ts'
|
||||
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
|
||||
import VtsObjectIcon from '@core/components/object-icon/VtsObjectIcon.vue'
|
||||
import VtsStatus from '@core/components/status/VtsStatus.vue'
|
||||
import UiLink from '@core/components/ui/link/UiLink.vue'
|
||||
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
|
||||
import { vTooltip } from '@core/directives/tooltip.directive.ts'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import { useRouter } from 'vue-router'
|
||||
|
||||
const { pif } = defineProps<{
|
||||
pif: XenApiPif
|
||||
compact?: boolean
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const { getByOpaqueRef } = useHostStore().subscribe()
|
||||
const { getHostPowerState } = useHostMetricsStore().subscribe()
|
||||
const { isHostRunning } = useHostMetricsStore().subscribe()
|
||||
const { getPifStatus } = usePifStore().subscribe()
|
||||
const { isMasterHost } = usePoolStore().subscribe()
|
||||
|
||||
const host = computed(() => getByOpaqueRef(pif.host))
|
||||
const router = useRouter()
|
||||
|
||||
const status = computed(() => getPifStatus(pif))
|
||||
|
||||
const pifHost = computed(() => {
|
||||
const host = getByOpaqueRef(pif.host)
|
||||
|
||||
if (!host) {
|
||||
return
|
||||
}
|
||||
|
||||
return {
|
||||
label: host.name_label,
|
||||
powerState: isHostRunning(host) ? 'running' : 'halted',
|
||||
redirect() {
|
||||
router.push({
|
||||
name: '/host/[uuid]/network',
|
||||
params: { uuid: host.uuid },
|
||||
query: { id: pif.uuid },
|
||||
})
|
||||
},
|
||||
} as const
|
||||
})
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
.pif-row {
|
||||
&.clickable {
|
||||
cursor: pointer;
|
||||
|
||||
&:hover {
|
||||
background-color: var(--color-brand-background-hover);
|
||||
}
|
||||
}
|
||||
|
||||
td {
|
||||
color: var(--color-neutral-txt-primary);
|
||||
}
|
||||
|
||||
.host-link {
|
||||
max-width: 100%;
|
||||
}
|
||||
.host-container {
|
||||
max-width: 14rem;
|
||||
|
||||
&:not(.compact) {
|
||||
.host {
|
||||
max-width: 14rem;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.8rem;
|
||||
}
|
||||
|
||||
.device {
|
||||
width: 8rem;
|
||||
max-width: 8rem;
|
||||
}
|
||||
|
||||
.status {
|
||||
width: 11.5rem;
|
||||
max-width: 11.5rem;
|
||||
.host-name {
|
||||
color: var(--color-brand-txt-base);
|
||||
}
|
||||
}
|
||||
|
||||
&.compact .device {
|
||||
padding-inline-start: 1.6rem;
|
||||
.device {
|
||||
width: 8rem;
|
||||
max-width: 8rem;
|
||||
}
|
||||
|
||||
.status {
|
||||
width: 11.5rem;
|
||||
max-width: 11.5rem;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user