Compare commits

..

2 Commits

Author SHA1 Message Date
Simon Pacotte
f2e5384667 update changelog 2026-11-18 17:18:10 +01:00
Simon Pacotte
7a9eb86b87 fix(xo-server): keep server statuses in sync with the live connections 2026-11-18 16:59:14 +01:00
1204 changed files with 15065 additions and 57972 deletions

View File

@@ -59,33 +59,6 @@ module.exports = {
'n/no-unpublished-import': 'off',
},
},
// The XO 6 test files share their modules (no isolation): mocking or resetting a module from one file would leak
// into the others. See @xen-orchestra/web/docs/tests/mocking.md
{
files: ['@xen-orchestra/web/src/**/*.unit.test.ts'],
rules: {
'no-restricted-syntax': [
'error',
{
selector: "CallExpression[callee.object.name='vi'][callee.property.name=/^(mock|doMock|unmock|doUnmock)$/]",
message: 'Mock a module with `mockModule` from `@/test/spy-on-module.ts`, never `vi.mock`.',
},
{
selector: "CallExpression[callee.object.name='vi'][callee.property.name='resetModules']",
message: 'The test files share their modules: never reset them.',
},
{
selector: "CallExpression[callee.object.name='vi'][callee.property.name='hoisted']",
message: '`mockModule` is not hoisted: declare the stubs as plain constants.',
},
{
selector: "CallExpression[callee.object.name='vi'][callee.property.name='resetAllMocks']",
message:
'Reset the stubs with `resetStubs` from `@/test/reset-stubs.ts`: `vi.resetAllMocks()` also resets the module mocks.',
},
],
},
},
{
files: ['@xen-orchestra/{web-core,lite,web}/**/*.{vue,ts}'],
parser: 'vue-eslint-parser',
@@ -105,7 +78,6 @@ module.exports = {
typescript: true,
'eslint-import-resolver-custom-alias': {
alias: {
'@core-test': '../web-core/test',
'@core': '../web-core/lib',
'@': './src',
},
@@ -130,7 +102,6 @@ module.exports = {
{ pattern: '@core/packages/*', action: 'ignore' }, // barrel files
{ pattern: '@core/icons', action: 'ignore' },
{ pattern: '@core/**', action: 'enforce' },
{ pattern: '@core-test/**', action: 'enforce' },
{ pattern: '@/**', action: 'enforce' },
],
},
@@ -152,10 +123,6 @@ module.exports = {
pattern: '@core/**',
group: 'internal',
},
{
pattern: '@core-test/**',
group: 'internal',
},
],
},
],

View File

@@ -14,7 +14,7 @@
"url": "https://vates.fr"
},
"license": "ISC",
"version": "0.1.7",
"version": "0.1.6",
"engines": {
"node": ">=8.10"
},
@@ -25,7 +25,7 @@
"dependencies": {
"@vates/multi-key-map": "^0.2.0",
"@xen-orchestra/async-map": "^0.1.5",
"@xen-orchestra/log": "^1.0.0",
"@xen-orchestra/log": "^0.7.2",
"ensure-array": "^1.0.0"
},
"devDependencies": {

View File

@@ -1,6 +1,6 @@
{
"name": "@vates/fuse-vhd",
"version": "2.1.4",
"version": "2.1.3",
"license": "ISC",
"private": false,
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/@vates/fuse-vhd",
@@ -19,12 +19,12 @@
},
"main": "./index.mjs",
"dependencies": {
"@xen-orchestra/fs": "^4.11.0",
"@xen-orchestra/log": "^1.0.0",
"@xen-orchestra/fs": "^4.10.0",
"@xen-orchestra/log": "^0.7.2",
"fuse-native": "^2.2.6",
"lru-cache": "^7.14.0",
"promise-toolbox": "^0.21.0",
"vhd-lib": "^4.17.1"
"vhd-lib": "^4.17.0"
},
"bin": {
"xo-fuse-vhd": "./cli.mjs"

View File

@@ -1,6 +1,6 @@
{
"name": "@vates/iscsi",
"version": "0.4.1",
"version": "0.4.0",
"main": "dist/index.mjs",
"types": "dist/index.d.mts",
"bin": {
@@ -24,7 +24,7 @@
"@vates/async-each": "^1.0.3",
"@vates/read-chunk": "^1.2.1",
"@xen-orchestra/disk-transform": "^1.3.4",
"@xen-orchestra/log": "^1.0.0",
"@xen-orchestra/log": "^0.7.2",
"promise-toolbox": "^0.21.0"
},
"devDependencies": {

View File

@@ -13,7 +13,7 @@
"url": "https://vates.fr"
},
"license": "ISC",
"version": "3.7.1",
"version": "3.7.0",
"engines": {
"node": ">=14.0"
},
@@ -23,9 +23,9 @@
"@vates/read-chunk": "^1.2.1",
"@xen-orchestra/async-map": "^0.1.5",
"@xen-orchestra/disk-transform": "^1.3.4",
"@xen-orchestra/log": "^1.0.0",
"@xen-orchestra/log": "^0.7.2",
"promise-toolbox": "^0.21.0",
"xen-api": "^6.0.0"
"xen-api": "^5.1.0"
},
"devDependencies": {
"tap": "^18.7.0",

View File

@@ -1,6 +1,6 @@
{
"name": "@vates/node-vsphere-soap",
"version": "2.2.1",
"version": "2.2.0",
"description": "interface to vSphere SOAP/WSDL from node for interfacing with vCenter or ESXi, forked from node-vsphere-soap",
"main": "lib/client.mjs",
"author": "reedog117",
@@ -11,7 +11,7 @@
},
"bugs": "https://github.com/vatesfr/xen-orchestra/issues",
"dependencies": {
"@xen-orchestra/log": "^1.0.0",
"@xen-orchestra/log": "^0.7.2",
"axios": "^1.15.0",
"soap": "^1.0.0",
"soap-cookie": "^0.10.1"

View File

@@ -13,7 +13,7 @@
"url": "https://vates.fr"
},
"license": "ISC",
"version": "0.2.0",
"version": "0.1.0",
"engines": {
"node": ">=8.10"
},

View File

@@ -19,7 +19,7 @@
"url": "https://vates.fr"
},
"license": "ISC",
"version": "0.2.0",
"version": "0.1.0",
"engines": {
"node": ">=18"
},

View File

@@ -1,7 +1,7 @@
{
"name": "@vates/types",
"private": false,
"version": "3.0.0",
"version": "2.5.0",
"main": "./dist/index.mjs",
"exports": {
".": {

View File

@@ -759,10 +759,6 @@ export type TrafficRuleProtocol = (typeof TRAFFIC_RULE_PROTOCOLS)[number]
export const SDN_CONTROLLER_OF_RULES_KEY = 'xo:sdn-controller:of-rules'
export const SDN_CONTROLLER_OF_METHOD_KEY = 'xo:sdn-controller:of-method'
export const SDN_CONTROLLER_OF_FORMAT_KEY = 'xo:sdn-controller:of-format'
export const SDN_CONTROLLER_PRIVATE_NETWORK_UUID_KEY = 'xo:sdn-controller:private-network-uuid'
export const SDN_CONTROLLER_ENCRYPTED_KEY = 'xo:sdn-controller:encrypted'
export const SDN_CONTROLLER_ENCAPSULATION_KEY = 'xo:sdn-controller:encapsulation'
export const SDN_CONTROLLER_PREFERRED_CENTER_KEY = 'xo:sdn-controller:preferred-center'
export const TRAFFIC_RULE_PROTOCOLS = ['ARP', 'ICMP', 'IP', 'TCP', 'UDP'] as const
export const TRAFFIC_RULE_PROTOCOLS_WITH_PORT: readonly TrafficRuleProtocol[] = ['TCP', 'UDP']

View File

@@ -190,7 +190,7 @@ export interface Xapi {
deleteNetwork(id: XoNetwork['id']): Promise<void>
deleteVif(vifId: XoVif['id']): Promise<void>
disconnectVif(vifId: XoVif['id']): Promise<void>
exportVmOva(vmRef: XenApiVm['$ref'], opts?: { signal?: AbortSignal }): Promise<PassThrough>
exportVmOva(vmRef: XenApiVm['$ref']): Promise<PassThrough>
emergencyShutdownHost(hostId: XoHost['id']): Promise<void>
ejectHostFromPool(hostId: XoHost['id']): Promise<void>
host_smartReboot(
@@ -352,7 +352,7 @@ export interface Xapi {
): Promise<void>
VM_export(
vmRef: XenApiVm['$ref'],
opts?: { signal?: AbortSignal; compress?: boolean | 'zstd' | 'gzip'; useSnapshot?: boolean }
opts?: { cancelToken?: unknown; compress?: boolean | 'zstd' | 'gzip'; useSnapshot?: boolean }
): ReturnType<Xapi['getResource']>
VM_import(
stream: Readable,
@@ -455,12 +455,12 @@ export interface Xapi {
VDI_destroyCloudInitConfig(vdiRef: XenApiVdi['$ref'], opts?: { timeLimit?: number }): Promise<void>
VDI_exportContent(
vdiRef: XenApiVdi['$ref'],
opts: { baseRef?: string; signal?: AbortSignal; format: SUPPORTED_VDI_FORMAT }
opts: { baseRef?: string; cancelToken?: unknown; format: SUPPORTED_VDI_FORMAT }
): Promise<Readable & { length?: number }>
VDI_importContent(
vdiRef: XenApiVdi['$ref'],
stream: Readable | Buffer,
opts: { signal?: AbortSignal; format: SUPPORTED_VDI_FORMAT }
opts: { cancelToken?: unknown; format: SUPPORTED_VDI_FORMAT }
): Promise<void>
VIF_create(
options: {

View File

@@ -85,7 +85,7 @@ type WrapperXenApi<T, Type extends string, Fn = { (): void }> = T & {
$pool: XenApiPool
$type: Type
$snapshot(params: {
signal?: AbortSignal
cancelToken?: unknown
ignoredVdisTag?: string
name_label?: string
unplugVusbs?: boolean

View File

@@ -155,80 +155,26 @@ export type PoolRollingUpdateRecoveryError = {
}
export type PoolRollingUpdateRecoveryHost = {
/** `interrupted`: left in progress by a run that is over */
status: 'pending' | 'running' | 'interrupted' | 'succeeded' | 'failed' | 'not-needed'
status: 'pending' | 'running' | 'succeeded' | 'failed' | 'not-needed'
steps: Record<RPU_RECOVERY_STEP_NAME, PoolRollingUpdateRecoveryStep>
lastError: PoolRollingUpdateRecoveryError | null
}
/** a VM the last migrate back of the run could not bring to its original host */
export type PoolRollingUpdateRecoveryVmConflict = {
vmId: string
/** unknown for a VM deleted before the run could read it */
vmName?: string
/** UUID of the host the VM was running on before the run */
hostId: string
/** `stopped` and `deleted`: left to the operator; `migration-failed`: retried by a resume */
reason: 'stopped' | 'deleted' | 'migration-failed'
/** XAPI error of the last migration, `migration-failed` only */
message?: string
}
/** what an operator changed, since the run, on a setting the run left changed or on an object of the run */
export type PoolRollingUpdateRecoveryOperatorChange = {
/** `haHeartbeatSr`: a heartbeat SR needed to enable HA again no longer exists */
type: 'ha' | 'autoPowerOn' | 'wlb' | 'schedule' | 'haHeartbeatSr' | 'host' | 'vm'
/** pool, schedule, SR, host or VM UUID */
id: string
/** schedules enabled again only */
name?: string
/** `disabled` as the run left it, `present` for a heartbeat SR, a host or a VM */
expected: 'disabled' | 'present'
/** `missing` for a deleted schedule, heartbeat SR, host or VM */
observed: 'enabled' | 'missing'
}
/** hosts resumes added to the plan of the run: patches released since it started, or hosts new to the pool */
export type PoolRollingUpdateRecoveryPlanChange = {
/** the last resume which added hosts */
attempt: number
/** UUIDs of hosts the run did not plan to update, or had finished, added by any resume */
addedHostIds: string[]
}
export type PoolRollingUpdateRecoveryRun = {
runId: string
poolId: string
/** `awaiting-acceptance`: a resume found operator changes and waits for them to be accepted */
status:
| 'preparing'
| 'running'
| 'interrupted'
| 'resuming'
| 'failed'
| 'cleaning'
| 'succeeded'
| 'awaiting-acceptance'
status: 'preparing' | 'running' | 'interrupted' | 'resuming' | 'failed' | 'cleaning' | 'succeeded'
startedAt: string
updatedAt: string
finishedAt?: string
interruptedAt?: string
taskId?: string
variant?: 'xcp' | 'xs-cdn'
/** 1 for the first attempt, incremented by each resume of the run */
attempt?: number
/** whether a resume would be accepted: run failed, interrupted or awaiting the acceptance of operator changes */
resumable?: boolean
hostOrder?: string[]
hosts: Record<string, PoolRollingUpdateRecoveryHost>
lastError: PoolRollingUpdateRecoveryError | null
/** VM UUID -> UUID of the host it must be started on */
haltedPinnedVms: Record<string, string>
vmConflicts: PoolRollingUpdateRecoveryVmConflict[]
/** found by the last resume, the run stays `awaiting-acceptance` until they are accepted */
operatorChanges: PoolRollingUpdateRecoveryOperatorChange[]
/** absent when no resume changed the plan */
planChange?: PoolRollingUpdateRecoveryPlanChange
}
/** record unreadable or of an unknown schema version: recovery needs a human */
@@ -357,8 +303,6 @@ export type XoApp = EventEmitter & {
checkFeatureAuthorization(featureCode: FeatureCode): Promise<void>
/* whether this machine can run the tools of an import from VMware */
checkEsxiDependencies(): Promise<XoV2vStatus>
/* Throw if the proxy cannot be reached */
checkProxyHealth(id: XoProxy['id']): Promise<void>
/* validate, apply and persist the configuration of a plugin */
configurePlugin(id: string, configuration: unknown, mergeWithExisting?: boolean): Promise<void>
/* connect a server (XCP-ng/XenServer) */
@@ -673,10 +617,6 @@ export type XoApp = EventEmitter & {
): Promise<void>
getRollingUpdateRecovery(poolId: XoPool['id']): Promise<PoolRollingUpdateRecovery | undefined>
finalizeRollingUpdate(pool: XoPool, opts?: { force?: boolean; parentTask?: VatesTask }): Promise<void>
resumeRollingPoolUpdate(
pool: XoPool,
opts?: { acceptOperatorChanges?: boolean; bypassBackupCheck?: boolean; parentTask?: VatesTask }
): Promise<void>
setVmResourceSet(vmId: XoVm['id'], resourceSetId: string | null, force?: boolean): Promise<void>
shareVmResourceSet(vmId: XoVm['id']): Promise<void>
removeUserFromGroup(userId: XoUser['id'], id: XoGroup['id']): Promise<void>

View File

@@ -579,9 +579,6 @@ export type XoBrowserMediaSession = {
export type XoProxy = {
id: Branded<'proxy'>
/**
* @deprecated no replacement for this field
*/
url: string
version?: string
name: string

View File

@@ -6,7 +6,7 @@
"main": "dist/index.mjs",
"name": "@xen-orchestra/acl",
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/@xen-orchestra/acl",
"version": "1.9.0",
"version": "1.8.0",
"license": "AGPL-3.0-or-later",
"private": false,
"type": "module",
@@ -30,7 +30,7 @@
},
"devDependencies": {
"@eslint/js": "^9.19.0",
"@vates/types": "^3.0.0",
"@vates/types": "^2.5.0",
"rimraf": "^6.0.1",
"typescript": "~5.6",
"typescript-eslint": "^8.61.0"

View File

@@ -3,16 +3,7 @@ export default {
delete: true,
forget: true,
import: {
vdi: {
upload: true,
/**
* Warning: lets the holder make XO send a GET request to any HTTP(S) URL, including internal addresses
* reachable from the XO server (localhost, management network, etc.).
*
* Covered by `import:vdi`, `import` and `*`: only grant these to trusted users.
*/
url: true,
},
vdi: true,
vm: true,
},
'migrate-receive': true,

View File

@@ -38,10 +38,33 @@ export class Privilege<T extends SupportedResource> {
}
#matchAction<Resource extends SupportedResource = T>(action: SupportedActions<Resource>) {
// A privilege allows its own action and every action below it in the tree:
// e.g. `*`, `import`, `import:vdi` and `import:vdi:url` all allow `import:vdi:url`,
// but `import:vdi:upload` does not (it is a sibling, not a parent)
return this.#action === '*' || this.#action === action || action.startsWith(`${this.#action}:`)
// read:name_label - read:name_label
if (this.#action === action) {
return true
}
const [namespaceToMatch, actionToMatch] = action.split(':')
const [thisNamespace, thisAction] = this.#action.split(':')
if (thisNamespace === '*') {
return true
}
// update:vm - read:name_label
if (thisNamespace !== namespaceToMatch) {
return false
}
// read - read:name_label
if (thisAction === undefined) {
return true
}
// read:name_decription - read:name_label
if (thisAction !== actionToMatch) {
return false
}
throw new Error(`Unable to verify if ${this.#action} match ${action} `)
}
#matchSelector(object: object) {

View File

@@ -27,12 +27,6 @@ suite('Privilege.checkActionIsValid behavior', () => {
test('should work', () => {
assert.doesNotThrow(() => Privilege.checkActionIsValid('vm', 'read'))
})
test('should work with 3-level actions', () => {
assert.doesNotThrow(() => Privilege.checkActionIsValid('sr', 'import:vdi:url'))
// @ts-expect-error test invalid action
assert.throws(() => Privilege.checkActionIsValid('sr', 'import:vdi:foo'))
})
})
suite('Privilege.match behavior', () => {
@@ -65,22 +59,6 @@ suite('Privilege.match behavior', () => {
const cleanShutdownPrivilege = new Privilege({ action: 'shutdown:clean', resource: 'vm', effect: 'allow' })
assert.strictEqual(cleanShutdownPrivilege.match({ resource: 'vm', action: 'shutdown', object }), false)
})
test('Should match 3-level actions with any parent action', () => {
for (const action of ['*', 'import', 'import:vdi', 'import:vdi:url'] as const) {
const srPrivilege = new Privilege({ action, resource: 'sr', effect: 'allow' })
assert.strictEqual(srPrivilege.match({ resource: 'sr', action: 'import:vdi:url', object }), true, action)
}
})
test('Should not match 3-level actions with a sibling or a child action', () => {
const uploadPrivilege = new Privilege({ action: 'import:vdi:upload', resource: 'sr', effect: 'allow' })
assert.strictEqual(uploadPrivilege.match({ resource: 'sr', action: 'import:vdi:url', object }), false)
assert.strictEqual(uploadPrivilege.match({ resource: 'sr', action: 'import:vdi', object }), false)
const vmImportPrivilege = new Privilege({ action: 'import:vm', resource: 'sr', effect: 'allow' })
assert.strictEqual(vmImportPrivilege.match({ resource: 'sr', action: 'import:vdi:url', object }), false)
})
})
suite('ACL V2 behavior', async () => {
@@ -280,23 +258,6 @@ suite('ACL V2 behavior', async () => {
false
)
})
test('Should allow VDI upload but not URL import with import:vdi allowed and import:vdi:url denied', () => {
const sr = { id: 'sr-id' }
const userPrivileges = [
{ id: privilegeId, action: 'import:vdi', resource: 'sr', effect: 'allow', roleId },
{ id: privilegeId, action: 'import:vdi:url', resource: 'sr', effect: 'deny', roleId },
] satisfies TPrivilege<'sr'>[]
assert.strictEqual(
hasPrivilegeOn({ user, action: 'import:vdi:upload', resource: 'sr', objects: sr, userPrivileges }),
true
)
assert.strictEqual(
hasPrivilegeOn({ user, action: 'import:vdi:url', resource: 'sr', objects: sr, userPrivileges }),
false
)
})
})
suite('getMissingPrivileges behavior', () => {
@@ -414,12 +375,4 @@ suite('getActionStrings', () => {
assert.ok(actions.includes('shutdown:clean'))
assert.ok(actions.includes('shutdown:hard'))
})
test('3-level actions are included alongside their parents', () => {
const actions = getActionStrings('sr')
assert.ok(actions.includes('import'))
assert.ok(actions.includes('import:vdi'))
assert.ok(actions.includes('import:vdi:upload'))
assert.ok(actions.includes('import:vdi:url'))
})
})

View File

@@ -7,7 +7,7 @@
"type": "git",
"url": "https://github.com/vatesfr/xen-orchestra.git"
},
"version": "0.4.1",
"version": "0.4.0",
"engines": {
"node": ">=14"
},
@@ -17,7 +17,7 @@
},
"dependencies": {
"@vates/decorate-with": "^2.1.0",
"@xen-orchestra/log": "^1.0.0",
"@xen-orchestra/log": "^0.7.2",
"golike-defer": "^0.5.1",
"object-hash": "^2.0.1"
},

View File

@@ -1,7 +1,7 @@
{
"private": true,
"name": "@xen-orchestra/autopilot-docking",
"version": "0.1.0",
"version": "0.0.0",
"description": "Live ISO that prepares a VM imported from another hypervisor to boot on XCP-ng",
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/@xen-orchestra/autopilot-docking",
"bugs": "https://github.com/vatesfr/xen-orchestra/issues",

View File

@@ -1,6 +1,6 @@
{
"name": "@xen-orchestra/backup-archive",
"version": "1.2.1",
"version": "1.2.0",
"description": "Helper to handle generic backup archives",
"license": "ISC",
"author": "",
@@ -21,18 +21,18 @@
"tar-stream": "^3.1.8",
"@types/tar-stream": "^3.1.4",
"tmp": "^0.2.1",
"@vates/types": "^3.0.0"
"@vates/types": "^2.5.0"
},
"dependencies": {
"@xen-orchestra/log": "^1.0.0",
"@xen-orchestra/fs": "^4.11.0",
"@xen-orchestra/log": "^0.7.1",
"@xen-orchestra/fs": "^4.10.0",
"@xen-orchestra/disk-transform": "^1.3.4",
"@vates/task": "0.7.0",
"golike-defer": "0.5.1",
"uuid": "^9.0.0",
"promise-toolbox": "^0.21.0",
"@vates/async-each": "^1.0.1",
"vhd-lib": "^4.17.1"
"vhd-lib": "^4.17.0"
},
"scripts": {
"build": "yarn run clean && tsc",

View File

@@ -8,8 +8,8 @@
"dependencies": {
"@vates/async-each": "^1.0.3",
"@xen-orchestra/async-map": "^0.1.5",
"@xen-orchestra/backups": "^1.0.0",
"@xen-orchestra/fs": "^4.11.0",
"@xen-orchestra/backups": "^0.78.0",
"@xen-orchestra/fs": "^4.10.0",
"filenamify": "^6.0.0",
"getopts": "^2.2.5",
"lodash": "^4.18.0",
@@ -28,7 +28,7 @@
"scripts": {
"postversion": "npm publish --access public"
},
"version": "1.1.19",
"version": "1.1.18",
"license": "AGPL-3.0-or-later",
"author": {
"name": "Vates SAS",

View File

@@ -1,21 +0,0 @@
// Similar to `Promise.all` + `map` but passes an abort signal to the callback
//
// If any of the executions fails, the signal is aborted (it also follows the optional parent `signal`) and, once the
// other executions have settled, the first reason is rejected: the caller does not clean up while they are still
// running.
export async function abortableMap(signal, iterable, callback) {
const controller = new AbortController()
const childSignal = signal === undefined ? controller.signal : AbortSignal.any([signal, controller.signal])
const promises = []
try {
for (const item of iterable) {
promises.push(callback(childSignal, item))
}
return await Promise.all(promises)
} catch (error) {
controller.abort(error)
await Promise.allSettled(promises)
throw error
}
}

View File

@@ -1,93 +0,0 @@
import { describe, it } from 'node:test'
import { strict as assert } from 'node:assert'
import { abortableMap } from './_abortableMap.mjs'
const tick = () => new Promise(resolve => setImmediate(resolve))
// resolves once `signal` is aborted
const aborted = signal => new Promise(resolve => signal.addEventListener('abort', resolve, { once: true }))
describe('abortableMap()', () => {
it('works without a parent signal', async () => {
const signals = []
const result = await abortableMap(undefined, [1, 2, 3], async (signal, item) => {
signals.push(signal)
return item * 2
})
assert.deepEqual(result, [2, 4, 6])
assert.ok(signals.every(signal => signal instanceof AbortSignal && !signal.aborted))
})
it('aborts the other items and rejects with the first failure once they have settled', async () => {
const error = new Error('first failure')
const signals = []
const stopped = []
await assert.rejects(
abortableMap(undefined, [1, 2, 3], async (signal, item) => {
signals.push(signal)
if (item === 2) {
throw error
}
await aborted(signal)
await tick() // winds down after the abort
stopped.push(item)
throw new Error(`item ${item} aborted`)
}),
error
)
assert.equal(signals.length, 3)
assert.ok(signals.every(signal => signal.aborted))
// the other items have stopped before the rejection
assert.deepEqual(stopped.sort(), [1, 3])
})
it('stops at a synchronous failure, and aborts and waits for the items already started', async () => {
const error = new Error('synchronous failure')
const started = []
const stopped = []
await assert.rejects(
abortableMap(undefined, [1, 2, 3], (signal, item) => {
if (item === 2) {
throw error
}
started.push(item)
return aborted(signal).then(() => {
stopped.push(item)
})
}),
error
)
assert.deepEqual(started, [1])
assert.deepEqual(stopped, [1])
})
it('aborts every item when the parent signal is aborted', async () => {
const parent = new AbortController()
const signals = []
const promise = abortableMap(parent.signal, [1, 2], (signal, item) => {
signals.push(signal)
return new Promise((resolve, reject) => signal.addEventListener('abort', () => reject(signal.reason)))
})
await tick()
assert.ok(signals.every(signal => !signal.aborted))
const reason = new Error('cancelled')
parent.abort(reason)
await assert.rejects(promise, reason)
assert.ok(signals.every(signal => signal.aborted))
})
it('does not abort the parent signal on failure', async () => {
const parent = new AbortController()
await assert.rejects(abortableMap(parent.signal, [1], async () => Promise.reject(new Error('fail'))))
assert.equal(parent.signal.aborted, false)
})
})

View File

@@ -0,0 +1,20 @@
import cancelable from 'promise-toolbox/cancelable'
import CancelToken from 'promise-toolbox/CancelToken'
// Similar to `Promise.all` + `map` but pass a cancel token to the callback
//
// If any of the executions fails, the cancel token will be triggered and the
// first reason will be rejected.
export const cancelableMap = cancelable(async function cancelableMap($cancelToken, iterable, callback) {
const { cancel, token } = CancelToken.source([$cancelToken])
try {
return await Promise.all(
Array.from(iterable, function (item) {
return callback.call(this, token, item)
})
)
} catch (error) {
await cancel()
throw error
}
})

View File

@@ -1,11 +1,12 @@
import groupBy from 'lodash/groupBy.js'
import ignoreErrors from 'promise-toolbox/ignoreErrors'
import { asyncMap } from '@xen-orchestra/async-map'
import { CancelToken } from 'promise-toolbox'
import { compareVersions } from 'compare-versions'
import { defer } from 'golike-defer'
import { Task } from '@vates/task'
import { abortableMap } from './_abortableMap.mjs'
import { cancelableMap } from './_cancelableMap.mjs'
import pick from 'lodash/pick.js'
import { BASE_DELTA_VDI, CONTENT_KEY, COPY_OF, VM_UUID } from './_otherConfig.mjs'
@@ -26,13 +27,17 @@ export async function updateMemoryFields(xapi, targetVm, vmRecord) {
await xapi.call('VM.set_memory_limits', targetVm.$ref, staticMin, staticMax, dynamicMin, dynamicMax)
}
export async function exportIncrementalVm(vm, baseVdis = {}, { signal, nbdConcurrency = 1, preferNbd } = {}) {
export async function exportIncrementalVm(
vm,
baseVdis = {},
{ cancelToken = CancelToken.none, nbdConcurrency = 1, preferNbd } = {}
) {
// refs of VM's VDIs → base's VDIs.
const disks = {}
const vdis = {}
const vbds = {}
await abortableMap(signal, vm.$VBDs, async (signal, vbd) => {
await cancelableMap(cancelToken, vm.$VBDs, async (cancelToken, vbd) => {
let vdi
if (vbd.type !== 'Disk' || !(vdi = vbd.$VDI)) {
// Ignore this VBD.
@@ -130,7 +135,12 @@ export const importIncrementalVm = defer(async function importIncrementalVm(
$defer,
incrementalVm,
sr,
{ signal, newMacAddresses = false, targetRef = undefined, vmNamePrefix = '[Importing…] ' } = {}
{
cancelToken = CancelToken.none,
newMacAddresses = false,
targetRef = undefined,
vmNamePrefix = '[Importing…] ',
} = {}
) {
const { version } = incrementalVm
if (compareVersions(version, '1.0.0') < 0) {
@@ -331,7 +341,7 @@ export const importIncrementalVm = defer(async function importIncrementalVm(
const { disks } = incrementalVm
await Promise.all([
// Import VDI contents.
abortableMap(signal, Object.entries(newVdis), async (signal, [id, vdi]) => {
cancelableMap(cancelToken, Object.entries(newVdis), async (cancelToken, [id, vdi]) => {
for (const disk of ensureArray(disks[id])) {
if (disk === null) {
// we restore a backup and reuse completely a local snapshot
@@ -348,7 +358,7 @@ export const importIncrementalVm = defer(async function importIncrementalVm(
format = 'vhd'
}
await vdi.$importContent(stream, { signal, format })
await vdi.$importContent(stream, { cancelToken, format })
await xapi.setField('VDI', vdi.$ref, 'name_label', vdiRecords[id].name_label)
}

View File

@@ -8,9 +8,9 @@
"type": "git",
"url": "https://github.com/vatesfr/xen-orchestra.git"
},
"version": "1.0.0",
"version": "0.78.0",
"engines": {
"node": ">=22.19"
"node": ">=14.18"
},
"scripts": {
"postversion": "npm publish --access public",
@@ -24,20 +24,20 @@
"@vates/cached-dns.lookup": "^1.0.0",
"@vates/compose": "^2.1.0",
"@vates/decorate-with": "^2.1.0",
"@vates/disposable": "^0.1.7",
"@vates/fuse-vhd": "^2.1.4",
"@vates/disposable": "^0.1.6",
"@vates/fuse-vhd": "^2.1.3",
"@vates/generator-toolbox": "^1.1.3",
"@vates/nbd-client": "^3.7.1",
"@vates/nbd-client": "^3.7.0",
"@vates/parse-duration": "^0.1.1",
"@vates/task": "^0.7.0",
"@vates/types": "^3.0.0",
"@vates/types": "^2.5.0",
"@xen-orchestra/async-map": "^0.1.5",
"@xen-orchestra/disk-transform": "^1.3.4",
"@xen-orchestra/fs": "^4.11.0",
"@xen-orchestra/log": "^1.0.0",
"@xen-orchestra/fs": "^4.10.0",
"@xen-orchestra/log": "^0.7.2",
"@xen-orchestra/qcow2": "^1.4.1",
"@xen-orchestra/template": "^0.1.1",
"@xen-orchestra/backup-archive": "^1.2.1",
"@xen-orchestra/backup-archive": "^1.2.0",
"app-conf": "^3.0.0",
"compare-versions": "^6.0.0",
"complex-matcher": "^1.1.1",
@@ -56,8 +56,8 @@
"tar": "^7.5.19",
"uuid": "^9.0.0",
"value-matcher": "^0.2.0",
"vhd-lib": "^4.17.1",
"xen-api": "^6.0.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"
@@ -70,7 +70,7 @@
"typescript": "^5.9.3"
},
"peerDependencies": {
"@xen-orchestra/xapi": "^10.0.0"
"@xen-orchestra/xapi": "^9.1.0"
},
"license": "AGPL-3.0-or-later",
"author": {

View File

@@ -1,7 +1,7 @@
{
"private": false,
"name": "@xen-orchestra/cr-seed-cli",
"version": "1.0.4",
"version": "1.0.3",
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/@xen-orchestra/cr-seed-cli",
"bugs": "https://github.com/vatesfr/xen-orchestra/issues",
"repository": {
@@ -18,7 +18,7 @@
"preferGlobal": true,
"dependencies": {
"golike-defer": "^0.5.1",
"xen-api": "^6.0.0"
"xen-api": "^5.1.0"
},
"scripts": {
"postversion": "npm publish"

View File

@@ -1,7 +1,7 @@
{
"private": false,
"name": "@xen-orchestra/disk-cli",
"version": "2.2.6",
"version": "2.2.5",
"description": "CLI tool to inspect and manage disks in backup repositories",
"type": "module",
"bin": {
@@ -20,13 +20,13 @@
},
"dependencies": {
"@vates/async-each": "^1.0.3",
"@xen-orchestra/backups": "^1.0.0",
"@xen-orchestra/backup-archive": "^1.2.1",
"@xen-orchestra/backups": "^0.78.0",
"@xen-orchestra/backup-archive": "^1.2.0",
"@xen-orchestra/disk-transform": "^1.3.4",
"@xen-orchestra/fs": "^4.11.0",
"@xen-orchestra/fs": "^4.10.0",
"@xen-orchestra/qcow2": "^1.4.1",
"promise-toolbox": "^0.21.0",
"vhd-lib": "^4.17.1"
"vhd-lib": "^4.17.0"
},
"devDependencies": {
"@types/node": "^22.3.0",

View File

@@ -1,7 +1,7 @@
{
"private": false,
"name": "@xen-orchestra/fs",
"version": "4.11.0",
"version": "4.10.0",
"license": "AGPL-3.0-or-later",
"description": "The File System for Xen Orchestra backups.",
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/@xen-orchestra/fs",
@@ -30,7 +30,7 @@
"@vates/coalesce-calls": "^0.1.0",
"@vates/decorate-with": "^2.1.0",
"@vates/read-chunk": "^1.2.1",
"@xen-orchestra/log": "^1.0.0",
"@xen-orchestra/log": "^0.7.2",
"bind-property-descriptor": "^2.0.0",
"decorator-synchronized": "^0.6.0",
"execa": "^5.0.0",

View File

@@ -16,14 +16,14 @@
"xo-immutable-remote": "./dist/protectRemotes.mjs"
},
"license": "AGPL-3.0-or-later",
"version": "3.0.10",
"version": "3.0.9",
"engines": {
"node": ">=20.0.0"
},
"dependencies": {
"@vates/async-each": "^1.0.3",
"@xen-orchestra/backups": "^1.0.0",
"@xen-orchestra/log": "^1.0.0",
"@xen-orchestra/backups": "^0.78.0",
"@xen-orchestra/log": "^0.7.2",
"app-conf": "^3.0.0",
"execa": "^5.0.0",
"ms": "^2.1.3"

View File

@@ -2,8 +2,6 @@
## **next**
- [Web-Core/UiCircleProgressBar] Add a brand accent and an option to hide the value (PR [#10849](https://github.com/vatesfr/xen-orchestra/pull/10849))
- [Tables] Cells fit on one line: long names are cut in the middle, extra tags go under "+N" and long texts end with "…" (PR [#10850](https://github.com/vatesfr/xen-orchestra/pull/10850))
- [Pages] The page header and tabs now stay in place on every page: dashboards, System tabs, consoles, tasks, settings and creation forms scroll under them instead of scrolling with them (PR [#10822](https://github.com/vatesfr/xen-orchestra/pull/10822))
- [VM/Host] Main actions (shutdown, reboot, start, resume, migrate, snapshot) are shown as buttons in the VM and host headers and move one by one into "More actions" when space runs out; "More actions" groups them under "Change state" and "Actions" sections, and VMs without guest tools get force shutdown and force reboot instead (PR [#10815](https://github.com/vatesfr/xen-orchestra/pull/10815))
- [Web-Core/UiButtonIcon] Update icon buttons design, with a counter replacing the notification dot (PR [#10799](https://github.com/vatesfr/xen-orchestra/pull/10799))
@@ -14,8 +12,6 @@
- [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))
- [Side panels] Fix the double scrollbar when the side panel content is taller than the screen: the page header now stays in place, and the list and the side panel each scroll on their own. All scrollbars are now thin, like the side panel one (PR [#10807](https://github.com/vatesfr/xen-orchestra/pull/10807))
- [Mobile] Searchable dropdown lists no longer overflow the screen (PR [#10854](https://github.com/vatesfr/xen-orchestra/pull/10854))
- [New/VM] Fix the storage table overflowing horizontally, which hid part of the delete button (PR [#10851](https://github.com/vatesfr/xen-orchestra/pull/10851))
## **0.27.0** (2026-10-29)

View File

@@ -27,13 +27,13 @@
"@types/file-saver": "^2.0.7",
"@types/lodash-es": "^4.17.12",
"@types/node": "^18.19.80",
"@vates/types": "^3.0.0",
"@vates/types": "^2.5.0",
"@vitejs/plugin-vue": "^6.0.0",
"@vue/tsconfig": "^0.9.0",
"@vueuse/core": "^14.0.0",
"@vueuse/math": "^14.0.0",
"@vueuse/shared": "^14.0.0",
"@xen-orchestra/web-core": "^0.66.0",
"@xen-orchestra/web-core": "^0.65.0",
"complex-matcher": "^1.1.1",
"d3-time-format": "^4.1.0",
"decorator-synchronized": "^0.6.0",

View File

@@ -2,12 +2,12 @@
<div class="collection-filter-row">
<span class="or">{{ t('or') }}</span>
<div class="inputs">
<UiInput v-if="newFilter.isAdvanced" v-model="filterContent" accent="neutral" class="advanced-input" />
<UiInput v-if="newFilter.isAdvanced" v-model="filterContent" accent="brand" class="advanced-input" />
<template v-else>
<VtsSelect :id="builderPropertySelectId" accent="neutral" />
<VtsSelect v-if="hasComparisonSelect" :id="builderComparisonSelectId" accent="neutral" />
<VtsSelect v-if="currentFilter?.type === 'enum'" :id="builderValueSelectId" accent="neutral" />
<UiInput v-else-if="hasValueInput" v-model="newFilter.builder.value" accent="neutral" />
<VtsSelect :id="builderPropertySelectId" accent="brand" />
<VtsSelect v-if="hasComparisonSelect" :id="builderComparisonSelectId" accent="brand" />
<VtsSelect v-if="currentFilter?.type === 'enum'" :id="builderValueSelectId" accent="brand" />
<UiInput v-else-if="hasValueInput" v-model="newFilter.builder.value" accent="brand" />
</template>
</div>
<div class="buttons">

View File

@@ -1,9 +1,8 @@
<template>
<VtsResponsiveMenu :title="t('account')" :section-title="t('menu')" placement="bottom-end">
<template #trigger="{ open, isOpen, bindings }">
<template #trigger="{ open, isOpen }">
<UiAccountMenuButton
v-tooltip="isOpen ? false : { content: t('settings'), placement: 'left' }"
v-bind="bindings"
:selected="isOpen"
size="medium"
@click="open($event)"

View File

@@ -14,14 +14,8 @@
<UiTabItem v-bind="tab(TAB.SLOTS, slotParams)">Slots</UiTabItem>
<UiTabItem v-bind="tab(TAB.SETTINGS, settingParams)">Settings</UiTabItem>
<MenuList placement="bottom">
<template #trigger="{ open, isOpen, bindings }">
<UiTabItem
v-bind="bindings"
:active="isOpen"
:disabled="presets === undefined"
class="preset-tab"
@click="open"
>
<template #trigger="{ open, isOpen }">
<UiTabItem :active="isOpen" :disabled="presets === undefined" class="preset-tab" @click="open">
<VtsIcon name="fa:sliders" size="medium" />
Presets
</UiTabItem>

View File

@@ -1,5 +1,5 @@
<template>
<VtsSelect v-if="isSelectWidget(widget)" :id="selectId" accent="neutral" />
<VtsSelect v-if="isSelectWidget(widget)" :id="selectId" accent="brand" />
<UiRadioButtonGroup v-else-if="isRadioWidget(widget)" accent="brand" gap="wide">
<UiRadioButton
v-for="choice in widget.choices"

View File

@@ -1,7 +1,7 @@
<template>
<VtsInputGroup>
<UiInput v-model.number="sizeInput" accent="neutral" type="number" :max-decimals="3" />
<VtsSelect :id="prefixSelectId" accent="neutral" />
<UiInput v-model.number="sizeInput" accent="brand" type="number" :max-decimals="3" />
<VtsSelect :id="prefixSelectId" accent="brand" />
</VtsInputGroup>
</template>

View File

@@ -2,8 +2,8 @@
<UiModal accent="info" @dismiss="emit('cancel')" @confirm="handleSubmit()">
<template #content>
<div class="form-selects">
<VtsSelect :id="sortPropertySelectId" accent="neutral" />
<VtsSelect :id="isAscendingSelectId" accent="neutral" />
<VtsSelect :id="sortPropertySelectId" accent="brand" />
<VtsSelect :id="isAscendingSelectId" accent="brand" />
</div>
</template>

View File

@@ -7,7 +7,7 @@
@dismiss="emit('cancel')"
>
<template #content>
<UiTextarea v-model="editedJson" accent="neutral" class="modal-textarea" />
<UiTextarea v-model="editedJson" accent="brand" class="modal-textarea" />
<VtsOverlayButton variant="tertiary" @click="formatJson()">
{{ t('action:reformat') }}
</VtsOverlayButton>

View File

@@ -8,7 +8,7 @@
:label="t('select-compression')"
learn-more-url="https://xcp-ng.org/blog/2018/12/19/zstd-compression-for-xcp-ng/"
>
<VtsSelect :id="compressionSelectId" accent="neutral" />
<VtsSelect :id="compressionSelectId" accent="brand" />
</VtsInputWrapper>
</template>
<template #buttons>

View File

@@ -7,7 +7,7 @@
<template #content>
<div>
<VtsInputWrapper :label="t('select-destination-host')">
<VtsSelect :id="hostSelectId" accent="neutral" />
<VtsSelect :id="hostSelectId" accent="brand" />
</VtsInputWrapper>
</div>
</template>

View File

@@ -45,7 +45,6 @@ const emit = defineEmits<{
const { t } = useI18n()
const { HeadCells, BodyCells, colspan } = useNewVmNetworkColumns({
exclude: ['rank'],
body: ({ networkInterface, onRemove }: { networkInterface: NetworkInterface; onRemove: () => void }) => {
const { id: interfaceSelectId } = useFormSelect(networks, {
model: toRef(networkInterface, 'interface'),

View File

@@ -1,5 +1,5 @@
<template>
<VtsTable class="new-vm-sr-table" fixed>
<VtsTable>
<thead>
<tr>
<HeadCells />
@@ -49,7 +49,6 @@ const emit = defineEmits<{
const { t } = useI18n()
const { HeadCells, BodyCells, colspan } = useNewVmSrColumns({
exclude: ['rank'],
body: ({ vdi, onRemove }: { vdi: Vdi; onRemove?: () => void }) => {
const { id: srSelectId } = useFormSelect(() => srs, {
model: toRef(vdi, 'SR'),
@@ -77,9 +76,3 @@ const { HeadCells, BodyCells, colspan } = useNewVmSrColumns({
},
})
</script>
<style lang="postcss" scoped>
.new-vm-sr-table {
--vts-table-min-width: 80rem;
}
</style>

View File

@@ -59,7 +59,7 @@ const useTaskColumns = defineColumns(() => {
const { t } = useI18n()
return {
name: useTextColumn({ headerLabel: t('name'), flexible: true }),
name: useTextColumn({ headerLabel: t('name') }),
host: useLinkColumn({ headerLabel: t('host') }),
progress: useProgressBarColumn({ headerLabel: t('progress') }),
started: useDateColumn({ headerLabel: t('started') }),

View File

@@ -1,8 +1,7 @@
<template>
<VtsMobileMenu v-if="uiStore.isSmall" :title="t('actions')">
<template #trigger="{ isOpen, open, bindings }">
<template #trigger="{ isOpen, open }">
<UiButtonIcon
v-bind="bindings"
accent="brand"
size="small"
:disabled="selectedRefs.length === 0"

View File

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

View File

@@ -1,6 +1,6 @@
<template>
<VtsInputWrapper :label :message="error">
<VtsSelect :id accent="neutral" />
<VtsSelect :id accent="brand" />
</VtsInputWrapper>
</template>

View File

@@ -1,6 +1,6 @@
<template>
<VtsInputWrapper :label :message="error">
<UiInput v-model.trim="model" accent="neutral" :required :disabled />
<UiInput v-model.trim="model" accent="brand" :required :disabled />
</VtsInputWrapper>
</template>

View File

@@ -1,5 +1,5 @@
<template>
<UiTextarea v-model.trim="model" accent="neutral">
<UiTextarea v-model.trim="model" accent="brand">
{{ t('description') }}
</UiTextarea>
</template>

View File

@@ -1,5 +1,5 @@
<template>
<UiTextarea v-model.trim="model" :accent="errorMessage !== undefined ? 'danger' : 'neutral'">
<UiTextarea v-model.trim="model" :accent="errorMessage !== undefined ? 'danger' : 'brand'">
{{ t('allowed-ips') }}
<template #info>{{ t('allowed-ips-example') }}</template>

View File

@@ -1,11 +1,6 @@
<template>
<VtsInputWrapper :label="t('mac-address')" :message="messages" wrap-message>
<UiInput
v-model.trim="model"
accent="neutral"
:required
:placeholder="required ? undefined : t('auto-generated')"
/>
<UiInput v-model.trim="model" accent="brand" :required :placeholder="required ? undefined : t('auto-generated')" />
</VtsInputWrapper>
</template>

View File

@@ -1,6 +1,6 @@
<template>
<VtsInputWrapper :label="t('network')" :message="error">
<VtsSelect :id accent="neutral">
<VtsSelect :id accent="brand">
<template v-if="slots.option" #default="slotProps">
<slot name="option" v-bind="slotProps" />
</template>

View File

@@ -1,6 +1,6 @@
<template>
<VtsInputWrapper :label="t('rate-limit')" :message="error">
<UiInput v-model.number="model" accent="neutral" type="number">
<UiInput v-model.number="model" accent="brand" type="number">
<template #right-icon>
<span class="unit typo-body-regular">{{ t('bytes:kbs') }}</span>
</template>

View File

@@ -4,10 +4,8 @@
<PoolNetworksTable :networks="networksWithPifs" :busy="!isReady" :error="hasError">
<template #title-actions>
<VtsResponsiveMenu :title="t('new')" placement="bottom-end">
<template #trigger="{ open, bindings }">
<UiDropdownButton v-bind="bindings" size="medium" variant="primary" @click="open($event)">
{{ t('new') }}
</UiDropdownButton>
<template #trigger="{ open }">
<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">

View File

@@ -103,7 +103,7 @@
<VtsKeyValueList>
<VtsKeyValueRow>
<template #label>
<VtsSelect :id="localeSelectId" accent="neutral" />
<VtsSelect :id="localeSelectId" accent="brand" />
</template>
<template #value>
<UiLink size="medium" href="https://translate.vates.tech/engage/xen-orchestra/">

View File

@@ -10,7 +10,7 @@
<UiTitle>{{ t('template') }}</UiTitle>
<div class="template-container">
<VtsInputWrapper :label="t('action:pick-template')">
<VtsSelect :id="templateSelectId" accent="neutral" />
<VtsSelect :id="templateSelectId" accent="brand" />
</VtsInputWrapper>
</div>
<div v-if="vmState.new_vm_template" class="form-container">
@@ -30,7 +30,7 @@
{{ t('iso-dvd') }}
</UiRadioButton>
</UiRadioButtonGroup>
<VtsSelect v-if="vmState.installMode === 'ISO'" :id="vdiIsoSelectId" accent="neutral" />
<VtsSelect v-if="vmState.installMode === 'ISO'" :id="vdiIsoSelectId" accent="brand" />
</div>
<div v-else class="install-settings-container">
<UiRadioButtonGroup
@@ -45,7 +45,7 @@
{{ t('pxe') }}
</UiRadioButton>
</UiRadioButtonGroup>
<VtsSelect v-if="vmState.installMode === 'ISO'" :id="vdiIsoSelectId" accent="neutral" />
<VtsSelect v-if="vmState.installMode === 'ISO'" :id="vdiIsoSelectId" accent="brand" />
</div>
</div>
<!-- SYSTEM SECTION -->
@@ -54,11 +54,11 @@
<div class="system-container">
<div class="column">
<VtsInputWrapper :label="t('new-vm:name')">
<UiInput v-model.trim="vmState.name" accent="neutral" />
<UiInput v-model.trim="vmState.name" accent="brand" />
</VtsInputWrapper>
<VtsInputWrapper :label="t('tags')">
<!-- TODO Change input text into select when Thierry's component is available -->
<UiInput v-model.trim="vmState.tag" accent="neutral" @keydown.enter.prevent="addTag" />
<UiInput v-model.trim="vmState.tag" accent="brand" @keydown.enter.prevent="addTag" />
</VtsInputWrapper>
<div v-if="vmState.tags.length > 0" class="chips">
<UiChip v-for="(tag, index) in vmState.tags" :key="index" accent="info" @remove="removeTag(index)">
@@ -66,7 +66,7 @@
</UiChip>
</div>
<VtsInputWrapper :label="t('boot-firmware')">
<VtsSelect :id="bootFirmwareSelectId" accent="neutral" />
<VtsSelect :id="bootFirmwareSelectId" accent="brand" />
</VtsInputWrapper>
<div
v-if="vmState.boot_firmware !== 'uefi'"
@@ -93,11 +93,11 @@
</UiCheckboxGroup>
</div>
<div class="column">
<UiTextarea v-model="vmState.description" accent="neutral">
<UiTextarea v-model="vmState.description" accent="brand">
{{ t('new-vm:description') }}
</UiTextarea>
<VtsInputWrapper :label="t('affinity-host')">
<VtsSelect :id="affinityHostSelectId" accent="neutral" />
<VtsSelect :id="affinityHostSelectId" accent="brand" />
</VtsInputWrapper>
</div>
</div>
@@ -105,15 +105,15 @@
<UiTitle>{{ t('resource-management') }}</UiTitle>
<div class="resource-management-container">
<VtsInputWrapper :label="t('vcpus')">
<UiInput v-model.number="vmState.vCPU" type="number" accent="neutral" />
<UiInput v-model.number="vmState.vCPU" type="number" accent="brand" />
</VtsInputWrapper>
<!-- TODO remove (GB) when we can use new selector -->
<VtsInputWrapper :label="`${t('ram')} (GB)`">
<UiInput v-model.number="ramFormatted" type="number" accent="neutral" />
<UiInput v-model.number="ramFormatted" type="number" accent="brand" />
</VtsInputWrapper>
<VtsInputWrapper :label="t('topology')">
<div class="topology">
<VtsSelect :id="topologySelectId" accent="neutral" />
<VtsSelect :id="topologySelectId" accent="brand" />
</div>
</VtsInputWrapper>
</div>

View File

@@ -62,12 +62,12 @@
<FormSection :label="t('configuration')">
<div class="row">
<VtsInputWrapper :label="t('storage')" :message="t('n-gb-required', { n: REQUIRED_GB })">
<VtsSelect :id="srSelectId" accent="neutral" />
<VtsSelect :id="srSelectId" accent="brand" />
</VtsInputWrapper>
</div>
<div class="row">
<VtsInputWrapper :label="t('network')">
<VtsSelect :id="networkSelectId" accent="neutral" />
<VtsSelect :id="networkSelectId" accent="brand" />
</VtsInputWrapper>
<VtsInputWrapper
:label="t('deploy-xoa-custom-ntp-servers')"

View File

@@ -492,13 +492,6 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/middle-ellipsis/vts-middle-ellipsis': RouteRecordInfo<
'/story/web-core/middle-ellipsis/vts-middle-ellipsis',
'/story/web-core/middle-ellipsis/vts-middle-ellipsis',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/number-input/vts-number-input': RouteRecordInfo<
'/story/web-core/number-input/vts-number-input',
'/story/web-core/number-input/vts-number-input',
@@ -562,13 +555,6 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/select/vts-detailed-option': RouteRecordInfo<
'/story/web-core/select/vts-detailed-option',
'/story/web-core/select/vts-detailed-option',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/select/vts-select': RouteRecordInfo<
'/story/web-core/select/vts-select',
'/story/web-core/select/vts-select',
@@ -632,20 +618,6 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/tag/vts-tag': RouteRecordInfo<
'/story/web-core/tag/vts-tag',
'/story/web-core/tag/vts-tag',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/tag-select/vts-tag-select': RouteRecordInfo<
'/story/web-core/tag-select/vts-tag-select',
'/story/web-core/tag-select/vts-tag-select',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/tags-input/vts-tags-input': RouteRecordInfo<
'/story/web-core/tags-input/vts-tags-input',
'/story/web-core/tags-input/vts-tags-input',
@@ -653,13 +625,6 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/task/vts-task-list': RouteRecordInfo<
'/story/web-core/task/vts-task-list',
'/story/web-core/task/vts-task-list',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/tree/vts-tree-item': RouteRecordInfo<
'/story/web-core/tree/vts-tree-item',
'/story/web-core/tree/vts-tree-item',
@@ -996,13 +961,6 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/ui/overridden/ui-overridden': RouteRecordInfo<
'/story/web-core/ui/overridden/ui-overridden',
'/story/web-core/ui/overridden/ui-overridden',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/ui/panel/ui-panel': RouteRecordInfo<
'/story/web-core/ui/panel/ui-panel',
'/story/web-core/ui/panel/ui-panel',
@@ -1143,6 +1101,13 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/ui/task-list/ui-task-list': RouteRecordInfo<
'/story/web-core/ui/task-list/ui-task-list',
'/story/web-core/ui/task-list/ui-task-list',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/ui/title/ui-title': RouteRecordInfo<
'/story/web-core/ui/title/ui-title',
'/story/web-core/ui/title/ui-title',
@@ -1696,12 +1661,6 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/stories/web-core/middle-ellipsis/vts-middle-ellipsis.story.vue': {
routes:
| '/story/web-core/middle-ellipsis/vts-middle-ellipsis'
views:
| never
}
'src/stories/web-core/number-input/vts-number-input.story.vue': {
routes:
| '/story/web-core/number-input/vts-number-input'
@@ -1756,12 +1715,6 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/stories/web-core/select/vts-detailed-option.story.vue': {
routes:
| '/story/web-core/select/vts-detailed-option'
views:
| never
}
'src/stories/web-core/select/vts-select.story.vue': {
routes:
| '/story/web-core/select/vts-select'
@@ -1816,30 +1769,12 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/stories/web-core/tag/vts-tag.story.vue': {
routes:
| '/story/web-core/tag/vts-tag'
views:
| never
}
'src/stories/web-core/tag-select/vts-tag-select.story.vue': {
routes:
| '/story/web-core/tag-select/vts-tag-select'
views:
| never
}
'src/stories/web-core/tags-input/vts-tags-input.story.vue': {
routes:
| '/story/web-core/tags-input/vts-tags-input'
views:
| never
}
'src/stories/web-core/task/vts-task-list.story.vue': {
routes:
| '/story/web-core/task/vts-task-list'
views:
| never
}
'src/stories/web-core/tree/vts-tree-item.story.vue': {
routes:
| '/story/web-core/tree/vts-tree-item'
@@ -2128,12 +2063,6 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/stories/web-core/ui/overridden/ui-overridden.story.vue': {
routes:
| '/story/web-core/ui/overridden/ui-overridden'
views:
| never
}
'src/stories/web-core/ui/panel/ui-panel.story.vue': {
routes:
| '/story/web-core/ui/panel/ui-panel'
@@ -2254,6 +2183,12 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/stories/web-core/ui/task-list/ui-task-list.story.vue': {
routes:
| '/story/web-core/ui/task-list/ui-task-list'
views:
| never
}
'src/stories/web-core/ui/title/ui-title.story.vue': {
routes:
| '/story/web-core/ui/title/ui-title'

View File

@@ -4,7 +4,7 @@
<div class="row">
Choose a component
<VtsSelect :id="componentSelectId" accent="neutral" />
<VtsSelect :id="componentSelectId" accent="brand" />
</div>
<div class="row">

View File

@@ -4,7 +4,7 @@
<template #content>
<div class="demo-rename-modal-content">
<VtsInputWrapper label="New name">
<UiInput v-model.trim="newName" accent="neutral" required />
<UiInput v-model.trim="newName" accent="brand" required />
</VtsInputWrapper>
<p>
Tip: name the VM "fail" to make the fake API call fail: the confirmation modal closes and this modal stays

View File

@@ -20,8 +20,8 @@
]"
>
<MenuList v-if="settings.inMenu" placement="bottom-start">
<template #trigger="{ open, bindings }">
<UiButtonIcon v-bind="bindings" accent="brand" icon="action:more-actions" size="medium" @click="open($event)" />
<template #trigger="{ open }">
<UiButtonIcon accent="brand" icon="action:more-actions" size="medium" @click="open($event)" />
</template>
<VtsActionButton v-bind="properties">{{ settings.label }}</VtsActionButton>
</MenuList>

View File

@@ -1,8 +1,8 @@
<template>
<ComponentStory :params="[slot().help('Power state actions, shown in the submenu')]">
<MenuList placement="bottom-start">
<template #trigger="{ open, bindings }">
<UiButtonIcon v-bind="bindings" accent="brand" icon="action:more-actions" size="medium" @click="open($event)" />
<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>

View File

@@ -5,13 +5,13 @@
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').prop('bindings', 'MenuTriggerBindings'),
slot('trigger').prop('open', '() => void').prop('isOpen', 'boolean'),
slot().help('Menu items, a submenu opens in place'),
]"
>
<VtsMobileMenu v-bind="properties">
<template #trigger="{ open, bindings }">
<UiButtonIcon v-bind="bindings" accent="brand" icon="action:more-actions" size="medium" @click="open()" />
<template #trigger="{ open }">
<UiButtonIcon accent="brand" icon="action:more-actions" size="medium" @click="open()" />
</template>
<MenuItem accent="brand" icon="action:change-state">
Change state

View File

@@ -7,16 +7,13 @@
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')
.prop('bindings', 'MenuTriggerBindings'),
slot('trigger').prop('open', '(event: MouseEvent) => void').prop('isOpen', 'boolean'),
slot().help('Menu items'),
]"
>
<VtsResponsiveMenu v-bind="properties">
<template #trigger="{ open, isOpen, bindings }">
<UiDropdownButton v-bind="bindings" variant="primary" size="medium" :selected="isOpen" @click="open($event)">
<template #trigger="{ open, isOpen }">
<UiDropdownButton variant="primary" size="medium" :selected="isOpen" @click="open($event)">
New
</UiDropdownButton>
</template>

View File

@@ -1,24 +0,0 @@
<template>
<ComponentStory
v-slot="{ properties, settings }"
:params="[
prop('text')
.str()
.required()
.preset('prod-web-frontend-eu-west-01')
.widget()
.help('Rendered as is when it fits, cut in the middle otherwise, with the full text in a tooltip'),
prop('tailLength').num().default(10).widget().help('Number of characters kept visible at the end of a cut text'),
setting('width').widget(number()).preset(15).help('Available width, in rem'),
]"
>
<VtsMiddleEllipsis v-bind="properties" :style="{ width: `${settings.width}rem` }" />
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { prop, setting } from '@/libs/story/story-param.ts'
import { number } from '@/libs/story/story-widget.ts'
import VtsMiddleEllipsis from '@core/components/middle-ellipsis/VtsMiddleEllipsis.vue'
</script>

View File

@@ -1,53 +0,0 @@
<template>
<ComponentStory
v-slot="{ properties }"
:params="[
prop('option')
.required()
.obj('FormOption<{ accent?: DropdownAccent }>')
.help('Given by the default slot of VtsSelect'),
iconProp().preset('object:network'),
prop('iconTooltip').str().widget(),
prop('details').str().widget().preset('eth0').help('Displayed after a dash'),
]"
:presets="{
'PIF with VLAN': {
props: {
icon: 'object:network',
details: 'eth1, VLAN 20',
},
},
'Disabled VM': {
props: {
icon: 'object:vm:running',
iconTooltip: 'Running',
details: 'No VIF detected',
},
},
'Without details': {
props: {
icon: 'object:network',
details: undefined,
},
},
}"
>
<VtsSelect :id="optionSelectId" accent="neutral">
<template #default="{ option }">
<VtsDetailedOption v-bind="properties" :option />
</template>
</VtsSelect>
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { iconProp, prop } from '@/libs/story/story-param.ts'
import VtsDetailedOption from '@core/components/select/VtsDetailedOption.vue'
import VtsSelect from '@core/components/select/VtsSelect.vue'
import { useFormSelect } from '@core/packages/form-select'
const optionLabels = ['Pool-wide network associated with eth0', 'Storage network']
const { id: optionSelectId } = useFormSelect(optionLabels)
</script>

View File

@@ -2,32 +2,36 @@
<ComponentStory
v-slot="{ properties }"
:params="[
prop('accent').required().enum('neutral', 'success', 'warning', 'danger').preset('neutral').widget(),
prop('id').required().obj('FormSelectId').preset(id),
prop('accent').required().enum('brand', 'warning', 'danger').preset('brand').widget(),
prop('options').required().arr('FormOption<TEntry, TValue>').widget().preset(options),
prop('selectedLabel').str(),
prop('required').bool().widget(),
prop('placeholder').str().widget().preset('Choose colors'),
prop('searchPlaceholder').str().widget().preset('Search colors'),
prop('loading').bool().widget(),
model('search'),
slot(),
]"
>
<VtsSelect v-bind="properties" />
<VtsSelect v-bind="properties" v-model:search="searchTerm" :selected-label />
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { prop, slot } from '@/libs/story/story-param.ts'
import { model, prop, slot } from '@/libs/story/story-param.ts'
import VtsSelect from '@core/components/select/VtsSelect.vue'
import { useFormSelect } from '@core/packages/form-select'
import { upperFirst } from 'lodash-es'
const colors = ['blue', 'yellow', 'red', 'green', 'orange', 'purple', 'white', 'grey', 'black']
const { id } = useFormSelect(colors, {
option: {
label: color => `${upperFirst(color)} color`,
disabled: color => color === 'blue' || color === 'orange' || color === 'black',
},
const { options, searchTerm, selectedLabel } = useFormSelect(colors, {
properties: color => ({
value: color,
label: `${upperFirst(color)} color`,
disabled: color === 'blue' || color === 'orange' || color === 'black',
}),
multiple: true,
searchable: true,
placeholder: 'Choose colors',
searchPlaceholder: 'Search colors',
})
</script>

View File

@@ -1,46 +0,0 @@
<template>
<ComponentStory
v-slot="{ properties }"
:params="[
prop('tags').arr('string').required().help('Currently selected tags. The component never mutates it'),
prop('suggestions').arr('TagSelectSuggestion').preset(suggestions).widget(),
prop('iconOnly').bool().widget().help('Displays the `Add`/`Edit` trigger as an icon with a tooltip'),
prop('busy').bool().widget().help('Displays the trigger as busy, e.g. while the tags are being saved'),
event('save')
.args({ changes: 'TagSelectChanges' })
.help('Emitted with the added and removed tags when clicking `Save`. `Cancel` discards the changes'),
]"
>
<UiTagsList>
<VtsTag v-for="tag of tags" :key="tag" :value="tag" accent="brand" />
<VtsTagSelect v-bind="properties" :tags @save="changes => saveTags(changes)" />
</UiTagsList>
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { event, prop } from '@/libs/story/story-param.ts'
import VtsTag from '@core/components/tag/VtsTag.vue'
import VtsTagSelect, {
type TagSelectChanges,
type TagSelectSuggestion,
} from '@core/components/tag-select/VtsTagSelect.vue'
import UiTagsList from '@core/components/ui/tag/UiTagsList.vue'
import { ref } from 'vue'
const tags = ref(['production', 'env=prod'])
const suggestions: TagSelectSuggestion[] = [
{ tag: 'production' },
{ tag: 'staging' },
{ tag: 'env=prod' },
{ tag: 'env=dev' },
{ tag: 'xo:no-bak', info: 'Excludes the VM from backups' },
{ tag: 'xo:notify-on-snapshot', info: 'Notifies when a snapshot is created' },
]
function saveTags({ added, removed }: TagSelectChanges) {
tags.value = [...tags.value.filter(tag => !removed.includes(tag)), ...added]
}
</script>

View File

@@ -1,36 +0,0 @@
<template>
<ComponentStory
v-slot="{ properties }"
:params="[
prop('value')
.str()
.required()
.preset('env=prod')
.widget()
.help('Tags in the `term=label` form are displayed as a tertiary tag'),
prop('accent')
.type('TagAccent')
.enum('brand', 'info', 'neutral', 'success', 'warning', 'danger', 'muted')
.default('info')
.widget(),
prop('variant')
.type('TagVariant')
.enum('primary', 'secondary')
.default('secondary')
.widget()
.help('Ignored when the tag is displayed as a tertiary tag'),
prop('wrap')
.bool()
.widget()
.help('Stacks the term above the value when they do not fit on one line (tertiary tag only)'),
]"
>
<VtsTag v-bind="properties" />
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { prop } from '@/libs/story/story-param.ts'
import VtsTag from '@core/components/tag/VtsTag.vue'
</script>

View File

@@ -9,6 +9,6 @@ The label comes from the surrounding `VtsInputWrapper`.
```vue-template
<VtsInputWrapper label="Values">
<VtsTagsInput v-model="values" accent="neutral" placeholder="Add a value" />
<VtsTagsInput v-model="values" accent="brand" placeholder="Add a value" />
</VtsInputWrapper>
```

View File

@@ -3,7 +3,7 @@
v-slot="{ properties }"
:params="[
model().type('string[]').preset(['alpha', 'beta']).help('Enter or comma adds the typed value'),
prop('accent').enum('neutral', 'warning', 'danger').required().preset('neutral').widget(),
prop('accent').enum('brand', 'warning', 'danger').required().preset('brand').widget(),
prop('placeholder').str().preset('Add a value').widget(),
]"
>

View File

@@ -1,33 +0,0 @@
<template>
<ComponentStory
v-slot="{ properties }"
:params="[
prop('tasks').type('Task[]').required().preset(allTasks),
prop('selectedTaskId').str().widget(),
prop('showEyeIcon').bool().widget(),
prop('autoCollapseCompleted').bool().widget(),
prop('expandAll')
.bool()
.widget()
.help('Shows every task expanded; turning it off restores the tasks expanded before'),
prop('unreadTaskIds').type('ReadonlySet<string>').help('Shows an unread dot column, with a dot for these tasks'),
event('select').args({ id: 'string' }),
]"
:presets="{
'Unread tasks': {
props: {
unreadTaskIds: new Set(['1', '1-2', '4', '9', '9-2', '9-2-1']),
},
},
}"
>
<VtsTaskList v-bind="properties" />
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { event, prop } from '@/libs/story/story-param.ts'
import { allTasks } from '@/stories/web-core/ui/task-item/mock-tasks.ts'
import VtsTaskList from '@core/components/task/VtsTaskList.vue'
</script>

View File

@@ -14,7 +14,6 @@
prop('disabled').bool().widget().ctx(),
prop('lockIcon').bool().widget(),
iconProp('leftIcon'),
iconProp('rightIcon'),
setting('label').preset('Click me').widget(),
]"
:presets="{

View File

@@ -7,7 +7,7 @@
prop('accent')
.type('CircleProgressBarAccent')
.required()
.enum('brand', 'info', 'warning', 'danger')
.enum('info', 'warning', 'danger')
.preset('info')
.widget(),
prop('size')
@@ -16,7 +16,6 @@
.enum('extra-small', 'small', 'medium', 'large')
.preset('large')
.widget(),
prop('noValue').bool().widget(),
]"
:presets
>
@@ -36,7 +35,6 @@ const presets = {
maxValue: 500,
size: 'medium',
accent: 'info',
noValue: false,
},
},
'75% of 300': {
@@ -45,34 +43,6 @@ const presets = {
maxValue: 300,
size: 'medium',
accent: 'info',
noValue: false,
},
},
'Value above max (success)': {
props: {
value: 150,
maxValue: 100,
size: 'medium',
accent: 'info',
noValue: false,
},
},
'Value above max (warning)': {
props: {
value: 150,
maxValue: 100,
size: 'medium',
accent: 'warning',
noValue: false,
},
},
'Brand ring without value': {
props: {
value: 1,
maxValue: 3,
size: 'small',
accent: 'brand',
noValue: true,
},
},
}

View File

@@ -3,7 +3,7 @@
v-slot="{ properties }"
:params="[
model().type('string | number').preset(''),
prop('accent').enum('neutral', 'success', 'warning', 'danger').required().preset('neutral').widget(),
prop('accent').enum('brand', 'warning', 'danger').required().preset('brand').widget(),
prop('id').str().widget(),
prop('required').bool().widget(),
prop('selected').bool().widget(),

View File

@@ -3,7 +3,7 @@
v-slot="{ properties, settings }"
:params="[
model().type('string').preset(''),
prop('accent').enum('neutral', 'warning', 'danger').required().preset('neutral').widget(),
prop('accent').enum('brand', 'warning', 'danger').required().preset('brand').widget(),
prop('disabled').bool().widget(),
prop('href').str().widget(),
prop('max-characters').num().help('When used, it will display the character count under the input').widget(),

View File

@@ -1,19 +0,0 @@
<template>
<ComponentStory
v-slot="{ settings }"
:params="[
slot().help('Label displayed next to the dot, leave empty to only display the dot'),
setting('defaultSlot').widget(text()).preset('Overridden'),
]"
>
<UiOverridden v-if="settings.defaultSlot">{{ settings.defaultSlot }}</UiOverridden>
<UiOverridden v-else />
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { setting, slot } from '@/libs/story/story-param.ts'
import { text } from '@/libs/story/story-widget.ts'
import UiOverridden from '@core/components/ui/overridden/UiOverridden.vue'
</script>

View File

@@ -6,7 +6,7 @@
.type('TagAccent')
.required()
.preset('info')
.enum('brand', 'info', 'neutral', 'success', 'warning', 'danger', 'muted')
.enum('info', 'neutral', 'success', 'warning', 'danger', 'muted')
.widget(),
prop('variant').type('TagVariant').required().preset('primary').enum('primary', 'secondary').widget(),
slot(),

View File

@@ -6,21 +6,15 @@
.type('TagAccent')
.required()
.preset('info')
.enum('brand', 'info', 'neutral', 'success', 'warning', 'danger', 'muted')
.enum('info', 'neutral', 'success', 'warning', 'danger', 'muted')
.widget(),
prop('truncate')
.bool()
.widget()
.help('Keeps the tag on one line: the longer part ends with an ellipsis first, the shorter one stays whole'),
prop('wrap').bool().widget().help('Stacks the term above the value when they do not fit on one line'),
slot(),
slot('term'),
setting('slot').preset('Label').widget(),
setting('term').preset('term').widget(),
setting('maxWidth').widget(number()).help('Maximum width, in rem'),
]"
>
<UiTertiaryTag v-bind="properties" :style="{ maxWidth: settings.maxWidth ? `${settings.maxWidth}rem` : undefined }">
<UiTertiaryTag v-bind="properties">
{{ settings.slot }}
<template #term>
{{ settings.term }}
@@ -32,6 +26,5 @@
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { prop, setting, slot } from '@/libs/story/story-param.ts'
import { number } from '@/libs/story/story-widget.ts'
import UiTertiaryTag from '@core/components/ui/tag/UiTertiaryTag.vue'
</script>

View File

@@ -67,107 +67,10 @@ export const deepNestedTask: Task = {
],
}
export const pendingWithoutProgressTask: Task = {
id: '6',
name: 'Queued replication',
status: 'pending',
start: Date.now() - 2 * 60_000,
}
export const pendingFullProgressTask: Task = {
id: '7',
name: 'Finalize export',
status: 'pending',
progress: 100,
start: Date.now() - 60_000,
infos: [{ message: 'Waiting for cleanup', data: null }],
}
export const infosAndWarningsTask: Task = {
id: '8',
name: 'Rolling pool update',
status: 'pending',
progress: 50,
start: Date.now() - 3 * 60 * 60_000,
infos: [{ message: 'Hosts updated', data: { hosts: 4, done: 2 } }],
warnings: [{ message: 'Reboot required after update', data: { host: 'host-3' } }],
subtasks: [
{ id: '8-1', name: 'host-1', status: 'success', progress: 100, end: Date.now() - 2 * 60 * 60_000 },
{ id: '8-2', name: 'host-2', status: 'success', progress: 100, end: Date.now() - 60 * 60_000 },
{ id: '8-3', name: 'host-3', status: 'pending', progress: 30, start: Date.now() - 15 * 60_000 },
],
}
export const failedNestedTask: Task = {
id: '9',
name: 'Disaster recovery drill',
status: 'failure',
progress: 100,
start: Date.now() - 8 * 60 * 60_000,
end: Date.now() - 7 * 60 * 60_000,
subtasks: [
{ id: '9-1', name: 'Provision VM', status: 'success', progress: 100, end: Date.now() - 7.5 * 60 * 60_000 },
{
id: '9-2',
name: 'Restore data',
status: 'failure',
progress: 100,
end: Date.now() - 7 * 60 * 60_000,
warnings: [{ message: 'Missing backup files', data: { missing: 3 } }],
subtasks: [
{ id: '9-2-1', name: 'Mount SR', status: 'failure', progress: 100, end: Date.now() - 7.1 * 60 * 60_000 },
],
},
],
}
export const interruptedTask: Task = {
id: '10',
name: 'Storage migration',
status: 'interrupted',
progress: 10,
start: Date.now() - 2 * 60 * 60_000,
infos: [
{ message: 'Rows migrated before interruption', data: { rows: 1200 } },
{ message: 'Task manually aborted', data: null },
],
}
export const longNameTask: Task = {
id: '11',
name: 'Very long task name that should wrap gracefully in the task list UI when space is limited',
status: 'pending',
progress: 8,
start: Date.now() - 2 * 60 * 60_000,
}
export const longNameWithEverythingTask: Task = {
id: '12',
name: 'Very long task name for a full backup job that also has subtasks, infos, warnings and an end time to display',
to: '#',
status: 'failure',
progress: 100,
start: Date.now() - 5 * 60 * 60_000,
end: Date.now() - 4 * 60 * 60_000,
infos: [{ message: 'Transferred 120 GiB', data: { size: 120 } }],
warnings: [{ message: 'Some VDIs were skipped', data: { skipped: 2 } }],
subtasks: [
{ id: '12-1', name: 'Snapshot', status: 'success', progress: 100, end: Date.now() - 4.5 * 60 * 60_000 },
{ id: '12-2', name: 'Transfer', status: 'failure', progress: 100, end: Date.now() - 4 * 60 * 60_000 },
],
}
export const allTasks: Task[] = [
pendingBackupTask,
completedWithRootLinkTask,
failedWithWarningsTask,
migrationNamePartsTask,
deepNestedTask,
pendingWithoutProgressTask,
pendingFullProgressTask,
infosAndWarningsTask,
failedNestedTask,
interruptedTask,
longNameTask,
longNameWithEverythingTask,
]

View File

@@ -4,22 +4,27 @@
:presets
:params="[
prop('task').type('object').required().widget().preset(pendingBackupTask),
prop('depth').type('number').required().preset(1),
model('expanded').prop(p => p.type('boolean').widget(boolean()).preset(false)),
prop('selected').type('boolean').widget(boolean()).preset(false),
prop('showEyeIcon').type('boolean').widget(boolean()).preset(true),
prop('showUnread').bool().widget().help('Reserves the unread dot column'),
prop('unread').bool().widget(),
event('expand'),
event('select').args({ id: 'string' }),
]"
>
<UiTaskItem v-bind="properties" />
<ul>
<UiTaskItem v-bind="properties" @expand="properties['onUpdate:expanded']?.(!properties.expanded)" />
</ul>
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { event, prop } from '@/libs/story/story-param.ts'
import { event, model, prop } from '@/libs/story/story-param.ts'
import { boolean } from '@/libs/story/story-widget.ts'
import {
completedWithRootLinkTask,
deepNestedTask,
failedWithWarningsTask,
migrationNamePartsTask,
pendingBackupTask,
@@ -35,24 +40,45 @@ const presets: Record<
'Pending backup': {
props: {
task: pendingBackupTask,
depth: 1,
expanded: false,
selected: false,
showEyeIcon: true,
},
},
'Completed + root link': {
props: {
task: completedWithRootLinkTask,
depth: 1,
expanded: false,
selected: false,
showEyeIcon: true,
},
},
'Failed + warnings': {
props: {
task: failedWithWarningsTask,
depth: 1,
expanded: false,
selected: false,
showEyeIcon: true,
},
},
'Migration (nameParts)': {
props: {
task: migrationNamePartsTask,
depth: 1,
expanded: false,
selected: false,
showEyeIcon: true,
},
},
'Deep nested': {
props: {
task: deepNestedTask,
depth: 1,
expanded: true,
selected: false,
showEyeIcon: true,
},
},

View File

@@ -0,0 +1,15 @@
<template>
<ComponentStory
v-slot="{ properties }"
:params="[prop('tasks').type('Task[]').required().preset(allTasks), event('select')]"
>
<UiTaskList v-bind="properties" />
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { event, prop } from '@/libs/story/story-param.ts'
import { allTasks } from '@/stories/web-core/ui/task-item/mock-tasks.ts'
import UiTaskList from '@core/components/ui/task-list/UiTaskList.vue'
</script>

View File

@@ -1,7 +1,7 @@
{
"private": false,
"name": "@xen-orchestra/log",
"version": "1.0.0",
"version": "0.7.2",
"license": "ISC",
"description": "Logging system with decoupled producers/consumer",
"keywords": [

View File

@@ -1,7 +1,7 @@
{
"private": false,
"name": "@xen-orchestra/mcp",
"version": "1.4.4",
"version": "1.4.3",
"description": "MCP server for Xen Orchestra — allows AI assistants to query and manage XO infrastructure",
"type": "module",
"main": "./dist/index.mjs",
@@ -34,7 +34,7 @@
"devDependencies": {
"@eslint/js": "^9.19.0",
"@types/node": "^22.3.0",
"@vates/types": "^3.0.0",
"@vates/types": "^2.5.0",
"rimraf": "^6.0.0",
"typescript": "~5.6.3",
"typescript-eslint": "^8.61.0"

View File

@@ -1,9 +1,8 @@
import { createLogger } from '@xen-orchestra/log'
import { EventEmitter } from 'node:events'
import { makeOnProgress } from '@vates/task/combineEvents'
import { forbiddenOperation, noSuchObject } from 'xo-common/api-errors.js'
import { noSuchObject } from 'xo-common/api-errors.js'
import { Task, serializeError } from '@vates/task'
import jsonStringifySafe from 'json-stringify-safe'
import iteratee from 'lodash/iteratee.js'
import stubTrue from 'lodash/stubTrue.js'
@@ -11,30 +10,7 @@ export { Task }
const { warn } = createLogger('xo:mixins:Tasks')
// a copy, as the store returns: a live log keeps changing, and must not be changed by the caller. Like the store of
// xo-server when it saves a log, circular references are replaced instead of making the copy fail.
const copyLog = log => {
let json
try {
json = JSON.stringify(log)
} catch {
json = jsonStringifySafe(log)
}
return JSON.parse(json)
}
// the tasks of a log tree that have not ended, each one after its subtasks
function* openTasks(taskLog) {
const { tasks } = taskLog
if (tasks !== undefined) {
for (const subtask of tasks) {
yield* openTasks(subtask)
}
}
if (taskLog.status === 'pending') {
yield taskLog
}
}
const noop = Function.prototype
const DEFAULT_BACKUP_LOG_KEEP_DURATION = 31 * 24 * 60 * 60 * 1000
@@ -62,73 +38,33 @@ export default class Tasks extends EventEmitter {
#onProgressBuffer = new Map()
#handleOnProgressScheduled = false
// root logs of live tasks (internal and external), from their first event until their final state is persisted
#liveLogs = new Map()
// a watcher must not prevent the other watchers from being notified, nor the persistence of the other updates
#emitSafely(event, taskLog) {
for (const listener of this.rawListeners(event)) {
try {
listener.call(this, taskLog)
} catch (error) {
warn('failure in task watcher', { error, event, taskLog })
}
}
}
#handleOnProgressBuffer = async () => {
const buf = this.#onProgressBuffer
const liveLogs = this.#liveLogs
const store = this.#store
try {
do {
for (const [id, taskLog] of buf) {
buf.delete(id)
// read before the write: an event arriving during the write changes the log and buffers the id again
const { status } = taskLog
const isFinal = status !== 'pending'
const deleteAfterNotify = isFinal && this.#logsToClearOnSuccess.delete(id) && status === 'success'
// the final state of a clear-on-success task is notified on its id, then its log is deleted
let written = false
this.#emitSafely(id, taskLog)
if (deleteAfterNotify) {
try {
const storedLog = await this.#deleteStored(id)
if (storedLog !== undefined) {
this.#emitSafely('remove', storedLog)
}
written = true
} catch (error) {
warn('failure on deleting task log from store', { error, taskLog })
}
} else {
this.#emitSafely('update', taskLog)
try {
await store.put(id, taskLog)
written = true
} catch (error) {
warn('failure on saving task log in store', { error, taskLog })
}
do {
for (const [id, taskLog] of buf) {
buf.delete(id)
if (taskLog === null) {
try {
await this.deleteLog(id)
} catch (error) {
warn('failure on deleting task log from store', { error, taskLog })
}
} else {
this.emit(id, taskLog)
this.emit('update', taskLog)
// keep the live entry until the final state is persisted: a newer state of the same task may be buffered,
// and if the write failed the store still holds an older state, which watchers must not get
// (the entry then stays until restart, which marks the stored log interrupted)
if (isFinal && written && !buf.has(id)) {
liveLogs.delete(id)
try {
await store.put(id, taskLog)
} catch (error) {
warn('failure on saving task log in store', { error, taskLog })
}
}
} while (buf.size !== 0) // new events may have been added during iteration
} finally {
// re-armed right after the last check of the buffer, with no await in between: an event buffered after it
// schedules a new flush. Also re-armed if the flush failed, otherwise nothing is persisted until restart.
this.#handleOnProgressScheduled = false
}
}
} while (buf.size !== 0) // new events may have been added during iteration
this.#handleOnProgressScheduled = false
}
#bufferTaskUpdate = taskLog => {
@@ -149,8 +85,16 @@ export default class Tasks extends EventEmitter {
}
const { $root } = taskLog
const { id } = $root
this.#liveLogs.set(id, $root)
const { status, id } = $root
if (status !== 'pending') {
if (this.#logsToClearOnSuccess.has(id)) {
this.#logsToClearOnSuccess.delete(id)
if (status === 'success') {
return buf.set(id, null)
}
}
}
$root.updatedAt = Date.now()
buf.set(id, $root)
@@ -184,13 +128,10 @@ export default class Tasks extends EventEmitter {
.on('start', async () => {
this.#store = await app.getStore('tasks')
// from the store only: list() also returns the live tasks, which must not be marked interrupted
for await (const [, taskLog] of this.#store.iterator()) {
if (taskLog.status === 'pending') {
taskLog.status = 'interrupted'
taskLog.updatedAt = Date.now()
await this.#store.put(taskLog.id, taskLog)
}
for await (const taskLog of this.list({ filter: _ => _.status === 'pending' })) {
taskLog.status = 'interrupted'
taskLog.updatedAt = Date.now()
await this.#store.put(taskLog.id, taskLog)
}
return () => this.#store.close()
@@ -217,18 +158,7 @@ export default class Tasks extends EventEmitter {
const deleteEntry = data => {
++count
// cb may already have been called by the store if the error comes after the deletion
let done = false
const once = () => {
if (!done) {
done = true
cb()
}
}
this.deleteLog(data.key, once).catch(error => {
warn('failure on deleting task log from store', { error, id: data.key })
once()
})
this.deleteLog(data.key, cb)
}
const stream = db.createReadStream({
@@ -263,156 +193,26 @@ export default class Tasks extends EventEmitter {
* Each call returns an independent makeOnProgress context (isolated taskLogs
* Map), so concurrent backup jobs don't interfere with each other.
*
* Options:
* - abort: `(reason) => …` called by `tasks.abort(rootId, reason)` while the
* root task runs. Without it, aborting the task fails with `forbiddenOperation`.
*
* The returned handler has an `end({ status = 'interrupted', reason })` method for
* a source that disappeared without ending its root task. It ends the open
* tasks, innermost first, through the same path as the events of the source,
* so the caller's hooks run and may change the status (for backups,
* `handleBackupLog` recomputes it). Hook errors are rethrown once every open
* task is ended. Once `end()` has ended the open tasks, later events are
* dropped: the first one with a warning, the next ones silently. Called
* before the first event or after the root task ended, it does nothing.
* Abort support for external tasks is not implemented — the external process
* controls its own lifecycle.
*/
createExternalProgressHandler({ abort, onRootTaskEnd, onRootTaskStart, onTaskUpdate } = {}) {
// error thrown by the caller's onRootTaskEnd: the final state must still be buffered (see onTaskUpdate below)
let rootEndError
// logs of the root tasks accepted by makeOnProgress and not yet ended: end() walks their trees
const openRoots = new Set()
let closed = false
// a source that keeps sending events after end() is reported once
let warnedAfterClose = false
const onProgress = makeOnProgress({
onRootTaskEnd: (taskLog, event) => {
// the task can no longer be aborted once it ended
this.#tasks.delete(taskLog.id)
// subtasks the source left open end with their root: end() no longer sees them
openRoots.delete(taskLog)
try {
onRootTaskEnd?.(taskLog, event)
} catch (error) {
rootEndError = { error }
}
},
onRootTaskStart: (taskLog, event) => {
// tracked here, once makeOnProgress has registered it, in case the caller's hook throws
openRoots.add(taskLog)
if (abort !== undefined) {
this.#tasks.set(taskLog.id, { abort })
}
onRootTaskStart?.(taskLog, event)
},
createExternalProgressHandler({ onRootTaskEnd, onRootTaskStart, onTaskUpdate } = {}) {
return makeOnProgress({
onRootTaskEnd,
onRootTaskStart,
onTaskUpdate: (taskLog, event) => {
// a subtask whose start had an unknown parent is registered by makeOnProgress, which then throws before
// calling this hook: it has no root, so its later events are ignored
if (taskLog.$root === undefined) {
warn('event of a task without root task ignored', { event })
return
}
this.#bufferTaskUpdate(taskLog)
onTaskUpdate?.(taskLog, event)
},
})
// feeds one event, then rethrows the error of the root end hook, if any
const feed = event => {
try {
onProgress(event)
} catch (error) {
// the root end error carries the result of the task: it wins over a later hook error (onTaskUpdate),
// and must not be thrown on a later, unrelated event
if (rootEndError !== undefined) {
const rootError = rootEndError.error
rootEndError = undefined
// the update hook may rethrow the same error, like handleBackupLog() and forwardResult() for backups: only
// another error is worth a warning
if (error !== rootError) {
warn('failure in task update hook after the root task end hook failed', { error, event })
}
throw rootError
}
throw error
}
if (rootEndError !== undefined) {
const { error } = rootEndError
rootEndError = undefined
throw error
}
}
function handler(event) {
if (closed) {
if (!warnedAfterClose) {
warnedAfterClose = true
warn('event received after the external task was ended, later ones are dropped silently', { event })
}
return
}
feed(event)
}
function end({ status = 'interrupted', reason } = {}) {
// nothing to end: not started yet, or already ended
if (openRoots.size === 0) {
return
}
closed = true
// like the result of an event sent by a worker or a proxy: the update hook then rethrows the same object as the
// root end hook (handleBackupLog() and forwardResult() for backups), which the log keeps serialized
const result = reason instanceof Error ? serializeError(reason) : reason
let thrown
for (const root of [...openRoots]) {
// listed before ending them, as ending a task may sort the subtasks of its parent (handleBackupLog)
for (const { id } of [...openTasks(root)]) {
try {
feed({ type: 'end', id, timestamp: Date.now(), status, result })
} catch (error) {
// a root end error carries the result of its task: the first one wins, like in feed(); the others are
// logged
const isRoot = id === root.id
if (thrown === undefined) {
thrown = { error, id, isRoot }
} else if (isRoot && !thrown.isRoot) {
warn('failure in task end hook, superseded by the root task error', {
error: thrown.error,
id: thrown.id,
})
thrown = { error, id, isRoot }
} else {
warn('failure in task end hook', { error, id })
}
}
}
}
if (thrown !== undefined) {
throw thrown.error
}
}
return Object.assign(handler, { end })
}
async abort(id, reason) {
const task = this.#tasks.get(id)
if (task !== undefined) {
return task.abort(reason)
if (task === undefined) {
throw noSuchObject(id, 'task')
}
// running external task without abort option
const liveLog = this.#liveLogs.get(id)
if (liveLog !== undefined && liveLog.status === 'pending') {
throw forbiddenOperation('abort', 'this task cannot be aborted')
}
throw noSuchObject(id, 'task')
return task.abort(reason)
}
async clearLogs() {
@@ -445,64 +245,16 @@ export default class Tasks extends EventEmitter {
return task
}
/**
* Deletes the log of a task, stored or live: a live task may not be stored yet, or only in an older state if its
* last write failed.
*
* The log of a running task can be deleted too (XO 5 offers it for any task): the next event of the task writes it
* again.
*/
async deleteLog(id, cb) {
const storedLog = await this.#deleteStored(id, cb)
const log = await this.get(id).catch(noop)
const liveLog = this.#liveLogs.get(id)
this.#liveLogs.delete(id)
const log = liveLog ?? storedLog
if (log !== undefined) {
this.#emitSafely('remove', log)
await this.#store.del(id, cb)
this.emit('remove', log)
}
}
// deletes the stored log of a task and returns it, undefined if there is none; other store errors are thrown
async #deleteStored(id, cb) {
let log
try {
log = await this.#getStored(id)
} catch (error) {
if (noSuchObject.is(error)) {
// nothing to delete, but #gc waits for cb
cb?.()
return
}
throw error
}
await this.#store.del(id, cb)
return log
}
/**
* Returns the log of a task: its latest state if it is live, even if not yet persisted (e.g. an external task
* between its first event and its first write), its stored state otherwise.
*/
async get(id) {
const liveLog = this.#liveLogs.get(id)
if (liveLog !== undefined) {
return copyLog(liveLog)
}
try {
return await this.#getStored(id)
} catch (error) {
// the first event of the task may have arrived while the store was read
const liveLog = this.#liveLogs.get(id)
if (liveLog !== undefined && noSuchObject.is(error)) {
return copyLog(liveLog)
}
throw error
}
}
async #getStored(id) {
try {
return await this.#store.get(id)
} catch (error) {
@@ -513,107 +265,37 @@ export default class Tasks extends EventEmitter {
}
}
/**
* Lists the logs of the tasks: a live task in its latest state, like get(), even if it is not stored yet.
*/
async *list({ filter, limit = Infinity } = {}) {
const predicate = filter === undefined ? stubTrue : typeof filter === 'function' ? filter : iteratee(filter)
const liveLogs = this.#liveLogs
// ids of the live tasks already listed from the store
const listed = new Set()
for await (const [, storedLog] of this.#store.iterator()) {
const { id } = storedLog
const liveLog = liveLogs.get(id)
let taskLog = storedLog
if (liveLog !== undefined) {
listed.add(id)
taskLog = copyLog(liveLog)
} else if (storedLog.status === 'pending') {
// pending logs of the previous runs are marked interrupted at start: this one belongs to a task that ended or
// was deleted since the listing read the store
try {
taskLog = await this.#getStored(id)
} catch (error) {
if (noSuchObject.is(error)) {
continue
}
throw error
}
}
for await (const [, taskLog] of this.#store.iterator()) {
if (predicate(taskLog)) {
yield taskLog
if (--limit < 1) {
return
}
}
}
// live tasks the store did not list: not stored yet, or stored after the listing started
for (const [id, liveLog] of liveLogs) {
if (!listed.has(id)) {
const taskLog = copyLog(liveLog)
if (predicate(taskLog)) {
yield taskLog
if (--limit < 1) {
return
}
break
}
}
}
}
async watch(id, cb) {
// always called later: the caller may use the value returned by watch() in cb (e.g. to stop watching), and an
// error of cb must not escape as an uncaught exception
let stopped = false
const stop = () => {
stopped = true
}
const callLater = taskLog =>
setImmediate(() => {
if (stopped) {
return
}
try {
cb(taskLog)
} catch (error) {
warn('failure in task watcher', { error, id, taskLog })
}
})
// live task
if (this.#tasks.has(id)) {
this.on(id, cb)
// returns the function to stop watching if the task is live, undefined otherwise
const watchLive = () => {
// live task whose final state is already known, even if not yet persisted
const liveLog = this.#liveLogs.get(id)
if (liveLog !== undefined && liveLog.status !== 'pending') {
callLater(liveLog)
return stop
let stopWatch = () => {
this.off(id, cb)
stopWatch = noop
}
// live task
if (liveLog !== undefined || this.#tasks.has(id)) {
// the flush of updates may run before the caller gets the return value of watch()
this.on(id, callLater)
return () => {
stop()
this.off(id, callLater)
}
}
}
const stopLive = watchLive()
if (stopLive !== undefined) {
return stopLive
return () => stopWatch()
}
// unknown task will throw noSuchObject
const taskLog = await this.get(id)
// the first event of the task may have arrived while the store was read: watch it until it ends
return watchLive() ?? (callLater(taskLog), stop)
// finished task
setImmediate(cb, taskLog)
return noop
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -14,29 +14,28 @@
"url": "https://vates.fr"
},
"license": "AGPL-3.0-or-later",
"version": "0.24.0",
"version": "0.23.0",
"engines": {
"node": ">=15.6"
},
"dependencies": {
"@vates/async-each": "^1.0.3",
"@vates/event-listeners-manager": "^1.0.1",
"@vates/iscsi": "^0.4.1",
"@vates/iscsi": "^0.4.0",
"@vates/parse-duration": "^0.1.1",
"@vates/task": "^0.7.0",
"@xen-orchestra/backup-archive": "^1.2.1",
"@xen-orchestra/log": "^1.0.0",
"@xen-orchestra/backup-archive": "^1.2.0",
"@xen-orchestra/log": "^0.7.2",
"acme-client": "^5.0.0",
"app-conf": "^3.0.0",
"fast-xml-parser": "^4.0.0",
"golike-defer": "^0.5.1",
"json-stringify-safe": "^5.0.1",
"lodash": "^4.18.0",
"promise-toolbox": "^0.21.0",
"xo-common": "^0.11.0"
},
"devDependencies": {
"@vates/types": "^3.0.0"
"@vates/types": "^2.5.0"
},
"scripts": {
"postversion": "npm publish --access public",

View File

@@ -11,15 +11,14 @@ const { warn } = createLogger('xo:proxy:authentication')
const isValidToken = t => typeof t === 'string' && t.length !== 0
export default class Authentication {
// kept in memory because the config is not reloaded when the token is written at construction
#token
#app
constructor(app, { appName, config: { authenticationToken: token } }) {
this.#app = app
const setToken = ({ token }) => {
assert(isValidToken(token), 'invalid authentication token: ' + token)
this.#token = token
// save this token in the automatically handled conf file
fse.outputFileSync(
// this file must take precedence over normal user config
@@ -39,13 +38,6 @@ export default class Authentication {
}
}
// follow config changes (including the ones made by setToken)
app.config.watch('authenticationToken', token => {
if (isValidToken(token)) {
this.#token = token
}
})
app.api.addMethod('authentication.setToken', setToken, {
description: 'change the authentication token used by this XO Proxy',
params: {
@@ -58,9 +50,7 @@ export default class Authentication {
}
async findProfile(credentials) {
const token = credentials?.token
// never match an empty/missing token, even if no valid token is known
if (isValidToken(token) && token === this.#token) {
if (credentials?.token === this.#app.config.get('authenticationToken')) {
return new Profile()
}
}

View File

@@ -1,7 +1,7 @@
{
"private": true,
"name": "@xen-orchestra/proxy",
"version": "0.35.0",
"version": "0.34.0",
"license": "AGPL-3.0-or-later",
"description": "XO Proxy used to remotely execute backup jobs",
"keywords": [
@@ -31,16 +31,16 @@
"@vates/cached-dns.lookup": "^1.0.0",
"@vates/compose": "^2.1.0",
"@vates/decorate-with": "^2.1.0",
"@vates/disposable": "^0.1.7",
"@vates/disposable": "^0.1.6",
"@vates/task": "^0.7.0",
"@xen-orchestra/async-map": "^0.1.5",
"@xen-orchestra/backups": "^1.0.0",
"@xen-orchestra/fs": "^4.11.0",
"@xen-orchestra/log": "^1.0.0",
"@xen-orchestra/backups": "^0.78.0",
"@xen-orchestra/fs": "^4.10.0",
"@xen-orchestra/log": "^0.7.2",
"@xen-orchestra/mixin": "^0.2.1",
"@xen-orchestra/mixins": "^0.24.0",
"@xen-orchestra/mixins": "^0.23.0",
"@xen-orchestra/self-signed": "^0.2.1",
"@xen-orchestra/xapi": "^10.0.0",
"@xen-orchestra/xapi": "^9.1.0",
"ajv": "^8.0.3",
"app-conf": "^3.0.0",
"async-iterator-to-stream": "^1.1.0",
@@ -62,7 +62,7 @@
"source-map-support": "^0.5.16",
"stoppable": "^1.0.6",
"xdg-basedir": "^5.1.0",
"xen-api": "^6.0.0",
"xen-api": "^5.1.0",
"xo-common": "^0.11.0"
},
"devDependencies": {

View File

@@ -1,5 +1,3 @@
import { TEMPORARY_SCHEDULE_ID } from './utils/index.js'
/**
* Generates backup job configuration with optional health check and NBD support.
*
@@ -18,12 +16,10 @@ export function backupConfig(name, schedule, vms, backupRepository, options = {}
name,
mode: 'delta', // Will be overridden by tests
schedules: {
[TEMPORARY_SCHEDULE_ID]: schedule, // Default schedule slot
'': schedule, // Default schedule slot
},
settings: {
// General settings left empty, required by the REST API for backup and mirror jobs, and the settings go to the schedule
'': {},
[TEMPORARY_SCHEDULE_ID]: {
'': {
timezone: 'Europe/Paris',
exportRetention: 2,
mergeBackupsSynchronously: true,
@@ -38,24 +34,24 @@ export function backupConfig(name, schedule, vms, backupRepository, options = {}
// Add health check SR if provided
if (options.healthCheckSr) {
config.settings[TEMPORARY_SCHEDULE_ID].healthCheckSr = options.healthCheckSr
config.settings[''].healthCheckSr = options.healthCheckSr
}
// Add NBD settings if provided
if (options.preferNbd !== undefined) {
config.settings[TEMPORARY_SCHEDULE_ID].preferNbd = options.preferNbd
config.settings[''].preferNbd = options.preferNbd
}
if (options.nbdConcurrency !== undefined) {
config.settings[TEMPORARY_SCHEDULE_ID].nbdConcurrency = options.nbdConcurrency
config.settings[''].nbdConcurrency = options.nbdConcurrency
}
if (options.snapshotConcurrency !== undefined) {
config.settings[TEMPORARY_SCHEDULE_ID].snapshotConcurrency = options.snapshotConcurrency
config.settings[''].snapshotConcurrency = options.snapshotConcurrency
}
if (options.synchronizedSnapshot !== undefined) {
config.settings[TEMPORARY_SCHEDULE_ID].synchronizedSnapshot = options.synchronizedSnapshot
config.settings[''].synchronizedSnapshot = options.synchronizedSnapshot
}
return config
@@ -71,12 +67,10 @@ export function fleetDeltaBackupConfig(name, schedule, vmIds, backupRepositoryId
name,
mode: 'delta',
schedules: {
[TEMPORARY_SCHEDULE_ID]: schedule,
'': schedule,
},
settings: {
// General settings left empty, required by the REST API for backup and mirror jobs, and the settings go to the schedule
'': {},
[TEMPORARY_SCHEDULE_ID]: {
'': {
timezone: 'Europe/Paris',
concurrency,
exportRetention,

View File

@@ -2,7 +2,7 @@
"name": "@xen-orchestra/qa-test",
"private": true,
"type": "module",
"version": "1.5.0",
"version": "1.4.0",
"description": "XenOrchestra QA Test Suite",
"author": {
"name": "Vates SAS",
@@ -22,10 +22,10 @@
"dependencies": {
"@vates/async-each": "^1.0.3",
"@vates/read-chunk": "^1.2.1",
"@xen-orchestra/backups": "^1.0.0",
"@xen-orchestra/fs": "^4.11.0",
"@xen-orchestra/log": "^1.0.0",
"@xen-orchestra/vmware-explorer": "^1.3.0",
"@xen-orchestra/backups": "^0.78.0",
"@xen-orchestra/fs": "^4.10.0",
"@xen-orchestra/log": "^0.7.2",
"@xen-orchestra/vmware-explorer": "^1.2.0",
"nodemailer": "^7.0.13",
"xo-lib": "^0.11.2"
},

View File

@@ -9,7 +9,6 @@ import {
generateBackupJobName,
getBackupTransferredBytes,
getDefaultSchedule,
TEMPORARY_SCHEDULE_ID,
getScheduleKey,
getRequiredEnv,
} from '../utils/index.js'
@@ -116,10 +115,9 @@ describe('Mirror Backup - Full Remote', () => {
mode: 'full',
sourceRemote: sourceRepository.id,
remotes: { [destRepository.id]: {} },
schedules: { [TEMPORARY_SCHEDULE_ID]: schedule },
schedules: { '': schedule },
settings: {
'': {},
[TEMPORARY_SCHEDULE_ID]: {
'': {
exportRetention: 3,
mergeBackupsSynchronously: true,
bypassVdiChainsCheck: true,

View File

@@ -12,7 +12,6 @@ import {
generateBackupJobName,
getBackupTransferredBytes,
getDefaultSchedule,
TEMPORARY_SCHEDULE_ID,
getScheduleKey,
getRequiredEnv,
} from '../utils/index.js'
@@ -470,10 +469,9 @@ describe('Backup + Replication Combined Tests', () => {
const config = {
name,
mode: 'delta',
schedules: { [TEMPORARY_SCHEDULE_ID]: schedule },
schedules: { '': schedule },
settings: {
'': {},
[TEMPORARY_SCHEDULE_ID]: {
'': {
timezone: 'Europe/Paris',
copyRetention: 3,
bypassVdiChainsCheck: true,

View File

@@ -10,7 +10,6 @@ import {
findInfoByMessage,
generateBackupJobName,
getDefaultSchedule,
TEMPORARY_SCHEDULE_ID,
getScheduleKey,
getRequiredEnv,
} from '../utils/index.js'
@@ -162,10 +161,9 @@ describe('Backup basic tests', () => {
const crConfig = {
name: generateBackupJobName(),
mode: 'delta',
schedules: { [TEMPORARY_SCHEDULE_ID]: getDefaultSchedule() },
schedules: { '': getDefaultSchedule() },
settings: {
'': {},
[TEMPORARY_SCHEDULE_ID]: {
'': {
timezone: 'Europe/Paris',
copyRetention: 3,
preferNbd: true,

View File

@@ -5,14 +5,7 @@ import { createLogger } from '@xen-orchestra/log'
import { DispatchClient } from '../client/dispatchClient.js'
import { createResourceTracker } from '../utils/resourceTracker.js'
import {
delay,
generateBackupJobName,
getDefaultSchedule,
getRequiredEnv,
getScheduleKey,
TEMPORARY_SCHEDULE_ID,
} from '../utils/index.js'
import { delay, generateBackupJobName, getDefaultSchedule, getRequiredEnv, getScheduleKey } from '../utils/index.js'
import { assertBackupSuccess } from '../utils/backupUtils.js'
const log = createLogger('qa:backup:metadata')
@@ -112,8 +105,8 @@ describe('Metadata backup tests', () => {
name,
pools: { [poolId]: true },
remotes: { [backupRepository.id]: true },
schedules: { [TEMPORARY_SCHEDULE_ID]: getDefaultSchedule() },
settings: { [TEMPORARY_SCHEDULE_ID]: { retentionPoolMetadata: 2, retentionXoMetadata: 2 } },
schedules: { '': getDefaultSchedule() },
settings: { '': { retentionPoolMetadata: 2, retentionXoMetadata: 2 } },
xoMetadata: true,
})
@@ -148,8 +141,8 @@ describe('Metadata backup tests', () => {
name,
pools: { [poolId]: true },
remotes: { [backupRepository.id]: true },
schedules: { [TEMPORARY_SCHEDULE_ID]: getDefaultSchedule() },
settings: { [TEMPORARY_SCHEDULE_ID]: { retentionPoolMetadata: 2, retentionXoMetadata: 2 } },
schedules: { '': getDefaultSchedule() },
settings: { '': { retentionPoolMetadata: 2, retentionXoMetadata: 2 } },
xoMetadata: true,
})

View File

@@ -9,7 +9,6 @@ import {
generateBackupJobName,
getBackupTransferredBytes,
getDefaultSchedule,
TEMPORARY_SCHEDULE_ID,
getScheduleKey,
} from '../utils/index.js'
import { assertBackupSuccess } from '../utils/backupUtils.js'
@@ -96,10 +95,9 @@ describe('Incremental Replication', () => {
const config = {
name,
mode: 'delta',
schedules: { [TEMPORARY_SCHEDULE_ID]: schedule },
schedules: { '': schedule },
settings: {
'': {},
[TEMPORARY_SCHEDULE_ID]: {
'': {
timezone: 'Europe/Paris',
copyRetention: 3,
preferNbd: true,
@@ -171,7 +169,7 @@ describe('Incremental Replication', () => {
)
return scheduleIds.filter(id => id === scheduleId).length
}
/**
* @param {Error} error
* @returns {boolean} Whether the error looks like a "not found" response rather than a transient failure.

View File

@@ -3,10 +3,6 @@ import assert from 'node:assert'
import { after, before, describe, it } from 'node:test'
import { createLogger } from '@xen-orchestra/log'
import { DispatchClient } from '../client/dispatchClient.js'
import { RestApiClient } from '../client/restApiClient.js'
import { createTestUser, deleteTestUser } from '../utils/aclUtils.js'
import { getRequiredEnv } from '../utils/index.js'
import { setup, teardown } from './setup.js'
const log = createLogger('qa:sdn-controller')
@@ -521,142 +517,3 @@ describe('SDN Controller REST API', { skip: !process.env.SDN_CONTROLLER_VM_ID },
})
})
})
// ---------------------------------------------------------------------------
// The networks go on the pools the suite already tests on: the pool of SDN_CONTROLLER_VM_ID and, when it is another
// one, the pool of REFERENCE_VM_ID. Never any other pool XO is connected to: a private network sets the SDN controller
// of its pools. The tunnels go through the network of the management PIF of each pool's master
describe('SDN Controller private networks', { skip: !process.env.SDN_CONTROLLER_VM_ID }, () => {
let dispatchClient
let pools
const networkIds = []
// RestApiClient answers only the body, and the route's statuses are checked too
const createPrivateNetwork = async (body, client = dispatchClient.restApiClient) => {
const response = await fetch(`${client.baseUrl}${BASE}/pools/actions/create_private_network?sync=true`, {
method: 'POST',
headers: client.headers,
body: JSON.stringify(body),
})
const result = await response.json()
networkIds.push(...(result.networkIds ?? []))
return { status: response.status, result }
}
const bodyFor = (pools, params) => ({
poolIds: pools.map(pool => pool.id),
pifIds: pools.map(pool => pool.pifId),
name: `qa-sdn-private-network-${Date.now()}`,
description: 'created by the qa-test suite',
encapsulation: 'gre',
...params,
})
const networksNamed = async name =>
(await dispatchClient.restApiClient.getObjects('/rest/v0/networks')).filter(network => network.name_label === name)
before(async () => {
dispatchClient = new DispatchClient()
await dispatchClient.initialize()
const { restApiClient } = dispatchClient
const vmPoolIds = await Promise.all(
[process.env.SDN_CONTROLLER_VM_ID, getRequiredEnv('REFERENCE_VM_ID')].map(
async id => (await restApiClient.get(`/rest/v0/vms/${id}`)).$pool
)
)
const [allPools, hosts, pifs] = await Promise.all(
['pools', 'hosts', 'pifs'].map(collection => restApiClient.getObjects(`/rest/v0/${collection}`))
)
pools = [...new Set(vmPoolIds)].map(id => {
const { master } = allPools.find(pool => pool.id === id)
return {
id,
masterId: master,
pifId: pifs.find(pif => pif.$host === master && pif.management)?.id,
hostCount: hosts.filter(host => host.$pool === id).length,
}
})
log.debug('Private network pools', { pools })
})
after(async () => {
for (const id of networkIds) {
try {
await dispatchClient.restApiClient.delete(`/rest/v0/networks/${id}`)
} catch (error) {
log.warn('Failed to delete a private network', { error, networkId: id })
}
}
await dispatchClient?.close()
})
// the preferred center is a host of the last pool, so that its network is not the first one asked for
it('should create one network per pool, each with a tunnel on every host, in a single private network', async t => {
if (pools.length === 1) {
t.diagnostic('XO is connected to a single pool: the private network spans it alone')
}
const preferredCenterId = pools.at(-1).masterId
const body = bodyFor(pools, { mtu: 1400, preferredCenterId })
const { status, result } = await createPrivateNetwork(body)
assert.strictEqual(status, 201, JSON.stringify(result))
assert.strictEqual(result.networkIds.length, pools.length)
const networks = await Promise.all(
result.networkIds.map(id => dispatchClient.restApiClient.get(`/rest/v0/networks/${id}?fields=*`))
)
const { 'xo:sdn-controller:private-network-uuid': privateNetworkUuid, 'xo:sdn-controller:vni': vni } =
networks[0].other_config
assert.match(privateNetworkUuid, /^[0-9a-f-]{36}$/)
assert.match(vni, /^\d+$/)
assert.deepStrictEqual(networks.map(network => network.$pool).sort(), pools.map(pool => pool.id).sort())
for (const network of networks) {
const pool = pools.find(pool => pool.id === network.$pool)
assert.strictEqual(network.name_label, body.name)
assert.strictEqual(network.MTU, 1400)
assert.strictEqual(network.PIFs.length, pool.hostCount, 'one tunnel access PIF per host')
assert.deepStrictEqual(
{
encapsulation: network.other_config['xo:sdn-controller:encapsulation'],
preferredCenter: network.other_config['xo:sdn-controller:preferred-center'],
privateNetworkUuid: network.other_config['xo:sdn-controller:private-network-uuid'],
vni: network.other_config['xo:sdn-controller:vni'],
},
{ encapsulation: 'gre', preferredCenter: preferredCenterId, privateNetworkUuid, vni }
)
}
})
it('should refuse an unknown pool, a pool without a PIF or an unknown encapsulation, creating no network', async () => {
const body = bodyFor(pools.slice(0, 1))
for (const [params, expectedStatus] of [
[{ poolIds: ['00000000-0000-0000-0000-000000000000'] }, 404],
[{ pifIds: [] }, 422],
[{ encapsulation: 'ipip' }, 422],
]) {
const { status, result } = await createPrivateNetwork({ ...body, ...params })
assert.strictEqual(status, expectedStatus, `${JSON.stringify(params)}: ${JSON.stringify(result)}`)
}
assert.deepStrictEqual(await networksNamed(body.name), [])
})
it('should refuse a user who is not an admin', async () => {
const user = await createTestUser(dispatchClient.xoClient)
try {
const client = new RestApiClient({
xoUrl: getRequiredEnv('HOSTNAME'),
username: user.email,
password: user.password,
})
await client.connect()
const body = bodyFor(pools.slice(0, 1))
const { status, result } = await createPrivateNetwork(body, client)
assert.strictEqual(status, 403, JSON.stringify(result))
assert.deepStrictEqual(await networksNamed(body.name), [])
} finally {
await deleteTestUser(dispatchClient.xoClient, user.id)
}
})
})

View File

@@ -83,15 +83,6 @@ export const getDefaultSchedule = () => ({
cron: '0 0 * * *',
})
/**
* Temporary ID shared by schedule configuration and settings when creating a backup job.
*
* xo-server replaces it with the schedule's real ID.
* It must not be empty ('') because '' is the key of the general settings and
* REST API refuses it for a schedule.
*/
export const TEMPORARY_SCHEDULE_ID = 'temporary-schedule-id'
/**
* Simple delay function.
*

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