mirror of
https://github.com/vatesfr/xen-orchestra.git
synced 2026-11-23 07:18:09 -06:00
Compare commits
23 Commits
rest-api/p
...
docs/body-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
239db19d92 | ||
|
|
932794389d | ||
|
|
1f03e87932 | ||
|
|
0857694312 | ||
|
|
641b13e593 | ||
|
|
9866e0c47c | ||
|
|
6166c9321f | ||
|
|
8b4fd15a86 | ||
|
|
3eb48bdbdb | ||
|
|
83b1ce297f | ||
|
|
30d30a66c7 | ||
|
|
79219f2e1c | ||
|
|
67ed8f7eb3 | ||
|
|
2783e60933 | ||
|
|
7679bb0d44 | ||
|
|
b9f5b0724e | ||
|
|
7d5c818efb | ||
|
|
152365f984 | ||
|
|
83c3e344ba | ||
|
|
56ffcdba29 | ||
|
|
1d3e1fce39 | ||
|
|
4cd316d23b | ||
|
|
6e7a6659ab |
@@ -5,5 +5,7 @@ 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'
|
||||
|
||||
219
@vates/types/src/lib/xen-orchestra-v2v.mts
Normal file
219
@vates/types/src/lib/xen-orchestra-v2v.mts
Normal file
@@ -0,0 +1,219 @@
|
||||
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
|
||||
}
|
||||
103
@vates/types/src/lib/xen-orchestra-vmware-explorer.mts
Normal file
103
@vates/types/src/lib/xen-orchestra-vmware-explorer.mts
Normal file
@@ -0,0 +1,103 @@
|
||||
// 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[]
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import type {
|
||||
AnyXoJob,
|
||||
AnyXoLog,
|
||||
NonXapiXoRecord,
|
||||
XoBackupDiskPartition,
|
||||
XapiXoRecord,
|
||||
XoAuthenticationToken,
|
||||
XoBackupRepository,
|
||||
@@ -11,6 +12,7 @@ import type {
|
||||
XoHost,
|
||||
XoMetadataBackupJob,
|
||||
XoMirrorBackupJob,
|
||||
XoNetwork,
|
||||
XoPlugin,
|
||||
XoPool,
|
||||
XoPoolBackupArchive,
|
||||
@@ -24,9 +26,12 @@ import type {
|
||||
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,
|
||||
@@ -205,6 +210,15 @@ 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: {
|
||||
@@ -285,8 +299,8 @@ export type XoApp = EventEmitter & {
|
||||
backupGuard(objectId: XapiXoRecord['id'], opts?: { bypassBackupCheck?: boolean; operation: string }): Promise<void>
|
||||
/* Throw if no authorization */
|
||||
checkFeatureAuthorization(featureCode: FeatureCode): Promise<void>
|
||||
/* Throw if the proxy cannot be reached */
|
||||
checkProxyHealth(id: XoProxy['id']): 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) */
|
||||
@@ -400,7 +414,6 @@ export type XoApp = EventEmitter & {
|
||||
getPlugin(id: XoPlugin['id']): Promise<XoPlugin>
|
||||
getPlugins(): Promise<XoPlugin[]>
|
||||
getProxy(id: XoProxy['id']): Promise<XoProxy>
|
||||
getProxyApplianceUpdaterState(id: XoProxy['id']): Promise<{ level: string; message: string; state: string }>
|
||||
getRemote(id: XoBackupRepository['id']): Promise<XoBackupRepository>
|
||||
getAllRemotes(): Promise<XoBackupRepository[]>
|
||||
removeRemote(id: XoBackupRepository['id']): Promise<void>
|
||||
@@ -469,6 +482,7 @@ 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>(
|
||||
@@ -484,6 +498,22 @@ export type XoApp = EventEmitter & {
|
||||
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[]>
|
||||
@@ -494,6 +524,21 @@ 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`.
|
||||
@@ -631,8 +676,6 @@ export type XoApp = EventEmitter & {
|
||||
url?: string
|
||||
}
|
||||
): Promise<XoBackupRepository>
|
||||
/** Throw if backup jobs are running on the proxy, unless ignored; `force` reboots the proxy VM */
|
||||
upgradeProxyAppliance(id: XoProxy['id'], opts: { force?: boolean; ignoreRunningJobs?: boolean }): Promise<void>
|
||||
getAllXapis(): Record<string, Xapi>
|
||||
getObjects(opts?: { filter?: Record<string, unknown>; limit?: number }): Record<string, XapiXoRecord>
|
||||
getLicenses(params?: { productType?: LicenseProductType }): Promise<License[]>
|
||||
|
||||
@@ -180,6 +180,15 @@ 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'
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
export default {
|
||||
read: true,
|
||||
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
|
||||
}
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
export default {
|
||||
read: true,
|
||||
upgrade: true,
|
||||
}
|
||||
|
||||
@@ -27,6 +27,7 @@ import { formatFilenameDate } from './_filenameDate.mjs'
|
||||
import { isMetadataFile } from './_backupType.mjs'
|
||||
import {
|
||||
isKnownJournalEvent,
|
||||
purgeBackupJournal,
|
||||
readBackupJournal,
|
||||
writeBackupJournalEntries,
|
||||
writeBackupJournalEntry,
|
||||
@@ -65,6 +66,10 @@ 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() {
|
||||
@@ -555,6 +560,14 @@ 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.
|
||||
|
||||
@@ -393,6 +393,47 @@ 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,3 +309,47 @@ 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 })
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { strict as assert } from 'node:assert'
|
||||
import test from 'node:test'
|
||||
import { execFile } from 'node:child_process'
|
||||
import { copyFile, mkdtemp, rm, writeFile } from 'node:fs/promises'
|
||||
import { copyFile, mkdir, mkdtemp, rm, symlink, writeFile } from 'node:fs/promises'
|
||||
import { Stream } from 'node:stream'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
@@ -9,6 +9,7 @@ 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'
|
||||
|
||||
@@ -71,6 +72,83 @@ 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,7 +66,29 @@ export const toLvPartitions = (partitionId, originalVgName, lvItems) =>
|
||||
}))
|
||||
|
||||
const makeRelative = path => resolve('/', path).slice(1)
|
||||
const resolveSubpath = (root, path) => resolve(root, makeRelative(path))
|
||||
|
||||
// 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
|
||||
}
|
||||
|
||||
async function addZipEntries(zip, realBasePath, virtualBasePath, relativePaths) {
|
||||
for (const relativePath of relativePaths) {
|
||||
@@ -290,6 +312,12 @@ 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') {
|
||||
@@ -298,7 +326,13 @@ 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.
|
||||
const pack = tar.c({ cwd: path, gzip: true, jobs: 1 }, paths.map(makeRelative))
|
||||
//
|
||||
// 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
|
||||
)
|
||||
|
||||
// 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
|
||||
@@ -316,7 +350,7 @@ export const fileRestoreMethods = {
|
||||
// appear as a freeze with no response sent.
|
||||
outputStream = zip.outputStream
|
||||
resolve(zip.outputStream)
|
||||
await addZipEntries(zip, path, '', paths.map(makeRelative))
|
||||
await addZipEntries(zip, path, '', relativePaths)
|
||||
zip.end()
|
||||
} else {
|
||||
throw new Error('unsupported format ' + format)
|
||||
@@ -331,17 +365,23 @@ export const fileRestoreMethods = {
|
||||
},
|
||||
|
||||
async *getDisk(diskId) {
|
||||
if (this._useGetDiskLegacy) {
|
||||
yield* getDiskLegacy(this._handler, diskId)
|
||||
return
|
||||
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)
|
||||
}
|
||||
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:
|
||||
@@ -371,7 +411,7 @@ export const fileRestoreMethods = {
|
||||
|
||||
listPartitionFiles(diskId, partitionId, path) {
|
||||
return Disposable.use(this.getPartition(diskId, partitionId), async rootPath => {
|
||||
path = resolveSubpath(rootPath, path)
|
||||
path = join(rootPath, await resolveWithoutSymlinks(rootPath, path))
|
||||
const entriesMap = {}
|
||||
await asyncEach(
|
||||
await readdir(path),
|
||||
@@ -397,7 +437,13 @@ export const fileRestoreMethods = {
|
||||
},
|
||||
|
||||
listPartitions(diskId) {
|
||||
return Disposable.use(this.getDisk(diskId), async devicePath => {
|
||||
const cache = this._partitionsCache
|
||||
const cached = cache.get(diskId)
|
||||
if (cached !== undefined) {
|
||||
return cached
|
||||
}
|
||||
|
||||
const pPartitions = 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 —
|
||||
@@ -415,11 +461,14 @@ 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 []
|
||||
}
|
||||
}
|
||||
@@ -455,6 +504,16 @@ 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
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -60,7 +60,7 @@ const parsePartxLine = createParser({
|
||||
export async function listPartitions(devicePath) {
|
||||
const parts = await fromCallback(execFile, 'partx', [
|
||||
'--bytes',
|
||||
'--output=NR,START,SIZE,NAME,UUID,TYPE',
|
||||
'--output=START,SIZE,NAME,UUID,TYPE',
|
||||
'--pairs',
|
||||
devicePath,
|
||||
]).catch(error => {
|
||||
|
||||
@@ -65,6 +65,11 @@ 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
|
||||
|
||||
@@ -72,11 +77,9 @@ export class IncrementalXapiWriter extends MixinXapiWriter(AbstractIncrementalWr
|
||||
|
||||
if (contentKey !== undefined) {
|
||||
debug('got one content key, look for a candidate')
|
||||
target = sr.$VDIs.find(
|
||||
target = replicaSnapshots.find(
|
||||
vdi =>
|
||||
vdi?.managed &&
|
||||
vdi?.is_a_snapshot &&
|
||||
vdi.other_config[CONTENT_KEY] === contentKey && // &&
|
||||
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
|
||||
)
|
||||
@@ -85,13 +88,11 @@ 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 = sr.$VDIs.find(
|
||||
target = replicaSnapshots.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) {
|
||||
|
||||
@@ -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 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/<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/.queue/clean-vm/<YYYYMMDD>T<HHmmss>-<random>`, the merge worker queue
|
||||
- `.<VHD file name>.merge.json`, in a VDI directory, interrupted merge states.
|
||||
|
||||
@@ -167,6 +167,7 @@ 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
|
||||
|
||||
4
@xen-orchestra/fs/src/_lockedError.js
Normal file
4
@xen-orchestra/fs/src/_lockedError.js
Normal file
@@ -0,0 +1,4 @@
|
||||
// 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,9 +1,12 @@
|
||||
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')
|
||||
@@ -11,7 +14,52 @@ 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 { warn, info } = createLogger('xo:fs: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)
|
||||
}
|
||||
|
||||
export default class AzureHandler extends RemoteHandlerAbstract {
|
||||
#container
|
||||
@@ -330,4 +378,89 @@ 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 })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
252
@xen-orchestra/fs/src/azure.test.js
Normal file
252
@xen-orchestra/fs/src/azure.test.js
Normal file
@@ -0,0 +1,252 @@
|
||||
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,6 +19,7 @@ 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'
|
||||
@@ -36,6 +37,13 @@ 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
|
||||
@@ -43,6 +51,8 @@ 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
|
||||
@@ -514,6 +524,12 @@ 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 {
|
||||
@@ -521,4 +537,77 @@ 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 })
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
216
@xen-orchestra/fs/src/s3.test.js
Normal file
216
@xen-orchestra/fs/src/s3.test.js
Normal file
@@ -0,0 +1,216 @@
|
||||
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)
|
||||
})
|
||||
})
|
||||
@@ -2,10 +2,13 @@
|
||||
|
||||
## **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)
|
||||
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<MenuList placement="bottom-end">
|
||||
<VtsResponsiveMenu :title="t('account')" :section-title="t('menu')" 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>
|
||||
</MenuList>
|
||||
</VtsResponsiveMenu>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { useXenApiStore } from '@/stores/xen-api.store.ts'
|
||||
import MenuItem from '@core/components/menu/MenuItem.vue'
|
||||
import MenuList from '@core/components/menu/MenuList.vue'
|
||||
import VtsResponsiveMenu from '@core/components/menu/VtsResponsiveMenu.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>
|
||||
<td class="type">
|
||||
<CodeHighlight :code="param.getTypeLabel()" />
|
||||
</td>
|
||||
<td class="reset-param">
|
||||
@@ -161,6 +161,10 @@ function openRawValueModal(code: string) {
|
||||
}
|
||||
}
|
||||
|
||||
.type :deep(.code-highlight) {
|
||||
white-space: pre-wrap;
|
||||
}
|
||||
|
||||
.help {
|
||||
font-style: italic;
|
||||
color: var(--color-neutral-txt-secondary);
|
||||
|
||||
@@ -14,29 +14,12 @@
|
||||
<VtsIcon v-tooltip="t('master')" name="status:primary-circle" size="medium" />
|
||||
</template>
|
||||
<template #actions>
|
||||
<MenuList placement="bottom-end">
|
||||
<template #trigger="{ open }">
|
||||
<UiDropdownButton size="medium" variant="primary" @click="open($event)">
|
||||
{{ t('action:change-state') }}
|
||||
</UiDropdownButton>
|
||||
</template>
|
||||
<VtsChangeStateMenu v-if="!uiStore.isSmall">
|
||||
<HostPowerStateActions :host />
|
||||
</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>
|
||||
</VtsChangeStateMenu>
|
||||
<VtsActionsMenu :label="t('more-actions')" size="medium">
|
||||
<HostMoreActions :host :show-change-state="uiStore.isSmall" />
|
||||
</VtsActionsMenu>
|
||||
</template>
|
||||
</UiHeadBar>
|
||||
</template>
|
||||
@@ -48,12 +31,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 MenuList from '@core/components/menu/MenuList.vue'
|
||||
import VtsActionsMenu from '@core/components/menu/VtsActionsMenu.vue'
|
||||
import VtsChangeStateMenu from '@core/components/menu/VtsChangeStateMenu.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'
|
||||
|
||||
@@ -63,6 +46,8 @@ const { host } = defineProps<{
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const uiStore = useUiStore()
|
||||
|
||||
const { isMasterHost } = usePoolStore().subscribe()
|
||||
const isMaster = computed(() => isMasterHost(host.$ref))
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
<VtsForgetButton
|
||||
:busy="isForgettingPifs"
|
||||
:disabled="!canForgetPifs"
|
||||
:tooltip="!canForgetPifs && forgetPifsErrorMessage"
|
||||
:hint="forgetPifsErrorMessage"
|
||||
@click="forgetPifs()"
|
||||
/>
|
||||
</template>
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
</template>
|
||||
</UiTitle>
|
||||
<div class="container">
|
||||
<UiQuerySearchBar @search="(value: string) => (searchQuery = value)" />
|
||||
<UiQuerySearchBar v-bind="searchBindings" />
|
||||
<VtsTable :state :pagination-bindings sticky="right">
|
||||
<thead>
|
||||
<tr>
|
||||
@@ -35,11 +35,12 @@ 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, ref } from 'vue'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const { pifs } = defineProps<{
|
||||
@@ -75,21 +76,10 @@ const getIpConfigurationMode = (ipMode: string) => {
|
||||
}
|
||||
}
|
||||
|
||||
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 { items: filteredPifs, searchBindings } = useSearchFilter(
|
||||
() => pifs,
|
||||
pif => [...Object.values(pif), getNetworkName(pif.network)]
|
||||
)
|
||||
|
||||
const state = useTableState({
|
||||
busy: logicNot(isReady),
|
||||
|
||||
@@ -1,42 +1,42 @@
|
||||
<template>
|
||||
<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>
|
||||
<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>
|
||||
</td>
|
||||
<td v-tooltip class="typo-body-regular-small text-ellipsis device">{{ pif.device }}</td>
|
||||
<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 class="typo-body-regular-small status">
|
||||
<VtsStatus :status :icon-only="compact" />
|
||||
</td>
|
||||
</tr>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import type { XenApiPif } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { getHostState } from '@/modules/host/utils/host.util.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 VtsObjectIcon from '@core/components/object-icon/VtsObjectIcon.vue'
|
||||
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
|
||||
import VtsStatus from '@core/components/status/VtsStatus.vue'
|
||||
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
|
||||
import UiLink from '@core/components/ui/link/UiLink.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()
|
||||
@@ -44,68 +44,41 @@ const { t } = useI18n()
|
||||
const { getByOpaqueRef } = useHostStore().subscribe()
|
||||
const { getHostPowerState } = useHostMetricsStore().subscribe()
|
||||
const { getPifStatus } = usePifStore().subscribe()
|
||||
const { isMasterHost } = usePoolStore().subscribe()
|
||||
|
||||
const router = useRouter()
|
||||
const host = computed(() => getByOpaqueRef(pif.host))
|
||||
|
||||
const status = computed(() => getPifStatus(pif))
|
||||
|
||||
const pifHost = computed(() => {
|
||||
const host = getByOpaqueRef(pif.host)
|
||||
|
||||
if (!host) {
|
||||
return
|
||||
}
|
||||
|
||||
return {
|
||||
label: host.name_label,
|
||||
powerState: getHostState(host, getHostPowerState(host)),
|
||||
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-container {
|
||||
max-width: 14rem;
|
||||
.host-link {
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
&:not(.compact) {
|
||||
.host {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.8rem;
|
||||
max-width: 14rem;
|
||||
}
|
||||
|
||||
.host-name {
|
||||
color: var(--color-brand-txt-base);
|
||||
.device {
|
||||
width: 8rem;
|
||||
max-width: 8rem;
|
||||
}
|
||||
|
||||
.status {
|
||||
width: 11.5rem;
|
||||
max-width: 11.5rem;
|
||||
}
|
||||
}
|
||||
|
||||
.device {
|
||||
width: 8rem;
|
||||
max-width: 8rem;
|
||||
}
|
||||
|
||||
.status {
|
||||
width: 11.5rem;
|
||||
max-width: 11.5rem;
|
||||
&.compact .device {
|
||||
padding-inline-start: 1.6rem;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
</template>
|
||||
</UiTitle>
|
||||
<div class="container">
|
||||
<UiQuerySearchBar @search="value => (searchQuery = value)" />
|
||||
<UiQuerySearchBar v-bind="searchBindings" />
|
||||
<VtsTable :state :pagination-bindings sticky="right">
|
||||
<thead>
|
||||
<tr>
|
||||
@@ -38,10 +38,10 @@ 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 { useNetworkColumns } from '@core/tables/column-sets/network-columns.ts'
|
||||
import { logicNot } from '@vueuse/math'
|
||||
import { computed, ref } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const { networks } = defineProps<{
|
||||
@@ -60,19 +60,7 @@ const selectedNetworkId = useRouteQuery('id')
|
||||
|
||||
const getLockingMode = (lockingMode: string) => (lockingMode === 'disabled' ? t('disabled') : t('unlocked'))
|
||||
|
||||
const searchQuery = ref('')
|
||||
|
||||
const filteredNetworks = computed(() => {
|
||||
const searchTerm = searchQuery.value.trim().toLocaleLowerCase()
|
||||
|
||||
if (!searchTerm) {
|
||||
return networks
|
||||
}
|
||||
|
||||
return networks.filter(network =>
|
||||
Object.values(network).some(value => String(value).toLocaleLowerCase().includes(searchTerm))
|
||||
)
|
||||
})
|
||||
const { items: filteredNetworks, searchBindings } = useSearchFilter(() => networks)
|
||||
|
||||
const { pageRecords: paginatedNetworks, paginationBindings } = usePagination('internal-networks', filteredNetworks)
|
||||
|
||||
|
||||
@@ -1,22 +1,10 @@
|
||||
<template>
|
||||
<VtsSidePanel :has-selection="!!network" class="pool-network-side-panel" @close="emit('close')">
|
||||
<template v-if="network" #actions>
|
||||
<VtsDeleteButton v-if="network.PIFs.length === 0" :busy="isDeletingNetworks" @click="deleteNetworks()" />
|
||||
<MenuList placement="bottom-end">
|
||||
<template #trigger="{ open, isOpen }">
|
||||
<UiButtonIcon
|
||||
v-tooltip="copied && t('copied')"
|
||||
accent="brand"
|
||||
size="small"
|
||||
:icon="copied ? 'fa:check-circle' : 'action:more-actions'"
|
||||
:selected="isOpen"
|
||||
@click="open($event)"
|
||||
/>
|
||||
</template>
|
||||
<MenuItem accent="neutral" icon="action:copy" :disabled="!isClipboardSupported" @click="copy()">
|
||||
{{ t('action:copy-info-json') }}
|
||||
</MenuItem>
|
||||
</MenuList>
|
||||
<template v-if="network && network.PIFs.length === 0" #actions>
|
||||
<VtsDeleteButton :busy="isDeletingNetworks" @click="deleteNetworks()" />
|
||||
</template>
|
||||
<template v-if="network" #corner-actions>
|
||||
<VtsCopyButton :value="networkAsJson" :label="t('action:copy-info-json')" />
|
||||
</template>
|
||||
<template v-if="network" #default>
|
||||
<UiPanelCard>
|
||||
@@ -65,25 +53,28 @@
|
||||
</VtsCardRowKeyValue>
|
||||
</VtsCardRowList>
|
||||
</UiPanelCard>
|
||||
<UiPanelCard v-if="pifsCount && pifsCount > 0">
|
||||
<UiPanelCard v-if="pifsCount && pifsCount > 0" ref="pifsCard">
|
||||
<UiPanelCardTitle size="medium" :label="t('pifs')" :counter="pifsCount" />
|
||||
<table class="simple-table">
|
||||
<table class="simple-table" :class="{ compact: isPifsCardCompact }">
|
||||
<thead>
|
||||
<tr>
|
||||
<th class="text-left typo-body-regular-small">
|
||||
<th class="typo-body-regular-small">
|
||||
{{ t('host') }}
|
||||
</th>
|
||||
<th class="text-left typo-body-regular-small">
|
||||
<th class="typo-body-regular-small device">
|
||||
{{ t('device') }}
|
||||
</th>
|
||||
<th class="text-left typo-body-regular-small">
|
||||
<th
|
||||
v-tooltip="isPifsCardCompact"
|
||||
class="typo-body-regular-small status"
|
||||
:class="{ 'text-ellipsis': isPifsCardCompact }"
|
||||
>
|
||||
{{ t('pifs-status') }}
|
||||
</th>
|
||||
<th />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<PifRow v-for="pif in pifs" :key="pif.uuid" :pif />
|
||||
<PifRow v-for="pif in pifs" :key="pif.uuid" :pif :compact="isPifsCardCompact" />
|
||||
</tbody>
|
||||
</table>
|
||||
</UiPanelCard>
|
||||
@@ -100,15 +91,12 @@ import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
|
||||
import VtsCardRowList from '@core/components/card/VtsCardRowList.vue'
|
||||
import VtsCopyButton from '@core/components/copy-button/VtsCopyButton.vue'
|
||||
import VtsDeleteButton from '@core/components/delete-button/VtsDeleteButton.vue'
|
||||
import MenuItem from '@core/components/menu/MenuItem.vue'
|
||||
import MenuList from '@core/components/menu/MenuList.vue'
|
||||
import VtsSidePanel from '@core/components/panel/VtsSidePanel.vue'
|
||||
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
|
||||
import UiPanelCard from '@core/components/ui/panel-card/UiPanelCard.vue'
|
||||
import UiPanelCardTitle from '@core/components/ui/panel-card-title/UiPanelCardTitle.vue'
|
||||
import { vTooltip } from '@core/directives/tooltip.directive.ts'
|
||||
import { useClipboard } from '@vueuse/core'
|
||||
import { computed } from 'vue'
|
||||
import { useElementSize } from '@vueuse/core'
|
||||
import { computed, useTemplateRef } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const { network } = defineProps<{
|
||||
@@ -145,22 +133,37 @@ const pifsCount = computed(() => pifs.value.length)
|
||||
|
||||
const networkAsJson = computed(() => JSON.stringify(network))
|
||||
|
||||
const { copy, copied, isSupported: isClipboardSupported } = useClipboard({ source: networkAsJson, legacy: true })
|
||||
const PIFS_CARD_COMPACT_MAX_WIDTH = 400
|
||||
|
||||
const { width: pifsCardWidth } = useElementSize(useTemplateRef('pifsCard'))
|
||||
|
||||
const isPifsCardCompact = computed(() => pifsCardWidth.value > 0 && pifsCardWidth.value < PIFS_CARD_COMPACT_MAX_WIDTH)
|
||||
</script>
|
||||
|
||||
<style scoped lang="postcss">
|
||||
.pool-network-side-panel {
|
||||
.text-left {
|
||||
text-align: left;
|
||||
}
|
||||
|
||||
.simple-table {
|
||||
border-spacing: 0;
|
||||
padding: 0.4rem;
|
||||
|
||||
thead tr th {
|
||||
th {
|
||||
text-align: start;
|
||||
color: var(--color-neutral-txt-secondary);
|
||||
}
|
||||
|
||||
&.compact {
|
||||
width: 100%;
|
||||
table-layout: fixed;
|
||||
|
||||
.device {
|
||||
width: 7.6rem;
|
||||
padding-inline-start: 1.6rem;
|
||||
}
|
||||
|
||||
.status {
|
||||
width: 4rem;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
.value:empty::before {
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
</template>
|
||||
</UiTitle>
|
||||
<div class="container">
|
||||
<UiQuerySearchBar @search="value => (searchQuery = value)" />
|
||||
<UiQuerySearchBar v-bind="searchBindings" />
|
||||
<VtsTable :state :pagination-bindings sticky="right">
|
||||
<thead>
|
||||
<tr>
|
||||
@@ -38,9 +38,10 @@ 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 { useNetworkColumns } from '@core/tables/column-sets/network-columns.ts'
|
||||
import { computed, ref } from 'vue'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const { networks, busy, error } = defineProps<{
|
||||
@@ -70,19 +71,7 @@ const getNetworkVlan = (network: XenApiNetwork) => {
|
||||
|
||||
const getLockingMode = (lockingMode: string) => (lockingMode === 'disabled' ? t('disabled') : t('unlocked'))
|
||||
|
||||
const searchQuery = ref('')
|
||||
|
||||
const filteredNetworks = computed(() => {
|
||||
const searchTerm = searchQuery.value.trim().toLocaleLowerCase()
|
||||
|
||||
if (!searchTerm) {
|
||||
return networks
|
||||
}
|
||||
|
||||
return networks.filter(network =>
|
||||
Object.values(network).some(value => String(value).toLocaleLowerCase().includes(searchTerm))
|
||||
)
|
||||
})
|
||||
const { items: filteredNetworks, searchBindings } = useSearchFilter(() => networks)
|
||||
|
||||
const { pageRecords: paginatedNetworks, paginationBindings } = usePagination('networks', filteredNetworks)
|
||||
|
||||
|
||||
@@ -11,32 +11,18 @@
|
||||
/>
|
||||
</template>
|
||||
<template #actions>
|
||||
<MenuList v-if="vm !== undefined" placement="bottom-start">
|
||||
<template #trigger="{ open }">
|
||||
<UiDropdownButton size="medium" variant="primary" @click="open($event)">
|
||||
{{ t('action:change-state') }}
|
||||
</UiDropdownButton>
|
||||
</template>
|
||||
<VtsChangeStateMenu v-if="vm !== undefined && !uiStore.isSmall" placement="bottom-start">
|
||||
<VmActionPowerStateItems :vm-refs="[vm.$ref]" />
|
||||
</MenuList>
|
||||
<MenuList v-if="vm !== undefined" placement="bottom-end">
|
||||
<template #trigger="{ open }">
|
||||
<UiButtonIcon
|
||||
v-tooltip="{
|
||||
placement: 'left',
|
||||
content: t('more-actions'),
|
||||
}"
|
||||
icon="action:more-actions-vertical"
|
||||
accent="brand"
|
||||
size="medium"
|
||||
@click="open($event)"
|
||||
/>
|
||||
</template>
|
||||
</VtsChangeStateMenu>
|
||||
<VtsActionsMenu v-if="vm !== undefined" :label="t('more-actions')" size="medium">
|
||||
<VtsChangeStateMenuItem v-if="uiStore.isSmall">
|
||||
<VmActionPowerStateItems :vm-refs="[vm.$ref]" />
|
||||
</VtsChangeStateMenuItem>
|
||||
<VmActionCopyItem :selected-refs="[vm.$ref]" is-single-action />
|
||||
<VmActionExportItem :vm-refs="[vm.$ref]" is-single-action />
|
||||
<VmActionSnapshotItem :vm-refs="[vm.$ref]" />
|
||||
<VmActionMigrateItem :selected-refs="[vm.$ref]" is-single-action />
|
||||
</MenuList>
|
||||
</VtsActionsMenu>
|
||||
</template>
|
||||
</UiHeadBar>
|
||||
</template>
|
||||
@@ -50,12 +36,12 @@ import VmActionSnapshotItem from '@/components/vm/VmActionItems/VmActionSnapshot
|
||||
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { useVmOperation } from '@/modules/vm/composables/vm-operation.composable.ts'
|
||||
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
|
||||
import MenuList from '@core/components/menu/MenuList.vue'
|
||||
import VtsActionsMenu from '@core/components/menu/VtsActionsMenu.vue'
|
||||
import VtsChangeStateMenu from '@core/components/menu/VtsChangeStateMenu.vue'
|
||||
import VtsChangeStateMenuItem from '@core/components/menu/VtsChangeStateMenuItem.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 { toLower } from 'lodash-es'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
@@ -63,6 +49,8 @@ import { useRoute } from 'vue-router'
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const uiStore = useUiStore()
|
||||
|
||||
const { getByUuid: getVmByUuid } = useVmStore().subscribe()
|
||||
const route = useRoute<'/vm/[uuid]'>()
|
||||
|
||||
|
||||
@@ -1,44 +1,39 @@
|
||||
<template>
|
||||
<VtsMobileMenu v-if="uiStore.isSmall" :title="t('actions')">
|
||||
<template #trigger="{ isOpen, open }">
|
||||
<UiButtonIcon
|
||||
accent="brand"
|
||||
size="small"
|
||||
:disabled="selectedRefs.length === 0"
|
||||
:selected="isOpen"
|
||||
icon="fa:ellipsis"
|
||||
@click="open()"
|
||||
/>
|
||||
</template>
|
||||
<VmsBulkActionItems :selected-refs />
|
||||
</VtsMobileMenu>
|
||||
<MenuList
|
||||
v-else
|
||||
:disabled="selectedRefs.length === 0"
|
||||
:horizontal="!uiStore.isSmall"
|
||||
:no-border="!uiStore.isSmall"
|
||||
class="vms-actions-bar"
|
||||
horizontal
|
||||
no-border
|
||||
placement="bottom-end"
|
||||
>
|
||||
<template v-if="uiStore.isSmall" #trigger="{ isOpen, open }">
|
||||
<UiButtonIcon accent="brand" size="small" :selected="isOpen" icon="fa:ellipsis" @click="open" />
|
||||
</template>
|
||||
<MenuItem accent="brand" icon="fa:power-off">
|
||||
{{ t('action:change-state') }}
|
||||
<template #submenu>
|
||||
<VmActionPowerStateItems :vm-refs="selectedRefs" />
|
||||
</template>
|
||||
</MenuItem>
|
||||
<VmActionMigrateItem :selected-refs="selectedRefs" />
|
||||
<VmActionCopyItem :selected-refs="selectedRefs" />
|
||||
<VmActionSnapshotItem :vm-refs="selectedRefs" />
|
||||
<VmActionExportItems :vm-refs="selectedRefs" />
|
||||
<VmActionDeleteItem :vm-refs="selectedRefs" />
|
||||
<VmsBulkActionItems :selected-refs />
|
||||
</MenuList>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import VmActionCopyItem from '@/components/vm/VmActionItems/VmActionCopyItem.vue'
|
||||
import VmActionDeleteItem from '@/components/vm/VmActionItems/VmActionDeleteItem.vue'
|
||||
import VmActionExportItems from '@/components/vm/VmActionItems/VmActionExportItems.vue'
|
||||
import VmActionMigrateItem from '@/components/vm/VmActionItems/VmActionMigrateItem.vue'
|
||||
import VmActionPowerStateItems from '@/components/vm/VmActionItems/VmActionPowerStateItems.vue'
|
||||
import VmActionSnapshotItem from '@/components/vm/VmActionItems/VmActionSnapshotItem.vue'
|
||||
import VmsBulkActionItems from '@/components/vm/VmsBulkActionItems.vue'
|
||||
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import MenuItem from '@core/components/menu/MenuItem.vue'
|
||||
import MenuList from '@core/components/menu/MenuList.vue'
|
||||
import VtsMobileMenu from '@core/components/menu/VtsMobileMenu.vue'
|
||||
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
|
||||
import { useUiStore } from '@core/stores/ui.store.ts'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
defineProps<{
|
||||
disabled?: boolean
|
||||
selectedRefs: XenApiVm['$ref'][]
|
||||
}>()
|
||||
|
||||
|
||||
31
@xen-orchestra/lite/src/components/vm/VmsBulkActionItems.vue
Normal file
31
@xen-orchestra/lite/src/components/vm/VmsBulkActionItems.vue
Normal file
@@ -0,0 +1,31 @@
|
||||
<template>
|
||||
<MenuItem accent="brand" icon="fa:power-off">
|
||||
{{ t('action:change-state') }}
|
||||
<template #submenu>
|
||||
<VmActionPowerStateItems :vm-refs="selectedRefs" />
|
||||
</template>
|
||||
</MenuItem>
|
||||
<VmActionMigrateItem :selected-refs />
|
||||
<VmActionCopyItem :selected-refs />
|
||||
<VmActionSnapshotItem :vm-refs="selectedRefs" />
|
||||
<VmActionExportItems :vm-refs="selectedRefs" />
|
||||
<VmActionDeleteItem :vm-refs="selectedRefs" />
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import VmActionCopyItem from '@/components/vm/VmActionItems/VmActionCopyItem.vue'
|
||||
import VmActionDeleteItem from '@/components/vm/VmActionItems/VmActionDeleteItem.vue'
|
||||
import VmActionExportItems from '@/components/vm/VmActionItems/VmActionExportItems.vue'
|
||||
import VmActionMigrateItem from '@/components/vm/VmActionItems/VmActionMigrateItem.vue'
|
||||
import VmActionPowerStateItems from '@/components/vm/VmActionItems/VmActionPowerStateItems.vue'
|
||||
import VmActionSnapshotItem from '@/components/vm/VmActionItems/VmActionSnapshotItem.vue'
|
||||
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import MenuItem from '@core/components/menu/MenuItem.vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
defineProps<{
|
||||
selectedRefs: XenApiVm['$ref'][]
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
</script>
|
||||
16
@xen-orchestra/lite/src/libs/story/story-file.ts
Normal file
16
@xen-orchestra/lite/src/libs/story/story-file.ts
Normal file
@@ -0,0 +1,16 @@
|
||||
/**
|
||||
* Builds a `File` to be used as a stub in stories.
|
||||
*
|
||||
* `File.size` is derived from the blob content, so it is overridden here: it lets stories display
|
||||
* realistic sizes without allocating that many bytes.
|
||||
*
|
||||
* The blob is empty and carries no MIME type, so such a stub can never satisfy a `file.type` based
|
||||
* `accept` filter: it is meant for display only, never to be fed back into an uploader.
|
||||
*/
|
||||
export function createStoryFile(name: string, size: number): File {
|
||||
const file = new File([], name)
|
||||
|
||||
Object.defineProperty(file, 'size', { value: size })
|
||||
|
||||
return file
|
||||
}
|
||||
@@ -1,10 +1,7 @@
|
||||
<template>
|
||||
<MenuItem v-if="showChangeStateButton" icon="action:change-state" accent="brand">
|
||||
{{ t('action:change-state') }}
|
||||
<template #submenu>
|
||||
<HostPowerStateActions :host />
|
||||
</template>
|
||||
</MenuItem>
|
||||
<VtsChangeStateMenuItem v-if="showChangeState">
|
||||
<HostPowerStateActions :host />
|
||||
</VtsChangeStateMenuItem>
|
||||
<HostRestartToolstackButton :host />
|
||||
<HostDisableButton v-if="displayDisableButton" :host />
|
||||
<HostEnableButton v-else :host />
|
||||
@@ -25,18 +22,15 @@ import HostPowerStateActions from '@/modules/host/components/actions/HostPowerSt
|
||||
import HostRestartToolstackButton from '@/modules/host/components/actions/restart-toolstack/HostRestartToolstackButton.vue'
|
||||
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
|
||||
import VtsDivider from '@core/components/divider/VtsDivider.vue'
|
||||
import MenuItem from '@core/components/menu/MenuItem.vue'
|
||||
import VtsChangeStateMenuItem from '@core/components/menu/VtsChangeStateMenuItem.vue'
|
||||
import { HOST_POWER_STATE } from '@vates/types'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const { host } = defineProps<{
|
||||
host: XenApiHost
|
||||
showChangeStateButton?: boolean
|
||||
showChangeState?: boolean
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const { getHostPowerState } = useHostMetricsStore().subscribe()
|
||||
|
||||
const isHostHalted = computed(() => getHostPowerState(host) === HOST_POWER_STATE.HALTED)
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<UiTitle>
|
||||
{{ t('hosts') }}
|
||||
</UiTitle>
|
||||
<UiQuerySearchBar @search="(value: string) => (searchQuery = value)" />
|
||||
<UiQuerySearchBar v-bind="searchBindings" />
|
||||
<div class="container">
|
||||
<VtsTable :pagination-bindings :state sticky="right">
|
||||
<thead>
|
||||
@@ -34,11 +34,12 @@ 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 { useHostColumns } from '@core/tables/column-sets/host-columns.ts'
|
||||
import { logicAnd, logicNot, logicOr } from '@vueuse/math'
|
||||
import { computed, ref } from 'vue'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const {
|
||||
@@ -63,19 +64,7 @@ const hasError = logicOr(() => error, hasPifError)
|
||||
|
||||
const selectedHostId = useRouteQuery('id')
|
||||
|
||||
const searchQuery = ref('')
|
||||
|
||||
const filteredHosts = computed(() => {
|
||||
const searchTerm = searchQuery.value.trim().toLocaleLowerCase()
|
||||
|
||||
if (!searchTerm) {
|
||||
return rawHosts
|
||||
}
|
||||
|
||||
return rawHosts.filter(host =>
|
||||
Object.values(host).some(value => String(value).toLocaleLowerCase().includes(searchTerm))
|
||||
)
|
||||
})
|
||||
const { items: filteredHosts, searchBindings } = useSearchFilter(() => rawHosts)
|
||||
|
||||
const state = useTableState({
|
||||
busy: logicNot(isReady),
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
<template>
|
||||
<UiButton
|
||||
v-tooltip="!canConnectSrs && connectSrsErrorMessage"
|
||||
size="medium"
|
||||
<VtsActionButton
|
||||
:hint="connectSrsErrorMessage"
|
||||
variant="tertiary"
|
||||
accent="brand"
|
||||
:disabled="!canConnectSrs"
|
||||
left-icon="action:connect"
|
||||
icon="action:connect"
|
||||
:busy="isConnectingSrs"
|
||||
@click="connectSrs()"
|
||||
>
|
||||
@@ -17,7 +16,7 @@
|
||||
variant="secondary"
|
||||
size="small"
|
||||
/>
|
||||
</UiButton>
|
||||
</VtsActionButton>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
@@ -25,9 +24,8 @@ import type { XenApiSr } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { useSrUtils } from '@/modules/storage-repository/composables/sr-utils.composable.ts'
|
||||
import { useSrConnection } from '@/modules/storage-repository/composables/use-sr-connection.composable.ts'
|
||||
import type { SrScope } from '@core/types/storage-repository.type.ts'
|
||||
import UiButton from '@core/components/ui/button/UiButton.vue'
|
||||
import VtsActionButton from '@core/components/action-button/VtsActionButton.vue'
|
||||
import UiCounter from '@core/components/ui/counter/UiCounter.vue'
|
||||
import { vTooltip } from '@core/directives/tooltip.directive.ts'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const { sr, scope } = defineProps<{
|
||||
|
||||
@@ -1,28 +1,15 @@
|
||||
<template>
|
||||
<MenuItem
|
||||
v-tooltip="!canDeleteSrs && deleteSrsErrorMessage"
|
||||
accent="danger"
|
||||
icon="action:delete"
|
||||
:disabled="!canDeleteSrs"
|
||||
:busy="isDeletingSrs"
|
||||
@click="deleteSrs()"
|
||||
>
|
||||
{{ t('action:delete') }}
|
||||
</MenuItem>
|
||||
<VtsDeleteButton :hint="deleteSrsErrorMessage" :disabled="!canDeleteSrs" :busy="isDeletingSrs" @click="deleteSrs()" />
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import type { XenApiSr } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { useSrDelete } from '@/modules/storage-repository/composables/use-sr-delete.composable.ts'
|
||||
import MenuItem from '@core/components/menu/MenuItem.vue'
|
||||
import { vTooltip } from '@core/directives/tooltip.directive.ts'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
import VtsDeleteButton from '@core/components/delete-button/VtsDeleteButton.vue'
|
||||
|
||||
const { sr } = defineProps<{
|
||||
sr: XenApiSr
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const { deleteSrs, canDeleteSrs, isDeletingSrs, deleteSrsErrorMessage } = useSrDelete(() => [sr])
|
||||
</script>
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
<template>
|
||||
<MenuItem
|
||||
v-tooltip="!canDisconnectSrs && disconnectSrsErrorMessage"
|
||||
accent="neutral"
|
||||
<VtsActionButton
|
||||
:hint="disconnectSrsErrorMessage"
|
||||
variant="tertiary"
|
||||
accent="brand"
|
||||
icon="action:disconnect"
|
||||
:disabled="!canDisconnectSrs"
|
||||
:busy="isDisconnectingSrs"
|
||||
@@ -15,19 +16,16 @@
|
||||
variant="secondary"
|
||||
size="small"
|
||||
/>
|
||||
<i v-if="hint">{{ hint }}</i>
|
||||
</MenuItem>
|
||||
</VtsActionButton>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import type { XenApiSr } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { useSrConnection } from '@/modules/storage-repository/composables/use-sr-connection.composable.ts'
|
||||
import MenuItem from '@core/components/menu/MenuItem.vue'
|
||||
import VtsActionButton from '@core/components/action-button/VtsActionButton.vue'
|
||||
import UiCounter from '@core/components/ui/counter/UiCounter.vue'
|
||||
import { vTooltip } from '@core/directives/tooltip.directive.ts'
|
||||
import { type SrScope } from '@core/types/storage-repository.type.ts'
|
||||
import { shouldShowTargetCount } from '@core/utils/sr.utils.ts'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const { sr, scope } = defineProps<{
|
||||
@@ -42,6 +40,4 @@ const { disconnectSrs, canDisconnectSrs, isDisconnectingSrs, disconnectSrsErrorM
|
||||
srs: () => [sr],
|
||||
scope: () => scope,
|
||||
})
|
||||
|
||||
const hint = computed(() => (!canDisconnectSrs.value ? disconnectSrsErrorMessage.value : undefined))
|
||||
</script>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<UiTitle>
|
||||
{{ t('storage-repositories') }}
|
||||
</UiTitle>
|
||||
<UiQuerySearchBar @search="value => (searchQuery = value)" />
|
||||
<UiQuerySearchBar v-bind="searchBindings" />
|
||||
<div class="container">
|
||||
<VtsTable :state :pagination-bindings sticky="right">
|
||||
<thead>
|
||||
@@ -33,12 +33,13 @@ 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 { useSrColumns } from '@core/tables/column-sets/sr-columns.ts'
|
||||
import { type SrScope } from '@core/types/storage-repository.type.ts'
|
||||
import { shouldShowTargetCount } from '@core/utils/sr.utils.ts'
|
||||
import { computed, ref } from 'vue'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const {
|
||||
@@ -61,17 +62,7 @@ const { isReady, hasError, isDefaultSr } = useSrStore().subscribe()
|
||||
|
||||
const selectedSrId = useRouteQuery('id')
|
||||
|
||||
const searchQuery = ref('')
|
||||
|
||||
const filteredSrs = computed(() => {
|
||||
const searchTerm = searchQuery.value.trim().toLocaleLowerCase()
|
||||
|
||||
if (!searchTerm) {
|
||||
return rawSrs
|
||||
}
|
||||
|
||||
return rawSrs.filter(sr => Object.values(sr).some(value => String(value).toLocaleLowerCase().includes(searchTerm)))
|
||||
})
|
||||
const { items: filteredSrs, searchBindings } = useSearchFilter(() => rawSrs)
|
||||
|
||||
const state = useTableState({
|
||||
busy: () => busy ?? !isReady.value,
|
||||
|
||||
@@ -2,13 +2,8 @@
|
||||
<VtsSidePanel :key="panelSignature" :has-selection="!!sr" @close="emit('close')">
|
||||
<template v-if="sr" #actions>
|
||||
<SrConnectButton :scope :sr />
|
||||
<MenuList placement="bottom-end">
|
||||
<template #trigger="{ open }">
|
||||
<UiButtonIcon accent="brand" icon="action:more-actions" size="medium" @click="open($event)" />
|
||||
</template>
|
||||
<SrDisconnectButton :scope :sr />
|
||||
<SrDeleteButton :sr />
|
||||
</MenuList>
|
||||
<SrDisconnectButton :scope :sr />
|
||||
<SrDeleteButton :sr />
|
||||
</template>
|
||||
<template v-if="sr" #default>
|
||||
<VtsStateHero v-if="!isReady" format="panel" type="busy" size="medium" />
|
||||
@@ -40,10 +35,8 @@ import { useHostStore } from '@/stores/xen-api/host.store.ts'
|
||||
import { usePbdStore } from '@/stores/xen-api/pbd.store.ts'
|
||||
import { useVdiStore } from '@/stores/xen-api/vdi.store.ts'
|
||||
import type { SrScope } from '@core/types/storage-repository.type.ts'
|
||||
import MenuList from '@core/components/menu/MenuList.vue'
|
||||
import VtsSidePanel from '@core/components/panel/VtsSidePanel.vue'
|
||||
import VtsStateHero from '@core/components/state-hero/VtsStateHero.vue'
|
||||
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
|
||||
import { logicAnd } from '@vueuse/math'
|
||||
import { computed } from 'vue'
|
||||
|
||||
|
||||
@@ -19,18 +19,9 @@
|
||||
size="small"
|
||||
variant="secondary"
|
||||
/>
|
||||
<MenuList placement="bottom-start">
|
||||
<template #trigger="{ open, isOpen }">
|
||||
<UiButtonIcon
|
||||
accent="brand"
|
||||
icon="action:more-actions"
|
||||
size="small"
|
||||
:selected="isOpen"
|
||||
@click="open($event)"
|
||||
/>
|
||||
</template>
|
||||
<HostMoreActions :host="branch.data" show-change-state-button />
|
||||
</MenuList>
|
||||
<VtsActionsMenu placement="bottom-start">
|
||||
<HostMoreActions :host="branch.data" show-change-state />
|
||||
</VtsActionsMenu>
|
||||
</template>
|
||||
</UiTreeItemLabel>
|
||||
</VtsTreeItem>
|
||||
@@ -43,10 +34,9 @@ import type { HostBranch } from '@/modules/treeview/types/tree.type.ts'
|
||||
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
|
||||
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
|
||||
import VtsIcon from '@core/components/icon/VtsIcon.vue'
|
||||
import MenuList from '@core/components/menu/MenuList.vue'
|
||||
import VtsActionsMenu from '@core/components/menu/VtsActionsMenu.vue'
|
||||
import VtsObjectIcon from '@core/components/object-icon/VtsObjectIcon.vue'
|
||||
import VtsTreeItem from '@core/components/tree/VtsTreeItem.vue'
|
||||
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
|
||||
import UiCounter from '@core/components/ui/counter/UiCounter.vue'
|
||||
import UiLoader from '@core/components/ui/loader/UiLoader.vue'
|
||||
import UiTreeItemLabel from '@core/components/ui/tree-item-label/UiTreeItemLabel.vue'
|
||||
|
||||
@@ -7,18 +7,9 @@
|
||||
>
|
||||
{{ branch.data.name_label || '(Pool)' }}
|
||||
<template #addons>
|
||||
<MenuList placement="bottom-start">
|
||||
<template #trigger="{ open, isOpen }">
|
||||
<UiButtonIcon
|
||||
accent="brand"
|
||||
icon="action:more-actions"
|
||||
size="small"
|
||||
:selected="isOpen"
|
||||
@click="open($event)"
|
||||
/>
|
||||
</template>
|
||||
<VtsActionsMenu placement="bottom-start">
|
||||
<PoolTreeActions :pool="branch.data" />
|
||||
</MenuList>
|
||||
</VtsActionsMenu>
|
||||
</template>
|
||||
</UiTreeItemLabel>
|
||||
</VtsTreeItem>
|
||||
@@ -27,9 +18,8 @@
|
||||
<script lang="ts" setup>
|
||||
import PoolTreeActions from '@/modules/pool/components/actions/PoolTreeActions.vue'
|
||||
import type { PoolBranch } from '@/modules/treeview/types/tree.type.ts'
|
||||
import MenuList from '@core/components/menu/MenuList.vue'
|
||||
import VtsActionsMenu from '@core/components/menu/VtsActionsMenu.vue'
|
||||
import VtsTreeItem from '@core/components/tree/VtsTreeItem.vue'
|
||||
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
|
||||
import UiTreeItemLabel from '@core/components/ui/tree-item-label/UiTreeItemLabel.vue'
|
||||
|
||||
defineProps<{
|
||||
|
||||
@@ -7,19 +7,9 @@
|
||||
</template>
|
||||
<template #addons>
|
||||
<UiLoader v-if="isChangingState" v-tooltip="{ placement: 'top', content: currentOperation }" />
|
||||
<MenuList placement="bottom-start">
|
||||
<template #trigger="{ open, isOpen }">
|
||||
<UiButtonIcon
|
||||
v-tooltip="{ placement: 'top', content: t('quick-actions') }"
|
||||
:selected="isOpen"
|
||||
accent="brand"
|
||||
icon="action:more-actions"
|
||||
size="small"
|
||||
@click="open($event)"
|
||||
/>
|
||||
</template>
|
||||
<VtsActionsMenu placement="bottom-start">
|
||||
<VmTreeActions :vm-opaque-ref="leaf.data.$ref" />
|
||||
</MenuList>
|
||||
</VtsActionsMenu>
|
||||
</template>
|
||||
</UiTreeItemLabel>
|
||||
</VtsTreeItem>
|
||||
@@ -30,23 +20,19 @@ import type { VmLeaf } from '@/modules/treeview/types/tree.type.ts'
|
||||
import VmTreeActions from '@/modules/vm/components/actions/VmTreeActions.vue'
|
||||
import { useVmOperation } from '@/modules/vm/composables/vm-operation.composable.ts'
|
||||
import { useVmUtils } from '@/modules/vm/composables/vm-utils.composable.ts'
|
||||
import MenuList from '@core/components/menu/MenuList.vue'
|
||||
import VtsActionsMenu from '@core/components/menu/VtsActionsMenu.vue'
|
||||
import VtsObjectIcon from '@core/components/object-icon/VtsObjectIcon.vue'
|
||||
import VtsTreeItem from '@core/components/tree/VtsTreeItem.vue'
|
||||
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
|
||||
import UiLoader from '@core/components/ui/loader/UiLoader.vue'
|
||||
import UiTreeItemLabel from '@core/components/ui/tree-item-label/UiTreeItemLabel.vue'
|
||||
import { vTooltip } from '@core/directives/tooltip.directive.ts'
|
||||
import { toLower } from 'lodash-es'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const { leaf } = defineProps<{
|
||||
leaf: VmLeaf
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const { isChangingState, currentOperation } = useVmOperation(() => leaf.data)
|
||||
const { powerState } = useVmUtils(() => leaf.data)
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<UiTitle>
|
||||
{{ t('vdis') }}
|
||||
</UiTitle>
|
||||
<UiQuerySearchBar @search="(value: string) => (searchQuery = value)" />
|
||||
<UiQuerySearchBar v-bind="searchBindings" />
|
||||
<div class="container">
|
||||
<VtsTable :state :pagination-bindings sticky="right">
|
||||
<thead>
|
||||
@@ -30,10 +30,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 { useVdiColumns } from '@core/tables/column-sets/vdi-columns.ts'
|
||||
import { formatSizeRaw } from '@core/utils/size.util.ts'
|
||||
import { computed, ref } from 'vue'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
const { vdis, vbds, busy, error } = defineProps<{
|
||||
vdis: XenApiVdi[]
|
||||
@@ -43,14 +44,7 @@ const { vdis, vbds, busy, error } = defineProps<{
|
||||
}>()
|
||||
const { t } = useI18n()
|
||||
const selectedVdiId = useRouteQuery('id')
|
||||
const searchQuery = ref('')
|
||||
const filteredVdis = computed(() => {
|
||||
const searchTerm = searchQuery.value.trim().toLocaleLowerCase()
|
||||
if (!searchTerm) {
|
||||
return vdis
|
||||
}
|
||||
return vdis.filter(vdi => Object.values(vdi).some(value => String(value).toLocaleLowerCase().includes(searchTerm)))
|
||||
})
|
||||
const { items: filteredVdis, searchBindings } = useSearchFilter(() => vdis)
|
||||
const state = useTableState({
|
||||
busy: () => busy,
|
||||
error: () => error,
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
<slot name="title-actions" />
|
||||
</template>
|
||||
</UiTitle>
|
||||
<UiQuerySearchBar @search="(value: string) => (searchQuery = value)" />
|
||||
<UiQuerySearchBar v-bind="searchBindings" />
|
||||
<VtsTable :state :pagination-bindings sticky="right">
|
||||
<thead>
|
||||
<tr>
|
||||
@@ -35,6 +35,7 @@ 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 { useMapper } from '@core/packages/mapper'
|
||||
import { type ActionItem } from '@core/tables/column-definitions/action-column.ts'
|
||||
@@ -42,7 +43,7 @@ import { useVifColumns } from '@core/tables/column-sets/vif-columns.ts'
|
||||
import { CONNECTION_ACTION } from '@core/types/connection.ts'
|
||||
import { getUniqueIpAddressesForDevice } from '@core/utils/ip-address.utils.ts'
|
||||
import { logicNot } from '@vueuse/math'
|
||||
import { computed, ref } from 'vue'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const { vifs, vm } = defineProps<{
|
||||
@@ -72,21 +73,10 @@ const getIpAddresses = (vif: XenApiVif) => {
|
||||
return getUniqueIpAddressesForDevice(networks, vif.device)
|
||||
}
|
||||
|
||||
const searchQuery = ref('')
|
||||
|
||||
const filteredVifs = computed(() => {
|
||||
const searchTerm = searchQuery.value.trim().toLocaleLowerCase()
|
||||
|
||||
if (!searchTerm) {
|
||||
return vifs
|
||||
}
|
||||
|
||||
return vifs.filter(vif =>
|
||||
[...Object.values(vif), getNetworkName(vif.network)].some(value =>
|
||||
String(value).toLocaleLowerCase().includes(searchTerm)
|
||||
)
|
||||
)
|
||||
})
|
||||
const { items: filteredVifs, searchBindings } = useSearchFilter(
|
||||
() => vifs,
|
||||
vif => [...Object.values(vif), getNetworkName(vif.network)]
|
||||
)
|
||||
|
||||
const state = useTableState({
|
||||
busy: logicNot(isReady),
|
||||
|
||||
@@ -1,23 +1,21 @@
|
||||
<template>
|
||||
<UiButton
|
||||
v-tooltip="!connection.canToggle && connection.errorMessage"
|
||||
size="medium"
|
||||
<VtsActionButton
|
||||
:hint="connection.errorMessage"
|
||||
variant="tertiary"
|
||||
accent="brand"
|
||||
:disabled="!connection.canToggle"
|
||||
:left-icon="connection.icon"
|
||||
:icon="connection.icon"
|
||||
:busy="connection.isToggling"
|
||||
@click="connection.toggle()"
|
||||
>
|
||||
{{ connection.label }}
|
||||
</UiButton>
|
||||
</VtsActionButton>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import type { XenApiVif, XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { useVifConnection } from '@/modules/vif/composables/use-vif-connection.composable.ts'
|
||||
import UiButton from '@core/components/ui/button/UiButton.vue'
|
||||
import { vTooltip } from '@core/directives/tooltip.directive.ts'
|
||||
import VtsActionButton from '@core/components/action-button/VtsActionButton.vue'
|
||||
import { useMapper } from '@core/packages/mapper'
|
||||
import { CONNECTION_ACTION } from '@core/types/connection.ts'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
@@ -1,13 +1,13 @@
|
||||
<template>
|
||||
<UiButton size="medium" variant="tertiary" accent="brand" left-icon="action:edit" @click="goToVifEdit(vif)">
|
||||
<VtsActionButton variant="tertiary" accent="brand" icon="action:edit" @click="goToVifEdit(vif)">
|
||||
{{ t('action:edit') }}
|
||||
</UiButton>
|
||||
</VtsActionButton>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import type { XenApiVif } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { useVifEdit } from '@/modules/vif/composables/use-vif-edit.composable.ts'
|
||||
import UiButton from '@core/components/ui/button/UiButton.vue'
|
||||
import VtsActionButton from '@core/components/action-button/VtsActionButton.vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const { vif } = defineProps<{
|
||||
|
||||
@@ -1,10 +1,7 @@
|
||||
<template>
|
||||
<MenuItem accent="brand" icon="action:change-state">
|
||||
{{ t('action:change-state') }}
|
||||
<template #submenu>
|
||||
<VmActionPowerStateItems :vm-refs />
|
||||
</template>
|
||||
</MenuItem>
|
||||
<VtsChangeStateMenuItem>
|
||||
<VmActionPowerStateItems :vm-refs />
|
||||
</VtsChangeStateMenuItem>
|
||||
<VmActionSnapshotItem :vm-refs />
|
||||
<VmActionCopyItem :selected-refs="vmRefs" is-single-action />
|
||||
<VmActionExportItem :vm-refs is-single-action />
|
||||
@@ -19,16 +16,13 @@ import VmActionExportItem from '@/components/vm/VmActionItems/VmActionExportItem
|
||||
import VmActionPowerStateItems from '@/components/vm/VmActionItems/VmActionPowerStateItems.vue'
|
||||
import VmActionSnapshotItem from '@/components/vm/VmActionItems/VmActionSnapshotItem.vue'
|
||||
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import MenuItem from '@core/components/menu/MenuItem.vue'
|
||||
import MenuSeparator from '@core/components/menu/MenuSeparator.vue'
|
||||
import VtsChangeStateMenuItem from '@core/components/menu/VtsChangeStateMenuItem.vue'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const { vmOpaqueRef } = defineProps<{
|
||||
vmOpaqueRef: XenApiVm['$ref']
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const vmRefs = computed(() => [vmOpaqueRef])
|
||||
</script>
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
<UiCard class="container">
|
||||
<PoolNetworksTable :networks="networksWithPifs" :busy="!isReady" :error="hasError">
|
||||
<template #title-actions>
|
||||
<MenuList placement="bottom-end">
|
||||
<VtsResponsiveMenu :title="t('new')" placement="bottom-end">
|
||||
<template #trigger="{ open }">
|
||||
<UiDropdownButton size="medium" variant="primary" @click="open($event)">{{ t('new') }}</UiDropdownButton>
|
||||
</template>
|
||||
@@ -17,7 +17,7 @@
|
||||
{{ t('action:create-bonded-network') }}
|
||||
</UiLink>
|
||||
</MenuItem>
|
||||
</MenuList>
|
||||
</VtsResponsiveMenu>
|
||||
</template>
|
||||
</PoolNetworksTable>
|
||||
<PoolHostInternalNetworksTable :networks="networksWithoutPifs">
|
||||
@@ -41,7 +41,7 @@ import { usePageTitleStore } from '@/stores/page-title.store.ts'
|
||||
import { useNetworkStore } from '@/stores/xen-api/network.store.ts'
|
||||
import VtsContentSidePanel from '@core/components/layout/VtsContentSidePanel.vue'
|
||||
import MenuItem from '@core/components/menu/MenuItem.vue'
|
||||
import MenuList from '@core/components/menu/MenuList.vue'
|
||||
import VtsResponsiveMenu from '@core/components/menu/VtsResponsiveMenu.vue'
|
||||
import UiCard from '@core/components/ui/card/UiCard.vue'
|
||||
import UiDropdownButton from '@core/components/ui/dropdown-button/UiDropdownButton.vue'
|
||||
import UiLink from '@core/components/ui/link/UiLink.vue'
|
||||
@@ -70,7 +70,7 @@ const selectedNetwork = useRouteQuery<XenApiNetwork | undefined>('id', {
|
||||
}
|
||||
|
||||
.new-network-link {
|
||||
height: 100%;
|
||||
width: 100%;
|
||||
flex-grow: 1;
|
||||
padding-block: 1.2rem;
|
||||
}
|
||||
</style>
|
||||
|
||||
117
@xen-orchestra/lite/src/route-map.d.ts
vendored
117
@xen-orchestra/lite/src/route-map.d.ts
vendored
@@ -296,6 +296,13 @@ declare module 'vue-router/auto-routes' {
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/action-button/vts-action-button': RouteRecordInfo<
|
||||
'/story/web-core/action-button/vts-action-button',
|
||||
'/story/web-core/action-button/vts-action-button',
|
||||
Record<never, never>,
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/banner/vts-banner': RouteRecordInfo<
|
||||
'/story/web-core/banner/vts-banner',
|
||||
'/story/web-core/banner/vts-banner',
|
||||
@@ -373,6 +380,13 @@ declare module 'vue-router/auto-routes' {
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/file-uploader-container/vts-file-uploader-container': RouteRecordInfo<
|
||||
'/story/web-core/file-uploader-container/vts-file-uploader-container',
|
||||
'/story/web-core/file-uploader-container/vts-file-uploader-container',
|
||||
Record<never, never>,
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/form-error-summary/vts-form-error-summary': RouteRecordInfo<
|
||||
'/story/web-core/form-error-summary/vts-form-error-summary',
|
||||
'/story/web-core/form-error-summary/vts-form-error-summary',
|
||||
@@ -429,6 +443,34 @@ declare module 'vue-router/auto-routes' {
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/menu/vts-change-state-menu': RouteRecordInfo<
|
||||
'/story/web-core/menu/vts-change-state-menu',
|
||||
'/story/web-core/menu/vts-change-state-menu',
|
||||
Record<never, never>,
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/menu/vts-change-state-menu-item': RouteRecordInfo<
|
||||
'/story/web-core/menu/vts-change-state-menu-item',
|
||||
'/story/web-core/menu/vts-change-state-menu-item',
|
||||
Record<never, never>,
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/menu/vts-mobile-menu': RouteRecordInfo<
|
||||
'/story/web-core/menu/vts-mobile-menu',
|
||||
'/story/web-core/menu/vts-mobile-menu',
|
||||
Record<never, never>,
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/menu/vts-responsive-menu': RouteRecordInfo<
|
||||
'/story/web-core/menu/vts-responsive-menu',
|
||||
'/story/web-core/menu/vts-responsive-menu',
|
||||
Record<never, never>,
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/object-icon/vts-object-icon': RouteRecordInfo<
|
||||
'/story/web-core/object-icon/vts-object-icon',
|
||||
'/story/web-core/object-icon/vts-object-icon',
|
||||
@@ -744,6 +786,27 @@ declare module 'vue-router/auto-routes' {
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/ui/file-item/ui-file-item': RouteRecordInfo<
|
||||
'/story/web-core/ui/file-item/ui-file-item',
|
||||
'/story/web-core/ui/file-item/ui-file-item',
|
||||
Record<never, never>,
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/ui/file-list/ui-file-list': RouteRecordInfo<
|
||||
'/story/web-core/ui/file-list/ui-file-list',
|
||||
'/story/web-core/ui/file-list/ui-file-list',
|
||||
Record<never, never>,
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/ui/file-uploader/ui-file-uploader': RouteRecordInfo<
|
||||
'/story/web-core/ui/file-uploader/ui-file-uploader',
|
||||
'/story/web-core/ui/file-uploader/ui-file-uploader',
|
||||
Record<never, never>,
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/ui/head-bar/ui-head-bar': RouteRecordInfo<
|
||||
'/story/web-core/ui/head-bar/ui-head-bar',
|
||||
'/story/web-core/ui/head-bar/ui-head-bar',
|
||||
@@ -1374,6 +1437,12 @@ declare module 'vue-router/auto-routes' {
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/action-button/vts-action-button.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/action-button/vts-action-button'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/banner/vts-banner.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/banner/vts-banner'
|
||||
@@ -1440,6 +1509,12 @@ declare module 'vue-router/auto-routes' {
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/file-uploader-container/vts-file-uploader-container.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/file-uploader-container/vts-file-uploader-container'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/form-error-summary/vts-form-error-summary.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/form-error-summary/vts-form-error-summary'
|
||||
@@ -1488,6 +1563,30 @@ declare module 'vue-router/auto-routes' {
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/menu/vts-change-state-menu.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/menu/vts-change-state-menu'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/menu/vts-change-state-menu-item.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/menu/vts-change-state-menu-item'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/menu/vts-mobile-menu.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/menu/vts-mobile-menu'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/menu/vts-responsive-menu.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/menu/vts-responsive-menu'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/object-icon/vts-object-icon.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/object-icon/vts-object-icon'
|
||||
@@ -1758,6 +1857,24 @@ declare module 'vue-router/auto-routes' {
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/ui/file-item/ui-file-item.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/ui/file-item/ui-file-item'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/ui/file-list/ui-file-list.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/ui/file-list/ui-file-list'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/ui/file-uploader/ui-file-uploader.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/ui/file-uploader/ui-file-uploader'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/ui/head-bar/ui-head-bar.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/ui/head-bar/ui-head-bar'
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
<template>
|
||||
<ComponentStory
|
||||
v-slot="{ properties, settings }"
|
||||
:params="[
|
||||
prop('variant')
|
||||
.type('ButtonVariant')
|
||||
.enum('primary', 'secondary', 'tertiary')
|
||||
.preset('tertiary')
|
||||
.required()
|
||||
.widget(),
|
||||
prop('accent').type('ButtonAccent').enum('brand', 'warning', 'danger').preset('brand').required().widget(),
|
||||
iconProp().preset('action:connect'),
|
||||
prop('disabled').bool().widget(),
|
||||
prop('busy').bool().widget(),
|
||||
prop('hint').str().preset('Already connected').widget().help('Shown when disabled'),
|
||||
event('click'),
|
||||
slot(),
|
||||
setting('label').preset('Connect').widget(text()),
|
||||
setting('inMenu').preset(false).widget(boolean()).help('Render the button inside a menu'),
|
||||
]"
|
||||
>
|
||||
<MenuList v-if="settings.inMenu" placement="bottom-start">
|
||||
<template #trigger="{ open }">
|
||||
<UiButtonIcon accent="brand" icon="action:more-actions" size="medium" @click="open($event)" />
|
||||
</template>
|
||||
<VtsActionButton v-bind="properties">{{ settings.label }}</VtsActionButton>
|
||||
</MenuList>
|
||||
<VtsActionButton v-else v-bind="properties">{{ settings.label }}</VtsActionButton>
|
||||
</ComponentStory>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { event, iconProp, prop, setting, slot } from '@/libs/story/story-param.ts'
|
||||
import { boolean, text } from '@/libs/story/story-widget.ts'
|
||||
import VtsActionButton from '@core/components/action-button/VtsActionButton.vue'
|
||||
import MenuList from '@core/components/menu/MenuList.vue'
|
||||
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
|
||||
</script>
|
||||
@@ -1,7 +1,10 @@
|
||||
<template>
|
||||
<ComponentStory
|
||||
v-slot="{ properties }"
|
||||
:params="[prop('value').type('string').preset('hello world').required().widget()]"
|
||||
:params="[
|
||||
prop('value').type('string').preset('hello world').required().widget(),
|
||||
prop('label').str().widget().help('Tooltip shown before the copy, also used as the accessible name'),
|
||||
]"
|
||||
>
|
||||
<VtsCopyButton v-bind="properties" />
|
||||
</ComponentStory>
|
||||
|
||||
@@ -0,0 +1,94 @@
|
||||
<template>
|
||||
<ComponentStory
|
||||
v-slot="{ settings }"
|
||||
:params="[
|
||||
slot().help('Meant to receive a UiFileUploader component, inside a VtsInputWrapper in a form'),
|
||||
slot('file-list').help('Meant to receive a UiFileList component'),
|
||||
setting('multiple')
|
||||
.widget(boolean())
|
||||
.preset(true)
|
||||
.help('When disabled, a new pick replaces the listed files: the replacement is up to the consumer'),
|
||||
]"
|
||||
>
|
||||
<VtsFileUploaderContainer>
|
||||
<VtsInputWrapper label="Upload images" :message="rejectionMessages">
|
||||
<UiFileUploader
|
||||
accent="neutral"
|
||||
accept="image/*"
|
||||
accept-label="PNG, JPG or GIF"
|
||||
:multiple="settings.multiple"
|
||||
:max-size="MAX_FILE_SIZE"
|
||||
@select="files => addFiles(files, settings.multiple)"
|
||||
@reject="rejections => showRejections(rejections)"
|
||||
/>
|
||||
</VtsInputWrapper>
|
||||
<template #file-list>
|
||||
<UiFileList>
|
||||
<UiFileItem
|
||||
v-for="storyFile of storyFiles"
|
||||
:key="storyFile.file.name"
|
||||
:file="storyFile.file"
|
||||
:status="storyFile.status"
|
||||
:error="storyFile.error"
|
||||
@delete="deleteFile(storyFile.file)"
|
||||
/>
|
||||
</UiFileList>
|
||||
</template>
|
||||
</VtsFileUploaderContainer>
|
||||
</ComponentStory>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { createStoryFile } from '@/libs/story/story-file.ts'
|
||||
import { setting, slot } from '@/libs/story/story-param.ts'
|
||||
import { boolean } from '@/libs/story/story-widget.ts'
|
||||
import VtsFileUploaderContainer from '@core/components/file-uploader-container/VtsFileUploaderContainer.vue'
|
||||
import VtsInputWrapper, { type InputWrapperMessage } from '@core/components/input-wrapper/VtsInputWrapper.vue'
|
||||
import UiFileItem, { type FileUploadStatus } from '@core/components/ui/file-item/UiFileItem.vue'
|
||||
import UiFileList from '@core/components/ui/file-list/UiFileList.vue'
|
||||
import UiFileUploader, { type FileRejection } from '@core/components/ui/file-uploader/UiFileUploader.vue'
|
||||
import { formatSize } from '@core/utils/size.util.ts'
|
||||
import { ref } from 'vue'
|
||||
|
||||
type StoryFile = {
|
||||
file: File
|
||||
status: FileUploadStatus
|
||||
error?: string[]
|
||||
}
|
||||
|
||||
const MAX_FILE_SIZE = 2_000_000
|
||||
|
||||
const storyFiles = ref<StoryFile[]>([
|
||||
{ file: createStoryFile('debian-12-generic-amd64.qcow2', 102_020_102), status: 'uploaded' },
|
||||
{ file: createStoryFile('xcp-ng-8.3.0.iso', 681_574_400), status: 'uploading' },
|
||||
{
|
||||
file: createStoryFile('backup-metadata.json', 4_096),
|
||||
status: 'error',
|
||||
error: ['Upload failed: connection lost', 'Retried 3 times'],
|
||||
},
|
||||
])
|
||||
|
||||
const rejectionMessages = ref<InputWrapperMessage>([])
|
||||
|
||||
function addFiles(files: File[], multiple: boolean) {
|
||||
const pickedFiles = files.map(file => ({ file, status: 'uploaded' }) satisfies StoryFile)
|
||||
|
||||
storyFiles.value = multiple ? [...storyFiles.value, ...pickedFiles] : pickedFiles
|
||||
rejectionMessages.value = []
|
||||
}
|
||||
|
||||
function showRejections(rejections: FileRejection[]) {
|
||||
rejectionMessages.value = rejections.map(({ file, reason }) => ({
|
||||
content:
|
||||
reason === 'type'
|
||||
? `${file.name}: file type not accepted`
|
||||
: `${file.name}: file larger than ${formatSize(MAX_FILE_SIZE, 0)}`,
|
||||
accent: 'danger' as const,
|
||||
}))
|
||||
}
|
||||
|
||||
function deleteFile(file: File) {
|
||||
storyFiles.value = storyFiles.value.filter(storyFile => storyFile.file !== file)
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,26 @@
|
||||
<template>
|
||||
<ComponentStory :params="[slot().help('Power state actions, shown in the submenu')]">
|
||||
<MenuList placement="bottom-start">
|
||||
<template #trigger="{ open }">
|
||||
<UiButtonIcon accent="brand" icon="action:more-actions" size="medium" @click="open($event)" />
|
||||
</template>
|
||||
<VtsChangeStateMenuItem>
|
||||
<MenuItem accent="neutral" icon="fa:play" :on-click>Start</MenuItem>
|
||||
<MenuItem accent="neutral" icon="fa:stop" :on-click>Shutdown</MenuItem>
|
||||
</VtsChangeStateMenuItem>
|
||||
</MenuList>
|
||||
</ComponentStory>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { slot } from '@/libs/story/story-param.ts'
|
||||
import MenuItem from '@core/components/menu/MenuItem.vue'
|
||||
import MenuList from '@core/components/menu/MenuList.vue'
|
||||
import VtsChangeStateMenuItem from '@core/components/menu/VtsChangeStateMenuItem.vue'
|
||||
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
|
||||
|
||||
function onClick() {
|
||||
return new Promise(resolve => setTimeout(resolve, 500))
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,25 @@
|
||||
<template>
|
||||
<ComponentStory
|
||||
v-slot="{ properties }"
|
||||
:params="[
|
||||
prop('placement').str().preset('bottom-end').widget().help('Placement of the dropdown'),
|
||||
slot().help('Power state actions'),
|
||||
]"
|
||||
>
|
||||
<VtsChangeStateMenu v-bind="properties">
|
||||
<MenuItem accent="neutral" icon="fa:play" :on-click>Start</MenuItem>
|
||||
<MenuItem accent="neutral" icon="fa:stop" :on-click>Shutdown</MenuItem>
|
||||
</VtsChangeStateMenu>
|
||||
</ComponentStory>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { prop, slot } from '@/libs/story/story-param.ts'
|
||||
import MenuItem from '@core/components/menu/MenuItem.vue'
|
||||
import VtsChangeStateMenu from '@core/components/menu/VtsChangeStateMenu.vue'
|
||||
|
||||
function onClick() {
|
||||
return new Promise(resolve => setTimeout(resolve, 500))
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,39 @@
|
||||
<template>
|
||||
<ComponentStory
|
||||
v-slot="{ properties }"
|
||||
:params="[
|
||||
prop('title').str().required().preset('More actions').widget(),
|
||||
prop('sectionTitle').str().preset('Actions').widget(),
|
||||
event('action').help('Emitted when a menu item closes the menu after its action'),
|
||||
slot('trigger').prop('open', '() => void').prop('isOpen', 'boolean'),
|
||||
slot().help('Menu items, a submenu opens in place'),
|
||||
]"
|
||||
>
|
||||
<VtsMobileMenu v-bind="properties">
|
||||
<template #trigger="{ open }">
|
||||
<UiButtonIcon accent="brand" icon="action:more-actions" size="medium" @click="open()" />
|
||||
</template>
|
||||
<MenuItem accent="brand" icon="action:change-state">
|
||||
Change state
|
||||
<template #submenu>
|
||||
<MenuItem accent="neutral" icon="fa:play" :on-click>Start</MenuItem>
|
||||
<MenuItem accent="neutral" icon="fa:stop" :on-click>Shutdown</MenuItem>
|
||||
</template>
|
||||
</MenuItem>
|
||||
<MenuItem accent="neutral" icon="action:copy" :on-click>Copy</MenuItem>
|
||||
<MenuItem accent="danger" icon="action:delete" :on-click>Delete</MenuItem>
|
||||
</VtsMobileMenu>
|
||||
</ComponentStory>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { event, prop, slot } from '@/libs/story/story-param.ts'
|
||||
import MenuItem from '@core/components/menu/MenuItem.vue'
|
||||
import VtsMobileMenu from '@core/components/menu/VtsMobileMenu.vue'
|
||||
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
|
||||
|
||||
function onClick() {
|
||||
return new Promise(resolve => setTimeout(resolve, 500))
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,36 @@
|
||||
<template>
|
||||
<ComponentStory
|
||||
v-slot="{ properties }"
|
||||
:params="[
|
||||
prop('title').str().required().preset('New').widget().help('Title of the full page menu on mobile'),
|
||||
prop('sectionTitle').str().widget().help('Section title of the full page menu on mobile'),
|
||||
prop('placement').str().preset('bottom-start').widget().help('Placement of the dropdown on desktop'),
|
||||
prop('disabled').bool().widget(),
|
||||
event('action').help('Emitted on mobile when a menu item closes the menu after its action'),
|
||||
slot('trigger').prop('open', '(event: MouseEvent) => void').prop('isOpen', 'boolean'),
|
||||
slot().help('Menu items'),
|
||||
]"
|
||||
>
|
||||
<VtsResponsiveMenu v-bind="properties">
|
||||
<template #trigger="{ open, isOpen }">
|
||||
<UiDropdownButton variant="primary" size="medium" :selected="isOpen" @click="open($event)">
|
||||
New
|
||||
</UiDropdownButton>
|
||||
</template>
|
||||
<MenuItem accent="neutral" icon="fa:plus" :on-click>Create network</MenuItem>
|
||||
<MenuItem accent="neutral" icon="fa:plus" :on-click>Create bonded network</MenuItem>
|
||||
</VtsResponsiveMenu>
|
||||
</ComponentStory>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { event, prop, slot } from '@/libs/story/story-param.ts'
|
||||
import MenuItem from '@core/components/menu/MenuItem.vue'
|
||||
import VtsResponsiveMenu from '@core/components/menu/VtsResponsiveMenu.vue'
|
||||
import UiDropdownButton from '@core/components/ui/dropdown-button/UiDropdownButton.vue'
|
||||
|
||||
function onClick() {
|
||||
return new Promise(resolve => setTimeout(resolve, 500))
|
||||
}
|
||||
</script>
|
||||
@@ -11,7 +11,7 @@
|
||||
event('close').args({}).help('Emitted when the user clicks the close button'),
|
||||
slot(),
|
||||
slot('header').help('Meant to receive text or other information'),
|
||||
slot('actions').help('For the main action buttons'),
|
||||
slot('actions').help('For the main action buttons, moved into the more actions menu when they do not fit'),
|
||||
slot('more-actions').help('For other action buttons, shown in a dropdown menu'),
|
||||
slot('corner-actions').help('For action icon buttons, like the pin button on VtsSidePanel'),
|
||||
setting('headerText').widget(text()),
|
||||
@@ -29,15 +29,15 @@
|
||||
<span>{{ settings.headerText }}</span>
|
||||
</template>
|
||||
<template v-if="settings.showButtons" #actions>
|
||||
<UiButton variant="tertiary" size="medium" accent="brand" left-icon="action:edit">Edit</UiButton>
|
||||
<UiButton variant="tertiary" size="medium" accent="danger" left-icon="action:delete">Delete</UiButton>
|
||||
<VtsActionButton variant="tertiary" accent="brand" icon="action:edit">Edit</VtsActionButton>
|
||||
<VtsActionButton variant="tertiary" accent="danger" icon="action:delete">Delete</VtsActionButton>
|
||||
</template>
|
||||
<template v-if="settings.showMoreButtons" #more-actions>
|
||||
<UiButton variant="tertiary" size="medium" accent="warning" left-icon="action:disconnect">
|
||||
<MenuItem accent="warning" icon="action:disconnect">
|
||||
Disconnect<UiCounter value="3" accent="warning" variant="primary" size="small" />
|
||||
</UiButton>
|
||||
<UiButton variant="tertiary" size="medium" accent="brand" left-icon="action:copy">Copy</UiButton>
|
||||
<UiButton variant="tertiary" size="medium" accent="brand" left-icon="action:download">Download</UiButton>
|
||||
</MenuItem>
|
||||
<MenuItem accent="neutral" icon="action:copy">Copy</MenuItem>
|
||||
<MenuItem accent="neutral" icon="action:download">Download</MenuItem>
|
||||
</template>
|
||||
<template #default>
|
||||
<VtsStateHero v-if="settings.showHero" format="card" :type="settings.heroType" size="medium" />
|
||||
@@ -53,9 +53,10 @@
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { event, iconProp, prop, setting, slot } from '@/libs/story/story-param.ts'
|
||||
import { boolean, choice, text } from '@/libs/story/story-widget.ts'
|
||||
import VtsActionButton from '@core/components/action-button/VtsActionButton.vue'
|
||||
import MenuItem from '@core/components/menu/MenuItem.vue'
|
||||
import VtsPanel from '@core/components/panel/VtsPanel.vue'
|
||||
import VtsStateHero from '@core/components/state-hero/VtsStateHero.vue'
|
||||
import UiButton from '@core/components/ui/button/UiButton.vue'
|
||||
import UiCounter from '@core/components/ui/counter/UiCounter.vue'
|
||||
import UiPanelCard from '@core/components/ui/panel-card/UiPanelCard.vue'
|
||||
import { STATE_HERO_TYPES } from '@core/types/state-hero.type.ts'
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
<template>
|
||||
<ComponentStory
|
||||
v-slot="{ properties }"
|
||||
:params="[prop('disabled').bool().widget(), slot().help('Contains <RouterTab> or <UiTabItem>')]"
|
||||
:params="[
|
||||
prop('label').str().widget().preset('Tabs'),
|
||||
prop('disabled').bool().widget(),
|
||||
slot().help('Contains <RouterTab> or <UiTabItem>'),
|
||||
]"
|
||||
>
|
||||
<TabList v-bind="properties">
|
||||
<UiTabItem>Foo</UiTabItem>
|
||||
|
||||
@@ -7,7 +7,10 @@
|
||||
prop('size').required().enum('small', 'medium', 'large').preset('medium').widget(),
|
||||
prop('disabled').bool().widget(),
|
||||
prop('selected').bool().widget(),
|
||||
prop('dot').bool().widget(),
|
||||
prop('counter')
|
||||
.type('CounterValue | { value: CounterValue; accent: CounterAccent }')
|
||||
.widget(object())
|
||||
.help('Info accent by default'),
|
||||
prop('targetScale')
|
||||
.type('number | { x: number; y: number }')
|
||||
.default(1)
|
||||
@@ -15,6 +18,32 @@
|
||||
.help('Meant to increase click target size if needed')
|
||||
.widget(),
|
||||
]"
|
||||
:presets="{
|
||||
'No counter': {
|
||||
props: {
|
||||
icon: 'fa:bars-progress',
|
||||
counter: undefined,
|
||||
},
|
||||
},
|
||||
'Number counter': {
|
||||
props: {
|
||||
icon: 'fa:bars-progress',
|
||||
counter: 6,
|
||||
},
|
||||
},
|
||||
'Percentage (warning)': {
|
||||
props: {
|
||||
icon: 'fa:bars-progress',
|
||||
counter: { value: '42%', accent: 'warning' },
|
||||
},
|
||||
},
|
||||
'Exclamation mark (danger)': {
|
||||
props: {
|
||||
icon: 'fa:bars-progress',
|
||||
counter: { value: '!', accent: 'danger' },
|
||||
},
|
||||
},
|
||||
}"
|
||||
>
|
||||
<UiButtonIcon v-bind="properties" />
|
||||
</ComponentStory>
|
||||
@@ -23,5 +52,6 @@
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { iconProp, prop } from '@/libs/story/story-param.ts'
|
||||
import { object } from '@/libs/story/story-widget.ts'
|
||||
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
|
||||
</script>
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
<template>
|
||||
<ComponentStory
|
||||
v-slot="{ properties, settings }"
|
||||
:params="[
|
||||
prop('file').type('File').required().help('Only `name` and `size` are read. Driven by the story settings tab'),
|
||||
prop('status').enum('uploading', 'uploaded', 'error').required().preset('uploading').widget(),
|
||||
prop('error')
|
||||
.type('MaybeArray<string>')
|
||||
.widget(object())
|
||||
.help('Displayed below the file as a danger message, one line per message, whatever the status'),
|
||||
event('retry').help('Emitted when the user clicks the Retry button, only shown when status is `error`'),
|
||||
event('cancel').help('Emitted when the user clicks the cancel button, only shown when status is `uploading`'),
|
||||
event('delete').help('Emitted when the user clicks the delete button, only shown when status is `uploaded`'),
|
||||
setting('fileName')
|
||||
.widget(text())
|
||||
.preset('debian-12-generic-amd64.qcow2')
|
||||
.help('Names too long for the available width are truncated in the middle, keeping the extension visible'),
|
||||
setting('fileSize')
|
||||
.widget(number())
|
||||
.preset(DEFAULT_FILE_SIZE)
|
||||
.help('File size in bytes. Only displayed when status is `uploaded`'),
|
||||
]"
|
||||
:presets
|
||||
>
|
||||
<ul>
|
||||
<UiFileItem v-bind="properties" :file="createStoryFile(settings.fileName, settings.fileSize)" />
|
||||
</ul>
|
||||
</ComponentStory>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { createStoryFile } from '@/libs/story/story-file.ts'
|
||||
import { event, prop, setting } from '@/libs/story/story-param.ts'
|
||||
import { number, object, text } from '@/libs/story/story-widget.ts'
|
||||
import UiFileItem from '@core/components/ui/file-item/UiFileItem.vue'
|
||||
|
||||
const DEFAULT_FILE_SIZE = 102_020_102
|
||||
|
||||
const presets = {
|
||||
Uploading: {
|
||||
props: {
|
||||
status: 'uploading',
|
||||
error: undefined,
|
||||
},
|
||||
},
|
||||
Uploaded: {
|
||||
props: {
|
||||
status: 'uploaded',
|
||||
error: undefined,
|
||||
},
|
||||
},
|
||||
'Failed with a message': {
|
||||
props: {
|
||||
status: 'error',
|
||||
error: 'File size exceeds 5 MB',
|
||||
},
|
||||
},
|
||||
'Failed with several messages': {
|
||||
props: {
|
||||
status: 'error',
|
||||
error: ['File size exceeds 5 MB', 'File type not accepted'],
|
||||
},
|
||||
},
|
||||
'Truncated file name': {
|
||||
props: {
|
||||
status: 'uploaded',
|
||||
error: undefined,
|
||||
},
|
||||
settings: {
|
||||
fileName: 'a-very-long-file-name-that-only-gets-truncated-when-the-available-width-is-too-small.qcow2',
|
||||
},
|
||||
},
|
||||
}
|
||||
</script>
|
||||
@@ -0,0 +1,37 @@
|
||||
<template>
|
||||
<ComponentStory :params="[slot().help('Meant to receive UiFileItem components')]">
|
||||
<UiFileList>
|
||||
<UiFileItem
|
||||
v-for="storyFile of storyFiles"
|
||||
:key="storyFile.file.name"
|
||||
:file="storyFile.file"
|
||||
:status="storyFile.status"
|
||||
:error="storyFile.error"
|
||||
/>
|
||||
</UiFileList>
|
||||
</ComponentStory>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { createStoryFile } from '@/libs/story/story-file.ts'
|
||||
import { slot } from '@/libs/story/story-param.ts'
|
||||
import UiFileItem, { type FileUploadStatus } from '@core/components/ui/file-item/UiFileItem.vue'
|
||||
import UiFileList from '@core/components/ui/file-list/UiFileList.vue'
|
||||
|
||||
type StoryFile = {
|
||||
file: File
|
||||
status: FileUploadStatus
|
||||
error?: string
|
||||
}
|
||||
|
||||
const storyFiles: StoryFile[] = [
|
||||
{ file: createStoryFile('debian-12-generic-amd64.qcow2', 102_020_102), status: 'uploaded' },
|
||||
{ file: createStoryFile('xcp-ng-8.3.0.iso', 681_574_400), status: 'uploading' },
|
||||
{
|
||||
file: createStoryFile('backup-metadata.json', 4_096),
|
||||
status: 'error',
|
||||
error: 'Upload failed: connection lost',
|
||||
},
|
||||
]
|
||||
</script>
|
||||
@@ -0,0 +1,94 @@
|
||||
<template>
|
||||
<ComponentStory
|
||||
v-slot="{ properties, settings }"
|
||||
:params="[
|
||||
prop('accent')
|
||||
.enum('neutral', 'warning', 'danger')
|
||||
.required()
|
||||
.preset('neutral')
|
||||
.widget()
|
||||
.help('Overridden by the accent of the parent VtsInputWrapper when that one is not neutral'),
|
||||
prop('maxSize').num().widget().help('Maximum file size in bytes. Larger files are rejected'),
|
||||
prop('accept')
|
||||
.type('MaybeArray<string>')
|
||||
.default('*/*')
|
||||
.widget(
|
||||
choice(
|
||||
{ label: 'Any file type', value: '*/*' },
|
||||
{ label: 'Images', value: 'image/*' },
|
||||
{ label: 'JSON files', value: '.json' },
|
||||
{ label: 'Images and JSON files', value: ['image/*', '.json'] }
|
||||
)
|
||||
)
|
||||
.help('A single MIME type or extension, or a list of them. Non-matching files are rejected'),
|
||||
prop('acceptLabel')
|
||||
.str()
|
||||
.widget()
|
||||
.help(
|
||||
'Readable list of the accepted types shown in the hint. Falls back to `Any file type` or the raw `accept` list'
|
||||
),
|
||||
prop('multiple').bool().widget().help('When disabled, only the first accepted file is emitted'),
|
||||
prop('required').bool().widget().help('Displayed by the label of the parent VtsInputWrapper'),
|
||||
prop('disabled').bool().widget().ctx(),
|
||||
event('select').args({ files: 'File[]' }).help('Emitted with the accepted files picked or dropped'),
|
||||
event('reject')
|
||||
.args({ rejections: 'FileRejection[]' })
|
||||
.help('Emitted with the files rejected because of their type or size, with the reason'),
|
||||
setting('label').widget(text()).preset('Upload files').help('Label of the parent VtsInputWrapper'),
|
||||
setting('message')
|
||||
.widget(object())
|
||||
.preset([])
|
||||
.help(
|
||||
'Message of the parent VtsInputWrapper (InputWrapperMessage). A danger message turns the uploader danger'
|
||||
),
|
||||
]"
|
||||
:presets
|
||||
>
|
||||
<VtsInputWrapper :label="settings.label" :message="settings.message">
|
||||
<UiFileUploader v-bind="properties" />
|
||||
</VtsInputWrapper>
|
||||
</ComponentStory>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { event, prop, setting } from '@/libs/story/story-param.ts'
|
||||
import { choice, object, text } from '@/libs/story/story-widget.ts'
|
||||
import VtsInputWrapper from '@core/components/input-wrapper/VtsInputWrapper.vue'
|
||||
import UiFileUploader from '@core/components/ui/file-uploader/UiFileUploader.vue'
|
||||
|
||||
const presets = {
|
||||
'Multiple images, max 2 MB': {
|
||||
props: {
|
||||
accept: 'image/*',
|
||||
acceptLabel: 'PNG, JPG or GIF',
|
||||
multiple: true,
|
||||
maxSize: 2_000_000,
|
||||
},
|
||||
settings: {
|
||||
label: 'Upload images',
|
||||
},
|
||||
},
|
||||
'Single required file': {
|
||||
props: {
|
||||
accept: '.json',
|
||||
acceptLabel: 'JSON',
|
||||
multiple: false,
|
||||
required: true,
|
||||
},
|
||||
settings: {
|
||||
label: 'Upload a configuration file',
|
||||
},
|
||||
},
|
||||
'With a danger message': {
|
||||
settings: {
|
||||
message: [{ content: 'A file is required', accent: 'danger' }],
|
||||
},
|
||||
},
|
||||
Disabled: {
|
||||
props: {
|
||||
disabled: true,
|
||||
},
|
||||
},
|
||||
}
|
||||
</script>
|
||||
@@ -13,6 +13,7 @@
|
||||
choice({ label: 'Search', value: 'fa:magnifying-glass' }, { label: 'AngleDown', value: 'fa:angle-down' })
|
||||
),
|
||||
prop('clearable').bool().widget(),
|
||||
prop('busy').bool().widget(),
|
||||
prop('prefix').str().widget(),
|
||||
prop('suffix').str().widget(),
|
||||
prop('disabled').bool().widget(),
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
<template>
|
||||
<ComponentStory v-slot="{ properties }" :params="[event('search').args({ value: 'string' })]">
|
||||
<UiQuerySearchBar id="search-bar" v-bind="properties" @search="(value: string) => (filter = value)" />
|
||||
<ComponentStory
|
||||
v-slot="{ properties }"
|
||||
:params="[model().type('string').required(), prop('busy').bool().widget(), event('search')]"
|
||||
>
|
||||
<UiQuerySearchBar id="search-bar" v-bind="properties" v-model="filter" :busy="properties.busy || isSearching" />
|
||||
|
||||
<p class="text">Example data:</p>
|
||||
<ul class="data-list">
|
||||
@@ -11,7 +14,7 @@
|
||||
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { event } from '@/libs/story/story-param.ts'
|
||||
import { event, model, prop } from '@/libs/story/story-param.ts'
|
||||
import UiQuerySearchBar from '@core/components/ui/query-search-bar/UiQuerySearchBar.vue'
|
||||
import { useTreeFilter } from '@core/composables/tree-filter.composable.ts'
|
||||
import { defineTree } from '@core/packages/tree/define-tree.ts'
|
||||
@@ -120,7 +123,7 @@ const data = [
|
||||
},
|
||||
]
|
||||
|
||||
const { filter, predicate } = useTreeFilter()
|
||||
const { filter, predicate, isSearching } = useTreeFilter()
|
||||
|
||||
const definitions = defineTree('vms', data, {
|
||||
getLabel: 'name_label',
|
||||
|
||||
@@ -423,6 +423,19 @@ export default class Backups {
|
||||
},
|
||||
},
|
||||
],
|
||||
purgeVmBackupsJournal: [
|
||||
// `before` is computed by the caller: the horizon is the one of XO, whatever the clock of this proxy
|
||||
({ remote, before }) =>
|
||||
Disposable.use(this.getAdapter(remote), adapter => adapter.purgeBackupJournal(before)),
|
||||
{
|
||||
description: 'remove the days of the backup journal of a remote before the one of a date',
|
||||
params: {
|
||||
remote: { type: 'object' },
|
||||
// timestamp in ms
|
||||
before: { type: 'number' },
|
||||
},
|
||||
},
|
||||
],
|
||||
restoreMetadataBackup: [
|
||||
({ backupId, remote, xapi: xapiOptions }) =>
|
||||
Disposable.use(app.remotes.getHandler(remote), xapiOptions && this.getXapi(xapiOptions), (handler, xapi) =>
|
||||
|
||||
@@ -53,6 +53,16 @@ The following are required only for mirror backup tests (`qa:mirror`):
|
||||
| `MIRROR_DESTINATION_REPOSITORY_NAME` | Mirror destination repository name | `Test mirror QA` |
|
||||
| `MIRROR_DESTINATION_REPOSITORY_URL` | `@xen-orchestra/fs` URL for the mirror destination. Same backend flexibility as `BACKUP_REPOSITORY_URL`. | `file:///tmp/xo-test-mirror` |
|
||||
|
||||
The following are optional, for the VM folder lock tests (`qa:backup:lock`), which skip a backend whose URL is unset.
|
||||
The machine running the suite must reach these repositories as XO does.
|
||||
|
||||
| Variable | Description | Example |
|
||||
| ------------------------------ | --------------------------------------------- | --------------------------------------------------------------------------------- |
|
||||
| `S3_BACKUP_REPOSITORY_NAME` | S3 backup repository name in XO | `Test backup QA S3` |
|
||||
| `S3_BACKUP_REPOSITORY_URL` | `@xen-orchestra/fs` URL of an S3 bucket | `s3://<access key>:<secret key>@<host>/<bucket>/<directory>` |
|
||||
| `AZURE_BACKUP_REPOSITORY_NAME` | Azure backup repository name in XO | `Test backup QA Azure` |
|
||||
| `AZURE_BACKUP_REPOSITORY_URL` | `@xen-orchestra/fs` URL of an Azure container | `azure://<account>:<key>@<account>.blob.core.windows.net/<container>/<directory>` |
|
||||
|
||||
The following are optional, for load tests (disk churn via SSH). Leave `TEST_VM_SSH_KEY` unset
|
||||
to let `ssh` fall back to its own default identity files / `ssh-agent`:
|
||||
|
||||
@@ -86,6 +96,7 @@ Log namespaces follow the pattern `qa:<suite>[:<variant>]`:
|
||||
| `qa:backup:base` | `tests/backup.test.js` |
|
||||
| `qa:backup:nbd` | `tests/backup.nbd.test.js` |
|
||||
| `qa:backup:combined` | `tests/backup-replication-combined.test.js` |
|
||||
| `qa:backup:lock` | `tests/backup.lock.test.js` |
|
||||
| `qa:mirror` | `tests/backup-mirror.test.js` |
|
||||
| `qa:export` | `tests/export.vhd.test.js` |
|
||||
| `qa:load:backup:delta` | `scripts/backup-load-delta.mjs` |
|
||||
@@ -106,9 +117,15 @@ yarn workspace @xen-orchestra/qa-test qa:vm # VM lifecycle (clone
|
||||
yarn workspace @xen-orchestra/qa-test qa:backup # Full and delta backup
|
||||
yarn workspace @xen-orchestra/qa-test qa:backup:nbd # Backup with NBD protocol
|
||||
yarn workspace @xen-orchestra/qa-test qa:backup:combined # Advanced scenarios (replication + backup)
|
||||
yarn workspace @xen-orchestra/qa-test qa:backup:lock # VM backup folder lock (S3 and Azure only)
|
||||
yarn workspace @xen-orchestra/qa-test qa:export # VHD/XVA export and restoration
|
||||
```
|
||||
|
||||
`qa:backup:lock` locks the backup folder of its test VM itself, from the machine running the suite, and checks that
|
||||
a backup of the VM fails while the folder is locked, and that XO releases its own lock at the end of a backup. It runs
|
||||
once per repository set in `S3_BACKUP_REPOSITORY_URL` and `AZURE_BACKUP_REPOSITORY_URL` (see above), and skips on an
|
||||
S3 bucket which XO does not lock (Object Lock).
|
||||
|
||||
### Test subsets
|
||||
|
||||
```bash
|
||||
|
||||
@@ -31,6 +31,19 @@ BACKUP_REPOSITORY_URL="file:///tmp/xo-test-backups"
|
||||
MIRROR_DESTINATION_REPOSITORY_NAME=Test mirror QA
|
||||
MIRROR_DESTINATION_REPOSITORY_URL="file:///tmp/xo-test-mirror"
|
||||
|
||||
# ===========================================
|
||||
# S3 AND AZURE BACKUP REPOSITORY CONFIGURATION
|
||||
# ===========================================
|
||||
|
||||
# Optional repositories for the VM folder lock tests (qa:backup:lock), which skip
|
||||
# a backend whose URL is unset. The suite locks a VM's backup folder itself, so
|
||||
# the machine running it must reach these repositories as XO does.
|
||||
# use " around the url to handle # escaping
|
||||
S3_BACKUP_REPOSITORY_NAME=Test backup QA S3
|
||||
S3_BACKUP_REPOSITORY_URL= # e.g. "s3://<access key>:<secret key>@<host>/<bucket>/<directory>"
|
||||
AZURE_BACKUP_REPOSITORY_NAME=Test backup QA Azure
|
||||
AZURE_BACKUP_REPOSITORY_URL= # e.g. "azure://<account>:<key>@<account>.blob.core.windows.net/<container>/<directory>"
|
||||
|
||||
# ===========================================
|
||||
# REPLICATION TEST CONFIGURATION
|
||||
# ===========================================
|
||||
@@ -75,7 +88,7 @@ VHD_EXPORT_PATH=/tmp/xo-test-exports
|
||||
# The source VM must be RUNNING and have NO SNAPSHOT: the test migrates a live VM and checks
|
||||
# that XO takes its own snapshot. It leaves the VM halted, with that snapshot — restart is
|
||||
# automatic, but the snapshot has to be removed by hand before the next run.
|
||||
# ESXI_VM_ID is the VMware MoRef id (a number, as shown by esxi.listVms), not a UUID.
|
||||
# ESXI_VM_ID is the VMware MoRef id (as listed by POST /rest/v0/v2v/inventory or esxi.listVms), not a UUID.
|
||||
ESXI_HOST=
|
||||
ESXI_USER=root
|
||||
ESXI_PASSWORD=
|
||||
|
||||
@@ -61,6 +61,16 @@ The following are required only for mirror backup tests (`qa:mirror`):
|
||||
| `MIRROR_DESTINATION_REPOSITORY_NAME` | Mirror destination repository name | `Test mirror QA` |
|
||||
| `MIRROR_DESTINATION_REPOSITORY_URL` | `@xen-orchestra/fs` URL for the mirror destination. Same backend flexibility as `BACKUP_REPOSITORY_URL`. | `file:///tmp/xo-test-mirror` |
|
||||
|
||||
The following are optional, for the VM folder lock tests (`qa:backup:lock`), which skip a backend whose URL is unset.
|
||||
The machine running the suite must reach these repositories as XO does.
|
||||
|
||||
| Variable | Description | Example |
|
||||
| ------------------------------ | --------------------------------------------- | --------------------------------------------------------------------------------- |
|
||||
| `S3_BACKUP_REPOSITORY_NAME` | S3 backup repository name in XO | `Test backup QA S3` |
|
||||
| `S3_BACKUP_REPOSITORY_URL` | `@xen-orchestra/fs` URL of an S3 bucket | `s3://<access key>:<secret key>@<host>/<bucket>/<directory>` |
|
||||
| `AZURE_BACKUP_REPOSITORY_NAME` | Azure backup repository name in XO | `Test backup QA Azure` |
|
||||
| `AZURE_BACKUP_REPOSITORY_URL` | `@xen-orchestra/fs` URL of an Azure container | `azure://<account>:<key>@<account>.blob.core.windows.net/<container>/<directory>` |
|
||||
|
||||
The following are optional, for load tests (disk churn via SSH). Leave `TEST_VM_SSH_KEY` unset
|
||||
to let `ssh` fall back to its own default identity files / `ssh-agent`:
|
||||
|
||||
@@ -94,6 +104,7 @@ Log namespaces follow the pattern `qa:<suite>[:<variant>]`:
|
||||
| `qa:backup:base` | `tests/backup.test.js` |
|
||||
| `qa:backup:nbd` | `tests/backup.nbd.test.js` |
|
||||
| `qa:backup:combined` | `tests/backup-replication-combined.test.js` |
|
||||
| `qa:backup:lock` | `tests/backup.lock.test.js` |
|
||||
| `qa:mirror` | `tests/backup-mirror.test.js` |
|
||||
| `qa:export` | `tests/export.vhd.test.js` |
|
||||
| `qa:load:backup:delta` | `scripts/backup-load-delta.mjs` |
|
||||
@@ -114,9 +125,15 @@ yarn workspace @xen-orchestra/qa-test qa:vm # VM lifecycle (clone
|
||||
yarn workspace @xen-orchestra/qa-test qa:backup # Full and delta backup
|
||||
yarn workspace @xen-orchestra/qa-test qa:backup:nbd # Backup with NBD protocol
|
||||
yarn workspace @xen-orchestra/qa-test qa:backup:combined # Advanced scenarios (replication + backup)
|
||||
yarn workspace @xen-orchestra/qa-test qa:backup:lock # VM backup folder lock (S3 and Azure only)
|
||||
yarn workspace @xen-orchestra/qa-test qa:export # VHD/XVA export and restoration
|
||||
```
|
||||
|
||||
`qa:backup:lock` locks the backup folder of its test VM itself, from the machine running the suite, and checks that
|
||||
a backup of the VM fails while the folder is locked, and that XO releases its own lock at the end of a backup. It runs
|
||||
once per repository set in `S3_BACKUP_REPOSITORY_URL` and `AZURE_BACKUP_REPOSITORY_URL` (see above), and skips on an
|
||||
S3 bucket which XO does not lock (Object Lock).
|
||||
|
||||
### Test subsets
|
||||
|
||||
```bash
|
||||
|
||||
@@ -39,6 +39,7 @@
|
||||
"qa:backup:combined": "node --env-file-if-exists=.env --test tests/backup-replication-combined.test.js",
|
||||
"qa:backup:combined:cycle": "node --env-file-if-exists=.env --test tests/backup-replication-combined.test.js --test-name-pattern='Full Cycle'",
|
||||
"qa:backup:sync": "node --env-file-if-exists=.env --test tests/backup.synchronized.test.js --test-concurrency=1",
|
||||
"qa:backup:lock": "node --env-file-if-exists=.env --test tests/backup.lock.test.js",
|
||||
"qa:mirror:cr": "node --env-file-if-exists=.env --test tests/backup-replication-combined.test.js --test-name-pattern='CR Mode'",
|
||||
"qa:mirror": "node --env-file-if-exists=.env --test tests/backup-mirror.test.js",
|
||||
"qa:replication": "node --env-file-if-exists=.env --test --test-concurrency=1 tests/replication.test.js",
|
||||
|
||||
@@ -9,17 +9,18 @@ import { setup, teardown } from './setup.js'
|
||||
|
||||
const log = createLogger('qa:backup:file-restore')
|
||||
|
||||
// Magic bytes used to validate archive format integrity
|
||||
// Magic bytes for archive format validation
|
||||
const TGZ_MAGIC = [0x1f, 0x8b]
|
||||
const ZIP_MAGIC = [0x50, 0x4b]
|
||||
|
||||
describe('Incremental backup file restore', () => {
|
||||
let dispatchClient
|
||||
let restApiClient
|
||||
let tracker
|
||||
let vm
|
||||
let backupRepository
|
||||
|
||||
// The second (delta) backup to run file restore on
|
||||
/** @type {import('@vates/types').XoVmBackupArchive} */
|
||||
let incrementalBackup
|
||||
|
||||
before(async () => {
|
||||
@@ -27,6 +28,7 @@ describe('Incremental backup file restore', () => {
|
||||
;({ dispatchClient, tracker, vms, backupRepository } = await setup())
|
||||
// Only using one VM
|
||||
vm = vms[0]
|
||||
restApiClient = dispatchClient.restApiClient
|
||||
|
||||
const name = generateBackupJobName()
|
||||
const schedule = getDefaultSchedule()
|
||||
@@ -41,7 +43,6 @@ describe('Incremental backup file restore', () => {
|
||||
if (scheduleKey) {
|
||||
tracker.trackResource('schedule', scheduleKey, { name, backupJobId })
|
||||
}
|
||||
|
||||
assert(scheduleKey, 'Schedule key is required for file restore tests')
|
||||
|
||||
// First run → full backup (base), second run → delta (incremental)
|
||||
@@ -51,22 +52,21 @@ describe('Incremental backup file restore', () => {
|
||||
log.debug(`Completed backup run ${i + 1}/2`, { status: result.status })
|
||||
}
|
||||
|
||||
// Pick the most recent delta backup for file restore testing
|
||||
const backupsByRemoteAndVm = await dispatchClient.xoClient.call('backupNg.listVmBackups', {
|
||||
remotes: [backupRepository.id],
|
||||
// Discover the incremental backup via REST API
|
||||
const allArchives = await restApiClient.getObjects('/rest/v0/backup-archives', {
|
||||
additionalParams: { 'backup-repository': backupRepository.id },
|
||||
})
|
||||
|
||||
const vmBackups = backupsByRemoteAndVm[backupRepository.id]?.[vm.uuid]
|
||||
assert(Array.isArray(vmBackups) && vmBackups.length >= 2, 'Expected at least 2 backups after two runs')
|
||||
const vmArchives = allArchives.filter(a => a.vm?.uuid === vm.uuid).sort((a, b) => a.timestamp - b.timestamp)
|
||||
|
||||
const sorted = [...vmBackups].sort((a, b) => a.timestamp - b.timestamp)
|
||||
incrementalBackup = sorted[sorted.length - 1]
|
||||
assert(vmArchives.length >= 2, `Expected at least 2 backups via REST API, got ${vmArchives.length}`)
|
||||
incrementalBackup = vmArchives[vmArchives.length - 1]
|
||||
|
||||
assert.strictEqual(incrementalBackup.mode, 'delta', 'Latest backup should be a delta (incremental) backup')
|
||||
assert(incrementalBackup.disks.length > 0, 'Incremental backup should contain at least one disk')
|
||||
assert.strictEqual(incrementalBackup.mode, 'delta', 'Latest backup should be a delta')
|
||||
assert(incrementalBackup.disks.length > 0, 'Archive should have at least one disk')
|
||||
|
||||
log.debug('Selected incremental backup for file restore', {
|
||||
backupId: incrementalBackup.id,
|
||||
log.debug('Selected incremental backup', {
|
||||
id: incrementalBackup.id,
|
||||
diskCount: incrementalBackup.disks.length,
|
||||
timestamp: new Date(incrementalBackup.timestamp).toISOString(),
|
||||
})
|
||||
@@ -76,109 +76,105 @@ describe('Incremental backup file restore', () => {
|
||||
await teardown(dispatchClient, tracker)
|
||||
})
|
||||
|
||||
it('should list partitions, list files, and restore first 2 files in tgz and zip for each disk', async () => {
|
||||
const remoteId = backupRepository.id
|
||||
it('should list disks, partitions, and files, then download as tgz and zip via REST API', async () => {
|
||||
const encodedId = encodeURIComponent(incrementalBackup.id)
|
||||
const archiveBase = `/rest/v0/backup-archives/${encodedId}`
|
||||
|
||||
const archive = await restApiClient.get(`${archiveBase}`)
|
||||
const disks = archive.disks
|
||||
assert(Array.isArray(disks) && disks.length > 0, 'archive should expose at least one disk')
|
||||
assert.deepStrictEqual(
|
||||
disks.map(d => d.id).sort(),
|
||||
incrementalBackup.disks.map(d => d.id).sort(),
|
||||
'Disk IDs from the archive should match the metadata discovered in setup'
|
||||
)
|
||||
|
||||
log.debug('Disks read from archive via REST API', { count: disks.length })
|
||||
|
||||
for (const disk of incrementalBackup.disks) {
|
||||
log.debug('Processing disk', { diskId: disk.id, diskName: disk.name })
|
||||
const encodedDiskId = encodeURIComponent(disk.id)
|
||||
const diskBase = `${archiveBase}/disks/${encodedDiskId}`
|
||||
|
||||
const partitions = await dispatchClient.xoClient.call('backupNg.listPartitions', {
|
||||
remote: remoteId,
|
||||
disk: disk.id,
|
||||
})
|
||||
// List partitions
|
||||
const partitions = await restApiClient.get(`${diskBase}/partitions`)
|
||||
assert(Array.isArray(partitions), `GET /partitions should return an array for disk ${disk.id}`)
|
||||
log.debug('Partitions listed via REST API', { diskId: disk.id, count: partitions.length })
|
||||
|
||||
assert(Array.isArray(partitions), `listPartitions should return an array for disk ${disk.id}`)
|
||||
log.debug('Found partitions', { diskId: disk.id, count: partitions.length })
|
||||
// When there are no partitions, treat the disk as a bare (unpartitioned) volume
|
||||
const targets = partitions.length > 0 ? partitions : [{ id: undefined }]
|
||||
|
||||
// When listPartitions returns empty, treat the disk as a single raw (unpartitioned) volume.
|
||||
// The API accepts partition: undefined for this case.
|
||||
const partitionTargets = partitions.length > 0 ? partitions : [{ id: undefined }]
|
||||
|
||||
for (const partition of partitionTargets) {
|
||||
for (const partition of targets) {
|
||||
const partitionId = partition.id
|
||||
log.debug('Processing partition', { diskId: disk.id, partitionId })
|
||||
|
||||
let fileEntries
|
||||
|
||||
try {
|
||||
fileEntries = await dispatchClient.xoClient.call('backupNg.listFiles', {
|
||||
remote: remoteId,
|
||||
disk: disk.id,
|
||||
...(partitionId !== undefined && { partition: partitionId }),
|
||||
path: '/',
|
||||
})
|
||||
} catch (error) {
|
||||
// Some partitions (swap, EFI system) cannot be mounted — skip gracefully
|
||||
log.warn('Could not list files for partition, skipping', {
|
||||
if (partitionId !== undefined) {
|
||||
const encodedPartId = encodeURIComponent(partitionId)
|
||||
fileEntries = await restApiClient.get(`${diskBase}/partitions/${encodedPartId}/files?path=/`)
|
||||
} else {
|
||||
fileEntries = await restApiClient.get(`${diskBase}/files?path=/`)
|
||||
}
|
||||
} catch (err) {
|
||||
// Some partitions (swap, EFI) cannot be mounted — skip gracefully
|
||||
log.warn('Could not list files via REST API, skipping partition', {
|
||||
diskId: disk.id,
|
||||
partitionId,
|
||||
error: error.message,
|
||||
error: err.message,
|
||||
})
|
||||
continue
|
||||
}
|
||||
|
||||
assert(
|
||||
fileEntries !== null && typeof fileEntries === 'object',
|
||||
`listFiles should return an object for disk ${disk.id} partition ${partitionId}`
|
||||
Array.isArray(fileEntries),
|
||||
`File listing should return an array for disk ${disk.id} / partition ${partitionId}`
|
||||
)
|
||||
|
||||
// Directories are suffixed with '/', files are not
|
||||
const fileNames = Object.keys(fileEntries).filter(name => !name.endsWith('/'))
|
||||
|
||||
if (fileNames.length === 0) {
|
||||
log.debug('No files at partition root, skipping', { diskId: disk.id, partitionId })
|
||||
const files = fileEntries.filter(e => e.isFile)
|
||||
if (files.length === 0) {
|
||||
log.debug('No files at partition root, skipping download test', { diskId: disk.id, partitionId })
|
||||
continue
|
||||
}
|
||||
|
||||
// Restore at most 2 files — paths must be absolute for fetchFiles
|
||||
const paths = fileNames.slice(0, 2).map(name => `/${name}`)
|
||||
|
||||
log.debug('Restoring files', { diskId: disk.id, partitionId, paths })
|
||||
const paths = files.slice(0, 2).map(f => `/${f.name}`)
|
||||
log.debug('Testing file download via REST API', { diskId: disk.id, partitionId, paths })
|
||||
|
||||
for (const format of ['tgz', 'zip']) {
|
||||
await assertFetchFiles(dispatchClient, { remote: remoteId, disk: disk.id, partitionId, paths, format })
|
||||
await assertRestDownload(restApiClient, { encodedId, encodedDiskId, partitionId, paths, format })
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
// ─── Helpers ─────────────────────────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
* Calls backupNg.fetchFiles, downloads the resulting archive, and validates
|
||||
* that the response is a non-empty, correctly-formatted archive.
|
||||
* Downloads files from a backup archive via the REST API and validates the archive format.
|
||||
*
|
||||
* @param {import('../client/dispatchClient.js').DispatchClient} dispatchClient
|
||||
* @param {{ remote: string, disk: string, partitionId: string|undefined, paths: string[], format: 'tgz'|'zip' }} opts
|
||||
* @param {import('../client/restApiClient.js').RestApiClient} restApiClient
|
||||
* @param {{ encodedId: string, encodedDiskId: string, partitionId: string|undefined, paths: string[], format: 'tgz'|'zip' }} opts
|
||||
*/
|
||||
async function assertFetchFiles(dispatchClient, { remote, disk, partitionId, paths, format }) {
|
||||
const params = {
|
||||
remote,
|
||||
disk,
|
||||
paths,
|
||||
format,
|
||||
...(partitionId !== undefined && { partition: partitionId }),
|
||||
}
|
||||
async function assertRestDownload(restApiClient, { encodedId, encodedDiskId, partitionId, paths, format }) {
|
||||
const params = new URLSearchParams(paths.map(p => ['paths[]', p]))
|
||||
const diskBase = `/rest/v0/backup-archives/${encodedId}/disks/${encodedDiskId}`
|
||||
const endpoint =
|
||||
partitionId !== undefined
|
||||
? `${diskBase}/partitions/${encodeURIComponent(partitionId)}/files.${format}?${params}`
|
||||
: `${diskBase}/files.${format}?${params}`
|
||||
|
||||
const result = await dispatchClient.xoClient.call('backupNg.fetchFiles', params)
|
||||
const downloadPath = result.$getFrom
|
||||
assert(
|
||||
typeof downloadPath === 'string' && downloadPath.length > 0,
|
||||
`fetchFiles (${format}) should return a non-empty $getFrom URL`
|
||||
)
|
||||
|
||||
const response = await fetch(`${dispatchClient.restApiClient.baseUrl}${downloadPath}`, {
|
||||
method: 'GET',
|
||||
headers: dispatchClient.restApiClient.headers,
|
||||
const response = await fetch(`${restApiClient.baseUrl}${endpoint}`, {
|
||||
headers: restApiClient.headers,
|
||||
signal: AbortSignal.timeout(120_000),
|
||||
})
|
||||
|
||||
assert(response.ok, `Download failed for ${format}: HTTP ${response.status} ${response.statusText}`)
|
||||
assert(response.ok, `REST download failed for format=${format}: HTTP ${response.status} ${response.statusText}`)
|
||||
|
||||
const bytes = Buffer.from(await response.arrayBuffer())
|
||||
assert(bytes.length > 0, `Downloaded ${format} archive should not be empty`)
|
||||
assert(bytes.length > 0, `Downloaded ${format} archive must not be empty`)
|
||||
|
||||
const magic = format === 'tgz' ? TGZ_MAGIC : ZIP_MAGIC
|
||||
assert.strictEqual(bytes[0], magic[0], `${format} archive should start with correct magic byte[0]`)
|
||||
assert.strictEqual(bytes[1], magic[1], `${format} archive should start with correct magic byte[1]`)
|
||||
assert.strictEqual(bytes[0], magic[0], `${format} archive byte[0] mismatch`)
|
||||
assert.strictEqual(bytes[1], magic[1], `${format} archive byte[1] mismatch`)
|
||||
|
||||
log.debug('File restore validated', { format, size: bytes.length, paths, partitionId })
|
||||
log.debug('REST download validated', { format, size: bytes.length, partitionId })
|
||||
}
|
||||
|
||||
145
@xen-orchestra/qa-test/tests/backup.lock.test.js
Normal file
145
@xen-orchestra/qa-test/tests/backup.lock.test.js
Normal file
@@ -0,0 +1,145 @@
|
||||
import assert from 'node:assert'
|
||||
import { after, before, describe, it } from 'node:test'
|
||||
import { createLogger } from '@xen-orchestra/log'
|
||||
import { getSyncedHandler } from '@xen-orchestra/fs'
|
||||
import { getVmBackupDir } from '@xen-orchestra/backups/_getVmBackupDir.mjs'
|
||||
|
||||
import { backupConfig } from '../backup.config.js'
|
||||
import {
|
||||
findTaskByMessage,
|
||||
generateBackupJobName,
|
||||
getDefaultSchedule,
|
||||
getRequiredEnv,
|
||||
getScheduleKey,
|
||||
} from '../utils/index.js'
|
||||
import { assertBackupSuccess, extractBackupErrors, resolveOrCreateBackupRepository } from '../utils/backupUtils.js'
|
||||
import { setup, teardown } from './setup.js'
|
||||
|
||||
const log = createLogger('qa:backup:lock')
|
||||
|
||||
// The suite locks the backup folder of a VM itself, from the machine it runs on, and checks that XO honours that
|
||||
// lock: it needs a repository which this machine reaches as XO reaches it, hence S3 or Azure. A local, NFS or SMB
|
||||
// repository is a directory of XO's host.
|
||||
const BACKENDS = [
|
||||
{ label: 'S3', envPrefix: 'S3' },
|
||||
{ label: 'Azure', envPrefix: 'AZURE' },
|
||||
]
|
||||
|
||||
const isConfigured = ({ envPrefix }) => Boolean(process.env[`${envPrefix}_BACKUP_REPOSITORY_URL`])
|
||||
|
||||
describe(
|
||||
'Backup VM folder lock',
|
||||
{ skip: !BACKENDS.some(isConfigured) && 'neither S3_BACKUP_REPOSITORY_URL nor AZURE_BACKUP_REPOSITORY_URL is set' },
|
||||
() => {
|
||||
let dispatchClient
|
||||
let tracker
|
||||
let vm
|
||||
|
||||
before(async () => {
|
||||
let vms
|
||||
;({ dispatchClient, tracker, vms } = await setup())
|
||||
vm = vms[0]
|
||||
})
|
||||
|
||||
for (const backend of BACKENDS) {
|
||||
const { label, envPrefix } = backend
|
||||
|
||||
describe(label, { skip: !isConfigured(backend) && `${envPrefix}_BACKUP_REPOSITORY_URL is not set` }, () => {
|
||||
let jobId
|
||||
let scheduleId
|
||||
let handler
|
||||
let disposeHandler
|
||||
let skipReason
|
||||
|
||||
before(async () => {
|
||||
const url = getRequiredEnv(`${envPrefix}_BACKUP_REPOSITORY_URL`)
|
||||
|
||||
// not tracked for cleanup: the tracker holds a single repository, the one setup() may have created, and
|
||||
// the next run reuses this one
|
||||
const backupRepository = await resolveOrCreateBackupRepository(dispatchClient, undefined, {
|
||||
name: getRequiredEnv(`${envPrefix}_BACKUP_REPOSITORY_NAME`),
|
||||
url,
|
||||
})
|
||||
|
||||
const config = backupConfig(generateBackupJobName(), getDefaultSchedule(), vm, backupRepository)
|
||||
jobId = await dispatchClient.backup.createBackupJob(config)
|
||||
tracker.trackResource('backupJob', jobId, { name: config.name, mode: config.mode })
|
||||
scheduleId = getScheduleKey(await dispatchClient.backup.details(jobId))
|
||||
tracker.trackResource('schedule', scheduleId, { name: config.name, backupJobId: jobId })
|
||||
|
||||
const { value, dispose } = await getSyncedHandler({ url })
|
||||
handler = value
|
||||
disposeHandler = dispose
|
||||
|
||||
// A second lock of the same folder must be refused. On S3, nothing is locked when the bucket has Object
|
||||
// Lock: XO does not lock either, and there is nothing to test.
|
||||
const dir = getVmBackupDir(vm.uuid)
|
||||
const lock = await handler.lock(dir)
|
||||
try {
|
||||
const secondLock = await handler.lock(dir)
|
||||
await secondLock.dispose()
|
||||
skipReason =
|
||||
'the repository is not locked: its S3 bucket has Object Lock, or its Object Lock configuration ' +
|
||||
'cannot be read (see the xo:fs:s3 warnings in the debug log)'
|
||||
log.warn('VM folder lock pre-check failed', { backend: label, skipReason })
|
||||
} catch (error) {
|
||||
if (error.code !== 'ELOCKED') {
|
||||
throw error
|
||||
}
|
||||
} finally {
|
||||
await lock.dispose()
|
||||
}
|
||||
})
|
||||
|
||||
it('fails the backup of a VM whose folder is locked', async t => {
|
||||
if (skipReason !== undefined) {
|
||||
return t.skip(skipReason)
|
||||
}
|
||||
|
||||
const lock = await handler.lock(getVmBackupDir(vm.uuid))
|
||||
let result
|
||||
try {
|
||||
result = await dispatchClient.backup.runJobAndGetLog(jobId, scheduleId)
|
||||
} finally {
|
||||
await lock.dispose()
|
||||
}
|
||||
|
||||
// the folder is locked before the snapshot is taken: the task of the VM fails at once
|
||||
const vmTask = findTaskByMessage(result, 'backup VM')
|
||||
assert.strictEqual(
|
||||
vmTask?.status,
|
||||
'failure',
|
||||
'the backup should fail while the folder of the VM is locked: XO did not lock it (see the xo:fs warnings in its log)'
|
||||
)
|
||||
assert.strictEqual(
|
||||
vmTask.result?.code,
|
||||
'ELOCKED',
|
||||
`the backup should fail on the lock, failed with: ${extractBackupErrors(result).join(' | ')}`
|
||||
)
|
||||
})
|
||||
|
||||
it('releases the lock at the end of the backup', async t => {
|
||||
if (skipReason !== undefined) {
|
||||
return t.skip(skipReason)
|
||||
}
|
||||
|
||||
const result = await dispatchClient.backup.runJobAndGetLog(jobId, scheduleId)
|
||||
assertBackupSuccess(result, `Backup to ${label} of a VM whose folder is not locked`)
|
||||
|
||||
// a lock left behind would fail the next backups of the VM until it goes stale: 3 minutes on S3, the 60
|
||||
// seconds of its lease on Azure
|
||||
const lock = await handler.lock(getVmBackupDir(vm.uuid))
|
||||
await lock.dispose()
|
||||
})
|
||||
|
||||
after(async () => {
|
||||
await disposeHandler?.()
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
after(async () => {
|
||||
await teardown(dispatchClient, tracker)
|
||||
})
|
||||
}
|
||||
)
|
||||
@@ -9,7 +9,7 @@ import { createLogger } from '@xen-orchestra/log'
|
||||
|
||||
import { DispatchClient } from '../client/dispatchClient.js'
|
||||
import { createResourceTracker } from '../utils/resourceTracker.js'
|
||||
import { getRequiredEnv } from '../utils/index.js'
|
||||
import { getRequiredEnv, waitUntil } from '../utils/index.js'
|
||||
import { formatBytes } from '../utils/exportUtils.js'
|
||||
import {
|
||||
assertRawExportsAreIdentical,
|
||||
@@ -42,7 +42,9 @@ describe('ESXi migration (V2V)', { skip: getEsxiSkipReason() }, () => {
|
||||
let esxiConfig
|
||||
/** @type {Object} */
|
||||
let sourceMetadata
|
||||
/** Parameters shared by every `vm.importFromEsxi` call */
|
||||
/** Pool the VMs are imported into */
|
||||
let poolId
|
||||
/** Body shared by every `import_vms_from_vmware` call */
|
||||
let migrationParams
|
||||
|
||||
before(async () => {
|
||||
@@ -58,24 +60,42 @@ describe('ESXi migration (V2V)', { skip: getEsxiSkipReason() }, () => {
|
||||
const sr = await dispatchClient.sr.details(getRequiredEnv('SR_ID'))
|
||||
assert.notEqual(sr, undefined, 'SR_ID does not resolve to an SR')
|
||||
|
||||
poolId = sr.$pool
|
||||
migrationParams = {
|
||||
host: esxiConfig.host,
|
||||
user: esxiConfig.user,
|
||||
password: esxiConfig.password,
|
||||
sslVerify: esxiConfig.sslVerify,
|
||||
vm: esxiConfig.vmId,
|
||||
sr: sr.uuid,
|
||||
network: await findNetwork(dispatchClient, sr.$pool),
|
||||
template: await findTemplate(dispatchClient, sr.$pool),
|
||||
connection: {
|
||||
host: esxiConfig.host,
|
||||
username: esxiConfig.user,
|
||||
password: esxiConfig.password,
|
||||
skipSslCheck: !esxiConfig.sslVerify,
|
||||
},
|
||||
defaults: {
|
||||
sr: sr.uuid,
|
||||
network: await findNetwork(dispatchClient, poolId),
|
||||
template: await findTemplate(dispatchClient, poolId),
|
||||
},
|
||||
vms: [{ id: esxiConfig.vmId }],
|
||||
}
|
||||
|
||||
// the wizard lists the VMs to migrate from the inventory: the source VM must be in it
|
||||
const inventory = await dispatchClient.restApiClient.post('/rest/v0/v2v/inventory', {
|
||||
platform: 'vmware',
|
||||
connection: migrationParams.connection,
|
||||
})
|
||||
assert.ok(
|
||||
inventory.vms.some(({ id }) => id === esxiConfig.vmId),
|
||||
`the inventory of the source should list ${esxiConfig.vmId}`
|
||||
)
|
||||
|
||||
log.info('Ready to migrate source VM', {
|
||||
name: sourceMetadata.name_label,
|
||||
vmId: esxiConfig.vmId,
|
||||
disks: sourceMetadata.disks.length,
|
||||
sr: sr.name_label,
|
||||
})
|
||||
log.debug('Migration parameters', { ...migrationParams, password: '<redacted>' })
|
||||
log.debug('Migration parameters', {
|
||||
...migrationParams,
|
||||
connection: { ...migrationParams.connection, password: '<redacted>' },
|
||||
})
|
||||
log.debug('Resolved timings', {
|
||||
requestTimeoutMinutes: Math.round(esxiConfig.timeout / 60_000),
|
||||
resetSettleSeconds: Math.round(esxiConfig.resetSettleMs / 1000),
|
||||
@@ -83,8 +103,8 @@ describe('ESXi migration (V2V)', { skip: getEsxiSkipReason() }, () => {
|
||||
log.debug('Target pool objects resolved', {
|
||||
pool: sr.$pool,
|
||||
sr: { uuid: sr.uuid, name_label: sr.name_label },
|
||||
network: migrationParams.network,
|
||||
template: migrationParams.template,
|
||||
network: migrationParams.defaults.network,
|
||||
template: migrationParams.defaults.template,
|
||||
})
|
||||
})
|
||||
|
||||
@@ -296,22 +316,38 @@ describe('ESXi migration (V2V)', { skip: getEsxiSkipReason() }, () => {
|
||||
*/
|
||||
async function migrate({ stopSource }) {
|
||||
const startTime = Date.now()
|
||||
log.debug('Calling vm.importFromEsxi', { vm: esxiConfig.vmId, stopSource })
|
||||
log.debug('Calling import_vms_from_vmware', { vm: esxiConfig.vmId, stopSource })
|
||||
|
||||
let result
|
||||
try {
|
||||
result = await dispatchClient.xoClient.call('vm.importFromEsxi', { ...migrationParams, stopSource })
|
||||
} catch (cause) {
|
||||
// asynchronous: a migration lasts far longer than an HTTP client waits for the headers of its answer
|
||||
const { taskId } = await dispatchClient.restApiClient.post(
|
||||
`/rest/v0/pools/${poolId}/actions/import_vms_from_vmware`,
|
||||
{ ...migrationParams, defaults: { ...migrationParams.defaults, stopSource } }
|
||||
)
|
||||
const task = await waitUntil(
|
||||
async () => {
|
||||
const task = await dispatchClient.restApiClient.get(`/rest/v0/tasks/${taskId}`)
|
||||
return task.status === 'pending' ? false : task
|
||||
},
|
||||
10_000,
|
||||
esxiConfig.timeout
|
||||
)
|
||||
log.debug('import_vms_from_vmware task ended', { status: task.status, result: task.result })
|
||||
|
||||
if (task.status !== 'success') {
|
||||
// `succeeded` maps the source VM to the XCP-ng VM created before the failure, and is
|
||||
// the only way to find the leftover VM to clean up
|
||||
log.warn('Migration failed', { stopSource, succeeded: cause.succeeded, error: cause })
|
||||
throw cause
|
||||
log.warn('Migration failed', { stopSource, succeeded: task.result?.succeeded, error: task.result })
|
||||
throw new Error(`the migration ended with the status ${task.status}: ${task.result?.message}`)
|
||||
}
|
||||
// the front tells the imports in progress by this property
|
||||
assert.deepEqual(task.properties.sourceVmIds, [esxiConfig.vmId])
|
||||
|
||||
const vmUuid = result[esxiConfig.vmId]
|
||||
log.debug('vm.importFromEsxi returned', { result })
|
||||
const vmUuid = task.result[esxiConfig.vmId]
|
||||
assert.equal(typeof vmUuid, 'string', `the migration did not return a VM for ${esxiConfig.vmId}`)
|
||||
|
||||
assert.equal(typeof vmUuid, 'string', `vm.importFromEsxi did not return a VM for ${esxiConfig.vmId}`)
|
||||
// the front tells an import from its clones, restores and replicas by the UUID it records
|
||||
const vm = await dispatchClient.restApiClient.get(`/rest/v0/vms/${vmUuid}`)
|
||||
assert.equal(vm.other['xo:v2v:importedVmUuid'], vmUuid)
|
||||
log.info('Migration done', { stopSource, vmUuid, durationSeconds: Math.round((Date.now() - startTime) / 1000) })
|
||||
|
||||
return vmUuid
|
||||
|
||||
@@ -31,6 +31,7 @@ import {
|
||||
badRequestResp,
|
||||
createdResp,
|
||||
forbiddenOperationResp,
|
||||
incorrectStateResp,
|
||||
invalidParameters,
|
||||
noContentResp,
|
||||
notFoundResp,
|
||||
@@ -389,6 +390,8 @@ export class AclRoleController extends XoController<XoAclRole> {
|
||||
/**
|
||||
* Attach an ACL V2 role to a user.
|
||||
*
|
||||
* An admin cannot be given a role: the RBAC does not apply to them.
|
||||
*
|
||||
* Required privilege:
|
||||
* - resource: acl-role, action: update:users
|
||||
*
|
||||
@@ -409,13 +412,11 @@ export class AclRoleController extends XoController<XoAclRole> {
|
||||
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
|
||||
@Response(notFoundResp.status, notFoundResp.description)
|
||||
@Response(resourceAlreadyExists.status, resourceAlreadyExists.description)
|
||||
@Response(incorrectStateResp.status, incorrectStateResp.description)
|
||||
async attachAclV2User(@Path() id: string, @Path() userId: string): Promise<void> {
|
||||
const roleId = id as XoAclRole['id']
|
||||
|
||||
// addAclV2UserRole does not check if the user exists so we get the user here to make sure it exists.
|
||||
const user = await this.restApi.xoApp.getUser(userId as XoUser['id'])
|
||||
|
||||
await this.restApi.xoApp.addAclV2UserRole(user.id, roleId)
|
||||
await this.restApi.xoApp.addAclV2UserRole(userId as XoUser['id'], roleId)
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -16,9 +16,16 @@ import {
|
||||
} from 'tsoa'
|
||||
import { inject } from 'inversify'
|
||||
import { provide } from 'inversify-binding-decorators'
|
||||
import type { Readable } from 'node:stream'
|
||||
import { json, type Request as ExRequest } from 'express'
|
||||
import { noSuchObject } from 'xo-common/api-errors.js'
|
||||
import type { BackupArchiveDiskMount, XoBackupRepository, XoHost, XoVm, XoVmBackupArchive } from '@vates/types'
|
||||
import type {
|
||||
BackupArchiveDiskMount,
|
||||
XoBackupDiskPartition,
|
||||
XoBackupRepository,
|
||||
XoHost,
|
||||
XoVmBackupArchive,
|
||||
} from '@vates/types'
|
||||
|
||||
import {
|
||||
asynchronousActionResp,
|
||||
@@ -37,6 +44,8 @@ import { RestApi } from '../rest-api/rest-api.mjs'
|
||||
import {
|
||||
backupArchive,
|
||||
backupArchiveDiskMount,
|
||||
backupArchiveDiskPartitions,
|
||||
backupArchiveFiles,
|
||||
backupArchiveIds,
|
||||
partialBackupArchives,
|
||||
} from '../open-api/oa-examples/backup-archive.oa-example.mjs'
|
||||
@@ -46,6 +55,12 @@ import { BackupArchiveService } from './backup-archive.service.mjs'
|
||||
import type { MountLiveDiskBody } from './backup-archive.type.mjs'
|
||||
import { acl, autoBindService } from '../middlewares/acl.middleware.mjs'
|
||||
|
||||
// MIME type of the archive streamed by the file-download routes, by requested format.
|
||||
const DOWNLOAD_CONTENT_TYPES = {
|
||||
tgz: 'application/gzip',
|
||||
zip: 'application/zip',
|
||||
} as const
|
||||
|
||||
@Route('backup-archives')
|
||||
@Security('*')
|
||||
@Response(badRequestResp.status, badRequestResp.description)
|
||||
@@ -234,4 +249,222 @@ export class BackupArchiveController extends XoController<XoVmBackupArchive> {
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the list of partitions of a disk in a backup archive.
|
||||
* Returns an empty array for disks without a partition table (use the files endpoints directly).
|
||||
*
|
||||
* Required privileges:
|
||||
* - resource: backup-archive, action: mount
|
||||
* - resource: backup-archive, action: read
|
||||
*
|
||||
* @example id "231264c3-af43-4ec0-a3be-394c5b1fdbfc/xo-vm-backups/6ef7c09e-677b-1e6f-0546-7ab30413c61c/20250801T080832Z.json"
|
||||
* @example diskId "/xo-vm-backups/6ef7c09e-677b-1e6f-0546-7ab30413c61c/vdis/8b650248-ddd6-4188-ad8b-c0502865ac6c/f1f3c902-dcaa-4ec6-943e-6162c9d85fb2/20250801T080832Z.vhd"
|
||||
*/
|
||||
@Example(backupArchiveDiskPartitions)
|
||||
@Extension('x-mcp-exposure', 'deny')
|
||||
@Get('{id}/disks/{diskId}/partitions')
|
||||
@Middlewares(
|
||||
acl({
|
||||
resource: 'backup-archive',
|
||||
actions: ['mount', 'read'],
|
||||
objectId: 'params.id',
|
||||
getObject: autoBindService(BackupArchiveService, 'getBackupArchive'),
|
||||
})
|
||||
)
|
||||
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
|
||||
@Response(notFoundResp.status, notFoundResp.description)
|
||||
async getBackupArchiveDiskPartitions(@Path() id: string, @Path() diskId: string): Promise<XoBackupDiskPartition[]> {
|
||||
return this.#backupArchiveService.listPartitions(id as XoVmBackupArchive['id'], diskId)
|
||||
}
|
||||
|
||||
// tsoa route-collision check (checkForPathParamSignatureDuplicates) is declaration-order
|
||||
// sensitive: a `…/files.{format}` route declared AFTER the plain `…/files` route is wrongly
|
||||
// flagged as overlapping (it does a startsWith, not an equality, on the last segment). So each
|
||||
// `.{format}` download route MUST stay declared before its plain listing sibling. Do not reorder.
|
||||
|
||||
/**
|
||||
* Downloads the selected files from a partition of a backup archive disk as a tgz or zip archive.
|
||||
* Symbolic links are not supported: a path going through one is refused, and the links found while
|
||||
* walking a directory are skipped.
|
||||
*
|
||||
* Required privileges:
|
||||
* - resource: backup-archive, action: mount
|
||||
* - resource: backup-archive, action: read
|
||||
* - resource: backup-archive, action: export
|
||||
*
|
||||
* @example id "231264c3-af43-4ec0-a3be-394c5b1fdbfc/xo-vm-backups/6ef7c09e-677b-1e6f-0546-7ab30413c61c/20250801T080832Z.json"
|
||||
* @example diskId "/xo-vm-backups/6ef7c09e-677b-1e6f-0546-7ab30413c61c/vdis/8b650248-ddd6-4188-ad8b-c0502865ac6c/f1f3c902-dcaa-4ec6-943e-6162c9d85fb2/20250801T080832Z.vhd"
|
||||
* @example partitionId "6c2d1b4a-0f3e-4c8d-9a1b-2e5f7c9d0a3b"
|
||||
* @example paths ["/etc/passwd", "/etc/hosts"]
|
||||
*/
|
||||
@Extension('x-mcp-exposure', 'deny')
|
||||
@Get('{id}/disks/{diskId}/partitions/{partitionId}/files.{format}')
|
||||
@Middlewares(
|
||||
acl({
|
||||
resource: 'backup-archive',
|
||||
actions: ['mount', 'read', 'export'],
|
||||
objectId: 'params.id',
|
||||
getObject: autoBindService(BackupArchiveService, 'getBackupArchive'),
|
||||
})
|
||||
)
|
||||
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
|
||||
@Response(notFoundResp.status, notFoundResp.description)
|
||||
@SuccessResponse(200, 'Download started', 'application/octet-stream')
|
||||
async downloadBackupArchivePartitionFiles(
|
||||
@Request() req: ExRequest,
|
||||
@Path() id: string,
|
||||
@Path() diskId: string,
|
||||
@Path() partitionId: string,
|
||||
@Path() format: 'tgz' | 'zip',
|
||||
@Query() paths: string[]
|
||||
): Promise<Readable> {
|
||||
const { stream, filename } = await this.#backupArchiveService.fetchFiles({
|
||||
archiveId: id as XoVmBackupArchive['id'],
|
||||
diskId,
|
||||
partitionId,
|
||||
paths,
|
||||
format,
|
||||
})
|
||||
this.setHeader('content-type', DOWNLOAD_CONTENT_TYPES[format])
|
||||
this.setHeader('content-disposition', `attachment; filename="${filename}"`)
|
||||
req.on('close', () => stream.destroy())
|
||||
return stream
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the list of files at the given path inside a partition of a backup archive disk.
|
||||
* Symbolic links are not supported: a path going through one is refused, and the links found while
|
||||
* walking a directory are skipped.
|
||||
*
|
||||
* Required privileges:
|
||||
* - resource: backup-archive, action: mount
|
||||
* - resource: backup-archive, action: read
|
||||
*
|
||||
* @example id "231264c3-af43-4ec0-a3be-394c5b1fdbfc/xo-vm-backups/6ef7c09e-677b-1e6f-0546-7ab30413c61c/20250801T080832Z.json"
|
||||
* @example diskId "/xo-vm-backups/6ef7c09e-677b-1e6f-0546-7ab30413c61c/vdis/8b650248-ddd6-4188-ad8b-c0502865ac6c/f1f3c902-dcaa-4ec6-943e-6162c9d85fb2/20250801T080832Z.vhd"
|
||||
* @example partitionId "6c2d1b4a-0f3e-4c8d-9a1b-2e5f7c9d0a3b"
|
||||
* @example path "/etc"
|
||||
*/
|
||||
@Example(backupArchiveFiles)
|
||||
@Extension('x-mcp-exposure', 'deny')
|
||||
@Get('{id}/disks/{diskId}/partitions/{partitionId}/files')
|
||||
@Middlewares(
|
||||
acl({
|
||||
resource: 'backup-archive',
|
||||
actions: ['mount', 'read'],
|
||||
objectId: 'params.id',
|
||||
getObject: autoBindService(BackupArchiveService, 'getBackupArchive'),
|
||||
})
|
||||
)
|
||||
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
|
||||
@Response(notFoundResp.status, notFoundResp.description)
|
||||
async getBackupArchivePartitionFiles(
|
||||
@Path() id: string,
|
||||
@Path() diskId: string,
|
||||
@Path() partitionId: string,
|
||||
@Query() path?: string
|
||||
): Promise<{ name: string; isFile: boolean; size?: number }[]> {
|
||||
const rawFiles = await this.#backupArchiveService.listFiles(
|
||||
id as XoVmBackupArchive['id'],
|
||||
diskId,
|
||||
partitionId,
|
||||
path ?? '/'
|
||||
)
|
||||
return Object.entries(rawFiles).map(([name, info]) => ({
|
||||
name,
|
||||
isFile: !name.endsWith('/'),
|
||||
size: info?.size,
|
||||
}))
|
||||
}
|
||||
|
||||
/**
|
||||
* Downloads the selected files from a bare disk (no partition table) of a backup archive as a tgz or zip archive.
|
||||
* Symbolic links are not supported: a path going through one is refused, and the links found while
|
||||
* walking a directory are skipped.
|
||||
*
|
||||
* Required privileges:
|
||||
* - resource: backup-archive, action: mount
|
||||
* - resource: backup-archive, action: read
|
||||
* - resource: backup-archive, action: export
|
||||
*
|
||||
* @example id "231264c3-af43-4ec0-a3be-394c5b1fdbfc/xo-vm-backups/6ef7c09e-677b-1e6f-0546-7ab30413c61c/20250801T080832Z.json"
|
||||
* @example diskId "/xo-vm-backups/6ef7c09e-677b-1e6f-0546-7ab30413c61c/vdis/8b650248-ddd6-4188-ad8b-c0502865ac6c/f1f3c902-dcaa-4ec6-943e-6162c9d85fb2/20250801T080832Z.vhd"
|
||||
* @example paths ["/etc/passwd"]
|
||||
*/
|
||||
@Extension('x-mcp-exposure', 'deny')
|
||||
@Get('{id}/disks/{diskId}/files.{format}')
|
||||
@Middlewares(
|
||||
acl({
|
||||
resource: 'backup-archive',
|
||||
actions: ['mount', 'read', 'export'],
|
||||
objectId: 'params.id',
|
||||
getObject: autoBindService(BackupArchiveService, 'getBackupArchive'),
|
||||
})
|
||||
)
|
||||
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
|
||||
@Response(notFoundResp.status, notFoundResp.description)
|
||||
@SuccessResponse(200, 'Download started', 'application/octet-stream')
|
||||
async downloadBackupArchiveDiskFiles(
|
||||
@Request() req: ExRequest,
|
||||
@Path() id: string,
|
||||
@Path() diskId: string,
|
||||
@Path() format: 'tgz' | 'zip',
|
||||
@Query() paths: string[]
|
||||
): Promise<Readable> {
|
||||
const { stream, filename } = await this.#backupArchiveService.fetchFiles({
|
||||
archiveId: id as XoVmBackupArchive['id'],
|
||||
diskId,
|
||||
paths,
|
||||
format,
|
||||
})
|
||||
this.setHeader('content-type', DOWNLOAD_CONTENT_TYPES[format])
|
||||
this.setHeader('content-disposition', `attachment; filename="${filename}"`)
|
||||
req.on('close', () => stream.destroy())
|
||||
return stream
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the list of files at the given path on a bare disk (no partition table) of a backup archive.
|
||||
* Symbolic links are not supported: a path going through one is refused, and the links found while
|
||||
* walking a directory are skipped.
|
||||
*
|
||||
* Required privileges:
|
||||
* - resource: backup-archive, action: mount
|
||||
* - resource: backup-archive, action: read
|
||||
*
|
||||
* @example id "231264c3-af43-4ec0-a3be-394c5b1fdbfc/xo-vm-backups/6ef7c09e-677b-1e6f-0546-7ab30413c61c/20250801T080832Z.json"
|
||||
* @example diskId "/xo-vm-backups/6ef7c09e-677b-1e6f-0546-7ab30413c61c/vdis/8b650248-ddd6-4188-ad8b-c0502865ac6c/f1f3c902-dcaa-4ec6-943e-6162c9d85fb2/20250801T080832Z.vhd"
|
||||
* @example path "/etc"
|
||||
*/
|
||||
@Example(backupArchiveFiles)
|
||||
@Extension('x-mcp-exposure', 'deny')
|
||||
@Get('{id}/disks/{diskId}/files')
|
||||
@Middlewares(
|
||||
acl({
|
||||
resource: 'backup-archive',
|
||||
actions: ['mount', 'read'],
|
||||
objectId: 'params.id',
|
||||
getObject: autoBindService(BackupArchiveService, 'getBackupArchive'),
|
||||
})
|
||||
)
|
||||
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
|
||||
@Response(notFoundResp.status, notFoundResp.description)
|
||||
async getBackupArchiveDiskFiles(
|
||||
@Path() id: string,
|
||||
@Path() diskId: string,
|
||||
@Query() path?: string
|
||||
): Promise<{ name: string; isFile: boolean; size?: number }[]> {
|
||||
const rawFiles = await this.#backupArchiveService.listFiles(
|
||||
id as XoVmBackupArchive['id'],
|
||||
diskId,
|
||||
undefined,
|
||||
path ?? '/'
|
||||
)
|
||||
return Object.entries(rawFiles).map(([name, info]) => ({
|
||||
name,
|
||||
isFile: !name.endsWith('/'),
|
||||
size: info?.size,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,11 +1,43 @@
|
||||
import { noSuchObject } from 'xo-common/api-errors.js'
|
||||
import type { XoBackupRepository, XoVm, XoVmBackupArchive } from '@vates/types'
|
||||
import type { Readable } from 'node:stream'
|
||||
import type { XoApp, XoBackupDiskPartition, XoBackupRepository, XoVm, XoVmBackupArchive } from '@vates/types'
|
||||
|
||||
import type { RestApi } from '../rest-api/rest-api.mjs'
|
||||
|
||||
// BR uuid/xo-vm-backups/VM uuid/(ISO 8601 compact).json
|
||||
const BACKUP_ARCHIVE_ID_REGEX = /^([0-9a-fA-F-]{36})\/+xo-vm-backups\/+([0-9a-fA-F-]{36})\/+(\d{8}T\d{6}Z)\.json$/
|
||||
|
||||
// Fold a free-form label (VM/disk/partition name) into a portion safe for both a filesystem
|
||||
// name and an HTTP Content-Disposition header: diacritics are stripped to ASCII and every
|
||||
// other unsafe character is collapsed to "_". An empty result means "nothing usable".
|
||||
const slugify = (value: string): string =>
|
||||
value
|
||||
.normalize('NFKD')
|
||||
.replace(/[\u0300-\u036f]/g, '') // strip combining diacritics
|
||||
.replace(/[^\w.-]+/g, '_')
|
||||
.replace(/^[_.]+|[_.]+$/g, '')
|
||||
|
||||
// Build a human-friendly download name from the backup labels, e.g.
|
||||
// "my-vm_data-disk_root_2026-06-26.tgz". Falls back to a generic name when no label is usable.
|
||||
const buildDownloadFilename = ({
|
||||
archive,
|
||||
disk,
|
||||
partition,
|
||||
format,
|
||||
}: {
|
||||
readonly archive: XoVmBackupArchive
|
||||
readonly disk: XoVmBackupArchive['disks'][number]
|
||||
readonly partition?: XoBackupDiskPartition
|
||||
readonly format: string
|
||||
}): string => {
|
||||
const date = new Date(archive.timestamp).toISOString().slice(0, 10) // YYYY-MM-DD
|
||||
const parts = [archive.vm.name_label, disk.name, partition?.name, date]
|
||||
.map(part => (part === undefined ? '' : slugify(part)))
|
||||
.filter(part => part !== '')
|
||||
const base = parts.length > 0 ? parts.join('_') : 'backup-archive'
|
||||
return `${base}.${format}`
|
||||
}
|
||||
|
||||
export class BackupArchiveService {
|
||||
#restApi: RestApi
|
||||
|
||||
@@ -28,4 +60,84 @@ export class BackupArchiveService {
|
||||
|
||||
return backupArchive
|
||||
}
|
||||
|
||||
#getBackupRepositoryId(archiveId: XoVmBackupArchive['id']): XoBackupRepository['id'] {
|
||||
const match = archiveId.match(BACKUP_ARCHIVE_ID_REGEX)
|
||||
if (match === null) {
|
||||
throw noSuchObject(archiveId, 'backup-archive')
|
||||
}
|
||||
return match[1] as XoBackupRepository['id']
|
||||
}
|
||||
|
||||
async listPartitions(archiveId: XoVmBackupArchive['id'], diskId: string): Promise<XoBackupDiskPartition[]> {
|
||||
const archive = await this.getBackupArchive(archiveId)
|
||||
// archive.disks is an array of { id, name, uuid } (see formatVmBackups), so look up by id
|
||||
if (archive.disks.find(disk => disk.id === diskId) === undefined) {
|
||||
throw noSuchObject(diskId, 'backup-archive-disk')
|
||||
}
|
||||
return this.#restApi.xoApp.listBackupNgDiskPartitions(this.#getBackupRepositoryId(archiveId), diskId)
|
||||
}
|
||||
|
||||
async listFiles(
|
||||
archiveId: XoVmBackupArchive['id'],
|
||||
diskId: string,
|
||||
partitionId: string | undefined,
|
||||
path: string
|
||||
): ReturnType<XoApp['listBackupNgPartitionFiles']> {
|
||||
const partitions = await this.listPartitions(archiveId, diskId)
|
||||
// partitionId is undefined for bare disks (no partition table); only validate when requested
|
||||
if (partitionId !== undefined && !partitions.find(partition => partition.id === partitionId)) {
|
||||
throw noSuchObject(partitionId, 'backup-archive-disk-partition')
|
||||
}
|
||||
return this.#restApi.xoApp.listBackupNgPartitionFiles(
|
||||
this.#getBackupRepositoryId(archiveId),
|
||||
diskId,
|
||||
partitionId,
|
||||
path
|
||||
)
|
||||
}
|
||||
|
||||
async fetchFiles({
|
||||
archiveId,
|
||||
diskId,
|
||||
partitionId,
|
||||
paths,
|
||||
format,
|
||||
}: {
|
||||
readonly archiveId: XoVmBackupArchive['id']
|
||||
readonly diskId: string
|
||||
readonly partitionId?: string
|
||||
readonly paths: string[]
|
||||
readonly format: 'tgz' | 'zip'
|
||||
}): Promise<{ stream: Readable; filename: string }> {
|
||||
const archive = await this.getBackupArchive(archiveId)
|
||||
|
||||
const disk = archive.disks.find(disk => disk.id === diskId)
|
||||
if (disk === undefined) {
|
||||
throw noSuchObject(diskId, 'backup-archive-disk')
|
||||
}
|
||||
|
||||
const backupRepositoryId = this.#getBackupRepositoryId(archiveId)
|
||||
|
||||
// partitionId is undefined for bare disks (no partition table); only resolve and validate a
|
||||
// partition when the caller actually requested one.
|
||||
let partition: XoBackupDiskPartition | undefined
|
||||
if (partitionId !== undefined) {
|
||||
const partitions = await this.#restApi.xoApp.listBackupNgDiskPartitions(backupRepositoryId, diskId)
|
||||
partition = partitions.find(partition => partition.id === partitionId)
|
||||
if (partition === undefined) {
|
||||
throw noSuchObject(partitionId, 'backup-archive-disk-partition')
|
||||
}
|
||||
}
|
||||
|
||||
const stream = await this.#restApi.xoApp.fetchBackupNgPartitionFiles(
|
||||
backupRepositoryId,
|
||||
diskId,
|
||||
partitionId,
|
||||
paths,
|
||||
format
|
||||
)
|
||||
|
||||
return { stream, filename: buildDownloadFilename({ archive, disk, partition, format }) }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -18,6 +18,7 @@ import { BackupArchiveService } from '../backup-archives/backup-archive.service.
|
||||
import { SrService } from '../srs/sr.service.mjs'
|
||||
import { LicenseService } from '../licenses/license.service.mjs'
|
||||
import { BackupRepositoryService } from '../backup-repositories/backup-repository.service.mjs'
|
||||
import { V2vService } from '../v2v/v2v.service.mjs'
|
||||
|
||||
const iocContainer = new Container()
|
||||
|
||||
@@ -145,6 +146,14 @@ export function setupContainer(xoApp: XoApp) {
|
||||
return new BackupRepositoryService(restApi)
|
||||
})
|
||||
.inSingletonScope()
|
||||
|
||||
iocContainer
|
||||
.bind(V2vService)
|
||||
.toDynamicValue(ctx => {
|
||||
const restApi = ctx.container.get(RestApi)
|
||||
return new V2vService(restApi)
|
||||
})
|
||||
.inSingletonScope()
|
||||
}
|
||||
|
||||
export { iocContainer }
|
||||
|
||||
@@ -57,11 +57,6 @@ export const notImplementedResp = {
|
||||
description: 'Not implemented',
|
||||
} as const
|
||||
|
||||
export const proxyUnreachableResp = {
|
||||
status: 502,
|
||||
description: 'Proxy unreachable',
|
||||
} as const
|
||||
|
||||
export const resourceAlreadyExists = {
|
||||
status: 409,
|
||||
description: 'Resource already exists',
|
||||
|
||||
@@ -70,3 +70,26 @@ export const backupArchive = {
|
||||
dynamicVhds: 0,
|
||||
withMemory: false,
|
||||
}
|
||||
|
||||
export const backupArchiveDiskPartitions = [
|
||||
{
|
||||
id: 'b2a7e4d1-5c3f-4e8a-9d06-1f7c2e9b4a53',
|
||||
name: 'boot',
|
||||
size: 1073741824,
|
||||
start: 2048,
|
||||
type: '0fc63daf-8483-4772-8e79-3d69d8477de4',
|
||||
},
|
||||
{
|
||||
id: '6c2d1b4a-0f3e-4c8d-9a1b-2e5f7c9d0a3b',
|
||||
name: 'root',
|
||||
size: 20398997504,
|
||||
start: 2099200,
|
||||
type: '0fc63daf-8483-4772-8e79-3d69d8477de4',
|
||||
},
|
||||
]
|
||||
|
||||
export const backupArchiveFiles = [
|
||||
{ name: 'ssh/', isFile: false },
|
||||
{ name: 'hosts', isFile: true, size: 221 },
|
||||
{ name: 'passwd', isFile: true, size: 1872 },
|
||||
]
|
||||
|
||||
@@ -25,11 +25,3 @@ export const proxy = {
|
||||
url: 'https://uxxa-NIAY9W29VlGMrRcKuxx2dsYMTldJo-7l2YnMNQ@10.1.7.238/',
|
||||
version: '0.29.29',
|
||||
}
|
||||
|
||||
export const proxyHealth = { success: true }
|
||||
|
||||
export const proxyUpdaterState = {
|
||||
level: 'info',
|
||||
message: 'All up to date',
|
||||
state: 'xoa-up-to-date',
|
||||
}
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
export const v2vStatus = {
|
||||
vectura: { status: 'success' },
|
||||
}
|
||||
|
||||
export const v2vInventory = {
|
||||
product: 'VMware vCenter Server',
|
||||
version: '8.0.2',
|
||||
instanceUuid: '5a7c1b0e-3f6d-4f2a-9b1e-2d8c4e6f7a90',
|
||||
datacenters: [{ id: 'datacenter-3', name: 'DC-Paris' }],
|
||||
clusters: [{ id: 'domain-c8', name: 'Cluster-Prod', datacenterId: 'datacenter-3' }],
|
||||
hosts: [{ id: 'host-12', name: 'esx01.example.org', clusterId: 'domain-c8', datacenterId: 'datacenter-3' }],
|
||||
datastores: [
|
||||
{
|
||||
id: 'datastore-15',
|
||||
name: 'ds-prod-01',
|
||||
type: 'VMFS',
|
||||
capacity: 2199023255552,
|
||||
free: 879609302220,
|
||||
hostIds: ['host-12'],
|
||||
},
|
||||
],
|
||||
portGroups: [
|
||||
{ id: 'network-16', name: 'VM Network' },
|
||||
{ id: 'dvportgroup-21', name: 'prod-vlan12', vlan: 12 },
|
||||
],
|
||||
vms: [
|
||||
{
|
||||
id: 'vm-1042',
|
||||
instanceUuid: '502c7a3b-9d1e-4e5f-8a6b-7c8d9e0f1a2b',
|
||||
name: 'web-01',
|
||||
description: '',
|
||||
powerState: 'poweredOn',
|
||||
hostId: 'host-12',
|
||||
nCpus: 2,
|
||||
memory: 4294967296,
|
||||
firmware: 'uefi',
|
||||
secureBoot: false,
|
||||
datastoreIds: ['datastore-15'],
|
||||
snapshotCount: 1,
|
||||
currentSnapshotId: 'snapshot-1101',
|
||||
disks: [
|
||||
{
|
||||
key: 'scsi0:0',
|
||||
label: 'Hard disk 1',
|
||||
datastoreId: 'datastore-15',
|
||||
capacity: 42949672960,
|
||||
mode: 'persistent',
|
||||
isRdm: false,
|
||||
isEncrypted: false,
|
||||
chainPaths: ['web-01/web-01.vmdk', 'web-01/web-01-000001.vmdk'],
|
||||
},
|
||||
],
|
||||
nics: [
|
||||
{ key: '4000', label: 'Network adapter 1', portGroupId: 'dvportgroup-21', macAddress: '00:50:56:9a:3c:11' },
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
export const v2vStartResult = {
|
||||
'vm-1042': '9d0d04f7-bb1f-8292-3294-17c6371827c5',
|
||||
}
|
||||
@@ -95,6 +95,10 @@ import { BASE_URL, escapeUnsafeComplexMatcher, NDJSON_CONTENT_TYPE } from '../he
|
||||
import { messageIds, partialMessages } from '../open-api/oa-examples/message.oa-example.mjs'
|
||||
import type { CreateActionReturnType } from '../abstract-classes/base-controller.mjs'
|
||||
import { NetworkService } from '../networks/network.service.mjs'
|
||||
import { v2vStartResult } from '../open-api/oa-examples/v2v.oa-example.mjs'
|
||||
import { V2V_TASK_PROPERTY } from '@vates/types'
|
||||
import { V2vService, V2V_TASK_NAME } from '../v2v/v2v.service.mjs'
|
||||
import type { V2vStartBody, V2vStartResult } from '../v2v/v2v.type.mjs'
|
||||
|
||||
@Route('pools')
|
||||
@Security('*')
|
||||
@@ -107,19 +111,22 @@ export class PoolController extends XapiXoController<XoPool> {
|
||||
#poolService: PoolService
|
||||
#alarmService: AlarmService
|
||||
#networkService: NetworkService
|
||||
#v2vService: V2vService
|
||||
|
||||
constructor(
|
||||
@inject(RestApi) restApi: RestApi,
|
||||
@inject(VmService) vmService: VmService,
|
||||
@inject(PoolService) poolService: PoolService,
|
||||
@inject(AlarmService) alarmService: AlarmService,
|
||||
@inject(NetworkService) networkService: NetworkService
|
||||
@inject(NetworkService) networkService: NetworkService,
|
||||
@inject(V2vService) v2vService: V2vService
|
||||
) {
|
||||
super('pool', restApi)
|
||||
this.#vmService = vmService
|
||||
this.#poolService = poolService
|
||||
this.#alarmService = alarmService
|
||||
this.#networkService = networkService
|
||||
this.#v2vService = v2vService
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -608,6 +615,69 @@ export class PoolController extends XapiXoController<XoPool> {
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Imports a list of VMs from VMware (vCenter or ESXi) into this pool. A VM already partially imported
|
||||
* on this pool is resumed with a delta, otherwise it is imported entirely. With `stopSource`, the
|
||||
* source VM is stopped before the last delta, which completes the import.
|
||||
*
|
||||
* Each disk goes to the SR given for its key in `disks` (e.g. `scsi0:0`, as listed by
|
||||
* `POST /v2v/inventory`), each network card to the network given for its key in `nics` (e.g. `4000`),
|
||||
* the others to the defaults. A resumed import keeps the SRs and networks of its first run. An unknown
|
||||
* key fails the import of the VM before anything is done on either side.
|
||||
*
|
||||
* For now, the MAC addresses are kept, and `tags`, `startVm` and `cleanup` are refused.
|
||||
*
|
||||
* The request is checked before the import starts: 422 with the list of the problems.
|
||||
*
|
||||
* As in XO5, the XCP-ng side is not checked: that the SRs, networks and templates belong to this pool,
|
||||
* that no import of the same VM is already running, and that the VM has not already been imported.
|
||||
* Launching a VM twice at the same time leads to two imports competing for the same partial import:
|
||||
* wait for the end of a task before launching its VMs again. A VM already fully imported is imported
|
||||
* again, as a second VM.
|
||||
*
|
||||
* The task result is the UUID of the XCP-ng VM, by VMware VM id.
|
||||
*
|
||||
* No ACL privilege covers this route: it is restricted to administrators.
|
||||
*
|
||||
* @example id "355ee47d-ff4c-4924-3db2-fd86ae629677"
|
||||
* @example body { "connection": { "host": "vcenter.example.org", "username": "administrator@vsphere.local", "password": "secret" }, "defaults": { "sr": "c4284e12-37c9-7967-b9e8-83ef229c3e03", "network": "6b6ca0f5-6611-0636-4b0a-1fb1c815e898", "template": "0f3b3b5d-ef02-4fb5-9b7a-d4a2e5eb8e14", "stopSource": true }, "vms": [{ "id": "vm-1042" }], "concurrency": 2 }
|
||||
*/
|
||||
@Example(taskLocation)
|
||||
@Example(v2vStartResult)
|
||||
// the body carries the credentials of the source
|
||||
@Extension('x-mcp-exposure', 'deny')
|
||||
@Post('{id}/actions/import_vms_from_vmware')
|
||||
@Middlewares(json())
|
||||
@Tags('v2v')
|
||||
@SuccessResponse(asynchronousActionResp.status, asynchronousActionResp.description)
|
||||
@Response(200, 'OK')
|
||||
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
|
||||
@Response(notFoundResp.status, notFoundResp.description)
|
||||
@Response(invalidParametersResp.status, invalidParametersResp.description)
|
||||
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
|
||||
async importVmsFromVmware(
|
||||
@Path() id: string,
|
||||
@Body() body: V2vStartBody,
|
||||
@Query() sync?: boolean
|
||||
): CreateActionReturnType<V2vStartResult> {
|
||||
const poolId = id as XoPool['id']
|
||||
// 404 before anything is read from the source
|
||||
this.getObject(poolId)
|
||||
const plans = await this.#v2vService.prepareStart(body)
|
||||
|
||||
return this.createAction<V2vStartResult>(task => this.#v2vService.start(task, body, plans), {
|
||||
sync,
|
||||
taskProperties: {
|
||||
name: V2V_TASK_NAME,
|
||||
objectId: poolId,
|
||||
// read by the front to tell which source VMs are being imported
|
||||
[V2V_TASK_PROPERTY.SOURCE_VM_IDS]: plans.map(plan => plan.id),
|
||||
// the credentials stay out of the task, which every administrator can read
|
||||
params: { host: body.connection.host },
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Required privilege:
|
||||
* - resource: pool, action: read
|
||||
|
||||
@@ -10,7 +10,7 @@ const pool = { id: 'pool-1', name_label: 'pool 1' } as XoPool
|
||||
|
||||
type RollingOpts = NonNullable<Parameters<XoApp['rollingPoolUpdate']>[1]>
|
||||
|
||||
function createController() {
|
||||
function createController({ v2vService = {} }: { v2vService?: object } = {}) {
|
||||
const calls: unknown[] = []
|
||||
const record =
|
||||
(orchestrator: string) =>
|
||||
@@ -27,7 +27,14 @@ function createController() {
|
||||
},
|
||||
} as unknown as RestApi
|
||||
// the injected services are not used by the rolling actions
|
||||
const controller = new PoolController(restApi, {} as never, {} as never, {} as never, {} as never)
|
||||
const controller = new PoolController(
|
||||
restApi,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
{} as never,
|
||||
v2vService as never
|
||||
)
|
||||
return { calls, controller }
|
||||
}
|
||||
|
||||
@@ -64,3 +71,40 @@ describe('PoolController.finalizeRollingUpdate', () => {
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
describe('PoolController.importVmsFromVmware', () => {
|
||||
it('runs the import in a task of the pool, without the credentials of the source', async () => {
|
||||
const calls: unknown[] = []
|
||||
const plans = [{ id: 'vm-1' }, { id: 'vm-2' }]
|
||||
const v2vService = {
|
||||
prepareStart: async () => plans,
|
||||
start: async (task: { properties: unknown }, _body: unknown, startPlans: unknown) => {
|
||||
calls.push({ task: task.properties, plans: startPlans })
|
||||
return { 'vm-1': 'uuid-1', 'vm-2': 'uuid-2' }
|
||||
},
|
||||
}
|
||||
const { controller } = createController({ v2vService })
|
||||
const body = {
|
||||
connection: { host: 'vcenter', username: 'user', password: 'secret' },
|
||||
defaults: { sr: 'sr-1', network: 'net-1', template: 'tpl-1' },
|
||||
vms: [{ id: 'vm-1' }, { id: 'vm-2' }],
|
||||
}
|
||||
|
||||
const result = await controller.importVmsFromVmware('pool-1', body, true)
|
||||
|
||||
assert.deepEqual(result, { 'vm-1': 'uuid-1', 'vm-2': 'uuid-2' })
|
||||
assert.deepEqual(calls, [
|
||||
{
|
||||
task: {
|
||||
name: 'REST API: V2V migration',
|
||||
type: 'xo:rest-api:action',
|
||||
objectType: 'pool',
|
||||
objectId: 'pool-1',
|
||||
sourceVmIds: ['vm-1', 'vm-2'],
|
||||
params: { host: 'vcenter' },
|
||||
},
|
||||
plans,
|
||||
},
|
||||
])
|
||||
})
|
||||
})
|
||||
|
||||
@@ -1,67 +1,22 @@
|
||||
import {
|
||||
Body,
|
||||
Example,
|
||||
Extension,
|
||||
Get,
|
||||
Middlewares,
|
||||
Path,
|
||||
Post,
|
||||
Query,
|
||||
Request,
|
||||
Response,
|
||||
Route,
|
||||
Security,
|
||||
SuccessResponse,
|
||||
Tags,
|
||||
} from 'tsoa'
|
||||
import { Example, Extension, Get, Middlewares, Path, Query, Request, Response, Route, Security, Tags } from 'tsoa'
|
||||
import { inject } from 'inversify'
|
||||
import { json } from 'express'
|
||||
import { provide } from 'inversify-binding-decorators'
|
||||
import type { Request as ExRequest } from 'express'
|
||||
import type { XoApp, XoProxy } from '@vates/types'
|
||||
import type { XoProxy } from '@vates/types'
|
||||
|
||||
import { acl } from '../middlewares/acl.middleware.mjs'
|
||||
import { ApiError } from '../helpers/error.helper.mjs'
|
||||
import {
|
||||
asynchronousActionResp,
|
||||
badRequestResp,
|
||||
forbiddenOperationResp,
|
||||
incorrectStateResp,
|
||||
internalServerErrorResp,
|
||||
noContentResp,
|
||||
notFoundResp,
|
||||
proxyUnreachableResp,
|
||||
unauthorizedResp,
|
||||
type Unbrand,
|
||||
} from '../open-api/common/response.common.mjs'
|
||||
import type { CreateActionReturnType } from '../abstract-classes/base-controller.mjs'
|
||||
import { taskLocation } from '../open-api/oa-examples/task.oa-example.mjs'
|
||||
import {
|
||||
partialProxies,
|
||||
proxy,
|
||||
proxyHealth,
|
||||
proxyIds,
|
||||
proxyUpdaterState,
|
||||
} from '../open-api/oa-examples/proxy.oa-example.mjs'
|
||||
import { partialProxies, proxy, proxyIds } from '../open-api/oa-examples/proxy.oa-example.mjs'
|
||||
import type { SendObjects } from '../helpers/helper.type.mjs'
|
||||
import { XoController } from '../abstract-classes/xo-controller.mjs'
|
||||
import { RestApi } from '../rest-api/rest-api.mjs'
|
||||
|
||||
function isProxyUnreachable(error: unknown): boolean {
|
||||
return error instanceof Error && 'code' in error && error.code === 'PROXY_UNREACHABLE'
|
||||
}
|
||||
|
||||
async function callProxy<T>(call: Promise<T>): Promise<T> {
|
||||
try {
|
||||
return await call
|
||||
} catch (error) {
|
||||
if (isProxyUnreachable(error)) {
|
||||
throw new ApiError(proxyUnreachableResp.description, proxyUnreachableResp.status)
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
@Route('proxies')
|
||||
@Security('*')
|
||||
@Response(badRequestResp.status, badRequestResp.description)
|
||||
@@ -130,126 +85,4 @@ export class ProxyController extends XoController<XoProxy> {
|
||||
getProxy(@Path() id: string): Promise<Unbrand<XoProxy>> {
|
||||
return this.getObject(id as XoProxy['id'])
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks that the proxy can be reached
|
||||
*
|
||||
* Required privilege:
|
||||
* - resource: proxy, action: read
|
||||
*
|
||||
* @example id "e625ea0c-a876-405a-b838-109d762efe88"
|
||||
*/
|
||||
@Example(proxyHealth)
|
||||
@Extension('x-mcp-exposure', 'allow')
|
||||
@Get('{id}/health')
|
||||
@Middlewares(
|
||||
acl({
|
||||
resource: 'proxy',
|
||||
action: 'read',
|
||||
objectId: 'params.id',
|
||||
getObject: ({ restApi }) => restApi.xoApp.getProxy,
|
||||
})
|
||||
)
|
||||
@SuccessResponse(200, 'OK')
|
||||
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
|
||||
@Response(notFoundResp.status, notFoundResp.description)
|
||||
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
|
||||
@Response(proxyUnreachableResp.status, proxyUnreachableResp.description)
|
||||
async getProxyHealth(@Path() id: string): Promise<{ success: true }> {
|
||||
await callProxy(this.restApi.xoApp.checkProxyHealth(id as XoProxy['id']))
|
||||
|
||||
return { success: true }
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns the state of the proxy appliance updater (e.g. `xoa-up-to-date`, or a state ending with `-upgrade-needed`)
|
||||
*
|
||||
* Required privilege:
|
||||
* - resource: proxy, action: read
|
||||
*
|
||||
* @example id "e625ea0c-a876-405a-b838-109d762efe88"
|
||||
*/
|
||||
@Example(proxyUpdaterState)
|
||||
@Extension('x-mcp-exposure', 'allow')
|
||||
@Get('{id}/appliance_updater_state')
|
||||
@Middlewares(
|
||||
acl({
|
||||
resource: 'proxy',
|
||||
action: 'read',
|
||||
objectId: 'params.id',
|
||||
getObject: ({ restApi }) => restApi.xoApp.getProxy,
|
||||
})
|
||||
)
|
||||
@SuccessResponse(200, 'OK')
|
||||
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
|
||||
@Response(notFoundResp.status, notFoundResp.description)
|
||||
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
|
||||
@Response(proxyUnreachableResp.status, proxyUnreachableResp.description)
|
||||
getProxyUpdaterState(@Path() id: string): ReturnType<XoApp['getProxyApplianceUpdaterState']> {
|
||||
return callProxy(this.restApi.xoApp.getProxyApplianceUpdaterState(id as XoProxy['id']))
|
||||
}
|
||||
|
||||
/**
|
||||
* Upgrades the proxy appliance
|
||||
*
|
||||
* By default, the upgrade is refused with an `incorrect state` error if backup jobs are running on the proxy.
|
||||
*
|
||||
* Set `force` to `true` to upgrade by rebooting the proxy VM, which also ignores running jobs. Only available if the
|
||||
* proxy VM is known. No privilege on the VM is checked: the `upgrade` action is enough to reboot it.
|
||||
*
|
||||
* Required privilege:
|
||||
* - resource: proxy, action: upgrade
|
||||
*
|
||||
* @example id "e625ea0c-a876-405a-b838-109d762efe88"
|
||||
* @example body { "force": false, "ignoreRunningJobs": false }
|
||||
*/
|
||||
@Example(taskLocation)
|
||||
@Extension('x-mcp-exposure', 'confirm')
|
||||
@Post('{id}/actions/upgrade')
|
||||
@Middlewares([
|
||||
json(),
|
||||
acl({
|
||||
resource: 'proxy',
|
||||
action: 'upgrade',
|
||||
objectId: 'params.id',
|
||||
getObject: ({ restApi }) => restApi.xoApp.getProxy,
|
||||
}),
|
||||
])
|
||||
@SuccessResponse(asynchronousActionResp.status, asynchronousActionResp.description)
|
||||
@Response(noContentResp.status, noContentResp.description)
|
||||
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
|
||||
@Response(notFoundResp.status, notFoundResp.description)
|
||||
@Response(incorrectStateResp.status, incorrectStateResp.description)
|
||||
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
|
||||
@Response(proxyUnreachableResp.status, proxyUnreachableResp.description)
|
||||
upgradeProxy(
|
||||
@Path() id: string,
|
||||
@Body()
|
||||
body?: {
|
||||
force?: boolean
|
||||
ignoreRunningJobs?: boolean
|
||||
},
|
||||
@Query() sync?: boolean
|
||||
): CreateActionReturnType<void> {
|
||||
const proxyId = id as XoProxy['id']
|
||||
const force = body?.force ?? false
|
||||
const opts = {
|
||||
force,
|
||||
ignoreRunningJobs: body?.ignoreRunningJobs ?? force,
|
||||
}
|
||||
|
||||
const action = async () => {
|
||||
await callProxy(this.restApi.xoApp.upgradeProxyAppliance(proxyId, opts))
|
||||
}
|
||||
|
||||
return this.createAction<void>(action, {
|
||||
sync,
|
||||
statusCode: noContentResp.status,
|
||||
taskProperties: {
|
||||
name: 'upgrade proxy appliance',
|
||||
objectId: proxyId,
|
||||
params: body,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,133 +0,0 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { describe, it } from 'node:test'
|
||||
|
||||
import { ApiError } from '../helpers/error.helper.mjs'
|
||||
import { ProxyController } from './proxy.controller.mjs'
|
||||
import type { RestApi } from '../rest-api/rest-api.mjs'
|
||||
|
||||
const proxyId = 'e625ea0c-a876-405a-b838-109d762efe88'
|
||||
|
||||
const updaterState = { level: 'info', message: 'xoa is up to date', state: 'xoa-up-to-date' }
|
||||
|
||||
const unreachableErrors = [
|
||||
Object.assign(new TypeError('fetch failed'), { code: 'PROXY_UNREACHABLE' }),
|
||||
Object.assign(new Error('cannot get the proxy address'), { code: 'PROXY_UNREACHABLE' }),
|
||||
]
|
||||
|
||||
function createController(result: () => Promise<unknown>) {
|
||||
const calls: unknown[] = []
|
||||
const tasks: unknown[] = []
|
||||
const record =
|
||||
(method: string) =>
|
||||
async (...args: unknown[]) => {
|
||||
calls.push([method, ...args])
|
||||
return result()
|
||||
}
|
||||
const restApi = {
|
||||
tasks: {
|
||||
create: (properties: unknown) => {
|
||||
tasks.push(properties)
|
||||
return { id: 'task-1', properties, run: (fn: () => unknown) => fn() }
|
||||
},
|
||||
},
|
||||
xoApp: {
|
||||
checkProxyHealth: record('checkProxyHealth'),
|
||||
getProxyApplianceUpdaterState: record('getProxyApplianceUpdaterState'),
|
||||
upgradeProxyAppliance: record('upgradeProxyAppliance'),
|
||||
},
|
||||
} as unknown as RestApi
|
||||
const controller = new ProxyController(restApi)
|
||||
return { calls, controller, tasks }
|
||||
}
|
||||
|
||||
for (const [method, xoAppMethod, xoAppResult, expected] of [
|
||||
['getProxyHealth', 'checkProxyHealth', undefined, { success: true }],
|
||||
['getProxyUpdaterState', 'getProxyApplianceUpdaterState', updaterState, updaterState],
|
||||
] as const) {
|
||||
describe(`ProxyController.${method}`, () => {
|
||||
it(`forwards the id to ${xoAppMethod} and returns the result`, async () => {
|
||||
const { calls, controller } = createController(async () => xoAppResult)
|
||||
|
||||
assert.deepEqual(await controller[method](proxyId), expected)
|
||||
assert.deepEqual(calls, [[xoAppMethod, proxyId]])
|
||||
})
|
||||
|
||||
for (const unreachableError of unreachableErrors) {
|
||||
it(`throws a 502 ApiError on "${unreachableError.message}"`, async () => {
|
||||
const { controller } = createController(async () => {
|
||||
throw unreachableError
|
||||
})
|
||||
|
||||
await assert.rejects(
|
||||
controller[method](proxyId),
|
||||
error => error instanceof ApiError && error.status === 502 && error.message === 'Proxy unreachable'
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
it('rethrows unrelated errors unchanged', async () => {
|
||||
const unrelatedError = new Error('401 Unauthorized')
|
||||
const { controller } = createController(async () => {
|
||||
throw unrelatedError
|
||||
})
|
||||
|
||||
await assert.rejects(controller[method](proxyId), error => error === unrelatedError)
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
describe('ProxyController.upgradeProxy', () => {
|
||||
it('upgrades in a task without force by default', async () => {
|
||||
const { calls, controller, tasks } = createController(async () => undefined)
|
||||
|
||||
await controller.upgradeProxy(proxyId, undefined, true)
|
||||
|
||||
assert.deepEqual(calls, [['upgradeProxyAppliance', proxyId, { force: false, ignoreRunningJobs: false }]])
|
||||
assert.deepEqual(tasks, [
|
||||
{
|
||||
name: 'REST API: upgrade proxy appliance',
|
||||
objectId: proxyId,
|
||||
objectType: 'proxy',
|
||||
params: undefined,
|
||||
type: 'xo:rest-api:action',
|
||||
},
|
||||
])
|
||||
assert.equal(controller.getStatus(), 204)
|
||||
})
|
||||
|
||||
it('ignores running jobs by default when forced', async () => {
|
||||
const { calls, controller } = createController(async () => undefined)
|
||||
|
||||
await controller.upgradeProxy(proxyId, { force: true }, true)
|
||||
|
||||
assert.deepEqual(calls, [['upgradeProxyAppliance', proxyId, { force: true, ignoreRunningJobs: true }]])
|
||||
})
|
||||
|
||||
it('forwards an explicit ignoreRunningJobs', async () => {
|
||||
const { calls, controller } = createController(async () => undefined)
|
||||
|
||||
await controller.upgradeProxy(proxyId, { force: true, ignoreRunningJobs: false }, true)
|
||||
|
||||
assert.deepEqual(calls, [['upgradeProxyAppliance', proxyId, { force: true, ignoreRunningJobs: false }]])
|
||||
})
|
||||
|
||||
it('returns the task id when not synchronous', async () => {
|
||||
const { controller } = createController(async () => undefined)
|
||||
|
||||
assert.deepEqual(await controller.upgradeProxy(proxyId), { taskId: 'task-1' })
|
||||
assert.equal(controller.getStatus(), 202)
|
||||
})
|
||||
|
||||
for (const unreachableError of unreachableErrors) {
|
||||
it(`throws a 502 ApiError on "${unreachableError.message}"`, async () => {
|
||||
const { controller } = createController(async () => {
|
||||
throw unreachableError
|
||||
})
|
||||
|
||||
await assert.rejects(
|
||||
controller.upgradeProxy(proxyId, undefined, true),
|
||||
error => error instanceof ApiError && error.status === 502 && error.message === 'Proxy unreachable'
|
||||
)
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -432,6 +432,8 @@ export class UserController extends XoController<XoUser> {
|
||||
}
|
||||
|
||||
/**
|
||||
* An admin has no privileges listed as RBAC does not apply to them
|
||||
*
|
||||
* Returns all ACL privileges that match the following privilege:
|
||||
* - resource: acl-privilege, action: read (if not self)
|
||||
*
|
||||
@@ -455,15 +457,15 @@ export class UserController extends XoController<XoUser> {
|
||||
@Query() filter?: string,
|
||||
@Query() limit?: number
|
||||
): SendObjects<Partial<Unbrand<AnyPrivilege>>> {
|
||||
const user = await this.getObject(id as XoUser['id'])
|
||||
const userId = id as XoUser['id']
|
||||
const currentUser = this.restApi.getCurrentUser()
|
||||
|
||||
const userPrivileges = (await this.restApi.xoApp.getAclV2UserPrivileges(user.id)) as AnyPrivilege[]
|
||||
const userPrivileges = (await this.restApi.xoApp.getAclV2UserPrivileges(userId)) as AnyPrivilege[]
|
||||
|
||||
return this.sendObjects(limitAndFilterArray(userPrivileges, { filter }), req, {
|
||||
path: 'acl-privileges',
|
||||
limit,
|
||||
privilege: currentUser.id === user.id ? undefined : { action: 'read', resource: 'acl-privilege' },
|
||||
privilege: currentUser.id === userId ? undefined : { action: 'read', resource: 'acl-privilege' },
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
86
@xen-orchestra/rest-api/src/v2v/v2v.controller.mts
Normal file
86
@xen-orchestra/rest-api/src/v2v/v2v.controller.mts
Normal file
@@ -0,0 +1,86 @@
|
||||
import {
|
||||
Body,
|
||||
Controller,
|
||||
Example,
|
||||
Extension,
|
||||
Get,
|
||||
Middlewares,
|
||||
Post,
|
||||
Response,
|
||||
Route,
|
||||
Security,
|
||||
SuccessResponse,
|
||||
Tags,
|
||||
} from 'tsoa'
|
||||
import { inject } from 'inversify'
|
||||
import { json } from 'express'
|
||||
import { provide } from 'inversify-binding-decorators'
|
||||
|
||||
import {
|
||||
badRequestResp,
|
||||
forbiddenOperationResp,
|
||||
internalServerErrorResp,
|
||||
invalidParameters,
|
||||
unauthorizedResp,
|
||||
} from '../open-api/common/response.common.mjs'
|
||||
import { v2vInventory, v2vStatus } from '../open-api/oa-examples/v2v.oa-example.mjs'
|
||||
import { V2vService } from './v2v.service.mjs'
|
||||
import type { V2vInventory, V2vInventoryBody, V2vStatus } from './v2v.type.mjs'
|
||||
|
||||
/**
|
||||
* Migration of VMs from another virtualization platform (VMware only for now).
|
||||
*
|
||||
* Nothing is stored server side: every request carries the connection to the source.
|
||||
* No ACL privilege covers these routes: they are restricted to administrators.
|
||||
*/
|
||||
@Route('v2v')
|
||||
@Security('*')
|
||||
@Response(badRequestResp.status, badRequestResp.description)
|
||||
@Response(unauthorizedResp.status, unauthorizedResp.description)
|
||||
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
|
||||
@Tags('v2v')
|
||||
@provide(V2vController)
|
||||
export class V2vController extends Controller {
|
||||
#v2vService: V2vService
|
||||
|
||||
constructor(@inject(V2vService) v2vService: V2vService) {
|
||||
super()
|
||||
this.#v2vService = v2vService
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether this XO can migrate VMs: the tools of an import must run on its system, whatever the source.
|
||||
*
|
||||
* Checked before connecting to a source, which needs no credentials.
|
||||
*/
|
||||
@Example(v2vStatus)
|
||||
@Extension('x-mcp-exposure', 'allow')
|
||||
@Get('status')
|
||||
@SuccessResponse(200, 'OK')
|
||||
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
|
||||
getV2vStatus(): Promise<V2vStatus> {
|
||||
return this.#v2vService.getStatus()
|
||||
}
|
||||
|
||||
/**
|
||||
* Reads the whole inventory of the source: datacenters, clusters, hosts, datastores, networks and VMs
|
||||
* with their disks and network cards, with the product, version and instance UUID of the source.
|
||||
*
|
||||
* Also validates the credentials: 422 with the `V2V_INVALID_CREDENTIALS` code when they are refused by the source.
|
||||
*
|
||||
* A read, not an action: it is a `POST` only because the credentials have to stay out of the URL.
|
||||
*
|
||||
* @example body { "platform": "vmware", "connection": { "host": "vcenter.example.org", "username": "administrator@vsphere.local", "password": "secret", "skipSslCheck": true } }
|
||||
*/
|
||||
@Example(v2vInventory)
|
||||
// the body carries the credentials of the source
|
||||
@Extension('x-mcp-exposure', 'deny')
|
||||
@Post('inventory')
|
||||
@Middlewares(json())
|
||||
@SuccessResponse(200, 'OK')
|
||||
@Response(invalidParameters.status, invalidParameters.description)
|
||||
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
|
||||
getInventory(@Body() body: V2vInventoryBody): Promise<V2vInventory> {
|
||||
return this.#v2vService.getInventory(body.connection)
|
||||
}
|
||||
}
|
||||
132
@xen-orchestra/rest-api/src/v2v/v2v.inventory.mts
Normal file
132
@xen-orchestra/rest-api/src/v2v/v2v.inventory.mts
Normal file
@@ -0,0 +1,132 @@
|
||||
import {
|
||||
V2V_DISK_MODE,
|
||||
V2V_FIRMWARE,
|
||||
V2V_VM_POWER_STATE,
|
||||
type VmwareCluster,
|
||||
type VmwareDatastore,
|
||||
type VmwareHost,
|
||||
type VmwareInventory,
|
||||
type VmwareNetwork,
|
||||
type VmwareVm,
|
||||
type VmwareVmDisk,
|
||||
type VmwareVmNic,
|
||||
type XoV2vCluster,
|
||||
type XoV2vDatacenter,
|
||||
type XoV2vDatastore,
|
||||
type XoV2vDisk,
|
||||
type XoV2vHost,
|
||||
type XoV2vInventory,
|
||||
type XoV2vNic,
|
||||
type XoV2vPortGroup,
|
||||
type XoV2vVm,
|
||||
} from '@vates/types'
|
||||
|
||||
// The raw inventory of `@xen-orchestra/vmware-explorer` is shaped after the VMware API: the contract of the wizard
|
||||
// only keeps what it shows, with relations pointing up (host → cluster → datacenter) instead of down
|
||||
|
||||
type LocatedCluster = VmwareCluster & { datacenter: string }
|
||||
type LocatedHost = VmwareHost & { datacenter: string }
|
||||
type MigratableVm = VmwareVm & { isTemplate: false }
|
||||
|
||||
// a cluster or a host outside of any datacenter cannot be shown in the tree of the source
|
||||
const isLocatedCluster = (cluster: VmwareCluster): cluster is LocatedCluster => cluster.datacenter !== undefined
|
||||
const isLocatedHost = (host: VmwareHost): host is LocatedHost => host.datacenter !== undefined
|
||||
|
||||
// a VMware template cannot be powered on, so it is not a VM to migrate
|
||||
const isMigratableVm = (vm: VmwareVm): vm is MigratableVm => !vm.isTemplate
|
||||
|
||||
const DISK_MODES = new Set<string>(Object.values(V2V_DISK_MODE))
|
||||
|
||||
function toDiskMode(diskMode: string | undefined): V2V_DISK_MODE {
|
||||
// `persistent` is the default mode of vSphere when the backing does not say
|
||||
return diskMode !== undefined && DISK_MODES.has(diskMode) ? (diskMode as V2V_DISK_MODE) : V2V_DISK_MODE.PERSISTENT
|
||||
}
|
||||
|
||||
function toCluster({ id, name, datacenter }: LocatedCluster): XoV2vCluster {
|
||||
return { id: id as XoV2vCluster['id'], name, datacenterId: datacenter as XoV2vDatacenter['id'] }
|
||||
}
|
||||
|
||||
function toHost({ id, name, parent, datacenter }: LocatedHost, clusterIds: ReadonlySet<string>): XoV2vHost {
|
||||
// the parent of a standalone host is its own compute resource, not a cluster
|
||||
const clusterId = parent !== undefined && clusterIds.has(parent) ? (parent as XoV2vCluster['id']) : undefined
|
||||
return { id: id as XoV2vHost['id'], name, clusterId, datacenterId: datacenter as XoV2vDatacenter['id'] }
|
||||
}
|
||||
|
||||
function toDatastore({ id, name, type, capacity, freeSpace, hosts }: VmwareDatastore): XoV2vDatastore {
|
||||
return {
|
||||
id: id as XoV2vDatastore['id'],
|
||||
// an inaccessible datastore can come without its summary
|
||||
name: name ?? id,
|
||||
type: type ?? '',
|
||||
capacity: capacity ?? 0,
|
||||
free: freeSpace ?? 0,
|
||||
hostIds: hosts as XoV2vHost['id'][],
|
||||
}
|
||||
}
|
||||
|
||||
function toPortGroup(network: VmwareNetwork): XoV2vPortGroup {
|
||||
// a trunk carries VLAN ranges, which is not a VLAN of the network
|
||||
const vlan = network.distributed && typeof network.vlan === 'number' ? network.vlan : undefined
|
||||
return { id: network.id as XoV2vPortGroup['id'], name: network.name, vlan }
|
||||
}
|
||||
|
||||
function toDisk({ key, label, datastore, capacity, diskMode, rdm, encrypted, chainPaths }: VmwareVmDisk): XoV2vDisk {
|
||||
return {
|
||||
key: key as XoV2vDisk['key'],
|
||||
label,
|
||||
// a disk is always kept, even without a datastore: dropping it would hide it from the import
|
||||
datastoreId: (datastore ?? '') as XoV2vDatastore['id'],
|
||||
capacity,
|
||||
mode: toDiskMode(diskMode),
|
||||
isRdm: rdm,
|
||||
isEncrypted: encrypted,
|
||||
chainPaths,
|
||||
}
|
||||
}
|
||||
|
||||
function toNic({ key, label, network, macAddress }: VmwareVmNic): XoV2vNic {
|
||||
return {
|
||||
key: key as XoV2vNic['key'],
|
||||
label,
|
||||
// undefined for an opaque (NSX) network, which is not listed as a port group
|
||||
portGroupId: network as XoV2vPortGroup['id'] | undefined,
|
||||
macAddress: macAddress ?? '',
|
||||
}
|
||||
}
|
||||
|
||||
function toVm(vm: MigratableVm): XoV2vVm {
|
||||
return {
|
||||
id: vm.id as XoV2vVm['id'],
|
||||
instanceUuid: vm.instanceUuid ?? '',
|
||||
name: vm.name ?? vm.id,
|
||||
description: vm.annotation ?? '',
|
||||
powerState: vm.powerState ?? V2V_VM_POWER_STATE.POWERED_OFF,
|
||||
hostId: (vm.host ?? '') as XoV2vHost['id'],
|
||||
nCpus: vm.cpus ?? 0,
|
||||
memory: vm.memory ?? 0,
|
||||
firmware: vm.firmware === V2V_FIRMWARE.UEFI ? V2V_FIRMWARE.UEFI : V2V_FIRMWARE.BIOS,
|
||||
secureBoot: vm.secureBoot,
|
||||
datastoreIds: vm.datastores as XoV2vDatastore['id'][],
|
||||
snapshotCount: vm.snapshotCount,
|
||||
currentSnapshotId: vm.currentSnapshot,
|
||||
disks: vm.disks.map(toDisk),
|
||||
nics: vm.nics.map(toNic),
|
||||
}
|
||||
}
|
||||
|
||||
export function toXoV2vInventory(inventory: Readonly<VmwareInventory>): XoV2vInventory {
|
||||
const clusters = inventory.clusters.filter(isLocatedCluster)
|
||||
const clusterIds = new Set(clusters.map(cluster => cluster.id))
|
||||
|
||||
return {
|
||||
product: inventory.product ?? '',
|
||||
version: inventory.version ?? '',
|
||||
instanceUuid: inventory.instanceUuid,
|
||||
datacenters: inventory.datacenters.map(({ id, name }) => ({ id: id as XoV2vDatacenter['id'], name })),
|
||||
clusters: clusters.map(toCluster),
|
||||
hosts: inventory.hosts.filter(isLocatedHost).map(host => toHost(host, clusterIds)),
|
||||
datastores: inventory.datastores.map(toDatastore),
|
||||
portGroups: inventory.networks.map(toPortGroup),
|
||||
vms: inventory.vms.filter(isMigratableVm).map(toVm),
|
||||
}
|
||||
}
|
||||
245
@xen-orchestra/rest-api/src/v2v/v2v.inventory.test.mts
Normal file
245
@xen-orchestra/rest-api/src/v2v/v2v.inventory.test.mts
Normal file
@@ -0,0 +1,245 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { describe, it } from 'node:test'
|
||||
import type { VmwareInventory, VmwareVm } from '@vates/types'
|
||||
|
||||
import { toXoV2vInventory } from './v2v.inventory.mjs'
|
||||
|
||||
const sourceVm = (vm: Partial<VmwareVm> = {}): VmwareVm => ({
|
||||
id: 'vm-1',
|
||||
secureBoot: false,
|
||||
isTemplate: false,
|
||||
datastores: [],
|
||||
snapshotCount: 0,
|
||||
disks: [],
|
||||
nics: [],
|
||||
...vm,
|
||||
})
|
||||
|
||||
const sourceInventory = (inventory: Partial<VmwareInventory> = {}): VmwareInventory => ({
|
||||
datacenters: [],
|
||||
clusters: [],
|
||||
hosts: [],
|
||||
datastores: [],
|
||||
networks: [],
|
||||
vms: [],
|
||||
...inventory,
|
||||
})
|
||||
|
||||
describe('toXoV2vInventory', function () {
|
||||
it('keeps the identity of the source', function () {
|
||||
const inventory = toXoV2vInventory(
|
||||
sourceInventory({
|
||||
product: 'VMware vCenter Server',
|
||||
version: '8.0.2',
|
||||
instanceUuid: 'vc-1',
|
||||
})
|
||||
)
|
||||
|
||||
assert.deepEqual(
|
||||
{ product: inventory.product, version: inventory.version, instanceUuid: inventory.instanceUuid },
|
||||
{ product: 'VMware vCenter Server', version: '8.0.2', instanceUuid: 'vc-1' }
|
||||
)
|
||||
})
|
||||
|
||||
it('points the hosts and the clusters up to their cluster and datacenter', function () {
|
||||
const inventory = toXoV2vInventory(
|
||||
sourceInventory({
|
||||
datacenters: [{ id: 'datacenter-1', name: 'DC' }],
|
||||
clusters: [{ id: 'domain-c7', name: 'Cluster', datacenter: 'datacenter-1' }],
|
||||
hosts: [
|
||||
{ id: 'host-10', name: 'esx1', parent: 'domain-c7', datacenter: 'datacenter-1' },
|
||||
// a standalone host: its parent is its own compute resource
|
||||
{ id: 'host-11', name: 'esx2', parent: 'domain-s9', datacenter: 'datacenter-1' },
|
||||
],
|
||||
})
|
||||
)
|
||||
|
||||
assert.deepEqual(inventory.datacenters, [{ id: 'datacenter-1', name: 'DC' }])
|
||||
assert.deepEqual(inventory.clusters, [{ id: 'domain-c7', name: 'Cluster', datacenterId: 'datacenter-1' }])
|
||||
assert.deepEqual(inventory.hosts, [
|
||||
{ id: 'host-10', name: 'esx1', clusterId: 'domain-c7', datacenterId: 'datacenter-1' },
|
||||
{ id: 'host-11', name: 'esx2', clusterId: undefined, datacenterId: 'datacenter-1' },
|
||||
])
|
||||
})
|
||||
|
||||
it('leaves out the hosts and the clusters outside of any datacenter', function () {
|
||||
const inventory = toXoV2vInventory(
|
||||
sourceInventory({
|
||||
clusters: [{ id: 'domain-c7', name: 'Cluster' }],
|
||||
hosts: [{ id: 'host-10', name: 'esx1', parent: 'domain-c7' }],
|
||||
})
|
||||
)
|
||||
|
||||
assert.deepEqual({ clusters: inventory.clusters, hosts: inventory.hosts }, { clusters: [], hosts: [] })
|
||||
})
|
||||
|
||||
it('renames the space of the datastores, and names an inaccessible one after its id', function () {
|
||||
const inventory = toXoV2vInventory(
|
||||
sourceInventory({
|
||||
datastores: [
|
||||
{
|
||||
id: 'datastore-1',
|
||||
name: 'ds1',
|
||||
type: 'VMFS',
|
||||
capacity: 1000,
|
||||
freeSpace: 400,
|
||||
hosts: ['host-10'],
|
||||
},
|
||||
{ id: 'datastore-2', hosts: [] },
|
||||
],
|
||||
})
|
||||
)
|
||||
|
||||
assert.deepEqual(inventory.datastores, [
|
||||
{ id: 'datastore-1', name: 'ds1', type: 'VMFS', capacity: 1000, free: 400, hostIds: ['host-10'] },
|
||||
{ id: 'datastore-2', name: 'datastore-2', type: '', capacity: 0, free: 0, hostIds: [] },
|
||||
])
|
||||
})
|
||||
|
||||
it('lists the networks as port groups, with a VLAN only when it is a single one', function () {
|
||||
const inventory = toXoV2vInventory(
|
||||
sourceInventory({
|
||||
networks: [
|
||||
{ id: 'network-1', name: 'VM Network', distributed: false },
|
||||
{ id: 'dvportgroup-2', name: 'prod', distributed: true, vlan: 12 },
|
||||
{ id: 'dvportgroup-3', name: 'trunk', distributed: true, vlan: [{ start: 1, end: 4094 }] },
|
||||
],
|
||||
})
|
||||
)
|
||||
|
||||
assert.deepEqual(inventory.portGroups, [
|
||||
{ id: 'network-1', name: 'VM Network', vlan: undefined },
|
||||
{ id: 'dvportgroup-2', name: 'prod', vlan: 12 },
|
||||
{ id: 'dvportgroup-3', name: 'trunk', vlan: undefined },
|
||||
])
|
||||
})
|
||||
|
||||
it('describes a VM as the wizard shows it', function () {
|
||||
const {
|
||||
vms: [vm],
|
||||
} = toXoV2vInventory(
|
||||
sourceInventory({
|
||||
vms: [
|
||||
sourceVm({
|
||||
name: 'web',
|
||||
annotation: 'front',
|
||||
instanceUuid: 'uuid-1',
|
||||
firmware: 'uefi',
|
||||
secureBoot: true,
|
||||
cpus: 2,
|
||||
memory: 4096,
|
||||
powerState: 'poweredOn',
|
||||
host: 'host-10',
|
||||
datastores: ['datastore-1'],
|
||||
currentSnapshot: 'snapshot-2',
|
||||
snapshotCount: 2,
|
||||
}),
|
||||
],
|
||||
})
|
||||
)
|
||||
|
||||
assert.deepEqual(vm, {
|
||||
id: 'vm-1',
|
||||
instanceUuid: 'uuid-1',
|
||||
name: 'web',
|
||||
description: 'front',
|
||||
powerState: 'poweredOn',
|
||||
hostId: 'host-10',
|
||||
nCpus: 2,
|
||||
memory: 4096,
|
||||
firmware: 'uefi',
|
||||
secureBoot: true,
|
||||
datastoreIds: ['datastore-1'],
|
||||
snapshotCount: 2,
|
||||
currentSnapshotId: 'snapshot-2',
|
||||
disks: [],
|
||||
nics: [],
|
||||
})
|
||||
})
|
||||
|
||||
it('keeps the keys of the disks and of the network cards, which the start maps are indexed by', function () {
|
||||
const {
|
||||
vms: [vm],
|
||||
} = toXoV2vInventory(
|
||||
sourceInventory({
|
||||
vms: [
|
||||
sourceVm({
|
||||
disks: [
|
||||
{
|
||||
key: 'scsi0:0',
|
||||
label: 'Hard disk 1',
|
||||
capacity: 1024,
|
||||
datastore: 'datastore-1',
|
||||
diskMode: 'independent_persistent',
|
||||
rdm: true,
|
||||
encrypted: true,
|
||||
chainPaths: ['vm/vm.vmdk', 'vm/vm-000001.vmdk'],
|
||||
},
|
||||
],
|
||||
nics: [
|
||||
{ key: '4000', label: 'Network adapter 1', macAddress: '00:50:56:aa:bb:cc', network: 'dvportgroup-2' },
|
||||
// an NSX opaque network is not a port group
|
||||
{ key: '4001', label: 'Network adapter 2' },
|
||||
],
|
||||
}),
|
||||
],
|
||||
})
|
||||
)
|
||||
|
||||
assert.deepEqual(vm.disks, [
|
||||
{
|
||||
key: 'scsi0:0',
|
||||
label: 'Hard disk 1',
|
||||
datastoreId: 'datastore-1',
|
||||
capacity: 1024,
|
||||
mode: 'independent_persistent',
|
||||
isRdm: true,
|
||||
isEncrypted: true,
|
||||
chainPaths: ['vm/vm.vmdk', 'vm/vm-000001.vmdk'],
|
||||
},
|
||||
])
|
||||
assert.deepEqual(vm.nics, [
|
||||
{ key: '4000', label: 'Network adapter 1', portGroupId: 'dvportgroup-2', macAddress: '00:50:56:aa:bb:cc' },
|
||||
{ key: '4001', label: 'Network adapter 2', portGroupId: undefined, macAddress: '' },
|
||||
])
|
||||
})
|
||||
|
||||
it('falls back to the defaults of vSphere when the source does not tell', function () {
|
||||
const {
|
||||
vms: [vm],
|
||||
} = toXoV2vInventory(
|
||||
sourceInventory({
|
||||
vms: [
|
||||
sourceVm({
|
||||
disks: [
|
||||
{
|
||||
key: 'scsi0:0',
|
||||
label: 'Hard disk 1',
|
||||
capacity: 1024,
|
||||
rdm: false,
|
||||
encrypted: false,
|
||||
chainPaths: [],
|
||||
},
|
||||
],
|
||||
}),
|
||||
],
|
||||
})
|
||||
)
|
||||
|
||||
assert.deepEqual(
|
||||
{ name: vm.name, powerState: vm.powerState, firmware: vm.firmware, mode: vm.disks[0].mode },
|
||||
{ name: 'vm-1', powerState: 'poweredOff', firmware: 'bios', mode: 'persistent' }
|
||||
)
|
||||
})
|
||||
|
||||
it('leaves out the templates, which cannot be migrated', function () {
|
||||
const inventory = toXoV2vInventory(
|
||||
sourceInventory({ vms: [sourceVm({ id: 'vm-1' }), sourceVm({ id: 'vm-2', isTemplate: true })] })
|
||||
)
|
||||
|
||||
assert.deepEqual(
|
||||
inventory.vms.map(vm => vm.id),
|
||||
['vm-1']
|
||||
)
|
||||
})
|
||||
})
|
||||
108
@xen-orchestra/rest-api/src/v2v/v2v.plan.mts
Normal file
108
@xen-orchestra/rest-api/src/v2v/v2v.plan.mts
Normal file
@@ -0,0 +1,108 @@
|
||||
import type { VmwareVm, XoNetwork, XoSr, XoVmTemplate } from '@vates/types'
|
||||
|
||||
import type { V2vStartBody, V2vStartVm } from './v2v.type.mjs'
|
||||
|
||||
/** what the import of one VM will be given */
|
||||
export type V2vVmPlan = {
|
||||
id: string
|
||||
name: string
|
||||
sr: XoSr['id']
|
||||
network: XoNetwork['id']
|
||||
/** overrides `sr`, by disk key */
|
||||
disks: Record<string, XoSr['id']>
|
||||
/** overrides `network`, by NIC key */
|
||||
nics: Record<string, XoNetwork['id']>
|
||||
template: XoVmTemplate['id']
|
||||
stopSource: boolean
|
||||
}
|
||||
|
||||
export type V2vProblem = { vm?: string; field?: string; message: string }
|
||||
|
||||
/**
|
||||
* Checks a launch against the source and what the import supports, before anything is started.
|
||||
*
|
||||
* As in XO5, the XCP-ng side is not checked: neither the pool of the SRs, networks and templates, nor
|
||||
* the imports already running, nor the existing imports. The UI only offers valid choices, and the
|
||||
* import resumes a partial import by itself, or imports the VM again.
|
||||
*
|
||||
* The keys of `disks` and `nics` are checked by the import, before it does anything.
|
||||
*
|
||||
* Every problem is reported at once, so that a list can be fixed in one go.
|
||||
*/
|
||||
export function planMigration(
|
||||
body: Readonly<V2vStartBody>,
|
||||
/** VMs of the source, by id */
|
||||
sourceVms: ReadonlyMap<string, VmwareVm>
|
||||
): { plans: V2vVmPlan[]; problems: V2vProblem[] } {
|
||||
const { defaults } = body
|
||||
const problems: V2vProblem[] = []
|
||||
const plans: V2vVmPlan[] = []
|
||||
|
||||
if (defaults.startVm === true) {
|
||||
problems.push({ field: 'defaults.startVm', message: 'starting the VM after its import is not supported yet' })
|
||||
}
|
||||
if (defaults.cleanup === true) {
|
||||
problems.push({ field: 'defaults.cleanup', message: 'cleaning up the VM is not supported yet' })
|
||||
}
|
||||
|
||||
const seen = new Set<string>()
|
||||
for (const vm of body.vms) {
|
||||
const problemCount = problems.length
|
||||
const plan = planVm(vm)
|
||||
if (plan !== undefined && problems.length === problemCount) {
|
||||
plans.push(plan)
|
||||
}
|
||||
}
|
||||
return { plans, problems }
|
||||
|
||||
function planVm(vm: Readonly<V2vStartVm>): V2vVmPlan | undefined {
|
||||
const { id } = vm
|
||||
const report = (message: string, field?: string) => problems.push({ vm: id, field, message })
|
||||
|
||||
if (seen.has(id)) {
|
||||
report('the VM is listed more than once')
|
||||
return
|
||||
}
|
||||
seen.add(id)
|
||||
|
||||
const sourceVm = sourceVms.get(id)
|
||||
if (sourceVm === undefined) {
|
||||
report('no such VM on the source')
|
||||
return
|
||||
}
|
||||
|
||||
// options the import cannot honour yet: refused rather than silently ignored
|
||||
if (vm.startVm === true) {
|
||||
report('starting the VM after its import is not supported yet', 'startVm')
|
||||
}
|
||||
if (vm.cleanup === true) {
|
||||
report('cleaning up the VM is not supported yet', 'cleanup')
|
||||
}
|
||||
if (vm.tags !== undefined && vm.tags.length > 0) {
|
||||
report('setting tags is not supported yet', 'tags')
|
||||
}
|
||||
if (vm.keepMac === false) {
|
||||
report('the MAC addresses are always kept for now', 'keepMac')
|
||||
}
|
||||
|
||||
for (const disk of sourceVm.disks) {
|
||||
if (disk.rdm) {
|
||||
report(`the disk ${disk.key} is a raw device mapping, which cannot be imported`, 'disks')
|
||||
}
|
||||
if (disk.encrypted) {
|
||||
report(`the disk ${disk.key} is encrypted, which cannot be imported`, 'disks')
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
id,
|
||||
name: sourceVm.name ?? id,
|
||||
sr: defaults.sr as XoSr['id'],
|
||||
network: defaults.network as XoNetwork['id'],
|
||||
disks: (vm.disks ?? {}) as Record<string, XoSr['id']>,
|
||||
nics: (vm.nics ?? {}) as Record<string, XoNetwork['id']>,
|
||||
template: (vm.template ?? defaults.template) as XoVmTemplate['id'],
|
||||
stopSource: vm.stopSource ?? defaults.stopSource ?? false,
|
||||
}
|
||||
}
|
||||
}
|
||||
134
@xen-orchestra/rest-api/src/v2v/v2v.plan.test.mts
Normal file
134
@xen-orchestra/rest-api/src/v2v/v2v.plan.test.mts
Normal file
@@ -0,0 +1,134 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { describe, it } from 'node:test'
|
||||
import type { VmwareVm, XoV2vStartPayload, XoV2vStartPayloadVm } from '@vates/types'
|
||||
|
||||
import { planMigration } from './v2v.plan.mjs'
|
||||
import type { V2vStartBody, V2vStartVm } from './v2v.type.mjs'
|
||||
|
||||
// The front builds its request as `XoV2vStartPayload`, which cannot be the body of the route itself: its ids are
|
||||
// branded, which tsoa would validate as objects. Checked here at build time instead: the payload must be accepted,
|
||||
// and must not carry a key the route refuses (`throw-on-extras`)
|
||||
const frontPayload = {} as XoV2vStartPayload
|
||||
export const acceptedFrontPayload: V2vStartBody = frontPayload
|
||||
type ExtraKeys =
|
||||
| Exclude<keyof XoV2vStartPayload, keyof V2vStartBody>
|
||||
| Exclude<keyof XoV2vStartPayloadVm, keyof V2vStartVm>
|
||||
export const noExtraKeyInFrontPayload: [ExtraKeys] extends [never] ? true : false = true
|
||||
|
||||
const sourceVm = (id: string, { disks = ['scsi0:0'], nics = ['4000'] } = {}): VmwareVm => ({
|
||||
id,
|
||||
name: `name of ${id}`,
|
||||
secureBoot: false,
|
||||
isTemplate: false,
|
||||
datastores: [],
|
||||
snapshotCount: 0,
|
||||
disks: disks.map(key => ({ key, label: key, capacity: 1, rdm: false, encrypted: false, chainPaths: [] })),
|
||||
nics: nics.map(key => ({ key, label: key })),
|
||||
})
|
||||
|
||||
const makeContext = ({ vms = [sourceVm('vm-1')] }: { vms?: VmwareVm[] } = {}) => new Map(vms.map(vm => [vm.id, vm]))
|
||||
|
||||
const makeBody = (body: Partial<V2vStartBody> = {}): V2vStartBody => ({
|
||||
connection: { host: 'vcenter', username: 'user', password: 'password' },
|
||||
defaults: { sr: 'sr-1', network: 'net-1', template: 'tpl-1' },
|
||||
vms: [{ id: 'vm-1' }],
|
||||
...body,
|
||||
})
|
||||
|
||||
const messagesOf = ({ problems }: ReturnType<typeof planMigration>) => problems.map(({ message }) => message)
|
||||
|
||||
describe('planMigration', function () {
|
||||
it('applies the defaults', function () {
|
||||
const result = planMigration(makeBody(), makeContext())
|
||||
|
||||
assert.deepEqual(result.problems, [])
|
||||
assert.deepEqual(result.plans, [
|
||||
{
|
||||
id: 'vm-1',
|
||||
name: 'name of vm-1',
|
||||
sr: 'sr-1',
|
||||
network: 'net-1',
|
||||
disks: {},
|
||||
nics: {},
|
||||
template: 'tpl-1',
|
||||
stopSource: false,
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
it('applies the options of a VM over the defaults', function () {
|
||||
const result = planMigration(
|
||||
makeBody({
|
||||
defaults: { sr: 'sr-1', network: 'net-1', template: 'tpl-1', stopSource: true },
|
||||
vms: [
|
||||
{ id: 'vm-1', disks: { 'scsi0:0': 'sr-2' }, nics: { '4000': 'net-2' }, template: 'tpl-2', stopSource: false },
|
||||
],
|
||||
}),
|
||||
makeContext()
|
||||
)
|
||||
|
||||
assert.deepEqual(result.problems, [])
|
||||
assert.deepEqual(result.plans[0], {
|
||||
id: 'vm-1',
|
||||
name: 'name of vm-1',
|
||||
sr: 'sr-1',
|
||||
network: 'net-1',
|
||||
disks: { 'scsi0:0': 'sr-2' },
|
||||
nics: { '4000': 'net-2' },
|
||||
template: 'tpl-2',
|
||||
stopSource: false,
|
||||
})
|
||||
})
|
||||
|
||||
it('refuses the options the import does not support yet', function () {
|
||||
const result = planMigration(
|
||||
makeBody({ vms: [{ id: 'vm-1', startVm: true, cleanup: true, tags: ['migrated-from:vmware'], keepMac: false }] }),
|
||||
makeContext()
|
||||
)
|
||||
|
||||
assert.deepEqual(
|
||||
result.problems.map(({ field }) => field),
|
||||
['startVm', 'cleanup', 'tags', 'keepMac']
|
||||
)
|
||||
})
|
||||
|
||||
it('accepts the unsupported options when they ask for nothing', function () {
|
||||
const result = planMigration(
|
||||
makeBody({ vms: [{ id: 'vm-1', startVm: false, cleanup: false, tags: [], keepMac: true }] }),
|
||||
makeContext()
|
||||
)
|
||||
|
||||
assert.deepEqual(result.problems, [])
|
||||
})
|
||||
|
||||
it('refuses unknown VMs and a VM listed twice', function () {
|
||||
const result = planMigration(
|
||||
makeBody({ vms: [{ id: 'vm-1' }, { id: 'vm-1' }, { id: 'vm-unknown' }] }),
|
||||
makeContext()
|
||||
)
|
||||
|
||||
assert.deepEqual(messagesOf(result), ['the VM is listed more than once', 'no such VM on the source'])
|
||||
})
|
||||
|
||||
it('refuses disks which cannot be read', function () {
|
||||
const vm = sourceVm('vm-1')
|
||||
vm.disks[0].rdm = true
|
||||
const result = planMigration(makeBody(), makeContext({ vms: [vm] }))
|
||||
|
||||
assert.deepEqual(messagesOf(result), ['the disk scsi0:0 is a raw device mapping, which cannot be imported'])
|
||||
})
|
||||
|
||||
it('reports the problems of every VM, and plans only the valid ones', function () {
|
||||
const vms = [sourceVm('vm-1'), sourceVm('vm-2')]
|
||||
const result = planMigration(
|
||||
makeBody({ vms: [{ id: 'vm-1', startVm: true }, { id: 'vm-2' }] }),
|
||||
makeContext({ vms })
|
||||
)
|
||||
|
||||
assert.equal(result.problems.length, 1)
|
||||
assert.deepEqual(
|
||||
result.plans.map(({ id }) => id),
|
||||
['vm-2']
|
||||
)
|
||||
})
|
||||
})
|
||||
137
@xen-orchestra/rest-api/src/v2v/v2v.service.mts
Normal file
137
@xen-orchestra/rest-api/src/v2v/v2v.service.mts
Normal file
@@ -0,0 +1,137 @@
|
||||
import { asyncEach } from '@vates/async-each'
|
||||
import { Task } from '@vates/task'
|
||||
import { invalidParameters } from 'xo-common/api-errors.js'
|
||||
import type { VatesTask } from '@vates/types/lib/vates/task'
|
||||
import { V2V_ERROR_CODE, type EsxiConnectionParams, type VmwareInventory, type XoV2vStatus } from '@vates/types'
|
||||
|
||||
import { ApiError } from '../helpers/error.helper.mjs'
|
||||
import type { RestApi } from '../rest-api/rest-api.mjs'
|
||||
import { toXoV2vInventory } from './v2v.inventory.mjs'
|
||||
import { planMigration, type V2vVmPlan } from './v2v.plan.mjs'
|
||||
import type { V2vConnection, V2vInventory, V2vStartBody, V2vStartResult } from './v2v.type.mjs'
|
||||
|
||||
/** the name of the root task */
|
||||
export const V2V_TASK_NAME = 'V2V migration'
|
||||
|
||||
const DEFAULT_CONCURRENCY = 2
|
||||
|
||||
export class V2vService {
|
||||
#restApi: RestApi
|
||||
|
||||
constructor(restApi: RestApi) {
|
||||
this.#restApi = restApi
|
||||
}
|
||||
|
||||
/**
|
||||
* The SOAP client and the HTTP downloads of the disks both take the port as part of the host
|
||||
*/
|
||||
static toConnectionParams({ host, port, username, password, skipSslCheck = false }: V2vConnection) {
|
||||
let address = host.trim()
|
||||
// an IPv6 address has to be bracketed to be followed by a port
|
||||
const isIpv6 = address.split(':').length > 2 && !address.startsWith('[')
|
||||
if (isIpv6) {
|
||||
address = `[${address}]`
|
||||
}
|
||||
if (port !== undefined && port !== 443) {
|
||||
address = `${address}:${port}`
|
||||
}
|
||||
return { host: address, user: username, password, sslVerify: !skipSslCheck } satisfies EsxiConnectionParams
|
||||
}
|
||||
|
||||
getStatus(): Promise<XoV2vStatus> {
|
||||
return this.#restApi.xoApp.checkEsxiDependencies()
|
||||
}
|
||||
|
||||
async getInventory(connection: V2vConnection): Promise<V2vInventory> {
|
||||
return toXoV2vInventory(await this.#readSourceInventory(connection))
|
||||
}
|
||||
|
||||
// the import plans against the raw inventory, which keeps what the contract of the wizard leaves out
|
||||
async #readSourceInventory(connection: V2vConnection): Promise<VmwareInventory> {
|
||||
try {
|
||||
return await this.#restApi.xoApp.getEsxiInventory(V2vService.toConnectionParams(connection))
|
||||
} catch (error) {
|
||||
throw toSourceError(error, connection.host)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything is checked before the task is created: a refused launch imports nothing
|
||||
*/
|
||||
async prepareStart(body: V2vStartBody): Promise<V2vVmPlan[]> {
|
||||
const { vms } = await this.#readSourceInventory(body.connection)
|
||||
|
||||
const { plans, problems } = planMigration(body, new Map(vms.map(vm => [vm.id, vm])))
|
||||
|
||||
if (problems.length > 0) {
|
||||
throw invalidParameters('the migration cannot be started', problems)
|
||||
}
|
||||
return plans
|
||||
}
|
||||
|
||||
async start(
|
||||
task: VatesTask,
|
||||
{ connection, concurrency = DEFAULT_CONCURRENCY, stopOnError = false }: Readonly<V2vStartBody>,
|
||||
plans: readonly V2vVmPlan[]
|
||||
): Promise<V2vStartResult> {
|
||||
const connectionParams = V2vService.toConnectionParams(connection)
|
||||
const result: V2vStartResult = {}
|
||||
let done = 0
|
||||
task.set('total', plans.length)
|
||||
task.set('done', 0)
|
||||
task.set('progress', 0)
|
||||
|
||||
try {
|
||||
await asyncEach(
|
||||
plans,
|
||||
async ({ id, name, sr, network, disks, nics, template, stopSource }) => {
|
||||
await Task.run({ properties: { name: `importing VM ${name}`, sourceVmId: id } }, async () => {
|
||||
try {
|
||||
result[id] = await this.#restApi.xoApp.migrationfromEsxi({
|
||||
...connectionParams,
|
||||
vm: id,
|
||||
sr,
|
||||
network,
|
||||
disks,
|
||||
nics,
|
||||
template,
|
||||
stopSource,
|
||||
})
|
||||
} finally {
|
||||
done++
|
||||
task.set('done', done)
|
||||
task.set('progress', Math.round((done * 100) / plans.length))
|
||||
}
|
||||
})
|
||||
},
|
||||
{ concurrency, stopOnError }
|
||||
)
|
||||
return result
|
||||
} catch (error) {
|
||||
// same contract as `vm.importMultipleFromEsxi`: the VMs imported before the failure are not lost
|
||||
if (error instanceof Error) {
|
||||
Object.assign(error, { succeeded: result })
|
||||
}
|
||||
throw error
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Only a refused login is an answer of the source, the one the first step of the wizard waits for: 422
|
||||
* rather than 401, which would open the Basic authentication prompt of the browser. Any other failure,
|
||||
* like an unreachable host or a refused certificate, is rethrown as is
|
||||
*/
|
||||
function toSourceError(error: unknown, host: string): unknown {
|
||||
if (!(error instanceof Error)) {
|
||||
return error
|
||||
}
|
||||
if ('code' in error && error.code === 'InvalidLogin') {
|
||||
const apiError = new ApiError('invalid credentials for the source', 422, {
|
||||
data: { code: V2V_ERROR_CODE.INVALID_CREDENTIALS, host },
|
||||
})
|
||||
apiError.cause = error
|
||||
return apiError
|
||||
}
|
||||
return error
|
||||
}
|
||||
65
@xen-orchestra/rest-api/src/v2v/v2v.service.test.mts
Normal file
65
@xen-orchestra/rest-api/src/v2v/v2v.service.test.mts
Normal file
@@ -0,0 +1,65 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { describe, it } from 'node:test'
|
||||
import { V2V_ERROR_CODE } from '@vates/types'
|
||||
|
||||
import { ApiError } from '../helpers/error.helper.mjs'
|
||||
import type { RestApi } from '../rest-api/rest-api.mjs'
|
||||
import { V2vService } from './v2v.service.mjs'
|
||||
|
||||
const connection = { username: 'user', password: 'password' }
|
||||
|
||||
describe('V2vService.toConnectionParams', function () {
|
||||
it('verifies the certificate unless asked not to', function () {
|
||||
assert.equal(V2vService.toConnectionParams({ ...connection, host: 'vc' }).sslVerify, true)
|
||||
assert.equal(V2vService.toConnectionParams({ ...connection, host: 'vc', skipSslCheck: true }).sslVerify, false)
|
||||
})
|
||||
|
||||
it('adds the port to the host, unless it is the default one', function () {
|
||||
assert.equal(V2vService.toConnectionParams({ ...connection, host: ' vc ', port: 8443 }).host, 'vc:8443')
|
||||
assert.equal(V2vService.toConnectionParams({ ...connection, host: 'vc', port: 443 }).host, 'vc')
|
||||
})
|
||||
|
||||
it('brackets an IPv6 address', function () {
|
||||
assert.equal(V2vService.toConnectionParams({ ...connection, host: 'fe80::1', port: 8443 }).host, '[fe80::1]:8443')
|
||||
assert.equal(V2vService.toConnectionParams({ ...connection, host: '[fe80::1]' }).host, '[fe80::1]')
|
||||
})
|
||||
|
||||
it('keeps the username', function () {
|
||||
assert.equal(V2vService.toConnectionParams({ ...connection, host: 'vc' }).user, 'user')
|
||||
})
|
||||
})
|
||||
|
||||
describe('V2vService#getInventory', function () {
|
||||
function createService(getEsxiInventory: () => Promise<never>) {
|
||||
return new V2vService({ xoApp: { getEsxiInventory } } as unknown as RestApi)
|
||||
}
|
||||
|
||||
it('rejects refused credentials with a 422, not a 401 which would open the browser prompt', async function () {
|
||||
const loginError = Object.assign(new Error('Cannot complete login'), { code: 'InvalidLogin' })
|
||||
const service = createService(() => Promise.reject(loginError))
|
||||
|
||||
await assert.rejects(service.getInventory({ ...connection, host: 'vc' }), error => {
|
||||
assert(error instanceof ApiError)
|
||||
assert.equal(error.status, 422)
|
||||
assert.deepEqual(error.data, { code: V2V_ERROR_CODE.INVALID_CREDENTIALS, host: 'vc' })
|
||||
assert.equal(error.cause, loginError)
|
||||
return true
|
||||
})
|
||||
})
|
||||
|
||||
it('lets the other errors through', async function () {
|
||||
const networkError = Object.assign(new Error('connect ECONNREFUSED'), { code: 'ECONNREFUSED' })
|
||||
const service = createService(() => Promise.reject(networkError))
|
||||
|
||||
await assert.rejects(service.getInventory({ ...connection, host: 'vc' }), networkError)
|
||||
})
|
||||
})
|
||||
|
||||
describe('V2vService#getStatus', function () {
|
||||
it('reports the dependency check of xo-server as is', async function () {
|
||||
const status = { vectura: { status: 'error', error: 'vectura is not runnable: ENOENT' } } as const
|
||||
const service = new V2vService({ xoApp: { checkEsxiDependencies: async () => status } } as unknown as RestApi)
|
||||
|
||||
assert.deepEqual(await service.getStatus(), status)
|
||||
})
|
||||
})
|
||||
86
@xen-orchestra/rest-api/src/v2v/v2v.type.mts
Normal file
86
@xen-orchestra/rest-api/src/v2v/v2v.type.mts
Normal file
@@ -0,0 +1,86 @@
|
||||
import type { XoV2vInventory, XoV2vStatus } from '@vates/types'
|
||||
|
||||
/** only VMware in v1, other platforms will follow */
|
||||
export type V2vPlatform = 'vmware'
|
||||
|
||||
/**
|
||||
* Credentials are never stored: every request needing the source carries them
|
||||
*/
|
||||
export type V2vConnection = {
|
||||
/** address of the vCenter or of the ESXi */
|
||||
host: string
|
||||
/**
|
||||
* @isInt
|
||||
* @minimum 1
|
||||
* @maximum 65535
|
||||
*/
|
||||
port?: number
|
||||
username: string
|
||||
password: string
|
||||
/** do not verify the certificate of the source, for a self-signed one */
|
||||
skipSslCheck?: boolean
|
||||
}
|
||||
|
||||
export type V2vInventoryBody = {
|
||||
platform: V2vPlatform
|
||||
connection: V2vConnection
|
||||
}
|
||||
|
||||
/** the prerequisites of a migration on this XO: an error carries the reason to show */
|
||||
export type V2vStatus = XoV2vStatus
|
||||
|
||||
/** the inventory of the source, as the migration wizard shows it */
|
||||
export type V2vInventory = XoV2vInventory
|
||||
|
||||
/** options which can be set for the whole launch, then overridden for a VM */
|
||||
export type V2vVmOptions = {
|
||||
/** stop the source VM before the last delta, which completes the import */
|
||||
stopSource?: boolean
|
||||
/** not supported yet */
|
||||
startVm?: boolean
|
||||
/** not supported yet */
|
||||
cleanup?: boolean
|
||||
}
|
||||
|
||||
export type V2vDefaults = V2vVmOptions & {
|
||||
sr: string
|
||||
network: string
|
||||
template: string
|
||||
}
|
||||
|
||||
export type V2vStartVm = V2vVmOptions & {
|
||||
/** VMware managed object reference of the VM */
|
||||
id: string
|
||||
/** SR of a disk, by disk key (e.g. `scsi0:0`), when it is not the default one. Ignored for a disk already imported */
|
||||
disks?: Record<string, string>
|
||||
/** network of a card, by NIC key (e.g. `4000`), when it is not the default one. Ignored when resuming an import */
|
||||
nics?: Record<string, string>
|
||||
template?: string
|
||||
/** not supported yet: must be empty */
|
||||
tags?: string[]
|
||||
/** only `true` is supported for now: the MAC addresses are always kept */
|
||||
keepMac?: boolean
|
||||
}
|
||||
|
||||
/** the pool is the one of the route, and the platform is VMware */
|
||||
export type V2vStartBody = {
|
||||
connection: V2vConnection
|
||||
defaults: V2vDefaults
|
||||
/**
|
||||
* @minItems 1
|
||||
*/
|
||||
vms: V2vStartVm[]
|
||||
/** stop at the first failed VM instead of importing the others */
|
||||
stopOnError?: boolean
|
||||
/**
|
||||
* number of VMs imported in parallel, each one opens its own ESXi session and a host only
|
||||
* accepts a limited number of them
|
||||
* @isInt
|
||||
* @minimum 1
|
||||
* @maximum 8
|
||||
*/
|
||||
concurrency?: number
|
||||
}
|
||||
|
||||
/** UUID of the XCP-ng VM, by VMware VM id */
|
||||
export type V2vStartResult = Record<string, string>
|
||||
368
@xen-orchestra/vmware-explorer/_inventory.mjs
Normal file
368
@xen-orchestra/vmware-explorer/_inventory.mjs
Normal file
@@ -0,0 +1,368 @@
|
||||
import { parseDatastorePath } from './_paths.mjs'
|
||||
import { UNSAFE_KEYS } from './parsers/utils.mjs'
|
||||
import { asArray } from './soap/normalize.mjs'
|
||||
|
||||
// the references nested in a value are not normalized, only the value of the property itself is
|
||||
const refOf = value => value?.$value ?? value
|
||||
|
||||
// the SOAP library does not always convert the scalars of the answer
|
||||
const toNumber = value => (value === undefined ? undefined : Number(value))
|
||||
const isTrue = value => String(value) === 'true'
|
||||
|
||||
const typeOf = object => object?.attributes?.['xsi:type']
|
||||
|
||||
// the prefix the vmx uses for the disks of a controller, which is how the import names a disk
|
||||
const CONTROLLER_PREFIXES = {
|
||||
ParaVirtualSCSIController: 'scsi',
|
||||
VirtualBusLogicController: 'scsi',
|
||||
VirtualLsiLogicController: 'scsi',
|
||||
VirtualLsiLogicSASController: 'scsi',
|
||||
VirtualIDEController: 'ide',
|
||||
VirtualAHCIController: 'sata',
|
||||
VirtualNVMEController: 'nvme',
|
||||
}
|
||||
|
||||
/**
|
||||
* The backing of a device, as the SOAP library returns it: only the fields read here.
|
||||
*
|
||||
* @typedef {object} RawBacking
|
||||
* @property {string} [fileName]
|
||||
* @property {unknown} [datastore]
|
||||
* @property {string} [diskMode]
|
||||
* @property {unknown} [thinProvisioned]
|
||||
* @property {unknown} [keyId]
|
||||
* @property {{ portgroupKey?: string }} [port]
|
||||
* @property {unknown} [network]
|
||||
* @property {string} [opaqueNetworkId]
|
||||
* @property {RawBacking} [parent] - backing of the parent disk of a snapshot delta
|
||||
*/
|
||||
|
||||
/**
|
||||
* A `VirtualDevice`, as the SOAP library returns it: only the fields read here.
|
||||
*
|
||||
* @typedef {object} RawDevice
|
||||
* @property {string | number} [key]
|
||||
* @property {string | number} [busNumber]
|
||||
* @property {string | number} [controllerKey]
|
||||
* @property {string | number} [unitNumber]
|
||||
* @property {string | number} [capacityInBytes]
|
||||
* @property {string | number} [capacityInKB]
|
||||
* @property {{ label?: string }} [deviceInfo]
|
||||
* @property {string} [macAddress]
|
||||
* @property {string} [addressType]
|
||||
* @property {RawBacking} [backing]
|
||||
*/
|
||||
|
||||
/**
|
||||
* The value of `config.hardware.device`.
|
||||
*
|
||||
* @typedef {{ VirtualDevice?: RawDevice | RawDevice[] }} RawDevices
|
||||
*/
|
||||
|
||||
/**
|
||||
* A `VirtualMachineSnapshotTree`, as the SOAP library returns it: only the fields read here.
|
||||
*
|
||||
* @typedef {object} RawSnapshotTree
|
||||
* @property {RawSnapshotTree | RawSnapshotTree[]} [childSnapshotList]
|
||||
*/
|
||||
|
||||
/**
|
||||
* The `defaultPortConfig` of a distributed port group: only the fields read here.
|
||||
*
|
||||
* @typedef {{ vlan?: { vlanId?: unknown } }} RawPortConfig
|
||||
*/
|
||||
|
||||
/**
|
||||
* The objects of the inventory, as {@link Esxi#search} returns them: only the properties read by
|
||||
* `Esxi#getInventory`, any of them can be missing from the answer.
|
||||
*
|
||||
* @typedef {{ name?: string }} RawDatacenter
|
||||
* @typedef {{ name?: string, parent?: unknown }} RawCluster
|
||||
* @typedef {{ name?: string, parent?: unknown }} RawHost
|
||||
* @typedef {{ summary?: { name?: string, type?: string, capacity?: unknown, freeSpace?: unknown }, host?: unknown }} RawDatastore
|
||||
* @typedef {{ parent?: unknown }} RawChild
|
||||
* @typedef {{ name?: string }} RawNetwork
|
||||
* @typedef {{ name?: string, version?: string, instanceUuid?: string }} RawAboutInfo
|
||||
* @typedef {{ name?: string, key?: string, 'config.defaultPortConfig'?: RawPortConfig }} RawPortgroup
|
||||
* @typedef {{
|
||||
* 'config.name'?: string,
|
||||
* 'config.annotation'?: string,
|
||||
* 'config.instanceUuid'?: string,
|
||||
* 'config.firmware'?: string,
|
||||
* 'config.bootOptions.efiSecureBootEnabled'?: unknown,
|
||||
* 'config.template'?: unknown,
|
||||
* 'config.hardware.numCPU'?: unknown,
|
||||
* 'config.hardware.memoryMB'?: unknown,
|
||||
* 'config.hardware.device'?: RawDevices,
|
||||
* 'runtime.powerState'?: 'poweredOff' | 'poweredOn' | 'suspended',
|
||||
* 'runtime.host'?: unknown,
|
||||
* datastore?: unknown,
|
||||
* snapshot?: { currentSnapshot?: unknown, rootSnapshotList?: RawSnapshotTree | RawSnapshotTree[] },
|
||||
* }} RawVm
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {object} InventoryDisk
|
||||
* @property {string} key - the node of the disk, as the vmx and the import name it, e.g. `scsi0:0`
|
||||
* @property {string} label
|
||||
* @property {number} capacity - in bytes
|
||||
* @property {string | undefined} datastore - managed object reference
|
||||
* @property {string | undefined} diskMode - `persistent`, `independent_persistent`…
|
||||
* @property {boolean} rdm - raw device mapping, which cannot be read through the datastore
|
||||
* @property {boolean} encrypted
|
||||
* @property {string[]} chainPaths - `dir/disk.vmdk` in its datastore of the base disk, then of each snapshot delta down
|
||||
* to the active disk, as the import records the disk a VDI last received
|
||||
*/
|
||||
|
||||
/**
|
||||
* @typedef {object} InventoryNic
|
||||
* @property {string} key - the device key of the card
|
||||
* @property {string} label
|
||||
* @property {string | undefined} macAddress
|
||||
* @property {string | undefined} addressType - `generated`, `manual` or `assigned`
|
||||
* @property {string | undefined} network - managed object reference, of a port group when distributed
|
||||
*/
|
||||
|
||||
/**
|
||||
* The disks and network cards of a VM, from its `config.hardware.device`.
|
||||
*
|
||||
* @param {RawDevices | undefined} devices - value of `config.hardware.device`
|
||||
* @param {Record<string, string>} portgroupsByKey - managed object reference of the distributed port groups, by key
|
||||
* @returns {{ disks: InventoryDisk[], nics: InventoryNic[] }}
|
||||
*/
|
||||
export function parseDevices(devices, portgroupsByKey = {}) {
|
||||
const allDevices = asArray(devices?.VirtualDevice)
|
||||
|
||||
const controllers = new Map()
|
||||
for (const device of allDevices) {
|
||||
const prefix = CONTROLLER_PREFIXES[typeOf(device)]
|
||||
if (prefix !== undefined) {
|
||||
controllers.set(Number(device.key), `${prefix}${Number(device.busNumber)}`)
|
||||
}
|
||||
}
|
||||
|
||||
const disks = []
|
||||
const nics = []
|
||||
for (const device of allDevices) {
|
||||
const label = device.deviceInfo?.label ?? ''
|
||||
if (typeOf(device) === 'VirtualDisk') {
|
||||
const { backing } = device
|
||||
const controller = controllers.get(Number(device.controllerKey))
|
||||
const backingType = typeOf(backing)
|
||||
disks.push({
|
||||
// a disk on a controller the vmx does not name this way cannot be matched by the import
|
||||
key: controller === undefined ? `device-${device.key}` : `${controller}:${Number(device.unitNumber)}`,
|
||||
label,
|
||||
capacity: toNumber(device.capacityInBytes) ?? Number(device.capacityInKB) * 1024,
|
||||
datastore: refOf(backing?.datastore),
|
||||
diskMode: backing?.diskMode,
|
||||
rdm: backingType === 'VirtualDiskRawDiskMappingVer1BackingInfo',
|
||||
encrypted: backing?.keyId !== undefined,
|
||||
chainPaths: chainPathsOf(backing),
|
||||
})
|
||||
} else if (device.macAddress !== undefined || device.addressType !== undefined) {
|
||||
// every kind of network card (E1000, VMXNET3…) carries a MAC address, nothing else does
|
||||
const { backing } = device
|
||||
const portgroupKey = backing?.port?.portgroupKey
|
||||
nics.push({
|
||||
key: String(device.key),
|
||||
label,
|
||||
macAddress: device.macAddress,
|
||||
addressType: device.addressType,
|
||||
network: portgroupKey === undefined ? refOf(backing?.network) : portgroupsByKey[portgroupKey],
|
||||
})
|
||||
}
|
||||
}
|
||||
return { disks, nics }
|
||||
}
|
||||
|
||||
/**
|
||||
* The paths of the disks of a chain, from its base: the backing of a snapshot delta links to its parent's.
|
||||
*
|
||||
* @param {RawBacking | undefined} backing - backing of the active disk
|
||||
* @returns {string[]}
|
||||
*/
|
||||
function chainPathsOf(backing) {
|
||||
const paths = []
|
||||
// a parent loop would be a broken answer, VMware limits a chain to 255 disks
|
||||
for (let depth = 0; backing !== undefined && depth < 256; depth++, backing = backing.parent) {
|
||||
const path = parseDatastorePath(backing.fileName ?? '')?.path
|
||||
if (path !== undefined) {
|
||||
paths.unshift(path)
|
||||
}
|
||||
}
|
||||
return paths
|
||||
}
|
||||
|
||||
/**
|
||||
* The number of snapshots of a VM, at every depth of its tree.
|
||||
*
|
||||
* @param {RawSnapshotTree | RawSnapshotTree[] | undefined} rootList - a `rootSnapshotList`, or the `childSnapshotList` of the recursion
|
||||
* @returns {number}
|
||||
*/
|
||||
export function countSnapshots(rootList) {
|
||||
let count = 0
|
||||
for (const node of asArray(rootList)) {
|
||||
count += 1 + countSnapshots(node.childSnapshotList)
|
||||
}
|
||||
return count
|
||||
}
|
||||
|
||||
/**
|
||||
* The VLAN of a distributed port group: a single id, or the ranges of a trunk.
|
||||
*
|
||||
* @param {RawPortConfig | undefined} defaultPortConfig
|
||||
* @returns {number | { start: number, end: number }[] | undefined}
|
||||
*/
|
||||
export function parseVlan(defaultPortConfig) {
|
||||
const vlanId = refOf(defaultPortConfig?.vlan?.vlanId)
|
||||
if (vlanId === undefined) {
|
||||
return
|
||||
}
|
||||
if (typeof vlanId !== 'object') {
|
||||
return Number(vlanId)
|
||||
}
|
||||
return asArray(vlanId).map(({ start, end }) => ({ start: Number(start), end: Number(end) }))
|
||||
}
|
||||
|
||||
/**
|
||||
* The datacenter an object belongs to, found by walking up its parents: the folders and compute
|
||||
* resources between a host and its datacenter can be nested at any depth.
|
||||
*
|
||||
* @param {string | undefined} id - managed object reference
|
||||
* @param {Map<string, string | undefined>} parents - parent of each folder, compute resource and host
|
||||
* @param {Set<string>} datacenterIds
|
||||
* @returns {string | undefined}
|
||||
*/
|
||||
export function findDatacenter(id, parents, datacenterIds) {
|
||||
// a parent loop would be a broken answer, not a deep tree
|
||||
for (let depth = 0; id !== undefined && depth <= parents.size; depth++) {
|
||||
if (datacenterIds.has(id)) {
|
||||
return id
|
||||
}
|
||||
id = parents.get(id)
|
||||
}
|
||||
}
|
||||
|
||||
const refsOf = value => asArray(value?.ManagedObjectReference).map(refOf)
|
||||
|
||||
/**
|
||||
* The hosts which mount a datastore and can reach it.
|
||||
*
|
||||
* @param {unknown} mounts - value of the `host` property of the datastore
|
||||
* @returns {Set<string>} managed object references of the hosts
|
||||
*/
|
||||
export function reachingHostIds(mounts) {
|
||||
const hostIds = new Set()
|
||||
for (const { key, mountInfo } of asArray(mounts?.DatastoreHostMount)) {
|
||||
if (isTrue(mountInfo?.mounted) && isTrue(mountInfo?.accessible)) {
|
||||
hostIds.add(refOf(key))
|
||||
}
|
||||
}
|
||||
return hostIds
|
||||
}
|
||||
|
||||
/**
|
||||
* The inventory, from the objects `Esxi#getInventory` reads: no request is made here.
|
||||
* The objects reference each other through their managed object references.
|
||||
*
|
||||
* @param {object} raw
|
||||
* @param {RawAboutInfo} raw.about
|
||||
* @param {Record<string, RawDatacenter>} raw.datacenters
|
||||
* @param {Record<string, RawCluster>} raw.clusters
|
||||
* @param {Record<string, RawHost>} raw.hosts
|
||||
* @param {Record<string, RawDatastore>} raw.datastores
|
||||
* @param {Record<string, RawNetwork>} raw.networks
|
||||
* @param {Record<string, RawPortgroup>} raw.portgroups
|
||||
* @param {Record<string, RawVm>} raw.vms
|
||||
* @param {Record<string, RawChild>} raw.folders
|
||||
* @param {Record<string, RawChild>} raw.computeResources
|
||||
* @returns {import('@vates/types').VmwareInventory}
|
||||
*/
|
||||
export function buildInventory({
|
||||
about,
|
||||
datacenters,
|
||||
clusters,
|
||||
hosts,
|
||||
datastores,
|
||||
networks,
|
||||
portgroups,
|
||||
vms,
|
||||
folders,
|
||||
computeResources,
|
||||
}) {
|
||||
/** @type {Map<string, string | undefined>} */
|
||||
const parents = new Map()
|
||||
for (const objects of [folders, computeResources, hosts]) {
|
||||
for (const [id, { parent }] of Object.entries(objects)) {
|
||||
parents.set(id, refOf(parent))
|
||||
}
|
||||
}
|
||||
const datacenterIds = new Set(Object.keys(datacenters))
|
||||
|
||||
/** @type {Record<string, string>} */
|
||||
const portgroupsByKey = {}
|
||||
for (const [id, { key }] of Object.entries(portgroups)) {
|
||||
// `key` comes from the SOAP response: same prototype-pollution guard as in `search`
|
||||
if (UNSAFE_KEYS.has(key)) {
|
||||
continue
|
||||
}
|
||||
portgroupsByKey[key] = id
|
||||
}
|
||||
|
||||
return {
|
||||
product: about.name,
|
||||
version: about.version,
|
||||
instanceUuid: about.instanceUuid,
|
||||
datacenters: Object.entries(datacenters).map(([id, { name }]) => ({ id, name })),
|
||||
clusters: Object.entries(clusters).map(([id, { name, parent }]) => ({
|
||||
id,
|
||||
name,
|
||||
datacenter: findDatacenter(refOf(parent), parents, datacenterIds),
|
||||
})),
|
||||
hosts: Object.entries(hosts).map(([id, { name, parent }]) => ({
|
||||
id,
|
||||
name,
|
||||
parent: refOf(parent),
|
||||
datacenter: findDatacenter(id, parents, datacenterIds),
|
||||
})),
|
||||
datastores: Object.entries(datastores).map(([id, { summary, host }]) => ({
|
||||
id,
|
||||
name: summary?.name,
|
||||
type: summary?.type,
|
||||
capacity: toNumber(summary?.capacity),
|
||||
freeSpace: toNumber(summary?.freeSpace),
|
||||
hosts: [...reachingHostIds(host)],
|
||||
})),
|
||||
networks: Object.entries(networks).map(([id, { name }]) => {
|
||||
const portgroup = portgroups[id]
|
||||
return portgroup === undefined
|
||||
? { id, name, distributed: false }
|
||||
: { id, name, distributed: true, vlan: parseVlan(portgroup['config.defaultPortConfig']) }
|
||||
}),
|
||||
vms: Object.entries(vms).map(([id, properties]) => {
|
||||
const { disks, nics } = parseDevices(properties['config.hardware.device'], portgroupsByKey)
|
||||
const snapshot = properties.snapshot
|
||||
const firmware = properties['config.firmware']
|
||||
const memoryMb = toNumber(properties['config.hardware.memoryMB'])
|
||||
return {
|
||||
id,
|
||||
name: properties['config.name'],
|
||||
annotation: properties['config.annotation'],
|
||||
instanceUuid: properties['config.instanceUuid'],
|
||||
firmware: firmware === 'efi' ? 'uefi' : firmware,
|
||||
secureBoot: isTrue(properties['config.bootOptions.efiSecureBootEnabled']),
|
||||
isTemplate: isTrue(properties['config.template']),
|
||||
cpus: toNumber(properties['config.hardware.numCPU']),
|
||||
memory: memoryMb === undefined ? undefined : memoryMb * 1024 * 1024,
|
||||
powerState: properties['runtime.powerState'],
|
||||
host: refOf(properties['runtime.host']),
|
||||
datastores: refsOf(properties.datastore),
|
||||
currentSnapshot: refOf(snapshot?.currentSnapshot),
|
||||
snapshotCount: countSnapshots(snapshot?.rootSnapshotList),
|
||||
disks,
|
||||
nics,
|
||||
}
|
||||
}),
|
||||
}
|
||||
}
|
||||
162
@xen-orchestra/vmware-explorer/_inventory.test.mjs
Normal file
162
@xen-orchestra/vmware-explorer/_inventory.test.mjs
Normal file
@@ -0,0 +1,162 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { describe, it } from 'node:test'
|
||||
|
||||
import { countSnapshots, findDatacenter, parseDevices, parseVlan } from './_inventory.mjs'
|
||||
|
||||
// shaped as the SOAP library returns them: the nested references and types are not normalized
|
||||
const typed = (type, value) => ({ attributes: { 'xsi:type': type }, ...value })
|
||||
const ref = (type, value) => ({ attributes: { type }, $value: value })
|
||||
|
||||
const DEVICES = {
|
||||
VirtualDevice: [
|
||||
typed('VirtualLsiLogicController', { key: '1000', busNumber: '0', deviceInfo: { label: 'SCSI controller 0' } }),
|
||||
typed('VirtualAHCIController', { key: '15000', busNumber: '1' }),
|
||||
typed('VirtualDisk', {
|
||||
key: '2000',
|
||||
controllerKey: '1000',
|
||||
unitNumber: '1',
|
||||
capacityInBytes: '10737418240',
|
||||
deviceInfo: { label: 'Hard disk 1' },
|
||||
backing: typed('VirtualDiskFlatVer2BackingInfo', {
|
||||
fileName: '[ds1] vm/vm-000002.vmdk',
|
||||
datastore: ref('Datastore', 'datastore-11'),
|
||||
diskMode: 'persistent',
|
||||
thinProvisioned: 'true',
|
||||
parent: typed('VirtualDiskFlatVer2BackingInfo', {
|
||||
fileName: '[ds1] vm/vm-000001.vmdk',
|
||||
parent: typed('VirtualDiskFlatVer2BackingInfo', { fileName: '[ds2] base/vm.vmdk' }),
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
typed('VirtualDisk', {
|
||||
key: '16000',
|
||||
controllerKey: '15000',
|
||||
unitNumber: '0',
|
||||
capacityInKB: '1024',
|
||||
backing: typed('VirtualDiskRawDiskMappingVer1BackingInfo', { fileName: '[ds1] vm/rdm.vmdk', keyId: {} }),
|
||||
}),
|
||||
typed('VirtualVmxnet3', {
|
||||
key: '4000',
|
||||
macAddress: '00:50:56:aa:bb:cc',
|
||||
addressType: 'assigned',
|
||||
backing: typed('VirtualEthernetCardNetworkBackingInfo', { network: ref('Network', 'network-13') }),
|
||||
}),
|
||||
typed('VirtualE1000e', {
|
||||
key: '4001',
|
||||
macAddress: '00:50:56:aa:bb:cd',
|
||||
addressType: 'generated',
|
||||
backing: typed('VirtualEthernetCardDistributedVirtualPortBackingInfo', { port: { portgroupKey: 'dvpg-key' } }),
|
||||
}),
|
||||
typed('VirtualCdrom', { key: '3000', controllerKey: '200', unitNumber: '0' }),
|
||||
],
|
||||
}
|
||||
|
||||
describe('parseDevices', function () {
|
||||
it('names the disks as the vmx does, whatever their controller', function () {
|
||||
const { disks } = parseDevices(DEVICES)
|
||||
assert.deepEqual(
|
||||
disks.map(({ key }) => key),
|
||||
['scsi0:1', 'sata1:0']
|
||||
)
|
||||
})
|
||||
|
||||
it('reports the properties of a disk', function () {
|
||||
const [disk, rdm] = parseDevices(DEVICES).disks
|
||||
assert.deepEqual(disk, {
|
||||
key: 'scsi0:1',
|
||||
label: 'Hard disk 1',
|
||||
capacity: 10737418240,
|
||||
datastore: 'datastore-11',
|
||||
diskMode: 'persistent',
|
||||
rdm: false,
|
||||
encrypted: false,
|
||||
chainPaths: ['base/vm.vmdk', 'vm/vm-000001.vmdk', 'vm/vm-000002.vmdk'],
|
||||
})
|
||||
assert.deepEqual(rdm.chainPaths, ['vm/rdm.vmdk'])
|
||||
assert.equal(rdm.capacity, 1024 * 1024)
|
||||
assert.equal(rdm.rdm, true)
|
||||
assert.equal(rdm.encrypted, true)
|
||||
})
|
||||
|
||||
it('resolves the network of a card, distributed or not', function () {
|
||||
const { nics } = parseDevices(DEVICES, { 'dvpg-key': 'dvportgroup-5' })
|
||||
assert.deepEqual(
|
||||
nics.map(({ key, network, macAddress }) => ({ key, network, macAddress })),
|
||||
[
|
||||
{ key: '4000', network: 'network-13', macAddress: '00:50:56:aa:bb:cc' },
|
||||
{ key: '4001', network: 'dvportgroup-5', macAddress: '00:50:56:aa:bb:cd' },
|
||||
]
|
||||
)
|
||||
})
|
||||
|
||||
it('does not fail on a VM without devices', function () {
|
||||
assert.deepEqual(parseDevices(undefined), { disks: [], nics: [] })
|
||||
})
|
||||
|
||||
it('keeps a disk on an unknown controller, under its device key', function () {
|
||||
const { disks } = parseDevices({
|
||||
VirtualDevice: typed('VirtualDisk', { key: '2001', controllerKey: '999', unitNumber: '0', capacityInKB: '1' }),
|
||||
})
|
||||
assert.equal(disks[0].key, 'device-2001')
|
||||
})
|
||||
})
|
||||
|
||||
describe('countSnapshots', function () {
|
||||
it('counts the snapshots at every depth of the tree', function () {
|
||||
const count = countSnapshots({
|
||||
snapshot: ref('VirtualMachineSnapshot', 'snapshot-1'),
|
||||
childSnapshotList: [
|
||||
{ snapshot: ref('VirtualMachineSnapshot', 'snapshot-2') },
|
||||
{
|
||||
snapshot: ref('VirtualMachineSnapshot', 'snapshot-3'),
|
||||
childSnapshotList: { snapshot: ref('VirtualMachineSnapshot', 'snapshot-4') },
|
||||
},
|
||||
],
|
||||
})
|
||||
assert.equal(count, 4)
|
||||
})
|
||||
|
||||
it('is zero without snapshot', function () {
|
||||
assert.equal(countSnapshots(undefined), 0)
|
||||
})
|
||||
})
|
||||
|
||||
describe('parseVlan', function () {
|
||||
it('reads a single VLAN id', function () {
|
||||
assert.equal(parseVlan({ vlan: { vlanId: '42' } }), 42)
|
||||
assert.equal(parseVlan({ vlan: { vlanId: { $value: '0', attributes: {} } } }), 0)
|
||||
})
|
||||
|
||||
it('reads the ranges of a trunk', function () {
|
||||
assert.deepEqual(parseVlan({ vlan: { vlanId: { start: '1', end: '4094' } } }), [{ start: 1, end: 4094 }])
|
||||
})
|
||||
|
||||
it('returns undefined without VLAN', function () {
|
||||
assert.equal(parseVlan(undefined), undefined)
|
||||
})
|
||||
})
|
||||
|
||||
describe('findDatacenter', function () {
|
||||
const datacenterIds = new Set(['datacenter-1'])
|
||||
|
||||
it('walks up the nested folders', function () {
|
||||
const parents = new Map([
|
||||
['host-10', 'domain-s9'],
|
||||
['domain-s9', 'group-h20'],
|
||||
['group-h20', 'group-h4'],
|
||||
['group-h4', 'datacenter-1'],
|
||||
])
|
||||
|
||||
assert.equal(findDatacenter('host-10', parents, datacenterIds), 'datacenter-1')
|
||||
})
|
||||
|
||||
it('is undefined for an object outside of any datacenter, or a parent loop', function () {
|
||||
assert.equal(findDatacenter('host-10', new Map([['host-10', 'group-d1']]), datacenterIds), undefined)
|
||||
assert.equal(findDatacenter(undefined, new Map(), datacenterIds), undefined)
|
||||
const loop = new Map([
|
||||
['group-a', 'group-b'],
|
||||
['group-b', 'group-a'],
|
||||
])
|
||||
assert.equal(findDatacenter('group-a', loop, datacenterIds), undefined)
|
||||
})
|
||||
})
|
||||
@@ -6,6 +6,7 @@ import { setTimeout as delay } from 'node:timers/promises'
|
||||
import { Agent } from 'undici'
|
||||
|
||||
import { parseDatastorePath, resolveDiskLocation } from './_paths.mjs'
|
||||
import { buildInventory, parseDevices, reachingHostIds } from './_inventory.mjs'
|
||||
import { getCertificateThumbprint } from './_thumbprint.mjs'
|
||||
import { formatVecturaArgs, VECTURA_BIN } from './_vectura.mjs'
|
||||
import { COWD_HEADER_LENGTH, grainDirectoryToDataMap, parseCowdHeader } from './parsers/cowd.mjs'
|
||||
@@ -162,23 +163,6 @@ const READ_ONLY_DISK_MODE = 'independent_nonpersistent'
|
||||
// the SOAP library does not always convert the booleans of the answer
|
||||
const isTrue = value => String(value) === 'true'
|
||||
|
||||
/**
|
||||
* The hosts which mount a datastore and can reach it.
|
||||
*
|
||||
* @param {unknown} mounts - value of the `host` property of the datastore
|
||||
* @returns {Set<string>} managed object references of the hosts
|
||||
*/
|
||||
function reachingHostIds(mounts) {
|
||||
const hostIds = new Set()
|
||||
for (const { key, mountInfo } of asArray(mounts?.DatastoreHostMount)) {
|
||||
if (isTrue(mountInfo?.mounted) && isTrue(mountInfo?.accessible)) {
|
||||
// the references nested in the value are not normalized, only the value itself is
|
||||
hostIds.add(key?.$value ?? key)
|
||||
}
|
||||
}
|
||||
return hostIds
|
||||
}
|
||||
|
||||
const isScsiController = device => SCSI_CONTROLLER_TYPES.has(device?.attributes?.['xsi:type'])
|
||||
|
||||
/**
|
||||
@@ -600,6 +584,81 @@ export default class Esxi extends EventEmitter {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The instance UUID of the vCenter, a standalone ESXi has none.
|
||||
*
|
||||
* @returns {string | undefined}
|
||||
*/
|
||||
get instanceUuid() {
|
||||
/** @type {{ serviceContent?: { about?: import('./_inventory.mjs').RawAboutInfo } }} */
|
||||
const vimClient = this.#vimClient
|
||||
return vimClient.serviceContent?.about?.instanceUuid
|
||||
}
|
||||
|
||||
/**
|
||||
* Everything needed to choose what to migrate and where: the whole inventory, read once.
|
||||
*
|
||||
* Only the properties used are requested: `config` as a whole is large, and read for every VM.
|
||||
* The objects reference each other through their managed object references.
|
||||
*
|
||||
* The device list of every VM is built: the wizard shows the disks and the network cards of all of
|
||||
* them, and a start reads the inventory again so that it is planned against the current state.
|
||||
*
|
||||
* @returns {Promise<import('@vates/types').VmwareInventory>}
|
||||
*/
|
||||
async getInventory() {
|
||||
await this.#connected
|
||||
/** @type {[Record<string, import('./_inventory.mjs').RawDatacenter>, Record<string, import('./_inventory.mjs').RawCluster>, Record<string, import('./_inventory.mjs').RawHost>, Record<string, import('./_inventory.mjs').RawDatastore>, Record<string, import('./_inventory.mjs').RawNetwork>, Record<string, import('./_inventory.mjs').RawPortgroup>, Record<string, import('./_inventory.mjs').RawVm>, Record<string, import('./_inventory.mjs').RawChild>, Record<string, import('./_inventory.mjs').RawChild>]} */
|
||||
const [datacenters, clusters, hosts, datastores, networks, portgroups, vms, folders, computeResources] =
|
||||
await Promise.all([
|
||||
this.search('Datacenter', ['name']),
|
||||
this.search('ClusterComputeResource', ['name', 'parent']),
|
||||
this.search('HostSystem', ['name', 'parent']),
|
||||
this.search('Datastore', ['summary', 'host']),
|
||||
// the distributed port groups are networks too, with more properties of their own below
|
||||
this.search('Network', ['name']),
|
||||
this.search('DistributedVirtualPortgroup', ['name', 'key', 'config.defaultPortConfig']),
|
||||
this.search('VirtualMachine', [
|
||||
'config.name',
|
||||
'config.annotation',
|
||||
'config.instanceUuid',
|
||||
'config.firmware',
|
||||
'config.bootOptions.efiSecureBootEnabled',
|
||||
'config.template',
|
||||
'config.hardware.numCPU',
|
||||
'config.hardware.memoryMB',
|
||||
'config.hardware.device',
|
||||
'runtime.powerState',
|
||||
'runtime.host',
|
||||
'datastore',
|
||||
'snapshot',
|
||||
]),
|
||||
// only to walk up from a host or a cluster to its datacenter. A compute resource is the parent
|
||||
// of a standalone host, and the clusters are compute resources too
|
||||
this.search('Folder', ['parent']),
|
||||
this.search('ComputeResource', ['parent']),
|
||||
])
|
||||
|
||||
// AboutInfo: `instanceUuid` is only set by a vCenter, `apiType` is `VirtualCenter` or `HostAgent`
|
||||
/** @type {{ serviceContent?: { about?: import('./_inventory.mjs').RawAboutInfo } }} */
|
||||
const vimClient = this.#vimClient
|
||||
/** @type {import('./_inventory.mjs').RawAboutInfo} */
|
||||
const about = vimClient.serviceContent?.about ?? {}
|
||||
|
||||
return buildInventory({
|
||||
about,
|
||||
datacenters,
|
||||
clusters,
|
||||
hosts,
|
||||
datastores,
|
||||
networks,
|
||||
portgroups,
|
||||
vms,
|
||||
folders,
|
||||
computeResources,
|
||||
})
|
||||
}
|
||||
|
||||
async getAllVmMetadata() {
|
||||
const datas = await this.search('VirtualMachine', ['config', 'storage', 'runtime', 'layoutEx'])
|
||||
|
||||
@@ -688,45 +747,46 @@ export default class Esxi extends EventEmitter {
|
||||
})
|
||||
|
||||
const diskReferences = []
|
||||
const networks = []
|
||||
let cdrom = false
|
||||
|
||||
for (const key of Object.keys(vmx)) {
|
||||
const channelMatches = key.match(/^(scsi|ide|ethernet|sata)[0-9]+$/)
|
||||
const channelMatches = key.match(/^(scsi|ide|sata)[0-9]+$/)
|
||||
if (channelMatches === null) {
|
||||
continue
|
||||
}
|
||||
const channelType = channelMatches[1]
|
||||
if (channelType === 'ide' || channelType === 'scsi' || channelType === 'sata' /* cdrom */) {
|
||||
const diskChannel = vmx[key]
|
||||
// the indexes of the channel are its own: iterating the compacted values used to label a
|
||||
// channel holding only `scsi0:1` as `scsi0:0`, and `node` is the disk identity used to
|
||||
// build the chains and to order the VBDs
|
||||
for (const [diskIndex, disk] of Object.entries(diskChannel)) {
|
||||
if (typeof disk !== 'object' || disk === null) {
|
||||
continue
|
||||
}
|
||||
if (disk.deviceType?.match(/cdrom/i)) {
|
||||
cdrom = true
|
||||
continue
|
||||
}
|
||||
// can be something other than a disk, like a controller card
|
||||
if (channelType === 'scsi' && disk.deviceType !== 'scsi-hardDisk') {
|
||||
continue
|
||||
}
|
||||
|
||||
diskReferences.push({ fileName: disk.fileName, node: `${key}:${diskIndex}` })
|
||||
const diskChannel = vmx[key]
|
||||
// the indexes of the channel are its own: iterating the compacted values used to label a
|
||||
// channel holding only `scsi0:1` as `scsi0:0`, and `node` is the disk identity used to
|
||||
// build the chains and to order the VBDs
|
||||
for (const [diskIndex, disk] of Object.entries(diskChannel)) {
|
||||
if (typeof disk !== 'object' || disk === null) {
|
||||
continue
|
||||
}
|
||||
if (disk.deviceType?.match(/cdrom/i)) {
|
||||
cdrom = true
|
||||
continue
|
||||
}
|
||||
// can be something other than a disk, like a controller card
|
||||
if (channelType === 'scsi' && disk.deviceType !== 'scsi-hardDisk') {
|
||||
continue
|
||||
}
|
||||
} else if (channelType === 'ethernet') {
|
||||
const ethernet = vmx[key]
|
||||
|
||||
networks.push({
|
||||
label: ethernet.networkName,
|
||||
macAddress: ethernet.generatedAddress,
|
||||
isGenerated: ethernet.addressType === 'generated',
|
||||
})
|
||||
diskReferences.push({ fileName: disk.fileName, node: `${key}:${diskIndex}` })
|
||||
}
|
||||
}
|
||||
|
||||
// the cards are read from the devices and not from the vmx: they carry the key the inventory names
|
||||
// them by, the vmx only has the address of a generated MAC, and lists the cards which are not present
|
||||
const networks = parseDevices(config.hardware?.device).nics.map(
|
||||
({ key, label, macAddress, addressType, network }) => ({
|
||||
key,
|
||||
label,
|
||||
macAddress,
|
||||
isGenerated: addressType === 'generated',
|
||||
network,
|
||||
})
|
||||
)
|
||||
const inspect = fileName => this.#inspectVmdk(dataStores, dataStore, dirname(vmxPath), fileName, { signal })
|
||||
|
||||
// one descriptor to download per disk: read serially, a long chain added a full round trip per
|
||||
@@ -781,6 +841,8 @@ export default class Esxi extends EventEmitter {
|
||||
guestId: config.guestId,
|
||||
guestFullName: config.guestFullName,
|
||||
firmware: config.firmware === 'efi' ? 'uefi' : config.firmware, // bios or uefi
|
||||
// unlike the moref, it survives the VM being unregistered and registered again
|
||||
instanceUuid: config.instanceUuid,
|
||||
powerState: runtime.powerState,
|
||||
snapshots,
|
||||
cdrom,
|
||||
|
||||
@@ -119,6 +119,111 @@ describe('search', function () {
|
||||
})
|
||||
})
|
||||
|
||||
describe('getInventory', function () {
|
||||
it('reads every kind of object once, with the properties it needs only', async function () {
|
||||
const typesByPage = {
|
||||
Datacenter: DATACENTERS,
|
||||
HostSystem: [
|
||||
{
|
||||
obj: moRef('HostSystem', 'host-10'),
|
||||
propSet: [
|
||||
{ name: 'name', val: { $value: 'esx1' } },
|
||||
{ name: 'parent', val: moRef('ClusterComputeResource', 'domain-c7') },
|
||||
],
|
||||
},
|
||||
],
|
||||
// the cluster sits in a subfolder of the host folder of its datacenter
|
||||
ComputeResource: [
|
||||
{
|
||||
obj: moRef('ClusterComputeResource', 'domain-c7'),
|
||||
propSet: { name: 'parent', val: moRef('Folder', 'group-h20') },
|
||||
},
|
||||
],
|
||||
Folder: [
|
||||
{ obj: moRef('Folder', 'group-h20'), propSet: { name: 'parent', val: moRef('Folder', 'group-h4') } },
|
||||
{ obj: moRef('Folder', 'group-h4'), propSet: { name: 'parent', val: moRef('Datacenter', 'datacenter-1') } },
|
||||
],
|
||||
Datastore: [
|
||||
{
|
||||
obj: moRef('Datastore', 'datastore-11'),
|
||||
propSet: [
|
||||
{ name: 'summary', val: { name: 'ds1', accessible: 'true' } },
|
||||
{
|
||||
name: 'host',
|
||||
val: {
|
||||
DatastoreHostMount: [
|
||||
{ key: moRef('HostSystem', 'host-10'), mountInfo: { mounted: 'true', accessible: 'true' } },
|
||||
{ key: moRef('HostSystem', 'host-11'), mountInfo: { mounted: 'true', accessible: 'false' } },
|
||||
],
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
Network: [{ obj: moRef('DistributedVirtualPortgroup', 'dvportgroup-5'), propSet: { name: 'name', val: 'prod' } }],
|
||||
DistributedVirtualPortgroup: [
|
||||
{
|
||||
obj: moRef('DistributedVirtualPortgroup', 'dvportgroup-5'),
|
||||
propSet: [
|
||||
{ name: 'key', val: 'dvpg-key' },
|
||||
{ name: 'config.defaultPortConfig', val: { attributes: {}, vlan: { vlanId: '12' } } },
|
||||
],
|
||||
},
|
||||
],
|
||||
VirtualMachine: [
|
||||
{
|
||||
obj: moRef('VirtualMachine', 'vm-1'),
|
||||
propSet: [
|
||||
{ name: 'config.name', val: 'web' },
|
||||
{ name: 'config.firmware', val: 'efi' },
|
||||
{ name: 'config.hardware.memoryMB', val: '1024' },
|
||||
{ name: 'runtime.powerState', val: 'poweredOn' },
|
||||
{ name: 'runtime.host', val: moRef('HostSystem', 'host-10') },
|
||||
{
|
||||
name: 'config.hardware.device',
|
||||
val: {
|
||||
attributes: { 'xsi:type': 'ArrayOfVirtualDevice' },
|
||||
VirtualDevice: {
|
||||
attributes: { 'xsi:type': 'VirtualVmxnet3' },
|
||||
key: '4000',
|
||||
macAddress: '00:50:56:aa:bb:cc',
|
||||
backing: { port: { portgroupKey: 'dvpg-key' } },
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
const { esxi, vimClient } = await connectedEsxi({
|
||||
responses: { RetrievePropertiesEx: ({ specSet }) => page(typesByPage[specSet[0].propSet[0].type] ?? []) },
|
||||
})
|
||||
vimClient.serviceContent.about = { name: 'VMware vCenter Server', instanceUuid: 'vc-1' }
|
||||
|
||||
const inventory = await esxi.getInventory()
|
||||
|
||||
const requested = vimClient.callsTo('RetrievePropertiesEx').map(({ args }) => args.specSet[0].propSet[0])
|
||||
const vmSpec = requested.find(({ type }) => type === 'VirtualMachine')
|
||||
assert.ok(!vmSpec.pathSet.includes('config'), 'the whole config is never requested')
|
||||
assert.equal(vimClient.callsTo('DestroyView').length, requested.length)
|
||||
|
||||
assert.equal(inventory.product, 'VMware vCenter Server')
|
||||
assert.equal(inventory.instanceUuid, 'vc-1')
|
||||
assert.deepEqual(inventory.hosts, [
|
||||
{ id: 'host-10', name: 'esx1', parent: 'domain-c7', datacenter: 'datacenter-1' },
|
||||
])
|
||||
assert.deepEqual(inventory.datastores[0].hosts, ['host-10'], 'only the hosts which can reach the datastore')
|
||||
assert.deepEqual(inventory.networks, [{ id: 'dvportgroup-5', name: 'prod', distributed: true, vlan: 12 }])
|
||||
const [vm] = inventory.vms
|
||||
assert.equal(vm.id, 'vm-1')
|
||||
assert.equal(vm.firmware, 'uefi')
|
||||
assert.equal(vm.memory, 1024 * 1024 * 1024)
|
||||
assert.equal(vm.host, 'host-10')
|
||||
assert.equal(vm.nics[0].network, 'dvportgroup-5')
|
||||
assert.deepEqual(vm.disks, [])
|
||||
})
|
||||
})
|
||||
|
||||
describe('connection', function () {
|
||||
it('emits ready once the datacenters are known, without one request per datastore', async function () {
|
||||
const vimClient = new FakeVimClient()
|
||||
@@ -1236,7 +1341,30 @@ RW 67108864 VMFS "vm-000001-flat.vmdk"
|
||||
guestFullName: 'Ubuntu Linux (64-bit)',
|
||||
firmware: 'efi',
|
||||
files: { vmPathName },
|
||||
hardware: { memoryMB: '2048', numCPU: '2' },
|
||||
hardware: {
|
||||
memoryMB: '2048',
|
||||
numCPU: '2',
|
||||
device: {
|
||||
attributes: { 'xsi:type': 'ArrayOfVirtualDevice' },
|
||||
VirtualDevice: [
|
||||
{
|
||||
attributes: { 'xsi:type': 'VirtualVmxnet3' },
|
||||
key: '4000',
|
||||
deviceInfo: { label: 'Network adapter 1' },
|
||||
macAddress: '00:0c:29:00:00:01',
|
||||
addressType: 'generated',
|
||||
backing: { network: moRef('Network', 'network-13') },
|
||||
},
|
||||
{
|
||||
attributes: { 'xsi:type': 'VirtualE1000e' },
|
||||
key: '4001',
|
||||
deviceInfo: { label: 'Network adapter 2' },
|
||||
macAddress: '00:50:56:00:00:02',
|
||||
addressType: 'manual',
|
||||
},
|
||||
],
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
const RUNTIME = { attributes: { 'xsi:type': 'VirtualMachineRuntimeInfo' }, powerState: 'poweredOn' }
|
||||
@@ -1312,7 +1440,23 @@ RW 67108864 VMFS "vm-000001-flat.vmdk"
|
||||
assert.equal(metadata.memory, 2048 * 1024 * 1024)
|
||||
assert.equal(metadata.nCpus, 2)
|
||||
assert.equal(metadata.cdrom, true)
|
||||
assert.deepEqual(metadata.networks, [{ label: 'VM Network', macAddress: '00:0c:29:00:00:01', isGenerated: true }])
|
||||
assert.deepEqual(metadata.networks, [
|
||||
{
|
||||
key: '4000',
|
||||
label: 'Network adapter 1',
|
||||
macAddress: '00:0c:29:00:00:01',
|
||||
isGenerated: true,
|
||||
network: 'network-13',
|
||||
},
|
||||
// a MAC set by hand is not in the vmx as a generated one: it used to be lost
|
||||
{
|
||||
key: '4001',
|
||||
label: 'Network adapter 2',
|
||||
macAddress: '00:50:56:00:00:02',
|
||||
isGenerated: false,
|
||||
network: undefined,
|
||||
},
|
||||
])
|
||||
})
|
||||
|
||||
it('treats a missing vmsd as a VM without snapshot', async function () {
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
/**
|
||||
* The SOAP library returns a single element as the element itself, and a repeated one as an array.
|
||||
*
|
||||
* @param {unknown} value
|
||||
* @returns {Array<unknown>} - an empty array when the element is absent
|
||||
* @template T
|
||||
* @param {T | T[] | undefined | null} value
|
||||
* @returns {Array<T>} - an empty array when the element is absent
|
||||
*/
|
||||
export function asArray(value) {
|
||||
if (value === undefined || value === null) {
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user