Compare commits

..

11 Commits

Author SHA1 Message Date
KAN-vates
576d0670d5 feat(rest-api): accept the PATCH field names when creating a network
The network create routes take name, description and mtu, while PATCH
/networks/{id} takes the XoNetwork names name_label, name_description and
MTU, so a client had to learn two spellings for one network. The create
routes now accept the XoNetwork names too. normalizeNetworkCreateBody maps
them, in one place, to the names xapi.createNetwork reads. The old names
stay accepted and are marked deprecated, so no client breaks.

A body giving both spellings of one field, or no name at all, is refused
with a 422. The check runs in a middleware before the ACL: a refusal
inside the task would come back as a failed task, not a 422. The ACL then
matches the role's selectors against the normalized body, so a selector
on name still sees the name whichever spelling the client used.
tsoa cannot express "one of", so name and name_label are both optional in
the schema and the check is in the code.
2026-12-03 10:29:42 +01:00
KAN-vates
8eaa4c507a fix(xo-server): roll back network edits when one of their writes fails
editNetwork wrote its fields with a Promise.all, so they ran concurrently. A failure on one
field left the others applied, and the rejection reached the caller before the remaining
writes had ended: a multi-field PATCH /rest/v0/networks/{id}, or network.set, could answer
500 with part of the network already changed.

The writes now run one after the other. Each one that succeeds registers a $defer.onFailure
that restores its previous value: name_label, name_description, the automatic flag, the
default locking mode and the NBD purposes. MTU comes last because changing it replugs every
PIF and VIF, and its rollback replugs them again. On failure the rollbacks run in reverse
order; a rollback that fails itself is logged and the original error is the one rethrown.
2026-12-03 10:29:42 +01:00
KAN-vates
f22c27b863 fix(xo-server): skip the MTU replug when network.editNetwork's MTU is unchanged
editNetwork called network.$setMtu whenever the MTU key was present, even
with the value already set. $setMtu replugs every PIF and VIF, so a client
resending its full state on each update (Terraform) interrupted traffic on
every apply with no change.

editNetwork now calls $setMtu only when the requested MTU differs from the
network's current one. The comparison is numeric (+network.MTU), as in
xapi-object-to-xo. The shared Network.setMtu in @xen-orchestra/xapi is
unchanged.
2026-12-03 10:29:42 +01:00
KAN-vates
3e8658c906 feat(rest-api): add PATCH /rest/v0/networks/{id}
The REST API could read a network but not change it: the network controller had no PATCH
route, so a network's name, description, MTU, NBD purposes, automatic flag and default
locking mode could only be set through JSON-RPC network.set. The route is the REST
counterpart of network.set. It has one ACL action per field, update:name_label,
update:MTU and so on, named after the XoNetwork fields GET returns, so a client can send
back what it read. An action is checked only when its field is in the body. nbd: true also
removes the insecure_nbd purpose, and insecureNbd: true the nbd one, so each also requires
the other's action. A body with none of the fields is refused with a 422 before the ACL
runs, so it neither passes unchecked nor tells an existing network from a missing one.

The body is forwarded to Xapi.editNetwork, which holds the NBD rules shared with
JSON-RPC: copying them into rest-api would let the two drift. Changing the MTU unplugs
and replugs the network's interfaces, so the route is exposed to MCP with confirm.
2026-12-03 10:29:42 +01:00
KAN-vates
7b7fab8366 refactor(xo-server): share network.set's logic as Xapi editNetwork
network.set held the whole edit in the JSON-RPC method, where nothing
else could reach it. The REST route for PATCH /networks/{id} needs the
same edit, so the logic moves into Xapi.editNetwork, next to editVif,
and network.set calls it. JSON-RPC behaviour does not change.

The NBD rules (nbd and insecureNbd are exclusive, and a false value only
removes its own purpose) move with the edit. They must not be copied
into rest-api: they are subtle, and two copies would drift apart. The
mutual-exclusion check runs before any XAPI call, so a refused request
changes nothing.
2026-12-03 10:27:11 +01:00
Sylvère
22bcc37439 feat(web-core): add an optional details log viewer to the error modal (#10536) 2026-12-03 08:28:39 +01:00
Joris K
5ca2958d2a fix(web-core): stop the page sliding sideways to closed side panels (#10973) 2026-12-02 17:55:29 +01:00
Killian
205ae67940 docs(backups): add a procedure to repair a broken incremental chain (#10966)
* docs(backups): add a procedure to repair a broken incremental chain

No page told users what to do when a delta backup chain is broken on the
backup repository (a disk file missing or unreadable).

The new page works from the web interface and the REST API only, so it
applies to an air-gapped XOA. It starts from the job log's Clean VM
directory warnings, then relies on what each run already does since
XO 5.100.0: delete the broken restore points and fall back to a full
when no valid base is left. The manual steps (reclaim-space through the
REST API or Delete backups in XO 5, then a forced full) cover what that
run doesn't: failing runs, and corrupted data the header check misses.

The two new screenshots were taken on a chain broken on purpose. The
troubleshooting page links the procedure from the unexpected full
export section.
2026-12-02 17:33:30 +01:00
Florent BEAUCHAMP
addfdd5475 fix(vmware-explorer): detect secure boot -improve snapshots for esxi6 (#10968)
* fix(vmware-explorer): detect secure boot for esxi6

* changelog

* fix: improve compatibility with automatic snapshot
2026-12-02 15:43:36 +01:00
spacotte-vates
5512fc65a6 feat(acl): resolve selectors on partial objects (#10731)
* feat(complex-matcher): throw when unknown state

* update changelog

* lil fixes

* fix review Killian

* move code from package/complex-matcher to xen-orchestra/acl

* fix review MathieuRA

* improve comment
2026-12-02 12:27:06 +01:00
Marie Garde
1f8f265afc fix(xo5): fix crash on metadata job with all objects (#10933)
* fix(xo5): fix crash on metadata job with all objects

* fix changelog

* rebase ok
2026-12-02 10:59:48 +01:00
44 changed files with 1511 additions and 128 deletions

View File

@@ -101,6 +101,21 @@ export interface EditVifProps {
txChecksumming?: boolean
}
/**
* Properties accepted by {@link Xapi.editNetwork}: the fields of `XoNetwork` it can change.
*
* `nbd` and `insecureNbd` cannot both be true: `editNetwork` throws `invalidParameters` when they are.
*/
export interface EditNetworkProps {
automatic?: boolean
defaultIsLocked?: boolean
insecureNbd?: boolean
MTU?: number
name_description?: string
name_label?: string
nbd?: boolean
}
export type XcpPatches = {
changelog?: {
author: string
@@ -335,6 +350,7 @@ export interface Xapi {
checkLimits?: (limits: Record<string, number>, vm: XenApiVmWrapped) => Promise<void>
): Promise<void>
editVif(id: XoVif['id'], props: EditVifProps): Promise<void>
editNetwork(id: XoNetwork['id'], props: EditNetworkProps): Promise<void>
startVm(
id: XoVm['id'],
opts?: {

View File

@@ -5,5 +5,12 @@ export default {
update: {
tags: true,
other_config: true,
automatic: true,
defaultIsLocked: true,
insecureNbd: true,
MTU: true,
name_description: true,
name_label: true,
nbd: true,
},
}

View File

@@ -8,9 +8,28 @@ export type SupportedResource = XoAclSupportedResource<SupportedActionsByResourc
export type SupportedActions<T extends SupportedResource> = XoAclSupportedActions<SupportedActionsByResource, T>
export type TPrivilege<T extends SupportedResource> = XoAclPrivilege<SupportedActionsByResource, T>
export const UNKNOWN = Symbol('UNKNOWN')
/**
* Lists the top-level fields read by a selector.
*/
function getSelectorFields(node: CM.Node): string[] {
if (node instanceof CM.Property || node instanceof CM.TruthyProperty) {
return [node.name]
}
if (node instanceof CM.Not) {
return getSelectorFields(node.child)
}
if (node instanceof CM.And || node instanceof CM.Or) {
return node.children.flatMap(getSelectorFields)
}
return node instanceof CM.Null ? [] : ['*']
}
export class Privilege<T extends SupportedResource> {
#action: TPrivilege<T>['action']
#selector?: (object: object) => boolean
#selectorFields: string[] = []
#resource: TPrivilege<T>['resource']
#effect: TPrivilege<T>['effect']
@@ -28,9 +47,14 @@ export class Privilege<T extends SupportedResource> {
Privilege.checkActionIsValid(resource, action)
this.#action = action
this.#selector = selector !== undefined ? CM.parse(selector).createPredicate() : undefined
this.#resource = resource
this.#effect = effect
if (selector !== undefined) {
const node = CM.parse(selector)
this.#selector = node.createPredicate()
this.#selectorFields = getSelectorFields(node)
}
}
get effect() {
@@ -44,11 +68,20 @@ export class Privilege<T extends SupportedResource> {
return this.#action === '*' || this.#action === action || action.startsWith(`${this.#action}:`)
}
#matchSelector(object: object) {
#matchSelector(object: object, knownFields?: string[]) {
if (this.#selector === undefined) {
return true
}
// `*` is a term not bound to a property (e.g. `foo`), it may match any field, including missing ones
// The `*` check is there to handle the case where a `*` field would exist
if (
knownFields !== undefined &&
this.#selectorFields.some(field => field === '*' || !(field in object || knownFields.includes(field)))
) {
return UNKNOWN
}
return this.#selector(object)
}
@@ -60,11 +93,12 @@ export class Privilege<T extends SupportedResource> {
action: SupportedActions<Resource>
resource: Resource
object: object
}): boolean {
knownFields?: string[]
}): boolean | typeof UNKNOWN {
return (
this.#matchResource(constraint.resource) &&
this.#matchAction(constraint.action) &&
this.#matchSelector(constraint.object)
this.#matchSelector(constraint.object, constraint.knownFields)
)
}

View File

@@ -7,6 +7,7 @@ import {
SupportedActions,
SupportedActionsByResource,
SupportedResource,
UNKNOWN,
} from './class/privilege.mjs'
// Export all types constructed using SUPPORTED_ACTIONS_BY_RESOURCE
@@ -23,6 +24,7 @@ export type AnyPrivilegeOnParam = {
resource: Resource
action: SupportedActions<Resource>
objects: object | object[]
knownFields?: string[]
}
}[SupportedResource]
@@ -32,12 +34,14 @@ export function hasPrivilegeOn<T extends SupportedResource>({
resource,
objects,
userPrivileges,
knownFields,
}: {
user: XoUser
resource: T
action: SupportedActions<T>
objects: object | object[]
userPrivileges: AnyPrivilege[]
knownFields?: string[]
}) {
// Function that will be called outside of the module
// We cannot be sure types are respected
@@ -63,7 +67,7 @@ export function hasPrivilegeOn<T extends SupportedResource>({
return true
}
const effectsByObject = new Map<object, Privilege<T>['effect'][]>()
const effectsByObject = new Map<object, { known: boolean; effect: Privilege<T>['effect'] }[]>()
if (Array.isArray(objects)) {
objects.forEach(obj => effectsByObject.set(obj, []))
} else {
@@ -74,20 +78,49 @@ export function hasPrivilegeOn<T extends SupportedResource>({
const privilege = new CPrivilege(userPrivilege as Privilege<typeof userPrivilege.resource>)
for (const [object, effects] of effectsByObject.entries()) {
if (!privilege.match({ action, resource, object })) {
const result = privilege.match({ action, resource, object, knownFields })
if (!result) {
continue
}
effects.push(privilege.effect)
effects.push({ known: result !== UNKNOWN, effect: privilege.effect })
}
}
if (
Array.from(effectsByObject.values()).some(
effects => effects.length === 0 || effects.some(effect => effect === 'deny')
)
) {
return false
let isUndecidable = false
for (const effects of effectsByObject.values()) {
let hasAllow = false
let hasKnownAllow = false
let hasUnknownDeny = false
for (const { known, effect } of effects) {
if (effect === 'allow') {
hasAllow = true
hasKnownAllow ||= known
} else if (known) {
return false
} else {
hasUnknownDeny = true
}
}
if (!hasAllow) {
return false
}
// do not throw yet: another object may still be known to be denied
if (hasUnknownDeny || !hasKnownAllow) {
isUndecidable = true
}
}
if (isUndecidable) {
const error: Error & { code?: string } = new Error(
`The privilege couldn't be decided because the object is missing fields the selectors need. action: ${action}, resource: ${resource}`
)
error.code = 'RBAC_UNKNOWN_RESULT'
throw error
}
return true
}
@@ -101,6 +134,7 @@ export function getMissingPrivileges(params: AnyPrivilegeOnParam[], userPrivileg
action: param.action as SupportedActions<typeof param.resource>,
objects: param.objects,
userPrivileges,
knownFields: param.knownFields,
})
)
.map(({ action, objects, resource }) => {
@@ -142,6 +176,7 @@ export function filterObjectsWithPrivilege<Resource extends SupportedResource, O
action: SupportedActions<Resource>
objects: Object[]
userPrivileges: AnyPrivilege[]
knownFields?: string[]
}) {
return param.objects.filter(obj => hasPrivilegeOn({ ...param, objects: obj }))
}

View File

@@ -3,7 +3,7 @@ import assert from 'node:assert'
import type { Branded } from '@vates/types/common'
import type { XoUser } from '@vates/types/xo'
import { Privilege } from '../class/privilege.mjs'
import { Privilege, UNKNOWN } from '../class/privilege.mjs'
import type { Privilege as TPrivilege } from '../index.mjs'
import {
filterObjectsWithPrivilege,
@@ -81,6 +81,108 @@ suite('Privilege.match behavior', () => {
const vmImportPrivilege = new Privilege({ action: 'import:vm', resource: 'sr', effect: 'allow' })
assert.strictEqual(vmImportPrivilege.match({ resource: 'sr', action: 'import:vdi:url', object }), false)
})
suite('on a partial object', () => {
const ownVmPrivilege = new Privilege({
action: 'read',
resource: 'vm',
selector: 'creation:creator:2',
effect: 'allow',
})
const partialObject = { id: 'alma' }
test('Should not match a missing property if known fields are not provided', () => {
assert.strictEqual(ownVmPrivilege.match({ resource: 'vm', action: 'read', object: partialObject }), false)
})
test('Should not match a missing property if it is a known field', () => {
assert.strictEqual(
ownVmPrivilege.match({
resource: 'vm',
action: 'read',
object: partialObject,
knownFields: ['id', 'creation'],
}),
false
)
})
test('Should return UNKNOWN if the selector uses an unknown field', () => {
assert.strictEqual(
ownVmPrivilege.match({ resource: 'vm', action: 'read', object: partialObject, knownFields: ['id'] }),
UNKNOWN
)
})
test('Should not match because of the resource even if the selector is unknown', () => {
assert.strictEqual(
ownVmPrivilege.match({ resource: 'host', action: 'read', object: partialObject, knownFields: ['id'] }),
false
)
})
test('Should not match because of the action even if the selector is unknown', () => {
assert.strictEqual(
ownVmPrivilege.match({ resource: 'vm', action: 'start', object: partialObject, knownFields: ['id'] }),
false
)
})
test('Should match without selector', () => {
assert.strictEqual(
privilege.match({ resource: 'vm', action: 'read', object: partialObject, knownFields: [] }),
true
)
})
test('Should resolve a field present on the object even if it is not listed', () => {
assert.strictEqual(
ownVmPrivilege.match({
resource: 'vm',
action: 'read',
object: { creation: { creator: '2' } },
knownFields: [],
}),
true
)
})
test('Should resolve a field provided by a getter', () => {
class Vm {
get creation() {
return { creator: '2' }
}
}
assert.strictEqual(
ownVmPrivilege.match({ resource: 'vm', action: 'read', object: new Vm(), knownFields: [] }),
true
)
})
test('Should return UNKNOWN on a term not bound to a property', () => {
const bareTermPrivilege = new Privilege({ action: 'read', resource: 'vm', selector: 'alma', effect: 'allow' })
assert.strictEqual(
bareTermPrivilege.match({ resource: 'vm', action: 'read', object: partialObject, knownFields: ['id'] }),
UNKNOWN
)
})
test('Should return UNKNOWN if one of the fields is unknown, even if the others decide the result', () => {
const orPrivilege = new Privilege({
action: 'read',
resource: 'vm',
selector: '|(id:alma creation:creator:2)',
effect: 'allow',
})
assert.strictEqual(
orPrivilege.match({ resource: 'vm', action: 'read', object: partialObject, knownFields: ['id'] }),
UNKNOWN
)
})
})
})
suite('ACL V2 behavior', async () => {
@@ -397,6 +499,205 @@ suite('ACL V2 behavior', async () => {
assert.strictEqual(vms.length, 2)
})
})
suite('partial objects behavior', () => {
const UNKNOWN_RESULT = { code: 'RBAC_UNKNOWN_RESULT' }
const vmReadAll = {
id: privilegeId,
action: 'read',
resource: 'vm',
effect: 'allow',
roleId,
} satisfies TPrivilege<'vm'>
const vmReadOwn = {
id: privilegeId,
action: 'read',
resource: 'vm',
selector: `creation:creator:${user.id}`,
effect: 'allow',
roleId,
} satisfies TPrivilege<'vm'>
const vmDenyReadOnPool = {
id: privilegeId,
action: 'read',
resource: 'vm',
selector: '$pool:2',
effect: 'deny',
roleId,
} satisfies TPrivilege<'vm'>
const partialVm = { id: 'partial-vm' }
const partialVmOnDeniedPool = { id: 'partial-vm-denied', $pool: '2' }
suite('hasPrivilegeOn', () => {
test('Should always return true for admin', () => {
assert.strictEqual(
hasPrivilegeOn({
user: admin,
action: 'read',
resource: 'vm',
objects: partialVm,
knownFields: ['id'],
userPrivileges: [vmReadOwn],
}),
true
)
})
test('Should keep the current behavior if known fields are not provided', () => {
assert.strictEqual(
hasPrivilegeOn({ user, action: 'read', resource: 'vm', objects: partialVm, userPrivileges: [vmReadOwn] }),
false
)
})
test('Should throw if the only allow privilege is unknown', () => {
assert.throws(
() =>
hasPrivilegeOn({
user,
action: 'read',
resource: 'vm',
objects: partialVm,
knownFields: ['id'],
userPrivileges: [vmReadOwn],
}),
UNKNOWN_RESULT
)
})
test('Should return false if the unknown field is known to be absent', () => {
assert.strictEqual(
hasPrivilegeOn({
user,
action: 'read',
resource: 'vm',
objects: partialVm,
knownFields: ['id', 'creation'],
userPrivileges: [vmReadOwn],
}),
false
)
})
test('Should return true if an allow privilege is known even if another one is unknown', () => {
assert.strictEqual(
hasPrivilegeOn({
user,
action: 'read',
resource: 'vm',
objects: partialVm,
knownFields: ['id'],
userPrivileges: [vmReadOwn, vmReadAll],
}),
true
)
})
test('Should throw if a deny privilege is unknown, even with a known allow privilege', () => {
assert.throws(
() =>
hasPrivilegeOn({
user,
action: 'read',
resource: 'vm',
objects: partialVm,
knownFields: ['id'],
userPrivileges: [vmReadAll, vmDenyReadOnPool],
}),
UNKNOWN_RESULT
)
})
test('Should return true if a deny privilege is known not to match', () => {
assert.strictEqual(
hasPrivilegeOn({
user,
action: 'read',
resource: 'vm',
objects: partialVm,
knownFields: ['id', '$pool'],
userPrivileges: [vmReadAll, vmDenyReadOnPool],
}),
true
)
})
test('Should return false if a deny privilege is known to match, even with an unknown allow privilege', () => {
assert.strictEqual(
hasPrivilegeOn({
user,
action: 'read',
resource: 'vm',
objects: partialVmOnDeniedPool,
knownFields: ['id', '$pool'],
userPrivileges: [vmReadOwn, vmDenyReadOnPool],
}),
false
)
})
test('Should return false if one of the objects is known to be denied, even if another one is unknown', () => {
assert.strictEqual(
hasPrivilegeOn({
user,
action: 'read',
resource: 'vm',
objects: [partialVm, partialVmOnDeniedPool],
knownFields: ['id'],
userPrivileges: [vmReadAll, vmDenyReadOnPool],
}),
false
)
})
test('Should throw if the other objects are allowed and one is unknown', () => {
assert.throws(
() =>
hasPrivilegeOn({
user,
action: 'read',
resource: 'vm',
objects: [{ id: 'allowed-vm', $pool: '1' }, partialVm],
knownFields: ['id'],
userPrivileges: [vmReadAll, vmDenyReadOnPool],
}),
UNKNOWN_RESULT
)
})
})
suite('getMissingPrivileges', () => {
test('Should throw if a privilege is unknown', () => {
assert.throws(
() =>
getMissingPrivileges(
[{ user, action: 'read', resource: 'vm', objects: partialVm, knownFields: ['id'] }],
[vmReadOwn]
),
UNKNOWN_RESULT
)
})
})
suite('filterObjectsWithPrivilege', () => {
test('Should throw if a privilege is unknown on one of the objects', () => {
assert.throws(
() =>
filterObjectsWithPrivilege({
user,
action: 'read',
resource: 'vm',
objects: [partialVm],
knownFields: ['id'],
userPrivileges: [vmReadOwn],
}),
UNKNOWN_RESULT
)
})
})
})
})
suite('getActionStrings', () => {

View File

@@ -3,6 +3,7 @@
## **next**
- [VM/Network] Add possibility to delete a VIF (PR [#10726](https://github.com/vatesfr/xen-orchestra/pull/10726))
- [Web-Core/VtsErrorModal] Add an optional details log viewer, unified icon (PR [#10536](https://github.com/vatesfr/xen-orchestra/pull/10536))
## **0.28.0** (2026/12/01)

View File

@@ -1,8 +1,8 @@
import type { XenApiNetwork } from '@/libs/xen-api/xen-api.types.ts'
import { useNetworkDeleteJob } from '@/modules/network/jobs/network-delete.job.ts'
import { useDeleteModal } from '@core/composables/modals/use-delete-modal.ts'
import { useErrorModal } from '@core/composables/modals/use-error-modal.ts'
import { useRouteQuery } from '@core/composables/route-query.composable.ts'
import { useOverlay } from '@core/packages/overlay/use-overlay.ts'
import { toComputed } from '@core/utils/to-computed.util.ts'
import type { MaybeRefOrGetter } from 'vue'
import { useI18n } from 'vue-i18n'
@@ -23,12 +23,7 @@ export function useNetworkDelete(rawNetworks: MaybeRefOrGetter<XenApiNetwork[]>)
const { open: openNetworkDeleteModal } = useDeleteModal()
const { open: openNetworkDeleteErrorModal } = useOverlay({
component: () => import('@core/components/modal/VtsErrorModal.vue'),
events: {
onClose: true,
},
})
const { open: openNetworkDeleteErrorModal } = useErrorModal()
function deleteNetworks() {
if (!canDeleteNetworks.value) {

View File

@@ -499,6 +499,13 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/modal/vts-error-modal': RouteRecordInfo<
'/story/web-core/modal/vts-error-modal',
'/story/web-core/modal/vts-error-modal',
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',
@@ -1737,6 +1744,12 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/stories/web-core/modal/vts-error-modal.story.vue': {
routes:
| '/story/web-core/modal/vts-error-modal'
views:
| never
}
'src/stories/web-core/number-input/vts-number-input.story.vue': {
routes:
| '/story/web-core/number-input/vts-number-input'

View File

@@ -0,0 +1,29 @@
# Usage
Open the modal with `useErrorModal`.
```vue-script
import { useErrorModal } from '@core/composables/modals/use-error-modal.ts'
const { open: openErrorModal } = useErrorModal()
try {
// ...
} catch (error) {
void openErrorModal({
props: {
title: 'Unable to create cluster',
error: 'An error occurred',
details: error,
},
})
}
```
The `details` prop is displayed below the message, even when the `content` slot is overridden:
```vue-template
<VtsErrorModal title="Unable to delete network" :details @close="close()">
<template #content>Custom error message</template>
</VtsErrorModal>
```

View File

@@ -0,0 +1,60 @@
<template>
<ComponentStory
v-slot="{ properties, settings }"
:params="[
prop('title').str().required().preset('Unable to create cluster').widget(),
prop('error').str().preset('An error occurred').widget(),
prop('details')
.type('string | object')
.preset(details1)
.widget(object())
.help('When set, displayed in a log entry viewer below the error message'),
event('close'),
slot('content').help('Replaces the error message. The details are still displayed below it'),
setting('contentSlotContent').widget(text()).help('Leave empty to use the error prop'),
]"
:presets
>
<VtsErrorModal class="story" v-bind="properties">
<template v-if="settings.contentSlotContent" #content>{{ settings.contentSlotContent }}</template>
</VtsErrorModal>
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { event, prop, setting, slot } from '@/libs/story/story-param.ts'
import { object, text } from '@/libs/story/story-widget.ts'
import VtsErrorModal from '@core/components/modal/VtsErrorModal.vue'
const details1 = {
code: 'HOST_NOT_ENOUGH_FREE_MEMORY',
params: ['8589934592', '2147483648'],
call: {
method: 'VM.start',
params: ['OpaqueRef:3f2a9c1e-7b4d-4e8a-9f6c-2d1b5a8e7c90', false, false],
},
}
const details2 =
'TypeError: Failed to fetch\n at fetchApi (rest-api.ts:42:11)\n at async createCluster (cluster-create.job.ts:88:5)'
const presets = {
'Without details': {
props: { details: undefined },
},
'With details object': {
props: { details: details1 },
},
'With details string': {
props: { details: details2 },
},
}
</script>
<style lang="postcss" scoped>
.story {
position: relative;
height: 100%;
}
</style>

View File

@@ -1,9 +1,11 @@
import {
Body,
Delete,
Example,
Extension,
Get,
Middlewares,
Patch,
Path,
Put,
Query,
@@ -16,8 +18,9 @@ import {
} from 'tsoa'
import { inject } from 'inversify'
import { provide } from 'inversify-binding-decorators'
import { Request as ExRequest } from 'express'
import type { XoAlarm, XoMessage, XoNetwork, XoTask } from '@vates/types'
import { invalidParameters } from 'xo-common/api-errors.js'
import { json, NextFunction, Request as ExRequest, Response as ExResponse } from 'express'
import type { EditNetworkProps, XoAlarm, XoMessage, XoNetwork, XoTask } from '@vates/types'
import { AlarmService } from '../alarms/alarm.service.mjs'
import { escapeUnsafeComplexMatcher } from '../helpers/utils.helper.mjs'
@@ -26,6 +29,8 @@ import { network, networkIds, partialNetworks } from '../open-api/oa-examples/ne
import {
badRequestResp,
forbiddenOperationResp,
internalServerErrorResp,
invalidParameters as invalidParametersResp,
noContentResp,
notFoundResp,
unauthorizedResp,
@@ -36,7 +41,60 @@ import type { SendObjects } from '../helpers/helper.type.mjs'
import { XapiXoController } from '../abstract-classes/xapi-xo-controller.mjs'
import { messageIds, partialMessages } from '../open-api/oa-examples/message.oa-example.mjs'
import { partialTasks, taskIds } from '../open-api/oa-examples/task.oa-example.mjs'
import { acl } from '../middlewares/acl.middleware.mjs'
import { acl, actionsFromBody } from '../middlewares/acl.middleware.mjs'
import type { AuthenticatedRequest } from '../helpers/helper.type.mjs'
// the fields come from EditNetworkProps, so a field added there reaches the body too; MTU and insecureNbd
// are redeclared only to carry their tsoa JSDoc (validation and description in the OpenAPI spec)
type UpdateNetworkRequestBody = Omit<EditNetworkProps, 'MTU' | 'insecureNbd'> & {
/**
* @isInt
* @minimum 68 the MTU must be at least 68 (RFC 791)
*/
MTU?: number
/**
* NBD in clear, only on a network dedicated to backups. Mutually exclusive with `nbd`
*/
insecureNbd?: boolean
}
// the privileges a PATCH checks: update:<field> for each field in the body, and the other NBD
// purpose when one is set, since the XAPI side removes it (setNbdPurposes in
// xo-server/src/xapi/mixins/networking.mjs): nbd: true removes insecure_nbd, insecureNbd: true removes nbd
export function updateNetworkActions({ req }: { req: AuthenticatedRequest }) {
const actions = actionsFromBody<'network'>([
'update:automatic',
'update:defaultIsLocked',
'update:insecureNbd',
'update:MTU',
'update:name_description',
'update:name_label',
'update:nbd',
])({ req })
const body: UpdateNetworkRequestBody = req.body
if (body.insecureNbd === true) {
actions.push('update:nbd')
}
if (body.nbd === true) {
actions.push('update:insecureNbd')
}
return actions
}
// runs before acl(): a body with no gated field gets no privilege checked, so it is refused here, for a missing
// network too. Refusing it in the handler, after the ACL has resolved the network, would answer 404 for a missing
// network and 422 for an existing one, which tells them apart
export function refuseEmptyUpdate(req: AuthenticatedRequest, _res: ExResponse, next: NextFunction) {
if (updateNetworkActions({ req }).length > 0) {
return next()
}
// the api-errors factories throw, so the error is caught to reach next()
try {
invalidParameters('the body must contain at least one field to update')
} catch (error) {
return next(error)
}
}
@Route('networks')
@Security('*')
@@ -94,6 +152,56 @@ export class NetworkController extends XapiXoController<XoNetwork> {
return this.getObject(id as XoNetwork['id'])
}
/**
* Partial update of a network: only the fields present in the body are modified.
*
* Changing `MTU` unplugs and replugs the network's PIFs and the VIFs of its running VMs: their
* traffic is briefly interrupted.
* `nbd` and `insecureNbd` are mutually exclusive; setting one to `false` only removes that purpose.
* `automatic` adds the network to new VMs automatically; `defaultIsLocked` blocks the traffic of
* VIFs with no allowed IP.
* A body with none of the fields below is refused with a 422, whether or not the network exists.
*
* Required privilege per field provided in the body:
* - resource: network, action: update:&lt;field&gt;
* - and with `nbd: true`, also resource: network, action: update:insecureNbd (it removes the
* insecure NBD purpose); with `insecureNbd: true`, also action: update:nbd (it removes the NBD purpose)
*
* @example id "9fe12ca3-d75d-cfb0-492e-cfd2bc6c568f"
* @example body { "name_label": "backups", "MTU": 9000, "insecureNbd": true }
*/
@Extension('x-mcp-exposure', 'confirm')
@Patch('{id}')
@Middlewares([
json(),
refuseEmptyUpdate,
acl({
resource: 'network',
actions: updateNetworkActions,
objectId: 'params.id',
}),
])
@SuccessResponse(noContentResp.status, noContentResp.description)
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
@Response(notFoundResp.status, notFoundResp.description)
@Response(invalidParametersResp.status, invalidParametersResp.description)
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
async updateNetwork(@Path() id: string, @Body() body: UpdateNetworkRequestBody): Promise<void> {
const networkId = id as XoNetwork['id']
const { automatic, defaultIsLocked, insecureNbd, MTU, name_description, name_label, nbd } = body
// forward only the declared fields: the ACL above checked their privileges and the NBD purpose each one removes
await this.getXapi(networkId).editNetwork(networkId, {
automatic,
defaultIsLocked,
insecureNbd,
MTU,
name_description,
name_label,
nbd,
})
}
/**
* Required privilege:
* - resource: network, action: delete

View File

@@ -0,0 +1,90 @@
import assert from 'node:assert/strict'
import { describe, it, mock } from 'node:test'
import { getMissingPrivileges, type AnyPrivilege, type AnyPrivilegeOnParam } from '@xen-orchestra/acl'
import type { XoUser } from '@vates/types'
import type { NextFunction, Response } from 'express'
import { invalidParameters } from 'xo-common/api-errors.js'
import { NetworkController, refuseEmptyUpdate, updateNetworkActions } from './network.controller.mjs'
import type { AuthenticatedRequest } from '../helpers/helper.type.mjs'
import type { RestApi } from '../rest-api/rest-api.mjs'
const user = { id: 'user-1', permission: 'none' } as XoUser
const network = { id: 'network-1' }
const NETWORK_ID = '9fe12ca3-d75d-cfb0-492e-cfd2bc6c568f'
function missingPrivileges(body: object, userPrivileges: AnyPrivilege[]) {
const req = { body } as AuthenticatedRequest
const params = updateNetworkActions({ req }).map(
action => ({ user, resource: 'network', action, objects: [network] }) as AnyPrivilegeOnParam
)
return getMissingPrivileges(params, userPrivileges)
}
describe('updateNetworkActions', () => {
it('refuses insecureNbd: true to a user with only update:insecureNbd, as it removes the nbd purpose', () => {
const privileges = [
{ id: 'privilege-1', resource: 'network', action: 'update:insecureNbd', effect: 'allow', roleId: 'role-1' },
] as unknown as AnyPrivilege[]
const missing = missingPrivileges({ insecureNbd: true }, privileges)
assert.equal(missing.length, 1)
assert.equal(missing[0].action, 'update:nbd')
})
})
describe('refuseEmptyUpdate', () => {
it('refuses an empty body with a 422 before the ACL resolves the network', () => {
const next = mock.fn()
refuseEmptyUpdate({ body: {} } as AuthenticatedRequest, {} as Response, next as NextFunction)
assert.equal(next.mock.callCount(), 1)
assert.ok(invalidParameters.is(next.mock.calls[0].arguments[0]))
})
})
describe('NetworkController.updateNetwork', () => {
it('forwards only the seven declared fields to editNetwork, with the id the route got', async () => {
const editCalls: unknown[][] = []
const restApi = {
xoApp: {
getXapi: () => ({
editNetwork: async (...args: unknown[]) => {
editCalls.push(args)
},
}),
},
} as unknown as RestApi
const controller = new NetworkController(restApi, {} as never)
// not an object literal passed inline: an extra key is only allowed on a value, not on a fresh literal
const body = {
automatic: true,
defaultIsLocked: false,
insecureNbd: false,
MTU: 9000,
name_description: 'description',
name_label: 'label',
nbd: true,
notAField: 'dropped',
}
await controller.updateNetwork(NETWORK_ID, body)
assert.deepEqual(editCalls, [
[
NETWORK_ID,
{
automatic: true,
defaultIsLocked: false,
insecureNbd: false,
MTU: 9000,
name_description: 'description',
name_label: 'label',
nbd: true,
},
],
])
})
})

View File

@@ -1,10 +1,62 @@
import { invalidParameters } from 'xo-common/api-errors.js'
import type { CreateBondedNetworkBody, CreateInternalNetworkBody, CreateNetworkBody } from '../pools/pool.type.mjs'
import type { ReplaceKey } from '../helpers/helper.type.mjs'
import type { AuthenticatedRequest, ReplaceKey } from '../helpers/helper.type.mjs'
import type { NextFunction, Response as ExResponse } from 'express'
import type { RestApi } from '../rest-api/rest-api.mjs'
import type { Xapi, XenApiNetworkWrapped, XoNetwork, XoPool } from '@vates/types'
type NetworkCreateNames = Pick<
CreateNetworkBody,
'name' | 'name_label' | 'description' | 'name_description' | 'mtu' | 'MTU'
>
// maps the names the create routes accept to the ones xapi.createNetwork reads (name, description, mtu), and
// refuses a body giving both spellings of one field or no name. The create routes call it before their task
// starts, so the refusal is a 422 and not a failed task
export function normalizeNetworkCreateBody<T extends NetworkCreateNames>(body: T) {
const { name, name_label, description, name_description, mtu, MTU, ...rest } = body
if (name !== undefined && name_label !== undefined) {
throw invalidParameters('give either name or name_label, not both')
}
if (description !== undefined && name_description !== undefined) {
throw invalidParameters('give either description or name_description, not both')
}
if (mtu !== undefined && MTU !== undefined) {
throw invalidParameters('give either mtu or MTU, not both')
}
const networkName = name_label ?? name
if (networkName === undefined) {
throw invalidParameters('name_label is required')
}
return {
...rest,
name: networkName,
description: name_description ?? description,
mtu: MTU ?? mtu,
}
}
// runs before acl(): acl() awaits its object callback outside any try, and Express 4 does not catch that rejection,
// so a refusal thrown there would hang the request. Checked here, the callback below can't throw
export function refuseInvalidNetworkCreateBody(req: AuthenticatedRequest, _res: ExResponse, next: NextFunction) {
try {
normalizeNetworkCreateBody(req.body)
} catch (error) {
return next(error)
}
next()
}
// the ACL checks the privileges against the names xapi reads, so the selectors written on name, description and
// mtu match whatever spelling the client used
export function networkCreateAclObject({ req }: { req: AuthenticatedRequest }) {
return normalizeNetworkCreateBody(req.body)
}
export class NetworkService {
#restApi: RestApi
@@ -12,9 +64,12 @@ export class NetworkService {
this.#restApi = restApi
}
// body must come from normalizeNetworkCreateBody
async create(
poolId: XoPool['id'],
body: ReplaceKey<CreateNetworkBody, 'pif', 'pifId'> | CreateBondedNetworkBody | CreateInternalNetworkBody
body: (ReplaceKey<CreateNetworkBody, 'pif', 'pifId'> | CreateBondedNetworkBody | CreateInternalNetworkBody) & {
name: string
}
): Promise<XoNetwork['id']> {
const { nbd, insecureNbd, ...rest } = body
if (nbd && insecureNbd) {

View File

@@ -0,0 +1,43 @@
import assert from 'node:assert/strict'
import { describe, it } from 'node:test'
import { invalidParameters } from 'xo-common/api-errors.js'
import { networkCreateAclObject, normalizeNetworkCreateBody } from './network.service.mjs'
describe('normalizeNetworkCreateBody', () => {
it('maps name_label, name_description and MTU to the names xapi.createNetwork reads', () => {
const body = normalizeNetworkCreateBody({
name_label: 'label',
name_description: 'description',
MTU: 9000,
vlan: 0,
})
assert.deepEqual(body, { name: 'label', description: 'description', mtu: 9000, vlan: 0 })
})
it('still accepts the deprecated name, description and mtu', () => {
const body = normalizeNetworkCreateBody({ name: 'label', description: 'description', mtu: 1450 })
assert.deepEqual(body, { name: 'label', description: 'description', mtu: 1450 })
})
it('refuses a body giving both spellings of one field', () => {
assert.throws(() => normalizeNetworkCreateBody({ name: 'a', name_label: 'b' }), invalidParameters.is)
assert.throws(
() => normalizeNetworkCreateBody({ name_label: 'a', description: 'b', name_description: 'c' }),
invalidParameters.is
)
assert.throws(() => normalizeNetworkCreateBody({ name_label: 'a', mtu: 1450, MTU: 9000 }), invalidParameters.is)
})
it('refuses a body with no name', () => {
assert.throws(() => normalizeNetworkCreateBody({ name_description: 'description' }), invalidParameters.is)
})
it('gives the ACL the old keys for a body sent with the new names', () => {
const req = { body: { name_label: 'label', name_description: 'description', MTU: 9000 } }
assert.deepEqual(networkCreateAclObject({ req } as never), { name: 'label', description: 'description', mtu: 9000 })
})
})

View File

@@ -95,7 +95,12 @@ import { PoolService } from './pool.service.mjs'
import { BASE_URL, escapeUnsafeComplexMatcher, NDJSON_CONTENT_TYPE } from '../helpers/utils.helper.mjs'
import { messageIds, partialMessages } from '../open-api/oa-examples/message.oa-example.mjs'
import type { CreateActionReturnType } from '../abstract-classes/base-controller.mjs'
import { NetworkService } from '../networks/network.service.mjs'
import {
NetworkService,
networkCreateAclObject,
normalizeNetworkCreateBody,
refuseInvalidNetworkCreateBody,
} from '../networks/network.service.mjs'
import { v2vStartResult } from '../open-api/oa-examples/v2v.oa-example.mjs'
import { V2V_TASK_PROPERTY } from '@vates/types'
import { V2vService, V2V_TASK_NAME } from '../v2v/v2v.service.mjs'
@@ -180,8 +185,8 @@ export class PoolController extends XapiXoController<XoPool> {
*
* @example id "355ee47d-ff4c-4924-3db2-fd86ae629676"
* @example body {
* "name": "awes0me_network",
* "description": "random description",
* "name_label": "awes0me_network",
* "name_description": "random description",
* "pif": "ad15b2c8-3d9a-194e-c43a-e3dcda74b256",
* "vlan": 0
* }
@@ -192,10 +197,11 @@ export class PoolController extends XapiXoController<XoPool> {
@Post('{id}/actions/create_network')
@Middlewares([
json(),
refuseInvalidNetworkCreateBody,
acl([
// these two rights are a bit redundant, but for now this is the only way to restrict network creation on a given pool
{ resource: 'pool', action: 'create:network', objectId: 'params.id' },
{ resource: 'network', action: 'create', object: ({ req }) => req.body },
{ resource: 'network', action: 'create', object: networkCreateAclObject },
]),
])
@Tags('networks')
@@ -211,8 +217,8 @@ export class PoolController extends XapiXoController<XoPool> {
@Query() sync?: boolean
): CreateActionReturnType<{ id: Unbrand<XoNetwork>['id'] }> {
const poolId = id as XoPool['id']
const { pif, ...rest } = normalizeNetworkCreateBody(body)
const action = async () => {
const { pif, ...rest } = body
const networkId = await this.#networkService.create(poolId, { pifId: pif as XoPif['id'], ...rest })
return { id: networkId }
@@ -236,8 +242,8 @@ export class PoolController extends XapiXoController<XoPool> {
*
* @example id "355ee47d-ff4c-4924-3db2-fd86ae629676"
* @example body {
* "name": "awes0me_bonded_network",
* "description": "random description",
* "name_label": "awes0me_bonded_network",
* "name_description": "random description",
* "pifIds": ["ad15b2c8-3d9a-194e-c43a-e3dcda74b256", "7b6bed50-26b2-bd27-8f3a-1b5a81989a92"],
* "bondMode": "lacp"
* }
@@ -248,9 +254,10 @@ export class PoolController extends XapiXoController<XoPool> {
@Post('{id}/actions/create_bonded_network')
@Middlewares([
json(),
refuseInvalidNetworkCreateBody,
acl([
{ resource: 'pool', action: 'create:network', objectId: 'params.id' },
{ resource: 'network', action: 'create', object: ({ req }) => req.body },
{ resource: 'network', action: 'create', object: networkCreateAclObject },
]),
])
@Tags('networks')
@@ -266,8 +273,8 @@ export class PoolController extends XapiXoController<XoPool> {
@Query() sync?: boolean
): CreateActionReturnType<{ id: Unbrand<XoNetwork>['id'] }> {
const poolId = id as XoPool['id']
const { pifIds, ...rest } = normalizeNetworkCreateBody(body)
const action = async () => {
const { pifIds, ...rest } = body
const networkId = await this.#networkService.create(poolId, { pifIds: pifIds as XoPif['id'][], ...rest })
return { id: networkId }
@@ -291,8 +298,8 @@ export class PoolController extends XapiXoController<XoPool> {
*
* @example id "355ee47d-ff4c-4924-3db2-fd86ae629676"
* @example body {
* "name": "awes0me_internal_network",
* "description": "random description"
* "name_label": "awes0me_internal_network",
* "name_description": "random description"
* }
*/
@Example(taskLocation)
@@ -301,9 +308,10 @@ export class PoolController extends XapiXoController<XoPool> {
@Post('{id}/actions/create_internal_network')
@Middlewares([
json(),
refuseInvalidNetworkCreateBody,
acl([
{ resource: 'pool', action: 'create:network', objectId: 'params.id' },
{ resource: 'network', action: 'create', object: ({ req }) => req.body },
{ resource: 'network', action: 'create', object: networkCreateAclObject },
]),
])
@Tags('networks')
@@ -319,8 +327,9 @@ export class PoolController extends XapiXoController<XoPool> {
@Query() sync?: boolean
): CreateActionReturnType<{ id: Unbrand<XoNetwork>['id'] }> {
const poolId = id as XoPool['id']
const networkBody = normalizeNetworkCreateBody(body)
const action = async () => {
const networkId = await this.#networkService.create(poolId, body)
const networkId = await this.#networkService.create(poolId, networkBody)
return { id: networkId }
}

View File

@@ -12,13 +12,28 @@ import type {
} from '@vates/types'
import { Unbrand } from '../open-api/common/response.common.mjs'
// the names are the ones PATCH /networks/{id} takes (name_label, name_description, MTU); name, description and mtu
// are the names these routes took before and still work. tsoa cannot express "exactly one of", so name and
// name_label are both optional here and normalizeNetworkCreateBody (network.service.mts) refuses a body with neither
type BaseCreateNetworkBody = {
name: string
/**
* @deprecated use `name_label`
*/
name?: string
name_label?: string
/**
* @deprecated use `name_description`
*/
description?: string
name_description?: string
/**
* @deprecated use `MTU`
*/
mtu?: number
/**
* @default 1500
*/
mtu?: number
MTU?: number
nbd?: boolean
/**
* NBD in clear, only on a network dedicated to backups. Mutually exclusive with `nbd`

View File

@@ -89,7 +89,7 @@ const CONTROLLER_PREFIXES = {
* 'config.annotation'?: string,
* 'config.instanceUuid'?: string,
* 'config.firmware'?: string,
* 'config.bootOptions.efiSecureBootEnabled'?: unknown,
* 'config.bootOptions'?: { efiSecureBootEnabled?: unknown },
* 'config.template'?: unknown,
* 'config.hardware.numCPU'?: unknown,
* 'config.hardware.memoryMB'?: unknown,
@@ -379,7 +379,7 @@ export function buildInventory({
annotation: properties['config.annotation'],
instanceUuid: properties['config.instanceUuid'],
firmware: firmware === 'efi' ? 'uefi' : firmware,
secureBoot: isTrue(properties['config.bootOptions.efiSecureBootEnabled']),
secureBoot: isTrue(properties['config.bootOptions']?.efiSecureBootEnabled),
isTemplate: isTrue(properties['config.template']),
cpus: toNumber(properties['config.hardware.numCPU']),
memory: memoryMb === undefined ? undefined : memoryMb * 1024 * 1024,

View File

@@ -1,7 +1,14 @@
import assert from 'node:assert/strict'
import { describe, it } from 'node:test'
import { countSnapshots, findDatacenter, parseDevices, parseGuestNics, parseVlan } from './_inventory.mjs'
import {
buildInventory,
countSnapshots,
findDatacenter,
parseDevices,
parseGuestNics,
parseVlan,
} from './_inventory.mjs'
// shaped as the SOAP library returns them: the nested references and types are not normalized
const typed = (type, value) => ({ attributes: { 'xsi:type': type }, ...value })
@@ -202,3 +209,37 @@ describe('findDatacenter', function () {
assert.equal(findDatacenter('group-a', loop, datacenterIds), undefined)
})
})
describe('buildInventory', function () {
const EMPTY = {
about: {},
datacenters: {},
clusters: {},
hosts: {},
datastores: {},
networks: {},
portgroups: {},
folders: {},
computeResources: {},
}
it('reads secure boot from the boot options, absent before vSphere 6.5', function () {
const { vms } = buildInventory({
...EMPTY,
vms: {
'vm-65': { 'config.bootOptions': { efiSecureBootEnabled: 'true' } },
// ESXi 6.0: the boot options have no `efiSecureBootEnabled`
'vm-60': { 'config.bootOptions': { bootDelay: '0' } },
'vm-none': {},
},
})
assert.deepEqual(
vms.map(({ id, secureBoot }) => ({ id, secureBoot })),
[
{ id: 'vm-65', secureBoot: true },
{ id: 'vm-60', secureBoot: false },
{ id: 'vm-none', secureBoot: false },
]
)
})
})

View File

@@ -623,7 +623,9 @@ export default class Esxi extends EventEmitter {
'config.annotation',
'config.instanceUuid',
'config.firmware',
'config.bootOptions.efiSecureBootEnabled',
// the whole object rather than `config.bootOptions.efiSecureBootEnabled`: that property only
// exists since vSphere 6.5, and an unknown path fails the whole request (InvalidProperty)
'config.bootOptions',
'config.template',
'config.hardware.numCPU',
'config.hardware.memoryMB',
@@ -1134,9 +1136,11 @@ export default class Esxi extends EventEmitter {
* @returns {Promise<object>} the `info` of the successful task
*/
async snapshot(vmId, name, description, { signal, timeout = 30 * 60e3 } = {}) {
// not `CreateSnapshotEx_Task`: it only exists since vSphere 8 (absent from the WSDL of older
// hosts), and its only addition, the quiesce spec, is not used
return this.#runTask(
'CreateSnapshotEx_Task',
{ _this: vmId, name, description, memory: false },
'CreateSnapshot_Task',
{ _this: vmId, name, description, memory: false, quiesce: false },
{ signal, timeout }
)
}

View File

@@ -696,7 +696,7 @@ describe('tasks', function () {
const controller = new AbortController()
const { esxi, vimClient } = await connectedEsxi({
responses: {
CreateSnapshotEx_Task: () => startedTask(),
CreateSnapshot_Task: () => startedTask(),
RetrievePropertiesEx: () => {
controller.abort()
return taskInfo('running')

View File

@@ -59,6 +59,7 @@ Testing uses **Vitest 5** with a single `unit` project (see `vitest.config.ts`):
| `test/expect-loader.ts` | `hasLoader(wrapper)`: whether a `UiLoader` is rendered; `expectLoaderInsteadOf(wrapper, findContent)`: a `UiLoader` shown and the content it stands for empty (also used by XO 6) |
| `test/select.ts` | `openSelect`, `findShownSelections`, `findSelectOptionLabels`, `pickSelectOption(wrapper, label, { detailed? })`: opens a `VtsSelect`, reads the selection it shows, reads or picks its options (`detailed`: the option shows details after its label); `chooseSelectOption(wrapper, label, { container?, detailed? })`: opens the select inside `container`, then picks the option (also used by XO 6) |
| `test/is-placeholder-shown.ts` | `isPlaceholderShown(field)`: whether a readonly input shows its placeholder in place of its value |
| `test/can-focus-input.ts` | `canFocusInput(wrapper)`: whether the first input of a wrapper attached to the document takes the focus, which an `inert` ancestor prevents |
| `test/inject-or-throw.ts` | `injectOrThrow(key)`: `inject(key)`, throwing when nothing provides it |
| `test/mount-with-setup.ts` | `mountWithSetup(setup, { global?, attachTo? })`: mounts a component whose `setup` sets up what its render needs below it (a select, a provided context) and returns that render (XO 6 wraps it with its config); `mountWithSetupResult(setup, options)`: the same, keeping what `setup` builds (a form, a composable's return), `setup` returning `{ result, render }`, returns `{ wrapper, result }`; `mountComposableUnderSetup(setup, composable, options)`: runs `composable` (given what `setup` returned) in a child of the component whose `setup` provides what it injects, returns `{ provided, result }` |
| `test/mount-with-select.ts` | `renderSelect(id, { accent?, ref? }, slots?)`: renders the `VtsSelect` of a select id, `neutral` accent by default; `mountSelect`: a `VtsSelect` of string sources, its config, accent, wrapper message, option slot and a callback receiving the mounted select |

View File

@@ -46,7 +46,7 @@ const columnTransition = `grid-template-columns ${PANEL_TRANSITION_DURATION}ms`
display: grid;
grid-template-columns: minmax(0, 1fr) 0;
grid-template-rows: minmax(0, 1fr);
overflow: hidden;
overflow: clip;
.content {
overflow-y: auto;

View File

@@ -0,0 +1,38 @@
import VtsLayoutSidebar from '@core/components/layout/VtsLayoutSidebar.vue'
import { useRightSidebarStore } from '@core/packages/sidebar'
import { canFocusInput } from '@core-test/can-focus-input.ts'
import { createGlobalTestConfig } from '@core-test/create-global-test-config.ts'
import { mount } from '@vue/test-utils'
import { h, nextTick } from 'vue'
beforeEach(() => {
localStorage.clear()
})
function mountSidebar({ isExpanded }: { isExpanded: boolean }) {
localStorage.setItem('sidebar.right.expanded', String(isExpanded))
return mount(VtsLayoutSidebar, {
props: { side: 'right' },
slots: { default: () => h('input') },
global: createGlobalTestConfig(),
attachTo: document.body,
})
}
it('lets the focus into an expanded sidebar', () => {
expect(canFocusInput(mountSidebar({ isExpanded: true }))).toBe(true)
})
it('keeps the focus out of a collapsed sidebar', () => {
expect(canFocusInput(mountSidebar({ isExpanded: false }))).toBe(false)
})
it('lets the focus in once the sidebar expands', async () => {
const wrapper = mountSidebar({ isExpanded: false })
useRightSidebarStore().toggleExpand(true)
await nextTick()
expect(canFocusInput(wrapper)).toBe(true)
})

View File

@@ -1,5 +1,5 @@
<template>
<div :class="className" class="vts-layout-sidebar">
<div :class="className" class="vts-layout-sidebar" :inert="!sidebar.isExpanded">
<VtsResizeHandle v-if="showResizeHandle" :position="resizeHandlePosition" :resizable="sidebar" />
<div v-if="slots.header || (showLock && !ui.isSmall)" class="header">
<div v-if="slots.header" class="start">

View File

@@ -1,13 +1,29 @@
<template>
<UiModal accent="danger" icon="status:danger-picto" @dismiss="emit('close')" @confirm="emit('close')">
<UiModal
class="vts-error-modal"
accent="danger"
icon="status:info-picto"
@dismiss="emit('close')"
@confirm="emit('close')"
>
<template #title>
{{ title }}
</template>
<template #content>
<slot name="content">
{{ error }}
</slot>
<div class="content">
<slot name="content">
{{ error }}
</slot>
<UiLogEntryViewer
v-if="details !== undefined"
:label="t('see-details')"
:content="details"
accent="danger"
size="small"
class="details"
/>
</div>
</template>
<template #buttons>
@@ -20,12 +36,14 @@
<script lang="ts" setup>
import VtsOverlayConfirmButton from '@core/components/overlay/VtsOverlayConfirmButton.vue'
import UiLogEntryViewer from '@core/components/ui/log-entry-viewer/UiLogEntryViewer.vue'
import UiModal from '@core/components/ui/modal/UiModal.vue'
import { useI18n } from 'vue-i18n'
defineProps<{
title: string
error?: string
details?: string | object
}>()
const emit = defineEmits<{
@@ -38,3 +56,19 @@ defineSlots<{
const { t } = useI18n()
</script>
<style lang="postcss" scoped>
.vts-error-modal {
.content {
display: flex;
flex-direction: column;
gap: 0.8rem;
}
.details {
text-align: start;
/* The small action buttons must not overflow the scrollable modal content */
overflow-x: clip;
}
}
</style>

View File

@@ -0,0 +1,36 @@
import VtsSidePanel from '@core/components/panel/VtsSidePanel.vue'
import { canFocusInput } from '@core-test/can-focus-input.ts'
import { createGlobalTestConfig } from '@core-test/create-global-test-config.ts'
import { mount } from '@vue/test-utils'
import { h } from 'vue'
beforeEach(() => {
localStorage.clear()
})
function mountPanel({ hasSelection }: { hasSelection: boolean }) {
localStorage.setItem('panel.locked', 'false')
return mount(VtsSidePanel, {
props: { hasSelection, persistent: true },
slots: { default: () => h('input') },
global: createGlobalTestConfig(),
attachTo: document.body,
})
}
it('lets the focus into a panel that a selection expands', () => {
expect(canFocusInput(mountPanel({ hasSelection: true }))).toBe(true)
})
it('keeps the focus out of a collapsed panel', () => {
expect(canFocusInput(mountPanel({ hasSelection: false }))).toBe(false)
})
it('lets the focus in once a selection expands the panel', async () => {
const wrapper = mountPanel({ hasSelection: false })
await wrapper.setProps({ hasSelection: true })
expect(canFocusInput(wrapper)).toBe(true)
})

View File

@@ -1,6 +1,6 @@
<!-- v5 -->
<template>
<div class="vts-side-panel" :class="{ mobile: uiStore.isSmall }">
<div class="vts-side-panel" :class="{ mobile: uiStore.isSmall }" :inert="!panelStore.isExpanded">
<VtsResizeHandle v-if="showResizeHandle" position="start" :resizable="panelStore" />
<VtsPanel
:closable="isClosable"

View File

@@ -0,0 +1,10 @@
import { useOverlay } from '@core/packages/overlay/use-overlay.ts'
export function useErrorModal() {
return useOverlay({
component: () => import('@core/components/modal/VtsErrorModal.vue'),
events: {
onClose: true,
},
})
}

View File

@@ -95,7 +95,7 @@ function handleBackdropClick() {
display: flex;
flex: 1;
min-height: 0;
overflow-x: hidden;
overflow-x: clip;
}
.header {

View File

@@ -0,0 +1,10 @@
import type { VueWrapper } from '@vue/test-utils'
// Whether the first input of a wrapper attached to the document takes the focus, which an `inert` ancestor prevents
export function canFocusInput(wrapper: Pick<VueWrapper, 'get'>) {
const input = wrapper.get('input').element
input.focus()
return document.activeElement === input
}

View File

@@ -1,17 +1,14 @@
<template>
<VtsErrorModal :title="t('unable-to-delete-network')" @close="emit('close')">
<template #content>
{{ error ?? t('error') }}
<template v-if="showConnectedVifsMessage">
<br />
<I18nT keypath="disconnect-vifs-in-xo-5-to-delete-network" scope="global">
<template #xo-5>
<UiLink :href="xo5Link" size="medium">
{{ t('xo-5') }}
</UiLink>
</template>
</I18nT>
</template>
<p>{{ error ?? t('error') }}</p>
<I18nT v-if="showConnectedVifsMessage" keypath="disconnect-vifs-in-xo-5-to-delete-network" scope="global" tag="p">
<template #xo-5>
<UiLink :href="xo5Link" size="medium">
{{ t('xo-5') }}
</UiLink>
</template>
</I18nT>
</template>
</VtsErrorModal>
</template>

View File

@@ -13,6 +13,10 @@
- [@vates/task] With the new `skipSubtasksAfterAbort` option of a root task, a subtask created after the abort fails without running, unless it is created with `cleanup: true`, which is meant for the cleanup steps of an aborted task (PR [#10875](https://github.com/vatesfr/xen-orchestra/pull/10875))
- [Pool] In the pool header, the "New VM" button comes before "Add host", in the same order as in the treeview (PR [#10897](https://github.com/vatesfr/xen-orchestra/pull/10897))
- [Forms & backups] Checkboxes and radio buttons fix style, backup job form fix style (PR [#10940](https://github.com/vatesfr/xen-orchestra/pull/10940))
- [XO5/Backup] The backup job list no longer crashes on metadata jobs created in XO 6 with all or dynamically selected pools, and shows the modes of jobs targeting all or dynamically selected repositories (PR [#10933](https://github.com/vatesfr/xen-orchestra/pull/10933))
- [V2V] Fix the compatibility with ESXi 6: secure boot detection and snapshot creation (PR [#10968](https://github.com/vatesfr/xen-orchestra/pull/10968))
- [REST API/Networks] A network's name, description, MTU, NBD, `automatic` flag and default locking mode can be changed with `PATCH /rest/v0/networks/{id}` (PR [#XXXX](https://github.com/vatesfr/xen-orchestra/pull/XXXX))
- [REST API/Networks] Network creation accepts `name_label`, `name_description` and `MTU`, the names `PATCH /rest/v0/networks/{id}` takes; `name`, `description` and `mtu` are deprecated but still work (PR [#XXXX](https://github.com/vatesfr/xen-orchestra/pull/XXXX))
### Bug fixes
@@ -21,6 +25,9 @@
- [Backup reports] Aborted or interrupted VMs are no longer counted as failed (PR [#10875](https://github.com/vatesfr/xen-orchestra/pull/10875))
- [Backup] Correctly cleanup the snapshot of a VM without any backed up disk: only a CDROM or only `[NOBAK]` disks (PR [#10789](https://github.com/vatesfr/xen-orchestra/pull/10789))
- [SDN Controller] Network traffic rules are now enforced on VMs started after the rule was created, when a pool's first traffic rule is a network rule: only VIF rules used to set up the SDN controller's event handling, so such network rules were recorded but never (re)applied (PR [#10917](https://github.com/vatesfr/xen-orchestra/pull/10917))
- [Layout] The page no longer slides sideways to show the closed side panel or "My tasks" when the keyboard focus moves past the last element of the page, and their content can no longer be reached while they are closed (PR [#10973](https://github.com/vatesfr/xen-orchestra/pull/10973))
- [Network] Saving a network's settings no longer unplugs and replugs all its VIFs and PIFs when its MTU is unchanged (PR [#XXXX](https://github.com/vatesfr/xen-orchestra/pull/XXXX))
- [Network] When one of a network's new settings fails to apply, the settings already changed are restored instead of being left half-applied (PR [#XXXX](https://github.com/vatesfr/xen-orchestra/pull/XXXX))
### Packages to release
@@ -39,12 +46,17 @@
<!--packages-start-->
- @vates/task minor
- @vates/types minor
- @xen-orchestra/acl minor
- @xen-orchestra/backups minor
- @xen-orchestra/rest-api minor
- @xen-orchestra/vmware-explorer patch
- @xen-orchestra/web minor
- @xen-orchestra/web-core minor
- @xen-orchestra/xapi minor
- xo-server minor
- xo-server-backup-reports minor
- xo-server-sdn-controller patch
- xo-web minor
<!--packages-end-->

View File

@@ -0,0 +1,145 @@
---
sidebar_label: Repair a broken chain
sidebar_position: 8.5
---
# Repair a broken incremental backup chain
An [incremental backup](./backup-types/incremental_backups.md) is a chain: one key backup, then deltas that each depend on the previous one. _Key_ is the current term: older versions, and settings such as **Force full backup** or **Full backup interval**, call it a _full_ backup. If a disk file of the chain is missing or unreadable on the backup repository (BR), no restore point after it can be restored.
:::tip
A [full backup interval](./backup-types/incremental_backups.md#key-backup-interval) caps the length of a chain, and so the number of restore points one broken file can take down, at the cost of a regular full export.
:::
This procedure only uses the XO web interface and its REST API, so it also works on an [air-gapped](../airgap.md) XOA.
:::warning
Never delete, move or rename files on the BR by hand: that is how chains break.
:::
## In short
1. Read the job log to find the broken restore points.
2. Run the job once: in most cases, XO repairs the chain by itself.
3. If it doesn't, delete the broken restore points (from the break up to the next key backup),
4. then force a full backup of the VM, by deleting the job's snapshot on it, to start a new chain.
5. Check that the new chain restores.
## Before you start
- **An admin account**, and an [authentication token](../automation/restapi.md#creation) for the REST calls.
- **Healthy storage**: fix a BR that is full, read-only or disconnecting first.
- **Your XO version** (_About_ page in XO 5):
- 6.9.0 or later is needed for [option A](#clean) of step 3
- 6.10.0 fixes merges that fail at every run: if you are older, [upgrade](../getting-started/updater.md) first if you can
- **An XO Proxy**, if the BR uses one, at the same release as the XOA.
## 1. Read the job log {#identify}
In XO 5, open **Backup → Overview**, then the log of the last run (the button next to the schedule's **Run** button). The _Clean VM directory_ task of the VM lists what is broken:
<UiDetail src="/img/xo5/backup-log-broken-chain.png" alt="Log of a backup run: the Clean VM directory task of the VM shows the warnings disk broken: parent missing or broken, disk file missing, incremental backup is incomplete, disk check error and parent disk is missing; the run then ends with Type: full" width={600} />
| warning | before XO 6.5.0 | meaning |
| ----------------------------------------------------------------------- | -------------------------------------------- | --------------------------- |
| `parent disk is missing`, `disk broken: parent missing or broken` | `parent VHD is missing` | a delta lost its parent |
| `failed to open disk`, `disk check error` | `VHD check error` | a disk is unreadable |
| `incremental backup is incomplete`, `disk file missing` | `some VHDs linked to the backup are missing` | a restore point lost a disk |
| `merge chain lost disks before its cleanup step…`, `orphan merge state` | `orphan merge state` | a merge was interrupted |
The file name in a warning is the date of its backup: `20261130T220012Z.vhd` is the run of 30 November 2026 at 22:00:12 UTC. The restore points from that date up to the next key backup are broken: a key backup starts a new chain, which the break doesn't reach.
:::tip
Download the log first (the buttons at the top of the log window copy or download it): it is what Vates support needs if you open a ticket.
:::
## 2. Run the job once {#run}
Every run of an incremental backup job starts with this _Clean VM directory_ check, and repairs what it finds:
- it deletes the restore points whose chain is broken
- when no valid restore point is left to build on, the run exports a full backup (`Type: full` at the bottom of the log above), which starts a new chain
The run still ends successfully. So click the schedule's **Run** button, or wait for the next scheduled run, then check its log:
- **no warning anymore** in the next run's _Clean VM directory_ task: the chain is repaired, go to [step 5](#verify)
- **otherwise** (the run fails, the warnings come back, or a restore fails while the log shows no warning): go on with step 3
## 3. Delete the broken restore points {#clean}
First, in **Backup → Overview**, disable every schedule of the job and wait for a run in progress to end: a run could otherwise add a delta on top of the broken chain.
### Option A: let XO find them (XO 6.9.0 and later)
To find the ID of the BR, open it in XO 6 (**Administration → Backup & Replication → Backup repositories**): it is its **UUID**. The first call below is a dry run: with `merge` and `remove` disabled, XO only reports. The second cleans for real:
<Terminal shell title="clean one VM's backups through the REST API">{`TOKEN=KQxQdm2vMiv7jBIK0hgkmgxKzemd8wSJ7ugFGKFkTbs
XO=https://xoa.example.org
BR=c4284e12-37c9-7967-b9e8-83ef229c3e03
curl -X POST -b authenticationToken=$TOKEN -H 'Content-Type: application/json' -d '{"vmUuid":"9d0d04f7-bb1f-8292-3294-17c6371827c5","merge":false,"remove":false}' "$XO/rest/v0/backup-repositories/$BR/actions/reclaim-space"
curl -X POST -b authenticationToken=$TOKEN -H 'Content-Type: application/json' -d '{"vmUuid":"9d0d04f7-bb1f-8292-3294-17c6371827c5"}' "$XO/rest/v0/backup-repositories/$BR/actions/reclaim-space"`}</Terminal>
- `vmUuid` is the UUID of the VM (also the name of its folder in `xo-vm-backups/`); it works for a VM deleted from the pool too.
- Each call answers a `taskId`: once the task has ended, `GET /rest/v0/tasks/<taskId>` lists the `warnings` of [step 1](#identify).
- The real run deletes the broken restore points and the files nothing uses anymore, and finishes or drops interrupted merges. Valid restore points are kept.
### Option B: from the interface (any version)
1. In XO 5, open **Backup → Restore**, find the VM, then click its red **Delete backups…** button (the trash icon).
<UiDetail src="/img/xo5/restore-health-check.png" alt="The Backup → Restore view: each VM row ends with three buttons, Restore health check (check mark), Restore (arrow) and Delete backups (trash)" width={620} />
2. Select the restore points from the date of the break up to the last one before the next key backup (the newest one if there is none), keep **Free delta disk space now** enabled, then click **OK**:
<UiDetail src="/img/xo5/delete-vm-backups.png" alt="The Delete backups modal: the two most recent restore points, both differencing, are selected; the two key backups below are not; Free delta disk space now is enabled" width={600} />
## 4. Force a full backup {#full}
The check of step 2 reads the headers of the disks, not their data: when the data of a disk is corrupted, the next delta would still build on it. A full backup starts a new chain that depends on nothing.
### Option A: delete the job's snapshot on the VM (this VM only)
A delta is built on the snapshot the job left on the VM at its previous run. Without it, the next run exports a full backup of this VM, and of this VM only:
1. In XO 6, open the VM, then its **Snapshots** tab.
2. For each snapshot named `[XO Backup <job name>] <VM name>`, open its **⋯** menu, then click **Delete**:
<UiDetail src="/img/xo6/vm-snapshot-delete.png" alt="The Snapshots tab of a VM in XO 6: the actions menu of the snapshot [XO Backup Nightly delta backup] KAN-qa-reference is open, with Revert VM here and Delete" width={620} />
A job can leave more than one snapshot on the VM: delete them all, or the next run builds on the one left.
3. Enable the job's schedules again, and run it (or wait for its next run).
4. In the log, check `Type: full` at the bottom.
This works for backup jobs. An incremental replication job can also build on a snapshot left by another job, so it may still export a delta.
### Option B: force a full backup of every VM of the schedule
When several VMs of the job need a new chain:
1. In **Backup → Overview**, edit the job. In its **Schedules** panel, click the edit (pencil) button of the schedule:
<UiDetail src="/img/xo5/backup-schedule-list.png" alt="The job edit page: the Schedules panel lists each schedule with its state, cron pattern, timezone, Force full backup setting and retention, and an edit button" width={700} />
2. Check **Force full backup**, then click **OK** and save the job:
<UiDetail src="/img/xo5/create-backup-schedule.png" alt="The Schedule form: name, retention, then the Health check and Force full backup checkboxes above the month/day/hour/minute pickers" width={480} />
3. Back in **Backup → Overview**, enable this schedule and click its **Run** button.
4. In the log, check `Type: full` at the bottom.
5. **Uncheck Force full backup** again, or every run stays a full.
6. Enable the other schedules of the job again.
The BR needs room for one more full backup: the valid restore points of the old chain stay until retention removes them.
## 5. Check that the new chain restores {#verify}
- In **Backup → Restore**, find the VM, click its **Restore health check** button (the check mark, see [step 3](#clean)), then pick the newest restore point and an SR.
- To check every future run, enable [Health check](./backup-features-and-settings.md#backup-health-check) on the schedule.
## Special cases
- **A merge fails at every run** (for example with `ENOENT`): fixed in XO 6.10.0. [Upgrade](../getting-started/updater.md) the XOA and its proxies, then start over. If you can't, contact Vates support with the log before touching any file.
- **[Immutable BR](./scale-and-security/immutability.md)**: protected files can't be deleted before their protection ends, so the broken restore points stay until then. Steps 4 and 5 still give you a healthy chain right away.
- **[S3 Object Lock](./scale-and-security/object-lock.md)**: deleting doesn't fail: the broken restore points disappear from XO, but the bucket keeps a locked copy of their files, billed until its retention ends.
- **Incremental replication**: the chain lives on the target SR, see [Could not find the base VM](./backup_troubleshooting.md#could-not-find-the-base-vm).

View File

@@ -24,7 +24,7 @@ Nevertheless, there are several reasons for XO to trigger a key (full) export in
- the _Force full backup_ option is enabled for the current schedule
- a new disk has been added to the VM (only this disk is completely exported)
- the reference snapshot for this backup job is missing on the source VM
- the previously exported backup/replication is missing or corrupted
- the previously exported backup/replication is missing or corrupted (see [Repair a broken incremental backup chain](./backup_chain_repair.md))
- XO could not compute a safe delta for a disk (for example a qcow2 disk exported without NBD): it forces a full rather than risking a broken chain
:::tip

View File

@@ -244,13 +244,6 @@ To access advanced options:
#### Enabling Passkeys in XOA with Keycloak
:::warning Don't lock yourself out
If Keycloak is unreachable, nobody can sign in through it. Plan a way back in before you rely on it:
- **Keep a local admin account.** Enabling `auth-oidc` doesn't disable password login: the XOA login page still offers **Sign in with password**. Keep at least one [built-in](#built-in) _admin_ account with a password, store its credentials somewhere safe, and consider protecting it with [TOTP](#otp-authentication-2fa).
- **Don't host Keycloak only on the pool that XOA manages.** A Rolling Pool Update or a host reboot can stop or migrate its VM, locking you out of XOA right when you need it. Run it on separate hardware or another pool, ideally as several instances behind a load balancer.
:::
##### Generating certificates
To support passkeys in XOA, the Keycloak server must expose its OIDC endpoints over HTTPS.

View File

@@ -108,7 +108,7 @@ In practice, a Storage administrator can create and delete SRs, manage virtual d
| Resource | Access |
| --------- | ------------------------------------------------------------------------------------------------ |
| `network` | Every action (`*`): read, create, delete, update tags and `other_config`. |
| `network` | Every action (`*`): read, create, delete, update tags, `other_config`, name, description, MTU, NBD, `automatic` and default locking mode. |
| `vif` | Every action (`*`): read, create, delete, connect, disconnect, update locking mode, rate limit… |
| `pool` | `read` and `create:network` (create networks at the pool level, including bonded and internal). |
| `pif` | `read` and `update` (e.g. reconfigure the management interface). |
@@ -164,7 +164,7 @@ Actions are written using the exact string you pass in a privilege. A parent act
| `sr` | `read`, `create`, `delete`, `forget`, `migrate-receive`, `reclaim-space`, `scan`, `import:vdi`, `import:vdi:upload`, `import:vdi:url`, `import:vm`, `update:tags` | |
| `host` | `read`, `allow-vm`, `join-pool`, `export:logs`, `update:tags`, `migrate-receive`, `disable`, `enable`, `evacuate`, `detach`, `shutdown:clean`, `shutdown:emergency`, `forget`, `reboot:clean`, `reboot:smart`, `restart-toolstack`, `start`, `scan-pifs`, `probe:nfs`, `probe:zfs`, `probe:hba`, `probe:iscsiiqn`, `probe:iscsilun`, `probe:iscsi-exists`, `probe:hba-exists`, `probe:nfs-exists` |
| `pool` | `add-host`, `read`, `emergency-shutdown`, `rolling-reboot`, `rolling-update`, `create:network`, `create:vm`, `update:tags` |
| `network` | `read`, `create`, `delete`, `update:tags`,`update:other_config` |
| `network` | `read`, `create`, `delete`, `update:tags`,`update:other_config`, `update:automatic`, `update:defaultIsLocked`, `update:insecureNbd`, `update:MTU`, `update:name_description`, `update:name_label`, `update:nbd` |
| `pif` | `read`, `update:management` |
| `pbd` | `read`, `plug`, `unplug` |
| `pci` | `read` |

Binary file not shown.

After

Width:  |  Height:  |  Size: 84 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 38 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 24 KiB

View File

@@ -78,27 +78,23 @@ createBonded.description = 'Create a bonded network. bondMode can be balance-slb
export async function set({
network,
automatic,
defaultIsLocked,
mtu,
name_description: nameDescription,
name_label: nameLabel,
name_description,
name_label,
nbd,
insecureNbd,
}) {
assertNbdParams({ nbd, insecureNbd })
network = this.getXapiObject(network)
await Promise.all([
automatic !== undefined && network.update_other_config('automatic', automatic ? 'true' : null),
defaultIsLocked !== undefined && network.set_default_locking_mode(defaultIsLocked ? 'disabled' : 'unlocked'),
mtu !== undefined && network.$setMtu(mtu),
nameDescription !== undefined && network.set_name_description(nameDescription),
nameLabel !== undefined && network.set_name_label(nameLabel),
(nbd !== undefined || insecureNbd !== undefined) && setNbdPurposes(network, { nbd, insecureNbd }),
])
await this.getXapi(network).editNetwork(network._xapiId, {
automatic,
defaultIsLocked,
insecureNbd,
MTU: mtu,
name_description,
name_label,
nbd,
})
}
function assertNbdParams({ nbd, insecureNbd }) {
@@ -107,36 +103,6 @@ function assertNbdParams({ nbd, insecureNbd }) {
}
}
// nbd and insecure_nbd are incompatible purposes: the other one must be removed before adding one
//
// a false or missing param only touches its own purpose, so that a client unaware of insecureNbd
// sending nbd: false (e.g. the Terraform provider on each update) does not disable the insecure NBD
async function setNbdPurposes(network, { nbd, insecureNbd }) {
const purposesToRemove = new Set()
let purposeToAdd
if (nbd === true) {
purposesToRemove.add('insecure_nbd')
purposeToAdd = 'nbd'
} else if (nbd === false) {
purposesToRemove.add('nbd')
}
if (insecureNbd === true) {
purposesToRemove.add('nbd')
purposeToAdd = 'insecure_nbd'
} else if (insecureNbd === false) {
purposesToRemove.add('insecure_nbd')
}
for (const purpose of purposesToRemove) {
await network.remove_purpose(purpose)
}
if (purposeToAdd !== undefined) {
await network.add_purpose(purposeToAdd)
}
}
set.params = {
automatic: {
type: 'boolean',

View File

@@ -0,0 +1,165 @@
import assert from 'assert/strict'
import test from 'node:test'
import { invalidParameters } from 'xo-common/api-errors.js'
import networkingMethods from './networking.mjs'
const { describe, it } = test
// the XO id the REST route passes to editNetwork (a uuid, which xen-api's getObject resolves)
const NETWORK_ID = '9fe12ca3-d75d-cfb0-492e-cfd2bc6c568f'
// Fake XAPI: getObject returns a network whose methods record their calls, so that the tests
// assert what reaches XAPI and nothing else. fail(name, args) returns the error a call throws, if any
function makeFakeXapi(fail = () => undefined) {
const calls = []
const record =
name =>
async (...args) => {
calls.push([name, ...args])
const error = fail(name, args)
if (error !== undefined) {
throw error
}
}
const network = {
MTU: 1500,
name_label: 'old label',
name_description: 'old description',
other_config: {},
default_locking_mode: 'unlocked',
purpose: [],
update_other_config: record('update_other_config'),
set_default_locking_mode: record('set_default_locking_mode'),
$setMtu: record('$setMtu'),
set_name_description: record('set_name_description'),
set_name_label: record('set_name_label'),
add_purpose: record('add_purpose'),
remove_purpose: record('remove_purpose'),
}
return {
calls,
getObject(id) {
assert.equal(id, NETWORK_ID)
return network
},
editNetwork: networkingMethods.editNetwork,
}
}
const edit = (xapi, props) => xapi.editNetwork(NETWORK_ID, props)
describe('editNetwork', () => {
it('refuses nbd and insecureNbd together, before touching XAPI', async () => {
const xapi = makeFakeXapi()
await assert.rejects(edit(xapi, { nbd: true, insecureNbd: true }), error => invalidParameters.is(error))
assert.deepEqual(xapi.calls, [])
})
it('switches nbd on by removing insecure_nbd first', async () => {
const xapi = makeFakeXapi()
await edit(xapi, { nbd: true })
assert.deepEqual(xapi.calls, [
['remove_purpose', 'insecure_nbd'],
['add_purpose', 'nbd'],
])
})
it('switches insecure_nbd on by removing nbd first', async () => {
const xapi = makeFakeXapi()
await edit(xapi, { insecureNbd: true })
assert.deepEqual(xapi.calls, [
['remove_purpose', 'nbd'],
['add_purpose', 'insecure_nbd'],
])
})
it('only removes nbd on nbd: false, leaving insecure_nbd alone', async () => {
const xapi = makeFakeXapi()
await edit(xapi, { nbd: false })
assert.deepEqual(xapi.calls, [['remove_purpose', 'nbd']])
})
it('applies every other field to its XAPI call, in order, MTU last', async () => {
const xapi = makeFakeXapi()
await edit(xapi, {
automatic: false,
defaultIsLocked: true,
MTU: 9000,
name_label: 'a',
name_description: 'b',
})
assert.deepEqual(xapi.calls, [
['update_other_config', 'automatic', null],
['set_default_locking_mode', 'disabled'],
['set_name_description', 'b'],
['set_name_label', 'a'],
['$setMtu', 9000],
])
})
it('does not replug PIFs and VIFs when the MTU is unchanged', async () => {
const xapi = makeFakeXapi()
await edit(xapi, { MTU: 1500 })
assert.deepEqual(xapi.calls, [])
})
it('does nothing for an empty edit', async () => {
const xapi = makeFakeXapi()
await edit(xapi, {})
assert.deepEqual(xapi.calls, [])
})
it('restores the fields already applied, in reverse order, when a later write fails', async () => {
const boom = new Error('boom')
// $setMtu fails after set_MTU, so the MTU itself has changed and must be restored too
const xapi = makeFakeXapi((name, args) => (name === '$setMtu' && args[0] === 9000 ? boom : undefined))
await assert.rejects(edit(xapi, { name_description: 'b', name_label: 'a', MTU: 9000 }), error => error === boom)
assert.deepEqual(xapi.calls, [
['set_name_description', 'b'],
['set_name_label', 'a'],
['$setMtu', 9000],
['$setMtu', 1500],
['set_name_label', 'old label'],
['set_name_description', 'old description'],
])
})
it('still rethrows the original error when a rollback itself fails', async () => {
const boom = new Error('boom')
const rollbackBoom = new Error('rollback boom')
const xapi = makeFakeXapi((name, args) => {
if (name === '$setMtu' && args[0] === 9000) {
return boom
}
if (name === 'set_name_label' && args[0] === 'old label') {
return rollbackBoom
}
return undefined
})
await assert.rejects(edit(xapi, { name_label: 'a', MTU: 9000 }), error => error === boom)
assert.deepEqual(xapi.calls, [
['set_name_label', 'a'],
['$setMtu', 9000],
['$setMtu', 1500],
['set_name_label', 'old label'],
])
})
})

View File

@@ -1,6 +1,64 @@
import { decorateObject } from '@vates/decorate-with'
import { createLogger } from '@xen-orchestra/log'
import { defer as deferrable } from 'golike-defer'
import { invalidParameters } from 'xo-common/api-errors.js'
import { makeEditObject } from '../utils.mjs'
export default {
const log = createLogger('xo:xapi:networking')
// a rollback that fails must not replace the error it is undoing: the caller gets the original one
function restore(what, rollback) {
return async () => {
try {
await rollback()
} catch (error) {
log.warn(`could not restore ${what} after a failed network edit`, { error })
}
}
}
// nbd and insecure_nbd are incompatible purposes: the other one must be removed before adding one
//
// a false or missing param only touches its own purpose, so that a client unaware of insecureNbd
// sending nbd: false (e.g. the Terraform provider on each update) does not disable the insecure NBD
//
// a purpose is restored on failure only if this call changed it: removing one that was absent, or
// adding one that was already there, has nothing to undo
async function setNbdPurposes($defer, network, { nbd, insecureNbd }) {
const purposesBefore = network.purpose
const purposesToRemove = new Set()
let purposeToAdd
if (nbd === true) {
purposesToRemove.add('insecure_nbd')
purposeToAdd = 'nbd'
} else if (nbd === false) {
purposesToRemove.add('nbd')
}
if (insecureNbd === true) {
purposesToRemove.add('nbd')
purposeToAdd = 'insecure_nbd'
} else if (insecureNbd === false) {
purposesToRemove.add('insecure_nbd')
}
for (const purpose of purposesToRemove) {
await network.remove_purpose(purpose)
if (purposesBefore.includes(purpose)) {
$defer.onFailure(restore(`the ${purpose} purpose`, () => network.add_purpose(purpose)))
}
}
if (purposeToAdd !== undefined) {
await network.add_purpose(purposeToAdd)
if (!purposesBefore.includes(purposeToAdd)) {
$defer.onFailure(restore(`the ${purposeToAdd} purpose`, () => network.remove_purpose(purposeToAdd)))
}
}
}
const methods = {
async _connectVif(vif) {
await this.callAsync('VIF.plug', vif.$ref)
},
@@ -77,4 +135,63 @@ export default {
set: (value, vif) => vif.update_other_config('ethtool-tx', value === null ? null : String(value)),
},
}),
// shared by JSON-RPC network.set and the REST API's PATCH /networks/{id}, so that the NBD rules
// are written once
//
// the props are named after XoNetwork's fields, which the REST API exposes
//
// the writes run one after the other, each one that succeeds registering its own rollback: a
// failure on a later field restores the earlier ones, so a PATCH never leaves the network half
// edited, and the caller gets the original error once the rollbacks are done. MTU comes last
// because changing it replugs every PIF and VIF; its rollback replugs them a second time
async editNetwork(
$defer,
networkId,
{ automatic, defaultIsLocked, insecureNbd, MTU, name_description: nameDescription, name_label: nameLabel, nbd }
) {
if (nbd && insecureNbd) {
throw invalidParameters('nbd and insecureNbd are mutually exclusive')
}
const network = this.getObject(networkId)
if (automatic !== undefined) {
const previous = network.other_config.automatic
await network.update_other_config('automatic', automatic ? 'true' : null)
$defer.onFailure(restore('the automatic flag', () => network.update_other_config('automatic', previous ?? null)))
}
if (defaultIsLocked !== undefined) {
const previous = network.default_locking_mode
await network.set_default_locking_mode(defaultIsLocked ? 'disabled' : 'unlocked')
$defer.onFailure(restore('the default locking mode', () => network.set_default_locking_mode(previous)))
}
if (nameDescription !== undefined) {
const previous = network.name_description
await network.set_name_description(nameDescription)
$defer.onFailure(restore('the description', () => network.set_name_description(previous)))
}
if (nameLabel !== undefined) {
const previous = network.name_label
await network.set_name_label(nameLabel)
$defer.onFailure(restore('the name', () => network.set_name_label(previous)))
}
if (nbd !== undefined || insecureNbd !== undefined) {
await setNbdPurposes($defer, network, { nbd, insecureNbd })
}
// $setMtu unplugs and replugs every PIF and VIF, even for an unchanged MTU: clients resending
// their whole state on each update (Terraform) must not interrupt traffic
if (MTU !== undefined && MTU !== +network.MTU) {
const previous = +network.MTU
// registered before the write: $setMtu is set_MTU then the PIF and VIF replugs, so it can fail
// after the MTU has changed, and that case must still be rolled back
$defer.onFailure(restore('the MTU', () => network.$setMtu(previous)))
await network.$setMtu(MTU)
}
},
}
export default decorateObject(methods, {
editNetwork: deferrable,
})

View File

@@ -56,6 +56,8 @@ const isMirrorBackupType = item => item?.type === 'mirrorBackup'
const isBackupType = item => item?.type === 'backup'
const isPatternNotEmpty = pattern => typeof pattern === 'string' || !isEmpty(get(() => destructPattern(pattern)))
const MODES = [
{
label: 'mirrorFullBackup',
@@ -71,23 +73,23 @@ const MODES = [
},
{
label: 'backup',
test: job => isBackupType(job) && job.mode === 'full' && !isEmpty(get(() => destructPattern(job.remotes))),
test: job => isBackupType(job) && job.mode === 'full' && isPatternNotEmpty(job.remotes),
},
{
label: 'deltaBackup',
test: job => isBackupType(job) && job.mode === 'delta' && !isEmpty(get(() => destructPattern(job.remotes))),
test: job => isBackupType(job) && job.mode === 'delta' && isPatternNotEmpty(job.remotes),
},
{
label: 'continuousReplication',
test: job => isBackupType(job) && job.mode === 'delta' && !isEmpty(get(() => destructPattern(job.srs))),
test: job => isBackupType(job) && job.mode === 'delta' && isPatternNotEmpty(job.srs),
},
{
label: 'disasterRecovery',
test: job => isBackupType(job) && job.mode === 'full' && !isEmpty(get(() => destructPattern(job.srs))),
test: job => isBackupType(job) && job.mode === 'full' && isPatternNotEmpty(job.srs),
},
{
label: 'poolMetadata',
test: job => !isEmpty(destructPattern(job.pools)),
test: job => isPatternNotEmpty(job.pools),
},
{
label: 'xoConfig',

View File

@@ -24,6 +24,7 @@ export const constructPattern = values =>
export const usesExpressions = job =>
typeof job.srs === 'string' ||
typeof job.remotes === 'string' ||
typeof job.pools === 'string' ||
Object.values(job.settings ?? {}).some(settings =>
['healthCheckVmsWithTags', 'fullInterval', 'vmFilter'].some(key => typeof settings?.[key] === 'string')
)