mirror of
https://github.com/vatesfr/xen-orchestra.git
synced 2026-12-03 05:42:41 -06:00
Compare commits
5 Commits
feat/rest-
...
feat/rest-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
576d0670d5 | ||
|
|
8eaa4c507a | ||
|
|
f22c27b863 | ||
|
|
3e8658c906 | ||
|
|
7b7fab8366 |
@@ -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?: {
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
export default {
|
||||
clone: true,
|
||||
delete: true,
|
||||
'eject-cd': true,
|
||||
export: true,
|
||||
'migrate-send': true,
|
||||
pause: true,
|
||||
|
||||
@@ -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:<field>
|
||||
* - 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
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
],
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -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) {
|
||||
|
||||
@@ -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 })
|
||||
})
|
||||
})
|
||||
@@ -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 }
|
||||
}
|
||||
|
||||
@@ -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`
|
||||
|
||||
@@ -30,7 +30,6 @@ import type {
|
||||
XoVmBackupJob,
|
||||
XoHost,
|
||||
XoTask,
|
||||
XoVbd,
|
||||
XoVdi,
|
||||
XoVm,
|
||||
XoVmSnapshot,
|
||||
@@ -639,51 +638,6 @@ export class VmController extends XapiXoController<XoVm> {
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Eject CDs from the VM's CD drives. The VM must be halted or running.
|
||||
*
|
||||
* - Without `vbdIds`: ejects the CD inserted in the VM. Does nothing if no CD is inserted, and fails listing the VBDs
|
||||
* that can be ejected if several CDs are inserted.
|
||||
* - With `vbdIds`: ejects these VBDs, which must be CD drives of the VM, whatever the number of inserted CDs. An
|
||||
* already empty drive is ignored.
|
||||
*
|
||||
* Required privilege:
|
||||
* - resource: vm, action: eject-cd
|
||||
*
|
||||
* @example id "f07ab729-c0e8-721c-45ec-f11276377030"
|
||||
* @example body { "vbdIds": ["5f9a4c0b-3548-6171-4396-699a0e56cc60"] }
|
||||
*/
|
||||
@Example(taskLocation)
|
||||
@Extension('x-mcp-exposure', 'confirm')
|
||||
@Post('{id}/actions/eject_cd')
|
||||
@Middlewares([json(), acl({ resource: 'vm', action: 'eject-cd', objectId: 'params.id' })])
|
||||
@SuccessResponse(asynchronousActionResp.status, asynchronousActionResp.description)
|
||||
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
|
||||
@Response(noContentResp.status, noContentResp.description)
|
||||
@Response(notFoundResp.status, notFoundResp.description)
|
||||
@Response(incorrectStateResp.status, incorrectStateResp.description)
|
||||
@Response(invalidParametersResp.status, invalidParametersResp.description)
|
||||
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
|
||||
async ejectCdVm(
|
||||
@Path() id: string,
|
||||
@Body() body?: { vbdIds?: string[] },
|
||||
@Query() sync?: boolean
|
||||
): CreateActionReturnType<void> {
|
||||
const vmId = id as XoVm['id']
|
||||
const action = async () => {
|
||||
await this.#vmService.ejectCd(vmId, body?.vbdIds as XoVbd['id'][] | undefined)
|
||||
}
|
||||
|
||||
return this.createAction<void>(action, {
|
||||
sync,
|
||||
statusCode: noContentResp.status,
|
||||
taskProperties: {
|
||||
name: 'eject CD from VM',
|
||||
objectId: vmId,
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* Required privilege:
|
||||
* - resource: vm, action: revert-snapshot
|
||||
|
||||
@@ -21,7 +21,6 @@ import {
|
||||
type XoVm,
|
||||
type XoVmTemplate,
|
||||
} from '@vates/types'
|
||||
import { incorrectState, invalidParameters } from 'xo-common/api-errors.js'
|
||||
import { Response as ExResponse } from 'express'
|
||||
import { Readable, Writable } from 'node:stream'
|
||||
|
||||
@@ -243,61 +242,6 @@ export class VmService {
|
||||
await xoApp.getXapi(id).editVm(id, editProps)
|
||||
}
|
||||
|
||||
/**
|
||||
* Without `vbdIds`, eject the CD inserted in the VM, if any: when several are inserted, the ones to eject must be
|
||||
* chosen with `vbdIds`
|
||||
*/
|
||||
async ejectCd(id: XoVm['id'], vbdIds?: XoVbd['id'][]): Promise<void> {
|
||||
const vm = this.#restApi.getObject<XoVm>(id, 'VM')
|
||||
|
||||
// XAPI only allows VBD.eject on a halted or running VM
|
||||
if (vm.power_state !== VM_POWER_STATE.HALTED && vm.power_state !== VM_POWER_STATE.RUNNING) {
|
||||
throw incorrectState({
|
||||
actual: vm.power_state,
|
||||
expected: [VM_POWER_STATE.HALTED, VM_POWER_STATE.RUNNING],
|
||||
object: vm.id,
|
||||
property: 'power_state',
|
||||
})
|
||||
}
|
||||
|
||||
if (vbdIds === undefined) {
|
||||
// an empty CD drive has no VDI
|
||||
const insertedCdIds = vm.$VBDs.filter(vbdId => {
|
||||
const vbd = this.#restApi.getObject<XoVbd>(vbdId, 'VBD')
|
||||
return vbd.is_cd_drive && vbd.VDI !== undefined
|
||||
})
|
||||
|
||||
if (insertedCdIds.length > 1) {
|
||||
throw invalidParameters(`several CDs are inserted in VM ${vm.id}, choose the ones to eject with vbdIds`, {
|
||||
vbdIds: insertedCdIds,
|
||||
})
|
||||
}
|
||||
|
||||
vbdIds = insertedCdIds
|
||||
} else {
|
||||
// check all the VBDs before ejecting any of them
|
||||
for (const vbdId of vbdIds) {
|
||||
const vbd = this.#restApi.getObject<XoVbd>(vbdId, 'VBD')
|
||||
if (vbd.VM !== vm.id) {
|
||||
throw invalidParameters(`VBD ${vbdId} does not belong to VM ${vm.id}`)
|
||||
}
|
||||
if (!vbd.is_cd_drive) {
|
||||
throw invalidParameters(`VBD ${vbdId} is not a CD drive`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (const vbdId of vbdIds) {
|
||||
const xapiVbd = this.#restApi.getXapiObject<XoVbd>(vbdId, 'VBD')
|
||||
await xapiVbd.$xapi.callAsync('VBD.eject', xapiVbd.$ref).catch(error => {
|
||||
// the drive is already empty, which is the expected result
|
||||
if (error.code !== 'VBD_IS_EMPTY') {
|
||||
throw error
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
#getDashboardQuickInfo(id: XoVm['id']): VmDashboard['quickInfo'] {
|
||||
const {
|
||||
power_state,
|
||||
|
||||
@@ -1,157 +0,0 @@
|
||||
import assert from 'node:assert/strict'
|
||||
import { describe, it } from 'node:test'
|
||||
import type { XoVbd, XoVdi, XoVm } from '@vates/types'
|
||||
import { VM_POWER_STATE } from '@vates/types'
|
||||
import { incorrectState, invalidParameters } from 'xo-common/api-errors.js'
|
||||
import type { RestApi } from '../rest-api/rest-api.mjs'
|
||||
import type { XoError } from '../helpers/helper.type.mjs'
|
||||
|
||||
import { VmService } from './vm.service.mjs'
|
||||
|
||||
const VM_ID = 'f07ab729-c0e8-721c-45ec-f11276377030' as XoVm['id']
|
||||
const OTHER_VM_ID = '613f541c-4bed-fc77-7ca8-2db6b68f079c' as XoVm['id']
|
||||
const CD_1_ID = '5f9a4c0b-3548-6171-4396-699a0e56cc60' as XoVbd['id']
|
||||
const CD_2_ID = '60c7c9b6-35ba-1791-67b5-6aaf90eea11d' as XoVbd['id']
|
||||
const EMPTY_CD_ID = '0f8a2c1e-8a8c-4a5f-9d2e-6d6b0d1a3c55' as XoVbd['id']
|
||||
const DISK_ID = '9b2c3d4e-5f60-4718-8293-a4b5c6d7e8f9' as XoVbd['id']
|
||||
const FOREIGN_CD_ID = 'c3d4e5f6-0718-4293-a4b5-c6d7e8f90a1b' as XoVbd['id']
|
||||
const ISO_ID = '2e1b6c1f-3d0a-4c47-9b38-3b1f3a7c2d10' as XoVdi['id']
|
||||
|
||||
const vbds = {
|
||||
[CD_1_ID]: { id: CD_1_ID, is_cd_drive: true, VDI: ISO_ID, VM: VM_ID },
|
||||
[CD_2_ID]: { id: CD_2_ID, is_cd_drive: true, VDI: ISO_ID, VM: VM_ID },
|
||||
[EMPTY_CD_ID]: { id: EMPTY_CD_ID, is_cd_drive: true, VM: VM_ID },
|
||||
[DISK_ID]: { id: DISK_ID, is_cd_drive: false, VDI: ISO_ID, VM: VM_ID },
|
||||
[FOREIGN_CD_ID]: { id: FOREIGN_CD_ID, is_cd_drive: true, VDI: ISO_ID, VM: OTHER_VM_ID },
|
||||
}
|
||||
|
||||
const vbdRef = (id: XoVbd['id']) => `OpaqueRef:${id}`
|
||||
|
||||
function createRestApi({
|
||||
ejectError,
|
||||
power_state = VM_POWER_STATE.RUNNING,
|
||||
vbdIds = [CD_1_ID, EMPTY_CD_ID, DISK_ID],
|
||||
}: {
|
||||
ejectError?: Error
|
||||
power_state?: VM_POWER_STATE
|
||||
vbdIds?: XoVbd['id'][]
|
||||
} = {}) {
|
||||
const calls: unknown[][] = []
|
||||
|
||||
const xapi = {
|
||||
async callAsync(...args: unknown[]) {
|
||||
calls.push(args)
|
||||
if (ejectError !== undefined) {
|
||||
throw ejectError
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
const vm = { id: VM_ID, power_state, $VBDs: vbdIds }
|
||||
const restApi = {
|
||||
// the VmService constructor gets its dependencies from the IOC container, unused here
|
||||
ioc: { get: () => ({}) },
|
||||
getObject: (id: string) => (id === VM_ID ? vm : vbds[id]),
|
||||
getXapiObject: (id: XoVbd['id']) => ({ $ref: vbdRef(id), $xapi: xapi }),
|
||||
} as unknown as RestApi
|
||||
|
||||
return { calls, vmService: new VmService(restApi) }
|
||||
}
|
||||
|
||||
describe('VmService.ejectCd', () => {
|
||||
for (const power_state of [VM_POWER_STATE.PAUSED, VM_POWER_STATE.SUSPENDED]) {
|
||||
it(`refuses a ${power_state} VM`, async () => {
|
||||
const { calls, vmService } = createRestApi({ power_state })
|
||||
|
||||
await assert.rejects(vmService.ejectCd(VM_ID), (error: unknown) => {
|
||||
assert(incorrectState.is(error, { property: 'power_state' }))
|
||||
return true
|
||||
})
|
||||
assert.deepEqual(calls, [])
|
||||
})
|
||||
}
|
||||
|
||||
it('ejects the inserted CD of a halted VM', async () => {
|
||||
const { calls, vmService } = createRestApi({ power_state: VM_POWER_STATE.HALTED })
|
||||
|
||||
await vmService.ejectCd(VM_ID)
|
||||
assert.deepEqual(calls, [['VBD.eject', vbdRef(CD_1_ID)]])
|
||||
})
|
||||
|
||||
describe('without vbdIds', () => {
|
||||
it('does nothing when no CD is inserted', async () => {
|
||||
const { calls, vmService } = createRestApi({ vbdIds: [EMPTY_CD_ID, DISK_ID] })
|
||||
|
||||
await vmService.ejectCd(VM_ID)
|
||||
assert.deepEqual(calls, [])
|
||||
})
|
||||
|
||||
it('ejects the only inserted CD', async () => {
|
||||
const { calls, vmService } = createRestApi()
|
||||
|
||||
await vmService.ejectCd(VM_ID)
|
||||
assert.deepEqual(calls, [['VBD.eject', vbdRef(CD_1_ID)]])
|
||||
})
|
||||
|
||||
it('refuses to choose between several inserted CDs and lists them', async () => {
|
||||
const { calls, vmService } = createRestApi({ vbdIds: [CD_1_ID, EMPTY_CD_ID, DISK_ID, CD_2_ID] })
|
||||
|
||||
await assert.rejects(vmService.ejectCd(VM_ID), (error: XoError) => {
|
||||
assert(invalidParameters.is(error))
|
||||
assert.deepEqual(error.data, { errors: { vbdIds: [CD_1_ID, CD_2_ID] } })
|
||||
return true
|
||||
})
|
||||
assert.deepEqual(calls, [])
|
||||
})
|
||||
})
|
||||
|
||||
describe('with vbdIds', () => {
|
||||
it('ejects the given CDs, even when several are inserted', async () => {
|
||||
const { calls, vmService } = createRestApi({ vbdIds: [CD_1_ID, CD_2_ID, EMPTY_CD_ID] })
|
||||
|
||||
await vmService.ejectCd(VM_ID, [CD_2_ID, CD_1_ID])
|
||||
assert.deepEqual(calls, [
|
||||
['VBD.eject', vbdRef(CD_2_ID)],
|
||||
['VBD.eject', vbdRef(CD_1_ID)],
|
||||
])
|
||||
})
|
||||
|
||||
it('ejects nothing with an empty list', async () => {
|
||||
const { calls, vmService } = createRestApi()
|
||||
|
||||
await vmService.ejectCd(VM_ID, [])
|
||||
assert.deepEqual(calls, [])
|
||||
})
|
||||
|
||||
for (const [description, vbdId] of [
|
||||
['of another VM', FOREIGN_CD_ID],
|
||||
['which is not a CD drive', DISK_ID],
|
||||
] as const) {
|
||||
it(`refuses a VBD ${description} before ejecting anything`, async () => {
|
||||
const { calls, vmService } = createRestApi()
|
||||
|
||||
await assert.rejects(vmService.ejectCd(VM_ID, [CD_1_ID, vbdId]), (error: XoError) => {
|
||||
assert(invalidParameters.is(error))
|
||||
assert.match(error.message, new RegExp(vbdId))
|
||||
return true
|
||||
})
|
||||
assert.deepEqual(calls, [])
|
||||
})
|
||||
}
|
||||
})
|
||||
|
||||
it('ignores an already empty drive', async () => {
|
||||
const error = Object.assign(new Error('VBD_IS_EMPTY'), { code: 'VBD_IS_EMPTY' })
|
||||
const { calls, vmService } = createRestApi({ ejectError: error })
|
||||
|
||||
await vmService.ejectCd(VM_ID, [EMPTY_CD_ID])
|
||||
assert.deepEqual(calls, [['VBD.eject', vbdRef(EMPTY_CD_ID)]])
|
||||
})
|
||||
|
||||
it('propagates the other XAPI errors', async () => {
|
||||
const error = Object.assign(new Error('VM_BAD_POWER_STATE'), { code: 'VM_BAD_POWER_STATE' })
|
||||
const { vmService } = createRestApi({ ejectError: error })
|
||||
|
||||
await assert.rejects(vmService.ejectCd(VM_ID), error)
|
||||
})
|
||||
})
|
||||
@@ -15,7 +15,8 @@
|
||||
- [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] Add `POST /rest/v0/vms/{id}/actions/eject_cd` to eject the CD from a VM, or the CDs chosen with the optional `vbdIds` (PR [#10660](https://github.com/vatesfr/xen-orchestra/pull/10660))
|
||||
- [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
|
||||
|
||||
@@ -25,6 +26,8 @@
|
||||
- [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
|
||||
|
||||
@@ -43,6 +46,7 @@
|
||||
<!--packages-start-->
|
||||
|
||||
- @vates/task minor
|
||||
- @vates/types minor
|
||||
- @xen-orchestra/acl minor
|
||||
- @xen-orchestra/backups minor
|
||||
- @xen-orchestra/rest-api minor
|
||||
|
||||
@@ -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). |
|
||||
@@ -152,7 +152,7 @@ Actions are written using the exact string you pass in a privilege. A parent act
|
||||
|
||||
| Resource | Available actions |
|
||||
| --------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
|
||||
| `vm` | `read`, `clone`, `delete`, `eject-cd`, `migrate-send`, `export`, `pause`, `start`, `resume`, `revert-snapshot`, `snapshot`, `suspend`, `unpause`, `reboot:clean`, `reboot:hard`, `shutdown:clean`, `shutdown:hard`, `update:affinityHost`, `update:autoPoweron`, `update:blockedOperations`, `update:coresPerSocket`, `update:cpuCap`, `update:cpuMask`, `update:cpuWeight`, `update:cpus`, `update:cpusStaticMax`, `update:creation`, `update:datasources`, `update:expNestedHvm`, `update:hasVendorDevice`, `update:highAvailability`, `update:hvmBootFirmware`, `update:memory`, `update:memoryMax`, `update:memoryMin`, `update:memoryStaticMax`, `update:nameDescription`, `update:nameLabel`, `update:nestedVirt`, `update:nicType`, `update:notes`, `update:PV_args`, `update:resourceSet`, `update:secureBoot`, `update:share`, `update:startDelay`, `update:suspendSr`, `update:tags`, `update:uefiMode`, `update:vga`, `update:videoram`, `update:viridian`, `update:virtualizationMode`, `update:xenStoreData` |
|
||||
| `vm` | `read`, `clone`, `delete`, `migrate-send`, `export`, `pause`, `start`, `resume`, `revert-snapshot`, `snapshot`, `suspend`, `unpause`, `reboot:clean`, `reboot:hard`, `shutdown:clean`, `shutdown:hard`, `update:affinityHost`, `update:autoPoweron`, `update:blockedOperations`, `update:coresPerSocket`, `update:cpuCap`, `update:cpuMask`, `update:cpuWeight`, `update:cpus`, `update:cpusStaticMax`, `update:creation`, `update:datasources`, `update:expNestedHvm`, `update:hasVendorDevice`, `update:highAvailability`, `update:hvmBootFirmware`, `update:memory`, `update:memoryMax`, `update:memoryMin`, `update:memoryStaticMax`, `update:nameDescription`, `update:nameLabel`, `update:nestedVirt`, `update:nicType`, `update:notes`, `update:PV_args`, `update:resourceSet`, `update:secureBoot`, `update:share`, `update:startDelay`, `update:suspendSr`, `update:tags`, `update:uefiMode`, `update:vga`, `update:videoram`, `update:viridian`, `update:virtualizationMode`, `update:xenStoreData` |
|
||||
| `vm-snapshot` | `read`, `delete`, `export`, `update:tags` |
|
||||
| `vm-template` | `read`, `delete`, `export`, `instantiate`, `update:tags` |
|
||||
| `vm-controller` | `read`, `update:tags` |
|
||||
@@ -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` |
|
||||
|
||||
@@ -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',
|
||||
|
||||
@@ -1234,15 +1234,10 @@ export default class Xapi extends XapiBase {
|
||||
}
|
||||
}
|
||||
|
||||
// does nothing if the VM has no CD drive or if its drive is already empty
|
||||
async _ejectCdFromVm(vm) {
|
||||
const cdDrive = this._getVmCdDrive(vm)
|
||||
if (cdDrive) {
|
||||
await this.callAsync('VBD.eject', cdDrive.$ref).catch(error => {
|
||||
if (error.code !== 'VBD_IS_EMPTY') {
|
||||
throw error
|
||||
}
|
||||
})
|
||||
await this.callAsync('VBD.eject', cdDrive.$ref)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
165
packages/xo-server/src/xapi/mixins/_networking.test.mjs
Normal file
165
packages/xo-server/src/xapi/mixins/_networking.test.mjs
Normal 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'],
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -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,
|
||||
})
|
||||
|
||||
Reference in New Issue
Block a user