mirror of
https://github.com/vatesfr/xen-orchestra.git
synced 2026-11-16 20:11:12 -06:00
Compare commits
42 Commits
feat_sort_
...
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 | ||
|
|
2e67209418 | ||
|
|
03e93498fd | ||
|
|
50166fe3a4 | ||
|
|
724402733b | ||
|
|
abbe24631d | ||
|
|
8e81250ca3 | ||
|
|
c8c11ae63c | ||
|
|
8df236a512 | ||
|
|
8cc3384850 | ||
|
|
e4cc8df323 | ||
|
|
43a7e3d3ac | ||
|
|
2e586f0369 | ||
|
|
93dc079f71 | ||
|
|
9c6a59bb89 | ||
|
|
12aa9576b9 | ||
|
|
85541ce5d7 | ||
|
|
56a33c1639 | ||
|
|
7f6ea616ca | ||
|
|
5601a64703 |
@@ -11,6 +11,10 @@
|
||||
"./xo": "./dist/xo.d.mts",
|
||||
"./xo-app": "./dist/xo-app.d.mts",
|
||||
"./xen-api": "./dist/xen-api.d.mts",
|
||||
"./backup-expression-context": {
|
||||
"default": "./dist/backup-expression-context.mjs",
|
||||
"types": "./dist/backup-expression-context.d.mts"
|
||||
},
|
||||
"./common": {
|
||||
"default": "./dist/common.mjs",
|
||||
"types": "./dist/common.d.mts"
|
||||
|
||||
38
@vates/types/src/backup-expression-context.mts
Normal file
38
@vates/types/src/backup-expression-context.mts
Normal file
@@ -0,0 +1,38 @@
|
||||
export const BACKUP_EXPRESSION_CONTEXT = {
|
||||
run: {
|
||||
dayOfWeek: { type: 'number' },
|
||||
dayOfMonth: { type: 'number' },
|
||||
hour: { type: 'number' },
|
||||
month: { type: 'number' },
|
||||
year: { type: 'number' },
|
||||
},
|
||||
sr: {
|
||||
name_label: { type: 'string' },
|
||||
type: { type: 'string' },
|
||||
description: { type: 'string' },
|
||||
tags: { type: 'string[]' },
|
||||
},
|
||||
backupRepository: {
|
||||
name: { type: 'string' },
|
||||
type: { type: 'string' },
|
||||
tags: { type: 'string[]' },
|
||||
},
|
||||
vm: {
|
||||
name_label: { type: 'string' },
|
||||
tags: { type: 'string[]' },
|
||||
power_state: { type: 'string' },
|
||||
},
|
||||
chainLength: { type: 'number' },
|
||||
} as const
|
||||
|
||||
export type BACKUP_EXPRESSION_CONTEXT = (typeof BACKUP_EXPRESSION_CONTEXT)[keyof typeof BACKUP_EXPRESSION_CONTEXT]
|
||||
|
||||
export const BACKUP_SETTING_CONTEXT = {
|
||||
healthCheckVmsWithTags: ['vm', 'run'],
|
||||
fullInterval: ['vm', 'run', 'chainLength'],
|
||||
vmFilter: ['vm', 'run'],
|
||||
srs: ['sr', 'run'],
|
||||
remotes: ['backupRepository', 'run'],
|
||||
} as const
|
||||
|
||||
export type BACKUP_SETTING_CONTEXT = (typeof BACKUP_SETTING_CONTEXT)[keyof typeof BACKUP_SETTING_CONTEXT]
|
||||
@@ -772,6 +772,7 @@ export type RawTrafficRule = {
|
||||
ipRange: string
|
||||
direction: TrafficRuleDirection
|
||||
port?: string
|
||||
priority?: number
|
||||
}
|
||||
|
||||
type BaseTrafficRule = RawTrafficRule & {
|
||||
|
||||
@@ -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,12 +3,16 @@ import type {
|
||||
AnyXoJob,
|
||||
AnyXoLog,
|
||||
NonXapiXoRecord,
|
||||
XoBackupDiskPartition,
|
||||
XapiXoRecord,
|
||||
XoAuthenticationToken,
|
||||
XoBackupRepository,
|
||||
XoConfigBackupArchive,
|
||||
XoGroup,
|
||||
XoHost,
|
||||
XoMetadataBackupJob,
|
||||
XoMirrorBackupJob,
|
||||
XoNetwork,
|
||||
XoPlugin,
|
||||
XoPool,
|
||||
XoPoolBackupArchive,
|
||||
@@ -21,9 +25,13 @@ import type {
|
||||
XoVif,
|
||||
XoVm,
|
||||
XoVmBackupArchive,
|
||||
XoVmBackupJob,
|
||||
XoVmTemplate,
|
||||
} from './xo.mjs'
|
||||
import { VatesTask } from './lib/vates-task.mjs'
|
||||
import type { PluginRestRouteDefinition } from './lib/rest-api.mjs'
|
||||
import type { VmwareInventory } from './lib/xen-orchestra-vmware-explorer.mjs'
|
||||
import type { XoV2vStatus } from './lib/xen-orchestra-v2v.mjs'
|
||||
import type { RPU_RECOVERY_STEP_NAME } from './common.mjs'
|
||||
import {
|
||||
Xapi,
|
||||
@@ -202,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: {
|
||||
@@ -282,6 +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>
|
||||
/* 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) */
|
||||
@@ -309,6 +328,17 @@ export type XoApp = EventEmitter & {
|
||||
set(key: string, value: unknown): void
|
||||
unset(key: string): void
|
||||
}
|
||||
createBackupNgJob<T extends XoVmBackupJob | XoMirrorBackupJob>(
|
||||
type: T['type'],
|
||||
props: Omit<T, 'id' | 'type'>,
|
||||
/** keyed by temporary IDs, which can be used as keys in `props.settings` */
|
||||
schedules?: Record<string, Pick<XoSchedule, 'cron' | 'enabled' | 'name' | 'timezone'>>
|
||||
): Promise<T>
|
||||
createMetadataBackupJob(
|
||||
props: Omit<XoMetadataBackupJob, 'id' | 'type'>,
|
||||
/** keyed by temporary IDs, which can be used as keys in `props.settings` */
|
||||
schedules: Record<string, Pick<XoSchedule, 'cron' | 'enabled' | 'name' | 'timezone'>>
|
||||
): Promise<XoMetadataBackupJob>
|
||||
createAuthenticationToken(opts: {
|
||||
client?: {
|
||||
id?: string
|
||||
@@ -324,6 +354,14 @@ export type XoApp = EventEmitter & {
|
||||
proxy?: XoProxy['id']
|
||||
url: string
|
||||
}): Promise<XoBackupRepository>
|
||||
createSchedule(params: {
|
||||
cron: XoSchedule['cron']
|
||||
enabled: XoSchedule['enabled']
|
||||
jobId: XoSchedule['jobId']
|
||||
name?: XoSchedule['name']
|
||||
timezone?: XoSchedule['timezone']
|
||||
userId?: XoUser['id']
|
||||
}): Promise<XoSchedule>
|
||||
createUser(params: {
|
||||
firstname?: string
|
||||
lastname?: string
|
||||
@@ -340,6 +378,7 @@ export type XoApp = EventEmitter & {
|
||||
deleteAclV2Privilege(privilegeId: XoAclBasePrivilege['id'], options?: { force?: boolean }): Promise<boolean>
|
||||
deleteAclV2Role(roleId: XoAclRole['id'], options?: { force?: boolean }): Promise<boolean>
|
||||
deleteGroup(id: XoGroup['id']): Promise<void>
|
||||
deleteSchedule(id: XoSchedule['id']): Promise<void>
|
||||
deleteUser(id: XoUser['id']): Promise<void>
|
||||
detachHostFromPool(hostId: XoHost['id']): Promise<void>
|
||||
createGroup(params: { name: string; provider?: string; providerGroup?: string }): Promise<XoGroup>
|
||||
@@ -378,6 +417,8 @@ export type XoApp = EventEmitter & {
|
||||
getRemote(id: XoBackupRepository['id']): Promise<XoBackupRepository>
|
||||
getAllRemotes(): Promise<XoBackupRepository[]>
|
||||
removeRemote(id: XoBackupRepository['id']): Promise<void>
|
||||
/** Also deletes the schedules of the job */
|
||||
removeJob(id: AnyXoJob['id']): Promise<void>
|
||||
getAllRemotesInfo(): Promise<
|
||||
Record<
|
||||
XoBackupRepository['id'],
|
||||
@@ -441,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>(
|
||||
@@ -456,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[]>
|
||||
@@ -466,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`.
|
||||
@@ -543,6 +616,19 @@ export type XoApp = EventEmitter & {
|
||||
): Promise<{ vmUuid: string; success: boolean; merge?: boolean; size?: number; error?: string }[]>
|
||||
/** Remove a server from the DB (XCP-ng/XenServer) */
|
||||
unregisterXenServer(id: XoServer['id']): Promise<void>
|
||||
/**
|
||||
* Shallow merge of the properties into the existing job, a `null` value removes the property.
|
||||
*/
|
||||
updateJob(job: { id: AnyXoJob['id']; [key: string]: unknown }, merge?: boolean): Promise<void>
|
||||
updateSchedule(params: {
|
||||
id: XoSchedule['id']
|
||||
cron?: XoSchedule['cron']
|
||||
enabled?: XoSchedule['enabled']
|
||||
jobId?: XoSchedule['jobId']
|
||||
name?: XoSchedule['name']
|
||||
timezone?: XoSchedule['timezone']
|
||||
userId?: XoUser['id']
|
||||
}): Promise<void>
|
||||
updateUser(
|
||||
id: XoUser['id'],
|
||||
updates: {
|
||||
|
||||
@@ -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'
|
||||
@@ -530,15 +539,22 @@ type XoBackupJobGeneralSettings = {
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
/**
|
||||
* Keeps the last backup of each of the last `retention` days/weeks/months/years, in addition to `exportRetention`.
|
||||
*
|
||||
* Requires the `timezone` setting.
|
||||
*/
|
||||
export type XoBackupJobLongTermRetention = {
|
||||
daily?: { retention: number; settings: Record<string, unknown> }
|
||||
weekly?: { retention: number; settings: Record<string, unknown> }
|
||||
monthly?: { retention: number; settings: Record<string, unknown> }
|
||||
yearly?: { retention: number; settings: Record<string, unknown> }
|
||||
}
|
||||
|
||||
export type XoVmBackupJobGeneralSettings = XoBackupJobGeneralSettings & {
|
||||
cbtDestroySnapshotData?: boolean
|
||||
concurrency?: number
|
||||
longTermRetention?: {
|
||||
daily?: { retention: number; settings: Record<string, unknown> }
|
||||
weekly?: { retention: number; settings: Record<string, unknown> }
|
||||
monthly?: { retention: number; settings: Record<string, unknown> }
|
||||
yearly?: { retention: number; settings: Record<string, unknown> }
|
||||
}
|
||||
longTermRetention?: XoBackupJobLongTermRetention
|
||||
checkpointSnapshot?: boolean
|
||||
offlineSnapshot?: boolean
|
||||
maxExportRate?: number
|
||||
@@ -552,8 +568,8 @@ export type XoVmBackupJobGeneralSettings = XoBackupJobGeneralSettings & {
|
||||
}
|
||||
export type XoVmBackupJobScheduleSettings = {
|
||||
exportRetention?: number
|
||||
healthCheckVmsWithTags?: XoVm['tags']
|
||||
fullInterval?: number
|
||||
healthCheckVmsWithTags?: XoVm['tags'] | string
|
||||
fullInterval?: number | string
|
||||
copyRetention?: number
|
||||
snapshotRetention?: number
|
||||
cbtDestroySnapshotData?: boolean
|
||||
@@ -564,9 +580,9 @@ export type XoVmBackupJob = BaseXoJob & {
|
||||
compression?: 'native' | 'zstd' | ''
|
||||
proxy?: XoProxy['id']
|
||||
mode: 'full' | 'delta'
|
||||
remotes?: CMType.IdOr<XoBackupRepository['id']>
|
||||
remotes?: CMType.IdOr<XoBackupRepository['id']> | string
|
||||
vms: CMType.IdOr<XoVm['id']> | Record<string, unknown>
|
||||
srs?: CMType.IdOr<XoSr['id']>
|
||||
srs?: CMType.IdOr<XoSr['id']> | string
|
||||
type: 'backup'
|
||||
settings: {
|
||||
'': XoVmBackupJobGeneralSettings
|
||||
@@ -595,16 +611,17 @@ export type XoMetadataBackupJob = BaseXoJob & {
|
||||
|
||||
export type XoMirrorBackupGeneralSettings = XoBackupJobGeneralSettings & {
|
||||
concurrency?: number
|
||||
longTermRetention?: XoBackupJobLongTermRetention
|
||||
nRetriesVmBackupFailures?: number
|
||||
mergeBackupsSynchronously?: boolean
|
||||
timeout?: number
|
||||
timezone?: string
|
||||
maxExportRate?: number
|
||||
backupReportTpl?: 'compactMjml'
|
||||
reportWhen: 'failure'
|
||||
}
|
||||
export type XoMirrorBackupScheduleSettings = {
|
||||
exportRetention?: number
|
||||
healthCheckVmsWithTags?: XoVm['tags']
|
||||
healthCheckVmsWithTags?: XoVm['tags'] | string
|
||||
vmFilter?: string
|
||||
healthCheckSr?: XoSr['id']
|
||||
[key: string]: unknown
|
||||
}
|
||||
|
||||
@@ -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
|
||||
}
|
||||
|
||||
@@ -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 })
|
||||
}
|
||||
}
|
||||
|
||||
111
@xen-orchestra/backups/_buildContext.mjs
Normal file
111
@xen-orchestra/backups/_buildContext.mjs
Normal file
@@ -0,0 +1,111 @@
|
||||
// @ts-check
|
||||
|
||||
import { createLogger } from '@xen-orchestra/log'
|
||||
import moment from 'moment-timezone'
|
||||
import { parse } from 'xo-remote-parser'
|
||||
|
||||
const { warn } = createLogger('xo:backups:buildContext')
|
||||
|
||||
/**
|
||||
* @typedef {import('@vates/types/xen-api').XenApiVm} XenApiVm
|
||||
* @typedef {import('@vates/types/xo').XoSr} XoSr
|
||||
* @typedef {import('@vates/types/xo').XoBackupRepository} XoBackupRepository
|
||||
*
|
||||
* @typedef {object} RunContext
|
||||
* @property {number} dayOfWeek
|
||||
* @property {number} dayOfMonth
|
||||
* @property {number} hour
|
||||
* @property {number} month
|
||||
* @property {number} year
|
||||
*
|
||||
* @typedef {object} VmContext
|
||||
* @property {Record<string, unknown>} vm
|
||||
* @property {RunContext} run
|
||||
* @property {number} [chainLength]
|
||||
*
|
||||
* @typedef {object} SrContext
|
||||
* @property {{name_label: string, type: string, description: string, tags: string[]}} sr
|
||||
* @property {RunContext} run
|
||||
*
|
||||
* @typedef {object} BackupRepositoryContext
|
||||
* @property {{name: string, type: string | undefined, tags: string[]}} backupRepository
|
||||
* @property {RunContext} run
|
||||
*/
|
||||
|
||||
/**
|
||||
* @param {Date} date
|
||||
* @param {string | undefined} timezone
|
||||
* @returns {RunContext}
|
||||
*/
|
||||
export function buildRunContext(date, timezone) {
|
||||
const momentDate = timezone ? moment.tz(date, timezone) : moment(date)
|
||||
return {
|
||||
dayOfWeek: momentDate.day(),
|
||||
dayOfMonth: momentDate.date(),
|
||||
hour: momentDate.hour(),
|
||||
month: momentDate.month() + 1,
|
||||
year: momentDate.year(),
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {XenApiVm} vm
|
||||
* @param {RunContext} run
|
||||
* @param {number} [chainLength]
|
||||
* @returns {VmContext}
|
||||
*/
|
||||
export function buildVmContext(vm, run, chainLength) {
|
||||
/** @type {Record<string, unknown>} */
|
||||
const vmObject = {}
|
||||
for (const [key, value] of Object.entries(vm)) {
|
||||
if (!key.startsWith('$') && typeof value !== 'function') {
|
||||
vmObject[key] = value
|
||||
}
|
||||
}
|
||||
|
||||
if (!Array.isArray(vmObject.tags)) {
|
||||
vmObject.tags = []
|
||||
}
|
||||
|
||||
return { vm: vmObject, run, chainLength }
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {XoSr} sr
|
||||
* @param {RunContext} run
|
||||
* @returns {SrContext}
|
||||
*/
|
||||
export function buildSrContext(sr, run) {
|
||||
return {
|
||||
sr: {
|
||||
name_label: sr.name_label,
|
||||
type: sr.SR_type,
|
||||
description: sr.name_description,
|
||||
tags: Array.isArray(sr.tags) ? sr.tags : [],
|
||||
},
|
||||
run,
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {XoBackupRepository} backupRepository
|
||||
* @param {RunContext} run
|
||||
* @returns {BackupRepositoryContext}
|
||||
*/
|
||||
export function buildBackupRepositoryContext(backupRepository, run) {
|
||||
let type
|
||||
try {
|
||||
type = parse(backupRepository.url).type
|
||||
} catch (error) {
|
||||
warn('cannot parse backup repository URL', { backupRepositoryId: backupRepository.id, error })
|
||||
}
|
||||
|
||||
return {
|
||||
backupRepository: {
|
||||
name: backupRepository.name,
|
||||
type,
|
||||
tags: [], // Placeholder - Backup repositories don't have tags yet
|
||||
},
|
||||
run,
|
||||
}
|
||||
}
|
||||
147
@xen-orchestra/backups/_buildContext.test.mjs
Normal file
147
@xen-orchestra/backups/_buildContext.test.mjs
Normal file
@@ -0,0 +1,147 @@
|
||||
import { describe, it } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
|
||||
import { buildRunContext, buildVmContext, buildSrContext, buildBackupRepositoryContext } from './_buildContext.mjs'
|
||||
import { BACKUP_EXPRESSION_CONTEXT } from '@vates/types/backup-expression-context'
|
||||
|
||||
describe('buildContext', () => {
|
||||
const date = new Date('2025-01-05T03:00:00Z')
|
||||
const runContext = buildRunContext(date, 'America/New_York')
|
||||
const expectedRunContext = {
|
||||
dayOfWeek: 6,
|
||||
dayOfMonth: 4,
|
||||
hour: 22,
|
||||
month: 1,
|
||||
year: 2025,
|
||||
}
|
||||
|
||||
it('buildRunContext', () => {
|
||||
assert.deepEqual(runContext, expectedRunContext)
|
||||
})
|
||||
|
||||
it('buildVmContext', () => {
|
||||
const vm1 = { name: 'name', $value: '$value', func: () => {} }
|
||||
const vmContext1 = buildVmContext(vm1, runContext, 3)
|
||||
assert.deepEqual(vmContext1, {
|
||||
vm: {
|
||||
name: 'name',
|
||||
tags: [],
|
||||
},
|
||||
run: expectedRunContext,
|
||||
chainLength: 3,
|
||||
})
|
||||
|
||||
const vm2 = { name: 'name', $value: '$value', func: () => {}, tags: ['tag'] }
|
||||
const vmContext2 = buildVmContext(vm2, runContext, undefined)
|
||||
assert.deepEqual(vmContext2, {
|
||||
vm: {
|
||||
name: 'name',
|
||||
tags: ['tag'],
|
||||
},
|
||||
run: expectedRunContext,
|
||||
chainLength: undefined,
|
||||
})
|
||||
|
||||
const vm3 = { name: 'name', $value: '$value', func: () => {}, tags: 'tag' }
|
||||
const vmContext3 = buildVmContext(vm3, runContext, undefined)
|
||||
assert.deepEqual(vmContext3, {
|
||||
vm: {
|
||||
name: 'name',
|
||||
tags: [],
|
||||
},
|
||||
run: expectedRunContext,
|
||||
chainLength: undefined,
|
||||
})
|
||||
})
|
||||
|
||||
it('buildVmContext exposes every field advertised by the schema', () => {
|
||||
// vm is an open context (buildVmContext copies through all real VM fields),
|
||||
// so we assert the schema's curated fields are a subset of the output, not equality.
|
||||
const vm = { name_label: 'name', power_state: 'Running', tags: ['tag'], $ref: 'ref', func: () => {} }
|
||||
const { vm: vmContext } = buildVmContext(vm, runContext)
|
||||
|
||||
for (const field of Object.keys(BACKUP_EXPRESSION_CONTEXT.vm)) {
|
||||
assert.ok(field in vmContext, `vm context is missing schema field: ${field}`)
|
||||
}
|
||||
})
|
||||
|
||||
it('buildSrContext', () => {
|
||||
const sr1 = {
|
||||
name_label: 'name_label',
|
||||
SR_type: 'type',
|
||||
name_description: 'description',
|
||||
ignored: 'ignored',
|
||||
}
|
||||
const srContext1 = buildSrContext(sr1, runContext)
|
||||
assert.deepEqual(srContext1, {
|
||||
sr: {
|
||||
name_label: 'name_label',
|
||||
type: 'type',
|
||||
description: 'description',
|
||||
tags: [],
|
||||
},
|
||||
run: expectedRunContext,
|
||||
})
|
||||
assert.deepEqual(Object.keys(srContext1.sr).sort(), Object.keys(BACKUP_EXPRESSION_CONTEXT.sr).sort())
|
||||
|
||||
const sr2 = {
|
||||
name_label: 'name_label',
|
||||
SR_type: 'type',
|
||||
name_description: 'description',
|
||||
tags: ['tag'],
|
||||
ignored: 'ignored',
|
||||
}
|
||||
const srContext2 = buildSrContext(sr2, runContext)
|
||||
assert.deepEqual(srContext2, {
|
||||
sr: {
|
||||
name_label: 'name_label',
|
||||
type: 'type',
|
||||
description: 'description',
|
||||
tags: ['tag'],
|
||||
},
|
||||
run: expectedRunContext,
|
||||
})
|
||||
assert.deepEqual(Object.keys(srContext2.sr).sort(), Object.keys(BACKUP_EXPRESSION_CONTEXT.sr).sort())
|
||||
})
|
||||
|
||||
it('buildBackupRepositoryContext', () => {
|
||||
const backupRepository1 = {
|
||||
name: 'name',
|
||||
url: 'nfs://host/path',
|
||||
ignored: 'ignored',
|
||||
}
|
||||
const backupRepositoryContext1 = buildBackupRepositoryContext(backupRepository1, runContext)
|
||||
assert.deepEqual(backupRepositoryContext1, {
|
||||
backupRepository: {
|
||||
name: 'name',
|
||||
type: 'nfs',
|
||||
tags: [],
|
||||
},
|
||||
run: expectedRunContext,
|
||||
})
|
||||
assert.deepEqual(
|
||||
Object.keys(backupRepositoryContext1.backupRepository).sort(),
|
||||
Object.keys(BACKUP_EXPRESSION_CONTEXT.backupRepository).sort()
|
||||
)
|
||||
|
||||
const backupRepository2 = {
|
||||
name: 'name',
|
||||
url: 'nfs://host/path',
|
||||
tags: [],
|
||||
ignored: 'ignored',
|
||||
}
|
||||
const backupRepositoryContext2 = buildBackupRepositoryContext(backupRepository2, runContext)
|
||||
assert.deepEqual(backupRepositoryContext2, {
|
||||
backupRepository: {
|
||||
name: 'name',
|
||||
type: 'nfs',
|
||||
tags: [],
|
||||
},
|
||||
run: expectedRunContext,
|
||||
})
|
||||
assert.deepEqual(
|
||||
Object.keys(backupRepositoryContext2.backupRepository).sort(),
|
||||
Object.keys(BACKUP_EXPRESSION_CONTEXT.backupRepository).sort()
|
||||
)
|
||||
})
|
||||
})
|
||||
24
@xen-orchestra/backups/_expressionPredicate.mjs
Normal file
24
@xen-orchestra/backups/_expressionPredicate.mjs
Normal file
@@ -0,0 +1,24 @@
|
||||
// @ts-check
|
||||
|
||||
import * as CM from 'complex-matcher'
|
||||
|
||||
/**
|
||||
* Parse and compile a complex-matcher expression into a predicate function.
|
||||
* Throws synchronously if the expression is syntactically invalid.
|
||||
*
|
||||
* @param {string} expression
|
||||
* @returns {(context: object) => boolean}
|
||||
*/
|
||||
export function compileExpression(expression) {
|
||||
return CM.parse(expression).createPredicate()
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns true if value is a non-empty string — i.e. a complex-matcher expression.
|
||||
*
|
||||
* @param {unknown} value
|
||||
* @returns {value is string}
|
||||
*/
|
||||
export function isExpression(value) {
|
||||
return typeof value === 'string' && value.length > 0 && !Number.isFinite(Number(value))
|
||||
}
|
||||
95
@xen-orchestra/backups/_expressionPredicate.test.mjs
Normal file
95
@xen-orchestra/backups/_expressionPredicate.test.mjs
Normal file
@@ -0,0 +1,95 @@
|
||||
import { describe, it } from 'node:test'
|
||||
import assert from 'node:assert/strict'
|
||||
|
||||
import { compileExpression, isExpression } from './_expressionPredicate.mjs'
|
||||
|
||||
describe('compileExpression', () => {
|
||||
it('run:dayOfWeek:0', () => {
|
||||
const predicate = compileExpression('run:dayOfWeek:0')
|
||||
|
||||
assert(predicate({ run: { dayOfWeek: 0 } }))
|
||||
assert(!predicate({ run: { dayOfWeek: 1 } }))
|
||||
})
|
||||
|
||||
it('chainLength:>5', () => {
|
||||
const predicate = compileExpression('chainLength:>5')
|
||||
|
||||
assert(predicate({ chainLength: 6 }))
|
||||
assert(!predicate({ chainLength: 5 }))
|
||||
})
|
||||
|
||||
it('vm:tags:prod', () => {
|
||||
const predicate = compileExpression('vm:tags:prod')
|
||||
|
||||
assert(predicate({ vm: { tags: ['prod'] } }))
|
||||
assert(predicate({ vm: { tags: ['prod', 'test'] } }))
|
||||
assert(!predicate({ vm: { tags: ['test'] } }))
|
||||
assert(!predicate({ vm: { tags: [] } }))
|
||||
})
|
||||
|
||||
it('run:dayOfWeek:0 chainLength:>3', () => {
|
||||
const predicate = compileExpression('run:dayOfWeek:0 chainLength:>3')
|
||||
|
||||
assert(predicate({ run: { dayOfWeek: 0 }, chainLength: 6 }))
|
||||
assert(!predicate({ run: { dayOfWeek: 0 }, chainLength: 2 }))
|
||||
assert(!predicate({ run: { dayOfWeek: 1 }, chainLength: 6 }))
|
||||
})
|
||||
|
||||
it('|(run:dayOfWeek:0 chainLength:>6)', () => {
|
||||
const predicate = compileExpression('|(run:dayOfWeek:0 chainLength:>6)')
|
||||
|
||||
assert(predicate({ run: { dayOfWeek: 0 }, chainLength: 7 }))
|
||||
assert(predicate({ run: { dayOfWeek: 1 }, chainLength: 7 }))
|
||||
assert(predicate({ run: { dayOfWeek: 0 }, chainLength: 6 }))
|
||||
assert(!predicate({ run: { dayOfWeek: 1 }, chainLength: 6 }))
|
||||
})
|
||||
|
||||
it('missing field', () => {
|
||||
const predicate = compileExpression('run:dayOfWeek:0')
|
||||
|
||||
assert(predicate({ run: { dayOfWeek: 0 }, chainLength: 6 }))
|
||||
assert(!predicate({ chainLength: 6 }))
|
||||
assert(!predicate({ run: {}, chainLength: 6 }))
|
||||
})
|
||||
|
||||
it('null-checking', () => {
|
||||
const predicate = compileExpression('!vm')
|
||||
|
||||
assert(predicate({}))
|
||||
assert(!predicate({ vm: [{ vm: 'vm' }] }))
|
||||
})
|
||||
|
||||
it('throws on invalid expression', () => {
|
||||
assert.throws(() => compileExpression('vm:('))
|
||||
})
|
||||
})
|
||||
|
||||
describe('isExpression', () => {
|
||||
it('non-empty string', () => {
|
||||
assert(isExpression('vm:tags:test'))
|
||||
})
|
||||
|
||||
it('number', () => {
|
||||
assert(!isExpression(0))
|
||||
})
|
||||
|
||||
it('string[]', () => {
|
||||
assert(!isExpression(['string']))
|
||||
})
|
||||
|
||||
it('undefined', () => {
|
||||
assert(!isExpression(undefined))
|
||||
})
|
||||
|
||||
it('empty string', () => {
|
||||
assert(!isExpression(''))
|
||||
})
|
||||
|
||||
it('number', () => {
|
||||
assert(!isExpression('3'))
|
||||
})
|
||||
|
||||
it('number with spaces', () => {
|
||||
assert(!isExpression(' 5 '))
|
||||
})
|
||||
})
|
||||
@@ -1,7 +1,7 @@
|
||||
import { strict as assert } from 'node:assert'
|
||||
import test from 'node:test'
|
||||
import { execFile } from 'node:child_process'
|
||||
import { copyFile, 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 => {
|
||||
|
||||
@@ -10,6 +10,8 @@ import { FullRemote } from './_vmRunners/FullRemote.mjs'
|
||||
import { IncrementalRemote } from './_vmRunners/IncrementalRemote.mjs'
|
||||
import { Throttle } from '@vates/generator-toolbox'
|
||||
import createStreamThrottle from './_createStreamThrottle.mjs'
|
||||
import { compileExpression, isExpression } from '../_expressionPredicate.mjs'
|
||||
import { buildRunContext, buildVmContext } from '../_buildContext.mjs'
|
||||
|
||||
const noop = Function.prototype
|
||||
|
||||
@@ -60,21 +62,25 @@ export const VmsRemote = class RemoteVmsBackupRunner extends Abstract {
|
||||
return
|
||||
}
|
||||
|
||||
const runContext = job.runContext ?? buildRunContext(new Date(), settings.timezone)
|
||||
const predicate = isExpression(settings.vmFilter) ? compileExpression(settings.vmFilter) : null
|
||||
|
||||
const vmsUuids = await sourceRemoteAdapter.listAllVms()
|
||||
|
||||
const queue = new Set(vmsUuids)
|
||||
|
||||
Task.info('vms', { vms: vmsUuids })
|
||||
const nbVms = vmsUuids.length
|
||||
let nbVms = vmsUuids.length
|
||||
let nbVmsDone = 0
|
||||
|
||||
remoteAdapters = getAdaptersByRemote(remoteAdapters)
|
||||
const allSettings = this._job.settings
|
||||
const baseSettings = this._baseSettings
|
||||
|
||||
const queue = new Set(vmsUuids)
|
||||
const taskByVmId = {}
|
||||
const nTriesByVmId = {}
|
||||
|
||||
const handleVm = vmUuid => {
|
||||
const handleVm = async vmUuid => {
|
||||
if (nTriesByVmId[vmUuid] === undefined) {
|
||||
nTriesByVmId[vmUuid] = 0
|
||||
}
|
||||
@@ -84,12 +90,26 @@ export const VmsRemote = class RemoteVmsBackupRunner extends Abstract {
|
||||
const vmSettings = { ...settings, ...allSettings[vmUuid] }
|
||||
const isLastRun = nTriesByVmId[vmUuid] === vmSettings.nRetriesVmBackupFailures + 1
|
||||
|
||||
const vmBackups = await sourceRemoteAdapter.listVmBackups(vmUuid, ({ mode }) => mode === job.mode)
|
||||
|
||||
// avoiding to create tasks for empty directories
|
||||
if (vmBackups.length === 0) {
|
||||
nbVms--
|
||||
return
|
||||
}
|
||||
|
||||
if (predicate !== null && !predicate(buildVmContext(vmBackups.at(-1).vm, runContext))) {
|
||||
nbVms--
|
||||
return
|
||||
}
|
||||
|
||||
const opts = {
|
||||
baseSettings,
|
||||
config,
|
||||
job,
|
||||
healthCheckSr,
|
||||
remoteAdapters,
|
||||
runContext,
|
||||
schedule,
|
||||
settings: vmSettings,
|
||||
sourceRemoteAdapter,
|
||||
@@ -106,45 +126,39 @@ export const VmsRemote = class RemoteVmsBackupRunner extends Abstract {
|
||||
throw new Error(`Job mode ${job.mode} not implemented for mirror backup`)
|
||||
}
|
||||
|
||||
return sourceRemoteAdapter
|
||||
.listVmBackups(vmUuid, ({ mode }) => mode === job.mode)
|
||||
.then(vmBackups => {
|
||||
// avoiding to create tasks for empty directories
|
||||
if (vmBackups.length > 0) {
|
||||
if (taskByVmId[vmUuid] === undefined) {
|
||||
taskByVmId[vmUuid] = new Task(taskStart)
|
||||
}
|
||||
const task = taskByVmId[vmUuid]
|
||||
// error has to be caught in the task to prevent its failure, but handled outside the task to execute another task.run()
|
||||
let taskError
|
||||
return task
|
||||
.runInside(async () =>
|
||||
vmBackup.run().catch(error => {
|
||||
taskError = error
|
||||
})
|
||||
)
|
||||
.then(result => {
|
||||
if (taskError === undefined) {
|
||||
nbVmsDone++
|
||||
return task.success(result)
|
||||
}
|
||||
if (isLastRun) {
|
||||
nbVmsDone++
|
||||
return task.failure(taskError)
|
||||
}
|
||||
Task.set('progress', Math.round((nbVmsDone * 100) / nbVms))
|
||||
// don't end the task
|
||||
task.warning(`Retry the VM mirror backup due to an error`, {
|
||||
attempt: nTriesByVmId[vmUuid],
|
||||
error: taskError.message,
|
||||
isRetry: true,
|
||||
})
|
||||
queue.add(vmUuid)
|
||||
})
|
||||
.catch(noop)
|
||||
if (taskByVmId[vmUuid] === undefined) {
|
||||
taskByVmId[vmUuid] = new Task(taskStart)
|
||||
}
|
||||
const task = taskByVmId[vmUuid]
|
||||
// error has to be caught in the task to prevent its failure, but handled outside the task to execute another task.run()
|
||||
let taskError
|
||||
return task
|
||||
.runInside(async () =>
|
||||
vmBackup.run().catch(error => {
|
||||
taskError = error
|
||||
})
|
||||
)
|
||||
.then(result => {
|
||||
if (taskError === undefined) {
|
||||
nbVmsDone++
|
||||
return task.success(result)
|
||||
}
|
||||
if (isLastRun) {
|
||||
nbVmsDone++
|
||||
return task.failure(taskError)
|
||||
}
|
||||
Task.set('progress', Math.round((nbVmsDone * 100) / nbVms))
|
||||
// don't end the task
|
||||
task.warning(`Retry the VM mirror backup due to an error`, {
|
||||
attempt: nTriesByVmId[vmUuid],
|
||||
error: taskError.message,
|
||||
isRetry: true,
|
||||
})
|
||||
queue.add(vmUuid)
|
||||
})
|
||||
.catch(noop)
|
||||
}
|
||||
|
||||
const { concurrency } = settings
|
||||
const _handleVm = !concurrency ? handleVm : limitConcurrency(concurrency)(handleVm)
|
||||
|
||||
|
||||
@@ -12,6 +12,7 @@ import { Throttle } from '@vates/generator-toolbox'
|
||||
import { asyncEach } from '@vates/async-each'
|
||||
import createStreamThrottle from './_createStreamThrottle.mjs'
|
||||
import { selectSynchronizedSnapshotVms } from './_selectSynchronizedSnapshotVms.mjs'
|
||||
import { buildRunContext } from '../_buildContext.mjs'
|
||||
|
||||
const noop = Function.prototype
|
||||
|
||||
@@ -68,6 +69,7 @@ export const VmsXapi = class VmsXapiBackupRunner extends Abstract {
|
||||
const getSnapshotNameLabel = this._getSnapshotNameLabel
|
||||
const schedule = this._schedule
|
||||
const settings = this._settings
|
||||
const runContext = job.runContext ?? buildRunContext(new Date(), settings.timezone)
|
||||
|
||||
const throttleGenerator = new Throttle(settings.maxExportRate)
|
||||
const throttleStream = createStreamThrottle(settings.maxExportRate)
|
||||
@@ -151,6 +153,7 @@ export const VmsXapi = class VmsXapiBackupRunner extends Abstract {
|
||||
healthCheckSr,
|
||||
job,
|
||||
remoteAdapters,
|
||||
runContext,
|
||||
schedule,
|
||||
settings: vmSettings,
|
||||
srs,
|
||||
@@ -249,6 +252,7 @@ export const VmsXapi = class VmsXapiBackupRunner extends Abstract {
|
||||
throttleGenerator,
|
||||
throttleStream,
|
||||
vm,
|
||||
runContext,
|
||||
}
|
||||
|
||||
const vmBackup = this._getVmBackup(job.mode, opts)
|
||||
|
||||
@@ -53,7 +53,7 @@ export const FullRemote = class FullRemoteVmBackupRunner extends AbstractRemote
|
||||
'writer.run()'
|
||||
)
|
||||
// for healthcheck
|
||||
this._tags = metadata.vm.tags
|
||||
this._vm = metadata.vm
|
||||
nbTransferredVms++
|
||||
Task.set('progress', Math.round((nbTransferredVms * 100) / nbTransferrableVms))
|
||||
}
|
||||
|
||||
@@ -131,7 +131,7 @@ class IncrementalRemoteVmBackupRunner extends AbstractRemote {
|
||||
|
||||
await this._callWriters(writer => writer.cleanup(), 'writer.cleanup()')
|
||||
// for healthcheck
|
||||
this._tags = metadata.vm.tags
|
||||
this._vm = metadata.vm
|
||||
nbTransferredVms++
|
||||
Task.set('progress', Math.round((nbTransferredVms * 100) / nbTransferrableVms))
|
||||
}
|
||||
|
||||
@@ -18,10 +18,19 @@ import { ThrottledDisk, SynchronizedDisk } from '@xen-orchestra/disk-transform'
|
||||
import { AggregatedIncrementalRemoteWriter } from '../_writers/AggregatedIncrementalRemoteWriter.mjs'
|
||||
import { AggregatedIncrementalXapiWriter } from '../_writers/AggregatedIncrementalXapiWriter.mjs'
|
||||
import { TaskProgressHandler } from './_TaskProgressHandler.mjs'
|
||||
import { compileExpression, isExpression } from '../../_expressionPredicate.mjs'
|
||||
import { buildVmContext } from '../../_buildContext.mjs'
|
||||
|
||||
const { debug } = createLogger('xo:backups:IncrementalXapiVmBackup')
|
||||
|
||||
export const IncrementalXapi = class IncrementalXapiVmBackupRunner extends AbstractXapi {
|
||||
constructor(props) {
|
||||
super(props)
|
||||
|
||||
const fullInterval = this._settings.fullInterval
|
||||
this._fullIntervalPredicate = isExpression(fullInterval) ? compileExpression(fullInterval) : null
|
||||
}
|
||||
|
||||
_getWriters() {
|
||||
return [
|
||||
IncrementalRemoteWriter,
|
||||
@@ -229,15 +238,17 @@ export const IncrementalXapi = class IncrementalXapiVmBackupRunner extends Abstr
|
||||
}
|
||||
|
||||
// we do tafter checkbasevdis because we want the writer to know the target VM
|
||||
// especially on replication when we alwayr update the same VM
|
||||
// especially on replication when we always update the same VM
|
||||
const fullInterval = this._settings.fullInterval
|
||||
if (fullInterval !== 0 && fullInterval <= deltaChainLength + 1) {
|
||||
debug('not using base VM because fullInterval reached', {
|
||||
fullInterval,
|
||||
deltaChainLength,
|
||||
eq: fullInterval < deltaChainLength + 1,
|
||||
dc1: deltaChainLength + 1,
|
||||
})
|
||||
const chainLength = (deltaChainLength ?? 0) + 1
|
||||
if (isExpression(fullInterval)) {
|
||||
const context = buildVmContext(this._vm, this._runContext, chainLength)
|
||||
if (this._fullIntervalPredicate(context)) {
|
||||
debug('forcing full backup: fullInterval expression matched', { fullInterval })
|
||||
return
|
||||
}
|
||||
} else if (fullInterval !== 0 && fullInterval <= chainLength) {
|
||||
debug('not using base VM because fullInterval reached', { fullInterval, chainLength })
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { asyncMap } from '@xen-orchestra/async-map'
|
||||
import { createLogger } from '@xen-orchestra/log'
|
||||
import { Task } from '@vates/task'
|
||||
import { compileExpression, isExpression } from '../../_expressionPredicate.mjs'
|
||||
import { buildVmContext } from '../../_buildContext.mjs'
|
||||
|
||||
const { debug, warn } = createLogger('xo:backups:AbstractVmRunner')
|
||||
|
||||
@@ -73,24 +75,58 @@ export const Abstract = class AbstractVmBackupRunner {
|
||||
}
|
||||
|
||||
// check if current VM has tags
|
||||
const tags = this._tags
|
||||
const tags = this._vm.tags
|
||||
|
||||
// accept both 'xo:no-health-check' and 'xo:no-health-check=reason'
|
||||
const vmAlwaysIgnored = tags.some(t => t.startsWith('xo:no-health-check'))
|
||||
const intersect = !vmAlwaysIgnored && settings.healthCheckVmsWithTags.some(t => tags.includes(t))
|
||||
|
||||
if (vmAlwaysIgnored || (settings.healthCheckVmsWithTags.length !== 0 && !intersect)) {
|
||||
// create a task to have an info in the logs and reports
|
||||
if (tags.some(t => t.startsWith('xo:no-health-check'))) {
|
||||
return Task.run(
|
||||
{
|
||||
properties: { name: 'health check' },
|
||||
properties: {
|
||||
name: 'health check',
|
||||
},
|
||||
},
|
||||
() => {
|
||||
Task.info(`This VM doesn't match the health check's tags for this schedule`)
|
||||
Task.info(`This VM is excluded from health checks via tag`)
|
||||
}
|
||||
)
|
||||
}
|
||||
|
||||
if (isExpression(settings.healthCheckVmsWithTags)) {
|
||||
const context = buildVmContext(this._vm, this._runContext)
|
||||
if (!this._healthCheckPredicate(context)) {
|
||||
return Task.run(
|
||||
{
|
||||
properties: { name: 'health check' },
|
||||
},
|
||||
() => {
|
||||
Task.info(`VM did not match healthCheckVmsWithTags expression`)
|
||||
}
|
||||
)
|
||||
}
|
||||
} else {
|
||||
const intersect = settings.healthCheckVmsWithTags.some(t => tags.includes(t))
|
||||
if (settings.healthCheckVmsWithTags.length !== 0 && !intersect) {
|
||||
// create a task to have an info in the logs and reports
|
||||
return Task.run(
|
||||
{
|
||||
properties: { name: 'health check' },
|
||||
},
|
||||
() => {
|
||||
Task.info(`This VM doesn't match the health check's tags for this schedule`)
|
||||
}
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
await this._callWriters(writer => writer.healthCheck(), 'writer.healthCheck()')
|
||||
}
|
||||
|
||||
_compileHealthCheckPredicate() {
|
||||
const { healthCheckVmsWithTags } = this._settings
|
||||
if (isExpression(healthCheckVmsWithTags)) {
|
||||
this._healthCheckPredicate = compileExpression(healthCheckVmsWithTags)
|
||||
} else {
|
||||
this._healthCheckPredicate = undefined
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ export const AbstractRemote = class AbstractRemoteVmBackupRunner extends Abstrac
|
||||
job,
|
||||
healthCheckSr,
|
||||
remoteAdapters,
|
||||
runContext,
|
||||
schedule,
|
||||
settings,
|
||||
sourceRemoteAdapter,
|
||||
@@ -40,11 +41,14 @@ export const AbstractRemote = class AbstractRemoteVmBackupRunner extends Abstrac
|
||||
this._throttleGenerator = throttleGenerator
|
||||
this._throttleStream = throttleStream
|
||||
this._vmUuid = vmUuid
|
||||
this._runContext = runContext
|
||||
|
||||
const allSettings = job.settings
|
||||
const writers = new Set()
|
||||
this._writers = writers
|
||||
|
||||
this._compileHealthCheckPredicate()
|
||||
|
||||
const [BackupWriter, AggregratedBackupWriter] = this._getRemoteWriters()
|
||||
if (settings.distributeBackups) {
|
||||
writers.add(
|
||||
|
||||
@@ -36,6 +36,7 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
|
||||
job,
|
||||
remoteAdapters,
|
||||
remotes,
|
||||
runContext,
|
||||
schedule,
|
||||
settings,
|
||||
srs,
|
||||
@@ -63,12 +64,13 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
|
||||
this.timestamp = undefined
|
||||
|
||||
// VM currently backed up
|
||||
const tags = (this._tags = vm.tags)
|
||||
const tags = vm.tags
|
||||
|
||||
// VM (snapshot) that is really exported
|
||||
this._exportedVm = undefined
|
||||
this._synchronizedSnapshotTimestamp = synchronizedSnapshotTimestamp
|
||||
this._vm = vm
|
||||
this._runContext = runContext
|
||||
|
||||
this._getSnapshotNameLabel = getSnapshotNameLabel
|
||||
this._isIncremental = job.mode === 'delta'
|
||||
@@ -90,6 +92,9 @@ export const AbstractXapi = class AbstractXapiVmBackupRunner extends Abstract {
|
||||
settings.offlineSnapshot = true
|
||||
}
|
||||
this._settings = settings
|
||||
|
||||
this._compileHealthCheckPredicate()
|
||||
|
||||
// Create writers
|
||||
{
|
||||
const writers = new Set()
|
||||
|
||||
@@ -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) {
|
||||
|
||||
26
@xen-orchestra/backups/backupExpressions.mjs
Normal file
26
@xen-orchestra/backups/backupExpressions.mjs
Normal file
@@ -0,0 +1,26 @@
|
||||
import { isExpression, compileExpression } from './_expressionPredicate.mjs'
|
||||
import { invalidParameters } from 'xo-common/api-errors.js'
|
||||
|
||||
export function assertValidSettingsExpression(settings, keys) {
|
||||
for (const [scheduleId, scheduleSettings] of Object.entries(settings ?? {})) {
|
||||
for (const key of keys) {
|
||||
assertValidExpression(`settings/${scheduleId === '' ? 'general' : scheduleId}/${key}`, scheduleSettings?.[key])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function assertValidExpression(name, value) {
|
||||
if (isExpression(value)) {
|
||||
try {
|
||||
compileExpression(value)
|
||||
} catch (error) {
|
||||
throw invalidParameters(`Invalid ${name} expression: ${error.message}`, [
|
||||
{ instancePath: `/${name}`, message: error.message },
|
||||
])
|
||||
}
|
||||
} else if (typeof value === 'string' && value.trim() === '') {
|
||||
throw invalidParameters(`Invalid ${name} expression: must be a non-empty expression`, [
|
||||
{ instancePath: `/${name}`, message: 'must be a non-empty expression' },
|
||||
])
|
||||
}
|
||||
}
|
||||
77
@xen-orchestra/backups/backupExpressions.test.mjs
Normal file
77
@xen-orchestra/backups/backupExpressions.test.mjs
Normal file
@@ -0,0 +1,77 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { describe, it } from 'node:test'
|
||||
import { invalidParameters } from 'xo-common/api-errors.js'
|
||||
|
||||
import { assertValidExpression, assertValidSettingsExpression } from './backupExpressions.mjs'
|
||||
|
||||
const VALID = 'vm:tags:prod'
|
||||
const INVALID = 'vm:('
|
||||
|
||||
// checks that the error is `invalidParameters` and points to the expected field
|
||||
const isInvalidAt = instancePath => error =>
|
||||
invalidParameters.is(error) && error.data.errors[0].instancePath === instancePath
|
||||
|
||||
describe('assertValidExpression', function () {
|
||||
it('accepts a valid expression', function () {
|
||||
assert.doesNotThrow(() => assertValidExpression('srs', VALID))
|
||||
})
|
||||
|
||||
it('rejects an invalid expression with invalidParameters', function () {
|
||||
assert.throws(() => assertValidExpression('srs', INVALID), isInvalidAt('/srs'))
|
||||
})
|
||||
|
||||
it('ignores values which are not expressions', function () {
|
||||
for (const value of [undefined, '3', { id: 'sr-1' }, { id: { __or: ['sr-1', 'sr-2'] } }]) {
|
||||
assert.doesNotThrow(() => assertValidExpression('srs', value))
|
||||
}
|
||||
})
|
||||
|
||||
it('rejects blank strings', function () {
|
||||
for (const value of ['', ' ']) {
|
||||
assert.throws(() => assertValidExpression('srs', value), isInvalidAt('/srs'))
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('assertValidSettingsExpression', function () {
|
||||
const KEYS = ['healthCheckVmsWithTags', 'fullInterval']
|
||||
|
||||
it('accepts valid expressions in the general and the schedule settings', function () {
|
||||
assert.doesNotThrow(() =>
|
||||
assertValidSettingsExpression(
|
||||
{ '': { fullInterval: VALID }, 'schedule-1': { healthCheckVmsWithTags: VALID } },
|
||||
KEYS
|
||||
)
|
||||
)
|
||||
})
|
||||
|
||||
it('rejects an invalid expression in the schedule settings and points to it', function () {
|
||||
assert.throws(
|
||||
() => assertValidSettingsExpression({ '': {}, 'schedule-1': { fullInterval: INVALID } }, KEYS),
|
||||
isInvalidAt('/settings/schedule-1/fullInterval')
|
||||
)
|
||||
})
|
||||
|
||||
it('rejects an invalid expression in the general settings', function () {
|
||||
// the general settings are keyed by '', named "general" in the path.
|
||||
assert.throws(
|
||||
() => assertValidSettingsExpression({ '': { healthCheckVmsWithTags: INVALID } }, KEYS),
|
||||
isInvalidAt('/settings/general/healthCheckVmsWithTags')
|
||||
)
|
||||
})
|
||||
|
||||
it('ignores the legacy array and number values', function () {
|
||||
assert.doesNotThrow(() =>
|
||||
assertValidSettingsExpression({ 'schedule-1': { healthCheckVmsWithTags: ['tag'], fullInterval: 3 } }, KEYS)
|
||||
)
|
||||
})
|
||||
|
||||
it('ignores the keys it has not been asked to check', function () {
|
||||
assert.doesNotThrow(() => assertValidSettingsExpression({ 'schedule-1': { vmFilter: INVALID } }, KEYS))
|
||||
})
|
||||
|
||||
it('handles missing settings and undefined entries', function () {
|
||||
assert.doesNotThrow(() => assertValidSettingsExpression(undefined, KEYS))
|
||||
assert.doesNotThrow(() => assertValidSettingsExpression({ 'schedule-1': undefined }, KEYS))
|
||||
})
|
||||
})
|
||||
@@ -43,7 +43,7 @@ A VM directory holds **both** the full and the incremental backups of that VM: t
|
||||
|
||||
Transient entries, not listed in the trees below:
|
||||
|
||||
- `xo-vm-backups/<VM UUID>.lock`, held 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
|
||||
|
||||
@@ -40,6 +40,7 @@
|
||||
"@xen-orchestra/backup-archive": "^1.2.0",
|
||||
"app-conf": "^3.0.0",
|
||||
"compare-versions": "^6.0.0",
|
||||
"complex-matcher": "^1.1.1",
|
||||
"d3-time-format": "^4.1.0",
|
||||
"decorator-synchronized": "^0.6.0",
|
||||
"golike-defer": "^0.5.1",
|
||||
@@ -57,6 +58,8 @@
|
||||
"value-matcher": "^0.2.0",
|
||||
"vhd-lib": "^4.17.0",
|
||||
"xen-api": "^5.1.0",
|
||||
"xo-common": "^0.11.0",
|
||||
"xo-remote-parser": "^2.0.0",
|
||||
"yazl": "^2.5.1"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -9,7 +9,7 @@ async function consumeGenerator(source: AsyncGenerator) {
|
||||
return 'finished'
|
||||
}
|
||||
test('Disk class', async t => {
|
||||
const testRes = await t.test('synchronised fork disk ', async () => {
|
||||
const testRes = await t.test('synchronized fork disk ', async () => {
|
||||
const blockSize = 1024
|
||||
const nbBlocks = 20
|
||||
const source = new DebugDisk({ nbBlocks, blockSize, fillRate: 100 })
|
||||
|
||||
@@ -18,7 +18,7 @@ ee.on('start', async function () {
|
||||
// listeners have settled
|
||||
await ee.emitAsync('start')
|
||||
|
||||
// by default, it will rejects as soon as one listener reject, you can customise
|
||||
// by default, it will rejects as soon as one listener reject, you can customize
|
||||
// error handling though:
|
||||
await ee.emitAsync(
|
||||
{
|
||||
|
||||
@@ -36,7 +36,7 @@ ee.on('start', async function () {
|
||||
// listeners have settled
|
||||
await ee.emitAsync('start')
|
||||
|
||||
// by default, it will rejects as soon as one listener reject, you can customise
|
||||
// by default, it will rejects as soon as one listener reject, you can customize
|
||||
// error handling though:
|
||||
await ee.emitAsync(
|
||||
{
|
||||
|
||||
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)
|
||||
})
|
||||
})
|
||||
@@ -1,5 +1,15 @@
|
||||
# ChangeLog
|
||||
|
||||
## **next**
|
||||
|
||||
- [Web-Core/UiButtonIcon] Update icon buttons design, with a counter replacing the notification dot (PR [#10799](https://github.com/vatesfr/xen-orchestra/pull/10799))
|
||||
- [Mobile/Side panels] Full-page menus on mobile with "Change state" in "More actions", side panel actions shown as buttons when there is room, and fixes for long names in headers and menu placement (PR [#10745](https://github.com/vatesfr/xen-orchestra/pull/10745))
|
||||
- [Side panels] Side panels can be resized like the treeview, whose default width now adapts to the screen size (PR [#10725](https://github.com/vatesfr/xen-orchestra/pull/10725))
|
||||
- [Side panels] Values stay next to their label when they fit and move below it otherwise, fields with several values (IP addresses, bond devices) get a copy button per value and a "Copy all" action, and rows, links and statuses are more evenly spaced and sized (PR [#10733](https://github.com/vatesfr/xen-orchestra/pull/10733))
|
||||
- [Treeview] Fix translations of the tooltip for VM and host statuses in treeview (PR [#10643](https://github.com/vatesfr/xen-orchestra/pull/10643))
|
||||
- [Web-Core/UiDropdownButton] Update dropdown buttons design (PR [#9850](https://github.com/vatesfr/xen-orchestra/pull/9850))
|
||||
- [Tables] Tables are filtered as you type, half a second after the last keystroke, or right away with Enter; the "Search" button is removed (PR [#10797](https://github.com/vatesfr/xen-orchestra/pull/10797))
|
||||
|
||||
## **0.27.0** (2026-10-29)
|
||||
|
||||
- [New network] Choose between no NBD, secure NBD and insecure NBD (not encrypted) when creating a network (PR [#10540](https://github.com/vatesfr/xen-orchestra/pull/10540))
|
||||
|
||||
@@ -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,27 +14,12 @@
|
||||
<VtsIcon v-tooltip="t('master')" name="status:primary-circle" size="medium" />
|
||||
</template>
|
||||
<template #actions>
|
||||
<MenuList placement="bottom-end">
|
||||
<template #trigger="{ open }">
|
||||
<UiDropdownButton @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>
|
||||
@@ -46,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'
|
||||
|
||||
@@ -61,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>
|
||||
@@ -12,7 +12,7 @@
|
||||
<!-- PIF -->
|
||||
<UiPanelCard>
|
||||
<UiPanelCardTitle :id="pif.uuid" size="medium" :label="isBond ? t('bond') : t('pif')" />
|
||||
<div class="content">
|
||||
<VtsCardRowList>
|
||||
<!-- NETWORK -->
|
||||
<VtsCardRowKeyValue>
|
||||
<template #key>
|
||||
@@ -82,34 +82,15 @@
|
||||
</UiTagsList>
|
||||
</template>
|
||||
</VtsCardRowKeyValue>
|
||||
</div>
|
||||
</VtsCardRowList>
|
||||
</UiPanelCard>
|
||||
<!-- NETWORK INFORMATION -->
|
||||
<UiPanelCard>
|
||||
<UiPanelCardTitle size="medium" :label="t('network-information')" />
|
||||
<div class="content">
|
||||
<VtsCardRowList>
|
||||
<!-- IP ADDRESSES -->
|
||||
<div v-if="ipAddresses.length">
|
||||
<VtsCardRowKeyValue v-for="(ip, index) in ipAddresses" :key="ip">
|
||||
<template #key>
|
||||
<div v-if="index === 0">{{ t('ip-addresses') }}</div>
|
||||
</template>
|
||||
<template #value>
|
||||
<span v-tooltip class="text-ellipsis">{{ ip }}</span>
|
||||
</template>
|
||||
<template #addons>
|
||||
<VtsCopyButton :value="ip" />
|
||||
<VtsCopyAllMenuItem v-if="index === 0 && ipAddresses.length > 1" :values="ipAddresses" />
|
||||
</template>
|
||||
</VtsCardRowKeyValue>
|
||||
</div>
|
||||
<VtsCardRowKeyValue v-else>
|
||||
<template #key>
|
||||
{{ t('ip-addresses') }}
|
||||
</template>
|
||||
<template #value>
|
||||
<span class="value" />
|
||||
</template>
|
||||
<VtsCardRowKeyValue :values="ipAddresses">
|
||||
<template #key>{{ t('ip-addresses') }}</template>
|
||||
</VtsCardRowKeyValue>
|
||||
<!-- MAC ADDRESSES -->
|
||||
<VtsCardRowKeyValue>
|
||||
@@ -173,26 +154,15 @@
|
||||
</template>
|
||||
</VtsCardRowKeyValue>
|
||||
<!-- BOND DEVICES -->
|
||||
<div>
|
||||
<VtsCardRowKeyValue v-for="(device, index) in bondDevices" :key="device">
|
||||
<template #key>
|
||||
<div v-if="index === 0">{{ t('bond-devices') }}</div>
|
||||
</template>
|
||||
<template #value>
|
||||
<span v-tooltip class="text-ellipsis">{{ device }}</span>
|
||||
</template>
|
||||
<template v-if="device" #addons>
|
||||
<VtsCopyButton :value="device" />
|
||||
<VtsCopyAllMenuItem v-if="index === 0 && bondDevices.length > 1" :values="bondDevicesFiltered" />
|
||||
</template>
|
||||
</VtsCardRowKeyValue>
|
||||
</div>
|
||||
</div>
|
||||
<VtsCardRowKeyValue v-if="bondDevicesFiltered.length > 0" :values="bondDevicesFiltered">
|
||||
<template #key>{{ t('bond-devices') }}</template>
|
||||
</VtsCardRowKeyValue>
|
||||
</VtsCardRowList>
|
||||
</UiPanelCard>
|
||||
<!-- PROPERTIES -->
|
||||
<UiPanelCard>
|
||||
<UiPanelCardTitle size="medium" :label="t('properties')" />
|
||||
<div class="content">
|
||||
<VtsCardRowList>
|
||||
<!-- MTU -->
|
||||
<VtsCardRowKeyValue>
|
||||
<template #key>
|
||||
@@ -226,7 +196,7 @@
|
||||
<VtsCopyButton :value="networkPurpose" />
|
||||
</template>
|
||||
</VtsCardRowKeyValue>
|
||||
</div>
|
||||
</VtsCardRowList>
|
||||
</UiPanelCard>
|
||||
</template>
|
||||
</VtsSidePanel>
|
||||
@@ -239,7 +209,7 @@ import { useNetworkStore } from '@/stores/xen-api/network.store.ts'
|
||||
import { usePifMetricsStore } from '@/stores/xen-api/pif-metrics.store.ts'
|
||||
import { usePifStore } from '@/stores/xen-api/pif.store.ts'
|
||||
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
|
||||
import VtsCopyAllMenuItem from '@core/components/copy-all-menu-item/VtsCopyAllMenuItem.vue'
|
||||
import VtsCardRowList from '@core/components/card/VtsCardRowList.vue'
|
||||
import VtsCopyButton from '@core/components/copy-button/VtsCopyButton.vue'
|
||||
import VtsForgetButton from '@core/components/forget-button/VtsForgetButton.vue'
|
||||
import VtsIcon from '@core/components/icon/VtsIcon.vue'
|
||||
@@ -331,12 +301,6 @@ const speed = computed(() => {
|
||||
|
||||
<style scoped lang="postcss">
|
||||
.host-pif-side-panel {
|
||||
.content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.8rem;
|
||||
}
|
||||
|
||||
.network {
|
||||
display: flex;
|
||||
gap: 0.8rem;
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
</template>
|
||||
</UiTitle>
|
||||
<div class="container">
|
||||
<UiQuerySearchBar @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,27 +1,15 @@
|
||||
<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>
|
||||
<UiPanelCardTitle :id="network.uuid" size="medium" :label="network.name_label" />
|
||||
<div class="content">
|
||||
<VtsCardRowList>
|
||||
<!-- DESCRIPTION -->
|
||||
<VtsCardRowKeyValue truncate align-top>
|
||||
<template #key>{{ t('description') }}</template>
|
||||
@@ -63,27 +51,30 @@
|
||||
<template #key>{{ t('locking-mode-default') }}</template>
|
||||
<template #value>{{ networkDefaultLockingMode }}</template>
|
||||
</VtsCardRowKeyValue>
|
||||
</div>
|
||||
</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>
|
||||
@@ -97,17 +88,15 @@ import type { XenApiNetwork } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { useNetworkDelete } from '@/modules/network/composables/use-network-delete.composable.ts'
|
||||
import { usePifStore } from '@/stores/xen-api/pif.store.ts'
|
||||
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
|
||||
import 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<{
|
||||
@@ -144,28 +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 {
|
||||
.content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
|
||||
.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,30 +11,18 @@
|
||||
/>
|
||||
</template>
|
||||
<template #actions>
|
||||
<MenuList v-if="vm !== undefined" placement="bottom-start">
|
||||
<template #trigger="{ open }">
|
||||
<UiDropdownButton @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>
|
||||
@@ -48,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'
|
||||
@@ -61,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>
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<VtsQuickInfoCard class="vm-dashboard-quick-info" :loading="!isReady">
|
||||
<VtsQuickInfoCard :loading="!isReady" class="vm-dashboard-quick-info">
|
||||
<VtsKeyValueList>
|
||||
<VtsKeyValueRow :label="t('state')">
|
||||
<template #value>
|
||||
@@ -19,11 +19,11 @@
|
||||
<template #value>
|
||||
<UiLink
|
||||
v-if="host"
|
||||
:to="`/host/${host.uuid}`"
|
||||
size="medium"
|
||||
:icon="hostIcon"
|
||||
:is-primary="isPoolMaster"
|
||||
:primary-tooltip="t('master')"
|
||||
:to="`/host/${host.uuid}`"
|
||||
size="medium"
|
||||
>
|
||||
{{ host.name_label }}
|
||||
</UiLink>
|
||||
@@ -54,9 +54,9 @@
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import { VM_POWER_STATE } from '@/libs/xen-api/xen-api.enums.ts'
|
||||
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { getHostIcon } from '@/modules/host/utils/host.util.ts'
|
||||
import { useVmUtils } from '@/modules/vm/composables/vm-utils.composable.ts'
|
||||
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
|
||||
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
|
||||
import { useVmGuestMetricsStore } from '@/stores/xen-api/vm-guest-metrics.store.ts'
|
||||
@@ -70,7 +70,6 @@ import VtsTag from '@core/components/tag/VtsTag.vue'
|
||||
import UiLink from '@core/components/ui/link/UiLink.vue'
|
||||
import UiTagsList from '@core/components/ui/tag/UiTagsList.vue'
|
||||
import { useTimeAgo } from '@core/composables/locale-time-ago.composable.ts'
|
||||
import { useMapper } from '@core/packages/mapper'
|
||||
import { formatSizeRaw } from '@core/utils/size.util.ts'
|
||||
import { formatDate, parseDateTime } from '@core/utils/time.util.ts'
|
||||
import { computed } from 'vue'
|
||||
@@ -98,16 +97,7 @@ const isPoolMaster = computed(() => pool.value?.master === host.value?.$ref)
|
||||
|
||||
const hostIcon = computed(() => getHostIcon(host.value, getHostPowerState(host.value)))
|
||||
|
||||
const powerState = useMapper(
|
||||
() => vm.power_state,
|
||||
{
|
||||
[VM_POWER_STATE.RUNNING]: { icon: 'status:running-circle', text: t('vm:status:running') },
|
||||
[VM_POWER_STATE.HALTED]: { icon: 'status:halted-circle', text: t('vm:status:halted') },
|
||||
[VM_POWER_STATE.PAUSED]: { icon: 'status:paused-circle', text: t('vm:status:paused') },
|
||||
[VM_POWER_STATE.SUSPENDED]: { icon: 'status:suspended-circle', text: t('vm:status:suspended') },
|
||||
},
|
||||
VM_POWER_STATE.RUNNING
|
||||
)
|
||||
const { powerState } = useVmUtils(() => vm)
|
||||
|
||||
function getValidDateTime(dateTime: string | undefined): string | undefined {
|
||||
return dateTime === '19700101T00:00:00Z' ? undefined : dateTime
|
||||
|
||||
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,7 +1,7 @@
|
||||
<template>
|
||||
<UiPanelCard class="host-hardware-specifications-card">
|
||||
<UiPanelCard>
|
||||
<UiPanelCardTitle size="medium" :label="t('hardware-specifications')" />
|
||||
<div class="content">
|
||||
<VtsCardRowList>
|
||||
<VtsCardRowKeyValue>
|
||||
<template #key>{{ t('manufacturer-info') }}</template>
|
||||
<template #value>{{ manufacturerInfo }}</template>
|
||||
@@ -16,7 +16,7 @@
|
||||
<VtsCopyButton :value="coreSocketInfo" />
|
||||
</template>
|
||||
</VtsCardRowKeyValue>
|
||||
</div>
|
||||
</VtsCardRowList>
|
||||
</UiPanelCard>
|
||||
</template>
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { getHostCoreSocketInfo, getHostManufacturerInfo } from '@/modules/host/utils/host.util.ts'
|
||||
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 UiPanelCard from '@core/components/ui/panel-card/UiPanelCard.vue'
|
||||
import UiPanelCardTitle from '@core/components/ui/panel-card-title/UiPanelCardTitle.vue'
|
||||
@@ -40,13 +41,3 @@ const manufacturerInfo = computed(() => getHostManufacturerInfo(host))
|
||||
|
||||
const coreSocketInfo = computed(() => getHostCoreSocketInfo(host))
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
.host-hardware-specifications-card {
|
||||
.content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
:icon="hostIcon"
|
||||
:to="{ name: '/host/[uuid]/dashboard', params: { uuid: host.uuid } }"
|
||||
/>
|
||||
<div class="content">
|
||||
<VtsCardRowList class="content">
|
||||
<VtsCardRowKeyValue>
|
||||
<template #key>{{ t('state') }}</template>
|
||||
<template #value>
|
||||
@@ -98,7 +98,7 @@
|
||||
<VtsCopyButton :value="noMissingPatches ? t('patches-up-to-date') : t('n-missing', nMissingPatches)" />
|
||||
</template>
|
||||
</VtsCardRowKeyValue>
|
||||
</div>
|
||||
</VtsCardRowList>
|
||||
</UiPanelCard>
|
||||
</template>
|
||||
|
||||
@@ -110,6 +110,7 @@ import { getHostIcon } from '@/modules/host/utils/host.util.ts'
|
||||
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
|
||||
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
|
||||
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 VtsEnabledState from '@core/components/enabled-state/VtsEnabledState.vue'
|
||||
import VtsIcon from '@core/components/icon/VtsIcon.vue'
|
||||
@@ -146,10 +147,6 @@ const noMissingPatches = computed(() => nMissingPatches.value === 0)
|
||||
<style lang="postcss" scoped>
|
||||
.host-infos-card {
|
||||
.content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.4rem;
|
||||
|
||||
.value {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<template>
|
||||
<UiPanelCard class="host-network-card">
|
||||
<UiPanelCard>
|
||||
<UiPanelCardTitle :label="t('network')" size="medium" />
|
||||
<div class="content">
|
||||
<VtsCardRowList>
|
||||
<VtsCardRowKeyValue>
|
||||
<template #key>{{ t('management-ip') }}</template>
|
||||
<template #value>{{ host.address }}</template>
|
||||
@@ -9,37 +9,13 @@
|
||||
<VtsCopyButton :value="host.address" />
|
||||
</template>
|
||||
</VtsCardRowKeyValue>
|
||||
<template v-if="ipV4Addresses.length > 0">
|
||||
<VtsCardRowKeyValue v-for="(ip, index) in ipV4Addresses" :key="ip">
|
||||
<template #key>
|
||||
<div v-if="index === 0">{{ t('ipv4-addresses') }}</div>
|
||||
</template>
|
||||
<template #value>{{ ip }}</template>
|
||||
<template #addons>
|
||||
<VtsCopyButton :value="ip" />
|
||||
<VtsCopyAllMenuItem v-if="index === 0 && ipV4Addresses.length > 1" :values="ipV4Addresses" />
|
||||
</template>
|
||||
</VtsCardRowKeyValue>
|
||||
</template>
|
||||
<VtsCardRowKeyValue v-else>
|
||||
<VtsCardRowKeyValue :values="ipV4Addresses">
|
||||
<template #key>{{ t('ipv4-addresses') }}</template>
|
||||
</VtsCardRowKeyValue>
|
||||
<template v-if="ipV6Addresses.length > 0">
|
||||
<VtsCardRowKeyValue v-for="(ip, index) in ipV6Addresses" :key="ip">
|
||||
<template #key>
|
||||
<div v-if="index === 0">{{ t('ipv6-addresses') }}</div>
|
||||
</template>
|
||||
<template #value>{{ ip }}</template>
|
||||
<template #addons>
|
||||
<VtsCopyButton :value="ip" />
|
||||
<VtsCopyAllMenuItem v-if="index === 0 && ipV6Addresses.length > 1" :values="ipV6Addresses" />
|
||||
</template>
|
||||
</VtsCardRowKeyValue>
|
||||
</template>
|
||||
<VtsCardRowKeyValue v-else>
|
||||
<VtsCardRowKeyValue :values="ipV6Addresses">
|
||||
<template #key>{{ t('ipv6-addresses') }}</template>
|
||||
</VtsCardRowKeyValue>
|
||||
</div>
|
||||
</VtsCardRowList>
|
||||
</UiPanelCard>
|
||||
</template>
|
||||
|
||||
@@ -47,7 +23,7 @@
|
||||
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { usePifStore } from '@/stores/xen-api/pif.store.ts'
|
||||
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
|
||||
import VtsCopyAllMenuItem from '@core/components/copy-all-menu-item/VtsCopyAllMenuItem.vue'
|
||||
import VtsCardRowList from '@core/components/card/VtsCardRowList.vue'
|
||||
import VtsCopyButton from '@core/components/copy-button/VtsCopyButton.vue'
|
||||
import UiPanelCard from '@core/components/ui/panel-card/UiPanelCard.vue'
|
||||
import UiPanelCardTitle from '@core/components/ui/panel-card-title/UiPanelCardTitle.vue'
|
||||
@@ -66,13 +42,3 @@ const pifs = computed(() => pifsByHost.value.get(host.$ref))
|
||||
const ipV4Addresses = computed(() => pifs.value?.map(pif => pif.IP).filter(ip => ip) ?? [])
|
||||
const ipV6Addresses = computed(() => pifs.value?.flatMap(pif => pif.IPv6.filter(ip => ip)) ?? [])
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
.host-network-card {
|
||||
.content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<template>
|
||||
<UiPanelCard class="host-software-card">
|
||||
<UiPanelCard>
|
||||
<UiPanelCardTitle size="medium" :label="t('software')" />
|
||||
<div class="content">
|
||||
<VtsCardRowList>
|
||||
<VtsCardRowKeyValue>
|
||||
<template #key>{{ t('version') }}</template>
|
||||
<template #value>{{ host.software_version.product_version }}</template>
|
||||
@@ -9,13 +9,14 @@
|
||||
<VtsCopyButton :value="host.software_version.product_version" />
|
||||
</template>
|
||||
</VtsCardRowKeyValue>
|
||||
</div>
|
||||
</VtsCardRowList>
|
||||
</UiPanelCard>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
|
||||
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 UiPanelCard from '@core/components/ui/panel-card/UiPanelCard.vue'
|
||||
import UiPanelCardTitle from '@core/components/ui/panel-card-title/UiPanelCardTitle.vue'
|
||||
@@ -27,13 +28,3 @@ defineProps<{
|
||||
|
||||
const { t } = useI18n()
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
.host-software-card {
|
||||
.content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -5,7 +5,7 @@ import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
|
||||
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
|
||||
import type { IconName } from '@core/icons'
|
||||
import { useTimeAgo } from '@core/composables/locale-time-ago.composable.ts'
|
||||
import { useMapper } from '@core/packages/mapper'
|
||||
import { createMapper, useMapper } from '@core/packages/mapper'
|
||||
import { parseDateTime } from '@core/utils/time.util.ts'
|
||||
import { toComputed } from '@core/utils/to-computed.util.ts'
|
||||
import { HOST_POWER_STATE } from '@vates/types'
|
||||
@@ -70,20 +70,31 @@ export function useHostUtils(rawHost: MaybeRefOrGetter<XenApiHost | undefined>)
|
||||
|
||||
const currentOperation = useMapper<string, string>(
|
||||
() => pendingStateOperation.value,
|
||||
{
|
||||
() => ({
|
||||
[HOST_OPERATION.ENABLE]: t('operation:enable'),
|
||||
[HOST_OPERATION.EVACUATE]: t('operation:evacuate'),
|
||||
[HOST_OPERATION.POWER_ON]: t('operation:start'),
|
||||
[HOST_OPERATION.REBOOT]: t('operation:clean-reboot'),
|
||||
[HOST_OPERATION.SHUTDOWN]: t('operation:shutdown'),
|
||||
unknown: '',
|
||||
},
|
||||
}),
|
||||
'unknown'
|
||||
)
|
||||
|
||||
const getHostStatus = createMapper<HostState, { text: string; icon: IconName | undefined }>(
|
||||
() => ({
|
||||
running: { text: t('host:status:running'), icon: 'status:running-circle' },
|
||||
halted: { text: t('host:status:halted'), icon: 'status:halted-circle' },
|
||||
disabled: { text: t('host:status:disabled'), icon: 'status:host-disabled-circle' },
|
||||
unknown: { text: t('host:status:unknown'), icon: undefined },
|
||||
}),
|
||||
'unknown'
|
||||
)
|
||||
|
||||
return {
|
||||
isMaster,
|
||||
isRunning,
|
||||
getHostStatus,
|
||||
hostState,
|
||||
powerState,
|
||||
isChangingState,
|
||||
|
||||
@@ -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'
|
||||
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
<template>
|
||||
<UiPanelCard class="storage-repository-infos-card">
|
||||
<UiPanelCard>
|
||||
<UiPanelCardTitle
|
||||
:id="sr.uuid"
|
||||
size="medium"
|
||||
:label="sr.name_label"
|
||||
:icon="sr.name_label ? srStatusIcon : undefined"
|
||||
/>
|
||||
<div class="content">
|
||||
<VtsCardRowList>
|
||||
<VtsCardRowKeyValue>
|
||||
<template #key>{{ t('status') }}</template>
|
||||
<template #value>
|
||||
@@ -56,7 +56,7 @@
|
||||
<template #key>{{ t('high-availability') }}</template>
|
||||
<template #value><VtsStatus :status="isHaSr" /></template>
|
||||
</VtsCardRowKeyValue>
|
||||
</div>
|
||||
</VtsCardRowList>
|
||||
</UiPanelCard>
|
||||
</template>
|
||||
|
||||
@@ -66,6 +66,7 @@ import { useSrUtils } from '@/modules/storage-repository/composables/sr-utils.co
|
||||
import { useSrStore } from '@/stores/xen-api/sr.store.ts'
|
||||
import type { SrScope } from '@core/types/storage-repository.type.ts'
|
||||
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
|
||||
import VtsCardRowList from '@core/components/card/VtsCardRowList.vue'
|
||||
import VtsCopyButton from '@core/components/copy-button/VtsCopyButton.vue'
|
||||
import VtsStatus from '@core/components/status/VtsStatus.vue'
|
||||
import VtsTag from '@core/components/tag/VtsTag.vue'
|
||||
@@ -96,13 +97,3 @@ const allocationStrategy = computed(() => getAllocationStrategy(sr) ?? t('unknow
|
||||
|
||||
const isHaSr = computed(() => isHaSrForPool(sr, pool))
|
||||
</script>
|
||||
|
||||
<style scoped lang="postcss">
|
||||
.storage-repository-infos-card {
|
||||
.content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -5,10 +5,10 @@
|
||||
{{ t('no-pbd-attached') }}
|
||||
</VtsStateHero>
|
||||
<template v-else>
|
||||
<div class="content">
|
||||
<VtsCardRowList class="content">
|
||||
<VtsStatus :status="srConnectionStatus" />
|
||||
</div>
|
||||
<div v-if="areSomePbdsDisconnected" class="content">
|
||||
</VtsCardRowList>
|
||||
<VtsCardRowList v-if="areSomePbdsDisconnected" class="content">
|
||||
<template v-for="(pbd, index) in disconnectedPbds" :key="pbd.uuid">
|
||||
<VtsDivider v-if="index > 0" class="divider" type="stretch" />
|
||||
<UiPanelCardTitle size="small" :label="t('disconnected-pbd-number', { n: index + 1 })" class="subtitle" />
|
||||
@@ -31,7 +31,7 @@
|
||||
accent="info"
|
||||
/>
|
||||
</template>
|
||||
</div>
|
||||
</VtsCardRowList>
|
||||
</template>
|
||||
</UiPanelCard>
|
||||
</template>
|
||||
@@ -43,6 +43,7 @@ import { usePbdUtils } from '@/modules/storage-repository/composables/pbd-utils.
|
||||
import { useSrUtils } from '@/modules/storage-repository/composables/sr-utils.composable.ts'
|
||||
import type { SrScope } from '@core/types/storage-repository.type.ts'
|
||||
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
|
||||
import VtsCardRowList from '@core/components/card/VtsCardRowList.vue'
|
||||
import VtsDivider from '@core/components/divider/VtsDivider.vue'
|
||||
import VtsStateHero from '@core/components/state-hero/VtsStateHero.vue'
|
||||
import VtsStatus from '@core/components/status/VtsStatus.vue'
|
||||
@@ -70,10 +71,6 @@ const { areSomePbdsDisconnected, disconnectedPbds } = usePbdUtils(pbdsInScope)
|
||||
<style scoped lang="postcss">
|
||||
.storage-repository-pbds-card {
|
||||
.content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.4rem;
|
||||
|
||||
.subtitle {
|
||||
margin-block-end: 0.4rem;
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
>
|
||||
{{ branch.data.name_label || '(Host)' }}
|
||||
<template #icon>
|
||||
<VtsObjectIcon v-tooltip="hostState" type="host" size="medium" :state="hostState" />
|
||||
<VtsObjectIcon v-tooltip="powerState.text" type="host" size="medium" :state="hostState" />
|
||||
</template>
|
||||
<template #addons>
|
||||
<UiLoader v-if="isChangingState" v-tooltip="currentOperation" />
|
||||
@@ -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'
|
||||
@@ -63,7 +53,8 @@ const { t } = useI18n()
|
||||
const { isMasterHost } = usePoolStore().subscribe()
|
||||
const { runningVmsCountByHostRef } = useVmStore().subscribe()
|
||||
|
||||
const { hostState, isChangingState, currentOperation } = useHostUtils(() => branch.data)
|
||||
const { getHostStatus, hostState, isChangingState, currentOperation } = useHostUtils(() => branch.data)
|
||||
const powerState = computed(() => getHostStatus(hostState.value))
|
||||
|
||||
const isMaster = computed(() => isMasterHost(branch.data.$ref))
|
||||
|
||||
|
||||
@@ -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<{
|
||||
|
||||
@@ -1,52 +1,40 @@
|
||||
<template>
|
||||
<VtsTreeItem expanded :node-id="leaf.dataId">
|
||||
<VtsTreeItem :node-id="leaf.dataId" expanded>
|
||||
<UiTreeItemLabel :route="{ name: '/vm/[uuid]', params: { uuid: leaf.data.uuid } }" no-indent>
|
||||
{{ leaf.data.name_label || '(VM)' }}
|
||||
<template #icon>
|
||||
<VtsObjectIcon size="medium" :state="powerState" type="vm" />
|
||||
<VtsObjectIcon v-tooltip="powerState.text" :state="vmState" size="medium" type="vm" />
|
||||
</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') }"
|
||||
icon="action:more-actions"
|
||||
accent="brand"
|
||||
size="small"
|
||||
:selected="isOpen"
|
||||
@click="open($event)"
|
||||
/>
|
||||
</template>
|
||||
<VtsActionsMenu placement="bottom-start">
|
||||
<VmTreeActions :vm-opaque-ref="leaf.data.$ref" />
|
||||
</MenuList>
|
||||
</VtsActionsMenu>
|
||||
</template>
|
||||
</UiTreeItemLabel>
|
||||
</VtsTreeItem>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import type { VM_POWER_STATE } from '@/libs/xen-api/xen-api.enums.ts'
|
||||
import type { VmLeaf } from '@/modules/treeview/types/tree.type.ts'
|
||||
import VmTreeActions from '@/modules/vm/components/actions/VmTreeActions.vue'
|
||||
import { useVmOperation } from '@/modules/vm/composables/vm-operation.composable.ts'
|
||||
import MenuList from '@core/components/menu/MenuList.vue'
|
||||
import { useVmUtils } from '@/modules/vm/composables/vm-utils.composable.ts'
|
||||
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)
|
||||
|
||||
const powerState = computed(() => leaf.data.power_state.toLowerCase() as Lowercase<VM_POWER_STATE>)
|
||||
const vmState = computed(() => toLower(leaf.data.power_state))
|
||||
</script>
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<template>
|
||||
<UiPanelCard class="card-container">
|
||||
<UiPanelCardTitle size="medium" :label="t('configuration')" />
|
||||
<div class="content">
|
||||
<VtsCardRowList>
|
||||
<VdiFormatCardItem :format="vdi.sm_config['image-format']" />
|
||||
<VtsCardRowKeyValue>
|
||||
<template #key>
|
||||
@@ -43,7 +43,7 @@
|
||||
<VtsStatus :status="isBootable" />
|
||||
</template>
|
||||
</VtsCardRowKeyValue>
|
||||
</div>
|
||||
</VtsCardRowList>
|
||||
</UiPanelCard>
|
||||
</template>
|
||||
|
||||
@@ -53,6 +53,7 @@ import type { XenApiVbd, XenApiVdi } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import VdiFormatCardItem from '@/modules/vdi/components/list/panel/card-items/VdiFormatCardItem.vue'
|
||||
import { useSrStore } from '@/stores/xen-api/sr.store.ts'
|
||||
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 VtsStatus from '@core/components/status/VtsStatus.vue'
|
||||
import UiLink from '@core/components/ui/link/UiLink.vue'
|
||||
@@ -73,11 +74,6 @@ const isBootable = computed(() => vbd?.bootable ?? false)
|
||||
|
||||
<style scoped lang="postcss">
|
||||
.card-container {
|
||||
.content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
.storage {
|
||||
display: flex;
|
||||
gap: 0.8rem;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<template>
|
||||
<UiPanelCard class="card-container">
|
||||
<UiPanelCard>
|
||||
<UiPanelCardTitle :id="vdi.uuid" size="medium" :label="vdi.name_label" :icon="vdiIcon" />
|
||||
<div class="content">
|
||||
<VtsCardRowList>
|
||||
<VtsCardRowKeyValue truncate align-top>
|
||||
<template #key>{{ t('description') }}</template>
|
||||
<template #value>{{ vdi.name_description }}</template>
|
||||
@@ -36,7 +36,7 @@
|
||||
<VtsCopyButton :value="vbd.device" />
|
||||
</template>
|
||||
</VtsCardRowKeyValue>
|
||||
</div>
|
||||
</VtsCardRowList>
|
||||
</UiPanelCard>
|
||||
</template>
|
||||
|
||||
@@ -45,6 +45,7 @@ import type { XenApiVbd, XenApiVdi } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import { useVbdsStatus, type VbdAttachmentStatus } from '@/modules/vbd/composables/use-vbds-status.composable.ts'
|
||||
import type { IconName } from '@core/icons'
|
||||
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
|
||||
import VtsCardRowList from '@core/components/card/VtsCardRowList.vue'
|
||||
import VtsCopyButton from '@core/components/copy-button/VtsCopyButton.vue'
|
||||
import VtsStatus from '@core/components/status/VtsStatus.vue'
|
||||
import VtsTag from '@core/components/tag/VtsTag.vue'
|
||||
@@ -79,13 +80,3 @@ const vbdsStatus = useMapper<VbdAttachmentStatus, (typeof CONNECTION_STATUS)[key
|
||||
'noneAttached'
|
||||
)
|
||||
</script>
|
||||
|
||||
<style scoped lang="postcss">
|
||||
.card-container {
|
||||
.content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -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<{
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
<!-- VIF -->
|
||||
<UiPanelCard>
|
||||
<UiPanelCardTitle :id="vif.uuid" size="medium" :label="t('vif')" />
|
||||
<div class="content">
|
||||
<VtsCardRowList>
|
||||
<!-- NETWORK -->
|
||||
<VtsCardRowKeyValue>
|
||||
<template #key>
|
||||
@@ -79,32 +79,15 @@
|
||||
{{ isTxChecksummingEnabled(vif) }}
|
||||
</template>
|
||||
</VtsCardRowKeyValue>
|
||||
</div>
|
||||
</VtsCardRowList>
|
||||
</UiPanelCard>
|
||||
<!-- VIF NETWORK INFORMATION -->
|
||||
<UiPanelCard>
|
||||
<UiPanelCardTitle size="medium" :label="t('network-information')" />
|
||||
<div class="content">
|
||||
<VtsCardRowList>
|
||||
<!-- IP ADDRESSES -->
|
||||
<div v-if="ipAddresses.length">
|
||||
<VtsCardRowKeyValue v-for="(ip, index) in ipAddresses" :key="ip">
|
||||
<template #key>
|
||||
<div v-if="index === 0">{{ t('ip-addresses') }}</div>
|
||||
</template>
|
||||
<template #value>{{ ip }}</template>
|
||||
<template #addons>
|
||||
<VtsCopyButton :value="ip" />
|
||||
<VtsCopyAllMenuItem v-if="index === 0 && ipAddresses.length > 1" :values="ipAddresses" />
|
||||
</template>
|
||||
</VtsCardRowKeyValue>
|
||||
</div>
|
||||
<VtsCardRowKeyValue v-else>
|
||||
<template #key>
|
||||
{{ t('ip-addresses') }}
|
||||
</template>
|
||||
<template #value>
|
||||
<span class="value" />
|
||||
</template>
|
||||
<VtsCardRowKeyValue :values="ipAddresses">
|
||||
<template #key>{{ t('ip-addresses') }}</template>
|
||||
</VtsCardRowKeyValue>
|
||||
<!-- MAC ADDRESSES -->
|
||||
<VtsCardRowKeyValue>
|
||||
@@ -118,7 +101,7 @@
|
||||
<VtsCopyButton :value="vif.MAC" />
|
||||
</template>
|
||||
</VtsCardRowKeyValue>
|
||||
</div>
|
||||
</VtsCardRowList>
|
||||
</UiPanelCard>
|
||||
</template>
|
||||
</VtsSidePanel>
|
||||
@@ -133,7 +116,7 @@ import { useNetworkStore } from '@/stores/xen-api/network.store.ts'
|
||||
import { useVmGuestMetricsStore } from '@/stores/xen-api/vm-guest-metrics.store.ts'
|
||||
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
|
||||
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
|
||||
import VtsCopyAllMenuItem from '@core/components/copy-all-menu-item/VtsCopyAllMenuItem.vue'
|
||||
import VtsCardRowList from '@core/components/card/VtsCardRowList.vue'
|
||||
import VtsCopyButton from '@core/components/copy-button/VtsCopyButton.vue'
|
||||
import VtsSidePanel from '@core/components/panel/VtsSidePanel.vue'
|
||||
import VtsStatus from '@core/components/status/VtsStatus.vue'
|
||||
@@ -187,12 +170,6 @@ const rateLimit = computed(() => {
|
||||
|
||||
<style scoped lang="postcss">
|
||||
.vm-vifs-side-panel {
|
||||
.content {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.8rem;
|
||||
}
|
||||
|
||||
.value:empty::before {
|
||||
content: '-';
|
||||
}
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -17,7 +17,7 @@ export function useVmOperation(rawVm: MaybeRefOrGetter<XenApiVm | undefined>) {
|
||||
|
||||
const currentOperation = useMapper<string, string>(
|
||||
() => Object.values(vm.value?.current_operations ?? {})[0],
|
||||
{
|
||||
() => ({
|
||||
start: t('operation:start'),
|
||||
start_on: t('operation:start-on-host'),
|
||||
pause: t('operation:pause'),
|
||||
@@ -36,7 +36,7 @@ export function useVmOperation(rawVm: MaybeRefOrGetter<XenApiVm | undefined>) {
|
||||
export: t('operation:export'),
|
||||
import: t('operation:import'),
|
||||
unknown: '',
|
||||
},
|
||||
}),
|
||||
'unknown'
|
||||
)
|
||||
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
import { VM_POWER_STATE } from '@/libs/xen-api/xen-api.enums.ts'
|
||||
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
|
||||
import type { IconName } from '@core/icons'
|
||||
import { useMapper } from '@core/packages/mapper'
|
||||
import { toComputed } from '@core/utils/to-computed.util.ts'
|
||||
import type { MaybeRefOrGetter } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
export function useVmUtils(rawVm: MaybeRefOrGetter<XenApiVm>) {
|
||||
const { t } = useI18n()
|
||||
|
||||
const vm = toComputed(rawVm)
|
||||
|
||||
const powerState = useMapper<VM_POWER_STATE, { icon: IconName; text: string }>(
|
||||
() => vm.value.power_state,
|
||||
() => ({
|
||||
[VM_POWER_STATE.RUNNING]: { icon: 'status:running-circle', text: t('vm:status:running') },
|
||||
[VM_POWER_STATE.HALTED]: { icon: 'status:halted-circle', text: t('vm:status:halted') },
|
||||
[VM_POWER_STATE.PAUSED]: { icon: 'status:paused-circle', text: t('vm:status:paused') },
|
||||
[VM_POWER_STATE.SUSPENDED]: { icon: 'status:suspended-circle', text: t('vm:status:suspended') },
|
||||
}),
|
||||
VM_POWER_STATE.RUNNING
|
||||
)
|
||||
|
||||
return {
|
||||
powerState,
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,9 @@
|
||||
<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 @click="open($event)">{{ t('new') }}</UiDropdownButton>
|
||||
<UiDropdownButton size="medium" variant="primary" @click="open($event)">{{ t('new') }}</UiDropdownButton>
|
||||
</template>
|
||||
<MenuItem accent="neutral">
|
||||
<UiLink class="new-network-link" :to="{ name: '/network/new' }" icon="fa:plus" size="medium">
|
||||
@@ -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>
|
||||
|
||||
130
@xen-orchestra/lite/src/route-map.d.ts
vendored
130
@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',
|
||||
@@ -317,6 +324,13 @@ declare module 'vue-router/auto-routes' {
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/card/vts-card-row-list': RouteRecordInfo<
|
||||
'/story/web-core/card/vts-card-row-list',
|
||||
'/story/web-core/card/vts-card-row-list',
|
||||
Record<never, never>,
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/story/web-core/cell-object/vts-cell-object': RouteRecordInfo<
|
||||
'/story/web-core/cell-object/vts-cell-object',
|
||||
'/story/web-core/cell-object/vts-cell-object',
|
||||
@@ -366,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',
|
||||
@@ -422,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',
|
||||
@@ -737,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',
|
||||
@@ -1367,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'
|
||||
@@ -1385,6 +1461,12 @@ declare module 'vue-router/auto-routes' {
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/card/vts-card-row-list.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/card/vts-card-row-list'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/stories/web-core/cell-object/vts-cell-object.story.vue': {
|
||||
routes:
|
||||
| '/story/web-core/cell-object/vts-cell-object'
|
||||
@@ -1427,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'
|
||||
@@ -1475,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'
|
||||
@@ -1745,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>
|
||||
@@ -3,7 +3,7 @@
|
||||
v-slot="{ properties, settings }"
|
||||
:params="[
|
||||
slot('key').help('Meant to receive a title'),
|
||||
slot('value').help('Meant to receive text, tags or other value'),
|
||||
slot('value').help('Meant to receive text, tags or other value. Overrides the value rendered from `values`'),
|
||||
slot('addons').help('Meant to receive icons or other actions buttons '),
|
||||
prop('truncate')
|
||||
.type('boolean | number')
|
||||
@@ -21,6 +21,16 @@
|
||||
.help('Whether to align the key on the first line in case of multiline value')
|
||||
.type('boolean')
|
||||
.widget(),
|
||||
prop('values')
|
||||
.help('Values rendered as text with a copy button each, plus a copy all action when there are several')
|
||||
.type('string[]')
|
||||
.widget(object())
|
||||
.preset(['192.168.1.10', '192.168.1.11', '10.0.0.12', 'fe80::a00:27ff:fe4e:66a1']),
|
||||
prop('maxVisibleValues')
|
||||
.help('Number of values shown before a see more button')
|
||||
.type('number')
|
||||
.widget()
|
||||
.preset(3),
|
||||
setting('valueSlotDescription')
|
||||
.preset(
|
||||
'Lorem ipsum dolor sit, amet consectetur adipisicing elit. Velit facilis pariatur maiores officia fugit odit, doloremque obcaecati quisquam distinctio adipisci fugiat incidunt hic rerum? Ullam, natus. Iste eum porro dolorum!'
|
||||
@@ -29,12 +39,16 @@
|
||||
]"
|
||||
>
|
||||
<UiCard class="card">
|
||||
<VtsCardRowKeyValue v-bind="properties">
|
||||
<VtsCardRowKeyValue :values="properties.values" :max-visible-values="properties.maxVisibleValues">
|
||||
<template #key>IP addresses</template>
|
||||
</VtsCardRowKeyValue>
|
||||
|
||||
<VtsCardRowKeyValue v-bind="{ ...properties, values: undefined }">
|
||||
<template #key>Description</template>
|
||||
<template #value>{{ settings.valueSlotDescription }}</template>
|
||||
</VtsCardRowKeyValue>
|
||||
|
||||
<VtsCardRowKeyValue v-bind="properties">
|
||||
<VtsCardRowKeyValue v-bind="{ ...properties, values: undefined }">
|
||||
<template #key>Network</template>
|
||||
<template #value>
|
||||
<UiObjectLink route="`/vm/test/console`" icon="object:network:connected">
|
||||
@@ -46,7 +60,7 @@
|
||||
</template>
|
||||
</VtsCardRowKeyValue>
|
||||
|
||||
<VtsCardRowKeyValue v-bind="properties">
|
||||
<VtsCardRowKeyValue v-bind="{ ...properties, values: undefined }">
|
||||
<template #key>Status</template>
|
||||
<template #value>
|
||||
<UiInfo accent="success">Connected</UiInfo>
|
||||
@@ -57,7 +71,7 @@
|
||||
</template>
|
||||
</VtsCardRowKeyValue>
|
||||
|
||||
<VtsCardRowKeyValue v-bind="{ ...properties, truncate: false }">
|
||||
<VtsCardRowKeyValue v-bind="{ ...properties, truncate: false, values: undefined }">
|
||||
<template #key>Tags</template>
|
||||
<template #value>
|
||||
<UiTagsList v-if="tags.length > 0">
|
||||
@@ -75,7 +89,7 @@
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { prop, setting, slot } from '@/libs/story/story-param.ts'
|
||||
import { choice, text } from '@/libs/story/story-widget.ts'
|
||||
import { choice, object, text } from '@/libs/story/story-widget.ts'
|
||||
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
|
||||
import VtsCopyButton from '@core/components/copy-button/VtsCopyButton.vue'
|
||||
import UiButtonIcon from '@core/components/ui/button-icon/UiButtonIcon.vue'
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
<template>
|
||||
<ComponentStory :params="[slot().help('Meant to receive VtsCardRowKeyValue components')]">
|
||||
<UiCard class="card">
|
||||
<VtsCardRowList>
|
||||
<VtsCardRowKeyValue :values="['10.0.0.12']">
|
||||
<template #key>IP address</template>
|
||||
</VtsCardRowKeyValue>
|
||||
<VtsCardRowKeyValue :values="['1500']">
|
||||
<template #key>MTU</template>
|
||||
</VtsCardRowKeyValue>
|
||||
<VtsCardRowKeyValue>
|
||||
<template #key>Status</template>
|
||||
<template #value>
|
||||
<UiInfo accent="success">Connected</UiInfo>
|
||||
</template>
|
||||
</VtsCardRowKeyValue>
|
||||
</VtsCardRowList>
|
||||
</UiCard>
|
||||
</ComponentStory>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { slot } from '@/libs/story/story-param.ts'
|
||||
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
|
||||
import VtsCardRowList from '@core/components/card/VtsCardRowList.vue'
|
||||
import UiCard from '@core/components/ui/card/UiCard.vue'
|
||||
import UiInfo from '@core/components/ui/info/UiInfo.vue'
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
.card {
|
||||
width: 400px;
|
||||
}
|
||||
</style>
|
||||
@@ -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>
|
||||
|
||||
@@ -1,5 +1,11 @@
|
||||
<template>
|
||||
<ComponentStory v-slot="{ properties }" :params="[iconProp().preset('object:host').required()]">
|
||||
<ComponentStory
|
||||
v-slot="{ properties }"
|
||||
:params="[
|
||||
iconProp().preset('object:host').required(),
|
||||
prop('size').enum('small', 'medium').preset('medium').widget(),
|
||||
]"
|
||||
>
|
||||
<VtsTreeList>
|
||||
<VtsTreeLoadingItem v-bind="properties" />
|
||||
</VtsTreeList>
|
||||
@@ -8,7 +14,7 @@
|
||||
|
||||
<script lang="ts" setup>
|
||||
import ComponentStory from '@/components/component-story/ComponentStory.vue'
|
||||
import { iconProp } from '@/libs/story/story-param.ts'
|
||||
import { iconProp, prop } from '@/libs/story/story-param.ts'
|
||||
import VtsTreeList from '@core/components/tree/VtsTreeList.vue'
|
||||
import VtsTreeLoadingItem from '@core/components/tree/VtsTreeLoadingItem.vue'
|
||||
</script>
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -5,11 +5,15 @@
|
||||
iconProp(),
|
||||
prop('selected').bool().widget(),
|
||||
prop('disabled').bool().widget().ctx(),
|
||||
prop('variant').enum('primary', 'secondary').preset('primary').widget().required(),
|
||||
prop('size').enum('small', 'medium').preset('medium').widget().required(),
|
||||
slot(),
|
||||
setting('defaultSlotContent').preset('Dropdown title').widget(text()).help('Content for default slot'),
|
||||
]"
|
||||
>
|
||||
<UiDropdownButton v-bind="properties">{{ settings.defaultSlotContent }}</UiDropdownButton>
|
||||
<UiDropdownButton v-bind="properties">
|
||||
{{ settings.defaultSlotContent }}
|
||||
</UiDropdownButton>
|
||||
</ComponentStory>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -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>
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user