Compare commits

..

3 Commits

Author SHA1 Message Date
MelissaFrncJrg
f94b771f83 PR number 2026-11-25 10:22:00 +01:00
MelissaFrncJrg
3110d6c567 feat(rest-api): expose proxy deletion 2026-11-25 10:15:38 +01:00
MelissaFrncJrg
748843781f feat(rest-api): expose proxy deletion endpoint 2026-11-25 08:40:32 +01:00
19 changed files with 141 additions and 309 deletions

View File

@@ -22,11 +22,6 @@ export const BACKUP_EXPRESSION_CONTEXT = {
tags: { type: 'string[]' },
power_state: { type: 'string' },
},
pool: {
name_label: { type: 'string' },
description: { type: 'string' },
tags: { type: 'string[]' },
},
chainLength: { type: 'number' },
} as const
@@ -38,8 +33,6 @@ export const BACKUP_SETTING_CONTEXT = {
vmFilter: ['vm', 'run'],
srs: ['sr', 'run'],
remotes: ['backupRepository', 'run'],
vms: ['vm', 'run'],
pools: ['pool', 'run'],
} as const
export type BACKUP_SETTING_CONTEXT = (typeof BACKUP_SETTING_CONTEXT)[keyof typeof BACKUP_SETTING_CONTEXT]

View File

@@ -466,6 +466,8 @@ export type XoApp = EventEmitter & {
opts?: { bypassAuthorization?: boolean; fromGroup?: boolean; fromUser?: boolean }
): Promise<XoAclRole[]>
getAllGroups(): Promise<XoGroup[]>
/** Also destroys the VM of the proxy, if any */
destroyProxy(id: XoProxy['id']): Promise<void>
getAllProxies(): Promise<XoProxy[]>
getAllJobs<T extends AnyXoJob['type']>(type: T): Promise<Extract<AnyXoJob, { type: T }>[]>
getAllJobs(type?: string): Promise<AnyXoJob[]>
@@ -503,10 +505,7 @@ export type XoApp = EventEmitter & {
* `assertBrowserMediaInsertable` reports the predictable failures synchronously, e.g. before
* starting a task.
*/
insertBrowserMedia(params: {
id: XoBrowserMediaSession['id']
vmId: XoVm['id']
}): Promise<{ vdiId: XoVdi['id'] }>
insertBrowserMedia(params: { id: XoBrowserMediaSession['id']; vmId: XoVm['id'] }): Promise<{ vdiId: XoVdi['id'] }>
assertBrowserMediaInsertable(params: { id: XoBrowserMediaSession['id']; vmId: XoVm['id'] }): void
/** Eject the ISO of a browser media session, release its storage, and disconnect the browser */
ejectBrowserMedia(id: XoBrowserMediaSession['id']): Promise<void>

View File

@@ -646,7 +646,7 @@ export type XoVmBackupJob = BaseXoJob & {
proxy?: XoProxy['id']
mode: 'full' | 'delta'
remotes?: CMType.IdOr<XoBackupRepository['id']> | string
vms: CMType.IdOr<XoVm['id']> | Record<string, unknown> | string
vms: CMType.IdOr<XoVm['id']> | Record<string, unknown>
srs?: CMType.IdOr<XoSr['id']> | string
type: 'backup'
settings: {
@@ -663,7 +663,7 @@ export type XoMetadataBackupJobScheduleSettings = {
}
export type XoMetadataBackupJob = BaseXoJob & {
type: 'metadataBackup'
pools?: CMType.IdOr<XoPool['id']> | string
pools?: CMType.IdOr<XoPool['id']>
remotes: CMType.IdOr<XoBackupRepository['id']>
settings: {
''?: XoMetadataBackupJobGeneralSettings
@@ -696,7 +696,6 @@ export type XoMirrorBackupJob = BaseXoJob & {
sourceRemote: XoBackupRepository['id']
remotes: CMType.IdOr<XoBackupRepository['id']>
proxy?: XoProxy['id']
filter?: { vm: { uuid: { __or: XoVm['id'][] } } } | null
settings: {
'': XoMirrorBackupGeneralSettings
[scheduleId: XoSchedule['id']]: XoMirrorBackupScheduleSettings | undefined

View File

@@ -1,3 +1,4 @@
export default {
read: true,
delete: true,
}

View File

@@ -9,7 +9,6 @@ const { warn } = createLogger('xo:backups:buildContext')
/**
* @typedef {import('@vates/types/xen-api').XenApiVm} XenApiVm
* @typedef {import('@vates/types/xo').XoSr} XoSr
* @typedef {import('@vates/types/xo').XoPool} XoPool
* @typedef {import('@vates/types/xo').XoBackupRepository} XoBackupRepository
*
* @typedef {object} RunContext
@@ -31,10 +30,6 @@ const { warn } = createLogger('xo:backups:buildContext')
* @typedef {object} BackupRepositoryContext
* @property {{name: string, type: string | undefined, tags: string[]}} backupRepository
* @property {RunContext} run
*
* @typedef {object} PoolContext
* @property {{name_label: string, description: string, tags: string[]}} pool
* @property {RunContext} run
*/
/**
@@ -114,19 +109,3 @@ export function buildBackupRepositoryContext(backupRepository, run) {
run,
}
}
/**
* @param {XoPool} pool
* @param {RunContext} run
* @returns {PoolContext}
*/
export function buildPoolContext(pool, run) {
return {
pool: {
name_label: pool.name_label,
description: pool.name_description,
tags: Array.isArray(pool.tags) ? pool.tags : [],
},
run,
}
}

View File

@@ -1,13 +1,7 @@
import { describe, it } from 'node:test'
import assert from 'node:assert/strict'
import {
buildRunContext,
buildVmContext,
buildSrContext,
buildBackupRepositoryContext,
buildPoolContext,
} from './_buildContext.mjs'
import { buildRunContext, buildVmContext, buildSrContext, buildBackupRepositoryContext } from './_buildContext.mjs'
import { BACKUP_EXPRESSION_CONTEXT } from '@vates/types/backup-expression-context'
describe('buildContext', () => {
@@ -150,39 +144,4 @@ describe('buildContext', () => {
Object.keys(BACKUP_EXPRESSION_CONTEXT.backupRepository).sort()
)
})
it('buildPoolContext', () => {
const pool1 = {
name_label: 'name_label',
name_description: 'description',
ignored: 'ignored',
}
const poolContext1 = buildPoolContext(pool1, runContext)
assert.deepEqual(poolContext1, {
pool: {
name_label: 'name_label',
description: 'description',
tags: [],
},
run: expectedRunContext,
})
assert.deepEqual(Object.keys(poolContext1.pool).sort(), Object.keys(BACKUP_EXPRESSION_CONTEXT.pool).sort())
const pool2 = {
name_label: 'name_label',
name_description: 'description',
tags: ['tag'],
ignored: 'ignored',
}
const poolContext2 = buildPoolContext(pool2, runContext)
assert.deepEqual(poolContext2, {
pool: {
name_label: 'name_label',
description: 'description',
tags: ['tag'],
},
run: expectedRunContext,
})
assert.deepEqual(Object.keys(poolContext2.pool).sort(), Object.keys(BACKUP_EXPRESSION_CONTEXT.pool).sort())
})
})

View File

@@ -15,8 +15,6 @@ import type {
import type { RestApi } from '../rest-api/rest-api.mjs'
import { assertValidCron, vmContainsNoBakTag } from '../helpers/utils.helper.mjs'
import type { CreateBackupJobBody, CreateBackupJobSchedule, UpdateBackupJobBody } from './backup-job.type.mjs'
import { compileExpression, isExpression } from '@xen-orchestra/backups/_expressionPredicate.mjs'
import { buildRunContext, buildVmContext } from '@xen-orchestra/backups/_buildContext.mjs'
export class BackupJobService {
#backupJobTypes = ['backup', 'metadataBackup', 'mirrorBackup']
@@ -71,24 +69,12 @@ export class BackupJobService {
*/
assertJobHasValidExpressions(type: AnyXoBackupJob['type'], job: UpdateBackupJobBody): void {
if (type === 'backup') {
const { srs, remotes, vms, settings } = job as Extract<UpdateBackupJobBody, { srs?: unknown }>
const { srs, remotes, settings } = job as Extract<UpdateBackupJobBody, { srs?: unknown }>
assertValidExpression('srs', srs)
assertValidExpression('remotes', remotes)
assertValidExpression('vms', vms)
assertValidSettingsExpression(settings, ['healthCheckVmsWithTags', 'fullInterval'])
} else if (type === 'mirrorBackup') {
const { filter, remotes, settings } = job as Extract<UpdateBackupJobBody, { sourceRemote?: unknown }>
assertValidSettingsExpression(settings, ['healthCheckVmsWithTags', 'vmFilter'])
assertValidExpression('remotes', remotes)
if (filter != null && filter.vm.uuid.__or.length === 0) {
throw invalidParameters('filter must contain at least one VM', [
{ instancePath: '/filter/vm/uuid/__or', message: 'must NOT have fewer than 1 items' },
])
}
} else if (type === 'metadataBackup') {
const { remotes, pools } = job as Extract<UpdateBackupJobBody, { pools?: unknown }>
assertValidExpression('remotes', remotes)
assertValidExpression('pools', pools)
assertValidSettingsExpression(job.settings, ['healthCheckVmsWithTags', 'vmFilter'])
}
}
@@ -104,47 +90,16 @@ export class BackupJobService {
return false
}
const isVmInJob = await this.getBackupJobVmMatcher(backupJob)
return isVmInJob(vm)
}
/**
* Returns a function telling whether a VM is selected by the `vms` of the job,
* whether it is a list of IDs, an object pattern or an expression
*/
async getBackupJobVmMatcher(backupJob: XoVmBackupJob): Promise<(vm: XoVm) => boolean> {
try {
const vmIds = new Set<XoVm['id']>(extractIdsFromSimplePattern(backupJob.vms))
return vm => vmIds.has(vm.id)
const vmIds: XoVm['id'][] = extractIdsFromSimplePattern(backupJob.vms)
return vmIds.some(id => id === vm.id)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (_) {
if (!isExpression(backupJob.vms)) {
return createPredicate(backupJob.vms)
}
// `run:` clauses depend on the timezone, which is resolved per schedule like the executor does,
// so the VM is in the job if it matches for at least one of its schedules
const predicate = compileExpression(backupJob.vms)
const now = new Date()
const runContexts = (await this.#getScheduleTimezones(backupJob)).map(timezone => buildRunContext(now, timezone))
return vm => runContexts.some(runContext => predicate(buildVmContext(vm, runContext)))
const predicate = createPredicate(backupJob.vms)
return predicate(vm)
}
}
async #getScheduleTimezones(backupJob: XoVmBackupJob): Promise<(string | undefined)[]> {
const schedules = (await this.#restApi.xoApp.getAllSchedules()).filter(schedule => schedule.jobId === backupJob.id)
if (schedules.length === 0) {
return [backupJob.settings['']?.timezone]
}
return schedules.map(schedule => {
const scheduleTimezone = backupJob.settings[schedule.id]?.timezone
return typeof scheduleTimezone === 'string'
? scheduleTimezone
: (backupJob.settings['']?.timezone ?? schedule.timezone)
})
}
async backupJobHasAtLeastOneScheduleEnabled(id: XoVmBackupJob['id']): Promise<boolean> {
const backupJob = await this.#restApi.xoApp.getJob<XoVmBackupJob>(id)

View File

@@ -6,19 +6,15 @@ import type {
XoMetadataBackupJobGeneralSettings,
XoMetadataBackupJobScheduleSettings,
XoMirrorBackupGeneralSettings,
XoVm,
} from '@vates/types'
import { Unbrand } from '../open-api/common/response.common.mjs'
import type * as CMType from '@vates/types/lib/complex-matcher'
/**
* Copy of XoVmBackupJobScheduleSettings without the brand:
* tsoa empties any mapped type (Unbrand, Pick, Omit…) nested under Unbrand<UnbrandedXoVmBackupJob>,
* which dropped every schedule setting from the request bodies
*/
type VmBackupJobScheduleSettings = {
// Manual copy because with Unbrand<>, tsoa emits an empty schema. If XoVmBackupJobScheduleSettings changes
// in @vates/types, you have to update this copy too.
type UnbrandedXoVmBackupJobScheduleSettings = {
exportRetention?: number
healthCheckVmsWithTags?: XoVm['tags'] | string
healthCheckVmsWithTags?: string[] | string
fullInterval?: number | string
copyRetention?: number
snapshotRetention?: number
@@ -29,17 +25,17 @@ type VmBackupJobScheduleSettings = {
type UnbrandedXoVmBackupJob = Omit<XoVmBackupJob, 'settings' | 'remotes' | 'vms' | 'srs'> & {
remotes?: CMType.IdOr<string> | string
vms: CMType.IdOr<string> | Record<string, unknown> | string
vms: CMType.IdOr<string> | Record<string, unknown>
srs?: CMType.IdOr<string> | string
settings: {
'': XoVmBackupJobGeneralSettings
[scheduleId: string]: VmBackupJobScheduleSettings | undefined
[scheduleId: string]: UnbrandedXoVmBackupJobScheduleSettings | undefined
}
}
export type UnbrandXoVmBackupJob = Unbrand<UnbrandedXoVmBackupJob>
type UnbrandedXoMetadataBackupJob = Omit<XoMetadataBackupJob, 'settings' | 'pools' | 'remotes'> & {
pools?: CMType.IdOr<string> | string
pools?: CMType.IdOr<string>
remotes: CMType.IdOr<string>
settings: {
''?: XoMetadataBackupJobGeneralSettings
@@ -48,23 +44,21 @@ type UnbrandedXoMetadataBackupJob = Omit<XoMetadataBackupJob, 'settings' | 'pool
}
export type UnbrandXoMetadataBackupJob = Unbrand<UnbrandedXoMetadataBackupJob>
/**
* Same as VmBackupJobScheduleSettings
*/
type MirrorBackupJobScheduleSettings = {
// Manual copy because with Unbrand<>, tsoa emits an empty schema. If XoMirrorBackupScheduleSettings changes
// in @vates/types, you have to update this copy too.
type UnbrandedXoMirrorBackupScheduleSettings = {
exportRetention?: number
healthCheckVmsWithTags?: XoVm['tags'] | string
healthCheckVmsWithTags?: string[] | string
vmFilter?: string
healthCheckSr?: string
[key: string]: unknown
}
type UnbrandedXoMirrorBackupJob = Omit<XoMirrorBackupJob, 'settings' | 'remotes' | 'filter'> & {
type UnbrandedXoMirrorBackupJob = Omit<XoMirrorBackupJob, 'settings' | 'remotes'> & {
remotes: CMType.IdOr<string>
filter?: { vm: { uuid: { __or: string[] } } } | null
settings: {
'': XoMirrorBackupGeneralSettings
[scheduleId: string]: MirrorBackupJobScheduleSettings | undefined
[scheduleId: string]: UnbrandedXoMirrorBackupScheduleSettings | undefined
}
}
export type UnbrandXoMirrorBackupJob = Unbrand<UnbrandedXoMirrorBackupJob>

View File

@@ -1,4 +1,5 @@
import {
Delete,
Example,
Extension,
Get,
@@ -23,6 +24,7 @@ import {
badRequestResp,
forbiddenOperationResp,
internalServerErrorResp,
noContentResp,
notFoundResp,
proxyUnreachableResp,
unauthorizedResp,
@@ -146,4 +148,34 @@ export class ProxyController extends XoController<XoProxy> {
return { success: true }
}
/**
* Deletes a proxy
*
* Destroys the VM of the proxy, if it has one, with its disks and snapshots, then removes the proxy from Xen Orchestra.
*
* Required privilege:
* - resource: proxy, action: delete
*
* This privilege is enough to destroy the VM of the proxy: no privilege on that VM is checked.
*
* @example id "e625ea0c-a876-405a-b838-109d762efe88"
*/
@Extension('x-mcp-exposure', 'confirm')
@Delete('{id}')
@Middlewares(
acl({
resource: 'proxy',
action: 'delete',
objectId: 'params.id',
getObject: ({ restApi }) => restApi.xoApp.getProxy,
})
)
@SuccessResponse(noContentResp.status, noContentResp.description)
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
@Response(notFoundResp.status, notFoundResp.description)
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
async deleteProxy(@Path() id: string): Promise<void> {
await this.restApi.xoApp.destroyProxy(id as XoProxy['id'])
}
}

View File

@@ -49,3 +49,21 @@ describe('ProxyController.getProxyHealth', () => {
await assert.rejects(controller.getProxyHealth(proxyId), error => error === unrelatedError)
})
})
describe('ProxyController.deleteProxy', () => {
it('forwards the id to destroyProxy', async () => {
const calls: unknown[] = []
const restApi = {
xoApp: {
destroyProxy: async (id: string) => {
calls.push(['destroyProxy', id])
},
},
} as unknown as RestApi
const controller = new ProxyController(restApi)
await controller.deleteProxy(proxyId)
assert.deepEqual(calls, [['destroyProxy', proxyId]])
})
})

View File

@@ -14,6 +14,7 @@ import {
XoBackupLog,
} from '@vates/types'
import { createLogger } from '@xen-orchestra/log'
import { createPredicate } from 'value-matcher'
import { extractIdsFromSimplePattern } from '@xen-orchestra/backups/extractIdsFromSimplePattern.mjs'
import { noSuchObject } from 'xo-common/api-errors.js'
import { parse } from 'xo-remote-parser'
@@ -360,22 +361,23 @@ export class XoaService {
const nonReplicaVms = Object.values(this.#restApi.getObjectsByType<XoVm>('VM', { filter: vm => !isReplicaVm(vm) }))
const restApi = this.#restApi
const xoApp = restApi.xoApp
const backupJobService = this.#backupJobService
async function _extractVmIdsFromBackupJob(job: XoVmBackupJob): Promise<XoVm['id'][]> {
function _extractVmIdsFromBackupJob(job: XoVmBackupJob) {
let vmIds: XoVm['id'][]
try {
return extractIdsFromSimplePattern(job.vms)
vmIds = extractIdsFromSimplePattern(job.vms)
// eslint-disable-next-line @typescript-eslint/no-unused-vars
} catch (_) {
const isVmInJob = await backupJobService.getBackupJobVmMatcher(job)
return nonReplicaVms.filter(isVmInJob).map(vm => vm.id)
const predicate = createPredicate(job.vms)
vmIds = nonReplicaVms.filter(predicate).map(vm => vm.id)
}
return vmIds
}
async function _processVmsProtection(job: XoVmBackupJob, isProtected: boolean) {
function _processVmsProtection(job: XoVmBackupJob, isProtected: boolean) {
if (job.type !== BACKUP_TYPE.backup) {
return
}
;(await _extractVmIdsFromBackupJob(job)).forEach(vmId => {
_extractVmIdsFromBackupJob(job).forEach(vmId => {
_updateVmProtection(vmId, isProtected)
})
}
@@ -432,7 +434,7 @@ export class XoaService {
for (const job of jobs) {
if (!(await this.#backupJobService.backupJobHasAtLeastOneScheduleEnabled(job.id))) {
await _processVmsProtection(job, false)
_processVmsProtection(job, false)
disabledJobs++
continue
}
@@ -484,7 +486,7 @@ export class XoaService {
}
if (last3BackupLogs.length === 0) {
await _processVmsProtection(job, false)
_processVmsProtection(job, false)
continue
}
@@ -498,11 +500,11 @@ export class XoaService {
backupLogStatusesByVm[id].push(isSuccess)
}
let jobVmIds: XoVm['id'][] | undefined
for (const { tasks, status } of last3BackupLogs) {
last3BackupLogs.forEach(jobLob => {
const { tasks, status } = jobLob
if (tasks === undefined) {
jobVmIds ??= await _extractVmIdsFromBackupJob(job)
jobVmIds.forEach(vmId => updateVmBackupLogStatuses(vmId, status === 'success'))
const vmIds = _extractVmIdsFromBackupJob(job)
vmIds.forEach(vmId => updateVmBackupLogStatuses(vmId, status === 'success'))
} else {
tasks.forEach(task => {
if (task.data === undefined) {
@@ -511,7 +513,7 @@ export class XoaService {
updateVmBackupLogStatuses(task.data.id as XoVm['id'], task.status === 'success')
})
}
}
})
for (const [vmId, statuses] of Object.entries(backupLogStatusesByVm)) {
_updateVmProtection(

View File

@@ -9,6 +9,8 @@
> Users must be able to say: "Nice enhancement, I'm eager to test it"
- [REST API] Delete a proxy: `DELETE /rest/v0/proxies/:id` (PR [#10900](https://github.com/vatesfr/xen-orchestra/pull/10900))
### Bug fixes
> Users must be able to say: "I had this issue, happy to know it's fixed"
@@ -29,4 +31,7 @@
<!--packages-start-->
- @xen-orchestra/acl minor
- @xen-orchestra/rest-api minor
<!--packages-end-->

View File

@@ -190,7 +190,7 @@ This action makes the XO server send a GET request to the given URL, so the hold
| | `reclaim-space`, |
| `schedule` | `read`, `run` |
| `restore-log` | `read` |
| `proxy` | `read` |
| `proxy` | `read`, `delete` |
| `server` | `read`, `create`, `delete`, `connect`, `disconnect` |
| `task` | `read`, `abort`, `delete` |
| `alarm` | `read` |

View File

@@ -1,9 +1,5 @@
import { isSrWritable } from '../../utils.mjs'
import {
buildSrContext,
buildBackupRepositoryContext,
buildPoolContext,
} from '@xen-orchestra/backups/_buildContext.mjs'
import { buildSrContext, buildBackupRepositoryContext } from '@xen-orchestra/backups/_buildContext.mjs'
import { compileExpression } from '@xen-orchestra/backups/_expressionPredicate.mjs'
export function resolveBackupSrs(job, srs, runContext) {
@@ -44,16 +40,3 @@ export function resolveBackupRepositories(job, backupRepositories, runContext) {
return { backupRepositoryIds, proxySkippedIds, invalidUrlIds }
}
export function resolveBackupPools(job, pools, runContext) {
const predicate = compileExpression(job.pools)
const poolUuids = []
pools.forEach(pool => {
if (predicate(buildPoolContext(pool, runContext))) {
poolUuids.push(pool.uuid)
}
})
return poolUuids
}

View File

@@ -2,7 +2,7 @@ import assert from 'node:assert/strict'
import { describe, it } from 'node:test'
import { buildRunContext } from '@xen-orchestra/backups/_buildContext.mjs'
import { resolveBackupRepositories, resolveBackupSrs, resolveBackupPools } from './_resolveBackupTargets.mjs'
import { resolveBackupRepositories, resolveBackupSrs } from './_resolveBackupTargets.mjs'
// a Monday, at 22:00 UTC
const RUN_CONTEXT = buildRunContext(new Date('2026-11-02T22:00:00Z'), 'UTC')
@@ -25,13 +25,6 @@ const backupRepository = ({ id, name = id, url = 'nfs://nas:/backups', enabled =
proxy,
})
const pool = ({ uuid, name_label = uuid, tags = [] }) => ({
uuid,
name_label,
name_description: '',
tags,
})
describe('resolveBackupSrs()', () => {
it('returns the SRs matching the expression', () => {
const srs = [sr({ uuid: 'nfs-sr' }), sr({ uuid: 'local-sr', SR_type: 'ext' })]
@@ -155,24 +148,3 @@ describe('resolveBackupRepositories()', () => {
)
})
})
describe('resolveBackupPools()', () => {
it('returns the pools matching the expression', () => {
const pools = [pool({ uuid: 'pool1' }), pool({ uuid: 'pool2' })]
assert.deepEqual(resolveBackupPools({ pools: 'pool:name_label:pool1' }, pools, RUN_CONTEXT), ['pool1'])
})
it('evaluates the run context', () => {
const pools = [pool({ uuid: 'pool1' })]
assert.deepEqual(resolveBackupPools({ pools: 'run:hour:22' }, pools, RUN_CONTEXT), ['pool1'])
assert.deepEqual(resolveBackupPools({ pools: 'run:hour:23' }, pools, RUN_CONTEXT), [])
})
it('returns an empty array when nothing matches', () => {
const pools = [pool({ uuid: 'pool1' })]
assert.deepEqual(resolveBackupPools({ pools: 'pool:name_label:missing' }, pools, RUN_CONTEXT), [])
})
})

View File

@@ -22,8 +22,8 @@ import { serializeError, unboxIdsFromPattern } from '../../utils.mjs'
import { journalPurgeHorizon, serveVmBackups, VmBackupsCache } from './_vmBackupsCache.mjs'
import { VmBackupsSource } from './_vmBackupsSource.mjs'
import { waitAll } from '../../_waitAll.mjs'
import { compileExpression, isExpression } from '@xen-orchestra/backups/_expressionPredicate.mjs'
import { buildRunContext, buildVmContext } from '@xen-orchestra/backups/_buildContext.mjs'
import { isExpression } from '@xen-orchestra/backups/_expressionPredicate.mjs'
import { buildRunContext } from '@xen-orchestra/backups/_buildContext.mjs'
import { resolveBackupSrs, resolveBackupRepositories } from './_resolveBackupTargets.mjs'
const logger = createLogger('xo:xo-mixins:backups-ng')
@@ -214,41 +214,9 @@ export default class BackupNg {
job = { ...job, runContext }
const remotesExpression = isExpression(job.remotes) ? job.remotes : undefined
if (remotesExpression !== undefined) {
const {
backupRepositoryIds: remoteIds,
proxySkippedIds,
invalidUrlIds,
} = resolveBackupRepositories(job, await app.getAllRemotes(), runContext)
if (proxySkippedIds.length > 0) {
jobsLogger.warning(
'some backup repositories matched the expression but are not linked to the proxy of this job, they are skipped',
{
event: 'task.warning',
taskId: runJobId,
data: { backupRepositories: proxySkippedIds, proxy: job.proxy },
}
)
}
if (invalidUrlIds.length > 0) {
jobsLogger.warning(
'some backup repositories matched the expression but have an invalid URL, they are skipped',
{
event: 'task.warning',
taskId: runJobId,
data: { backupRepositories: invalidUrlIds },
}
)
}
job.remotes = { id: { __or: remoteIds } }
}
if (job.type === 'backup') {
const srsExpression = isExpression(job.srs) ? job.srs : undefined
const remotesExpression = isExpression(job.remotes) ? job.remotes : undefined
if (isExpression(job.srs)) {
const srUuids = resolveBackupSrs(job, Object.values(app.getObjectsByType('SR')), runContext)
@@ -256,6 +224,38 @@ export default class BackupNg {
job.srs = { id: { __or: srUuids } }
}
if (isExpression(job.remotes)) {
const {
backupRepositoryIds: remoteIds,
proxySkippedIds,
invalidUrlIds,
} = resolveBackupRepositories(job, await app.getAllRemotes(), runContext)
if (proxySkippedIds.length > 0) {
jobsLogger.warning(
'some backup repositories matched the expression but are not linked to the proxy of this job, they are skipped',
{
event: 'task.warning',
taskId: runJobId,
data: { backupRepositories: proxySkippedIds, proxy: job.proxy },
}
)
}
if (invalidUrlIds.length > 0) {
jobsLogger.warning(
'some backup repositories matched the expression but have an invalid URL, they are skipped',
{
event: 'task.warning',
taskId: runJobId,
data: { backupRepositories: invalidUrlIds },
}
)
}
job.remotes = { id: { __or: remoteIds } }
}
if (
(srsExpression !== undefined || remotesExpression !== undefined) &&
unboxIdsFromPattern(job.srs).length === 0 &&
@@ -313,16 +313,10 @@ export default class BackupNg {
vmIds = Object.keys(
app.getObjects({
filter: (() => {
let isMatchingVm
if (isExpression(vmsPattern)) {
const predicate = compileExpression(vmsPattern)
isMatchingVm = obj => obj.type === 'VM' && predicate(buildVmContext(obj, runContext))
} else {
isMatchingVm = createPredicate({
type: 'VM',
...vmsPattern,
})
}
const isMatchingVm = createPredicate({
type: 'VM',
...vmsPattern,
})
return obj =>
isMatchingVm(obj) &&

View File

@@ -5,9 +5,6 @@ import { createLogger } from '@xen-orchestra/log'
import { createRunner } from '@xen-orchestra/backups/Backup.mjs'
import { parseMetadataBackupId } from '@xen-orchestra/backups/parseMetadataBackupId.mjs'
import { RestoreMetadataBackup } from '@xen-orchestra/backups/RestoreMetadataBackup.mjs'
import { isExpression } from '@xen-orchestra/backups/_expressionPredicate.mjs'
import { resolveBackupPools, resolveBackupRepositories } from './backups-ng/_resolveBackupTargets.mjs'
import { buildRunContext } from '@xen-orchestra/backups/_buildContext.mjs'
import { Task } from '@vates/task'
import { debounceWithKey, REMOVE_CACHE_ENTRY } from '../_pDebounceWithKey.mjs'
@@ -51,62 +48,12 @@ export default class metadataBackup {
}
const app = this._app
const runContext = buildRunContext(
new Date(),
job.settings[schedule.id]?.timezone ?? job.settings['']?.timezone ?? schedule.timezone
)
if (job.xoMetadata) {
const config = await app.exportConfig()
job.xoMetadata = typeof config === 'string' ? config : { encoding: 'base64', data: config.toString('base64') }
}
if (isExpression(job.remotes)) {
const {
backupRepositoryIds: remoteIds,
proxySkippedIds,
invalidUrlIds,
} = resolveBackupRepositories(job, await app.getAllRemotes(), runContext)
if (proxySkippedIds.length > 0) {
jobsLogger.warning(
'some backup repositories matched the expression but are not linked to the proxy of this job, they are skipped',
{
event: 'task.warning',
taskId: runJobId,
data: { backupRepositories: proxySkippedIds, proxy: job.proxy },
}
)
}
if (invalidUrlIds.length > 0) {
jobsLogger.warning(
'some backup repositories matched the expression but have an invalid URL, they are skipped',
{
event: 'task.warning',
taskId: runJobId,
data: { backupRepositories: invalidUrlIds },
}
)
}
job.remotes = { id: { __or: remoteIds } }
}
if (isExpression(job.pools)) {
const poolIds = resolveBackupPools(job, Object.values(app.getObjectsByType('pool')), runContext)
if (poolIds.length === 0) {
jobsLogger.warning('no matching pool found', {
event: 'task.warning',
taskId: runJobId,
data: { pools: job.pools },
})
}
job.pools = { id: { __or: poolIds } }
}
const remoteIds = unboxIdsFromPattern(job.remotes)
const proxyId = job.proxy
try {

View File

@@ -122,7 +122,7 @@
"relative-luminance": "^2.0.1",
"reselect": "^2.5.4",
"rimraf": "^6.0.1",
"sanitize-html": "2.17.4",
"sanitize-html": "^2.17.4",
"sass": "^1.38.1",
"semver": "^6.0.0",
"strip-ansi": "^5.2.0",

View File

@@ -17499,7 +17499,7 @@ safe-regex@^1.1.0:
resolved "https://registry.yarnpkg.com/safer-buffer/-/safer-buffer-2.1.2.tgz#44fa161b0187b9549dd84bb91802f9bd8385cd6a"
integrity sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==
sanitize-html@2.17.4:
sanitize-html@^2.17.4:
version "2.17.4"
resolved "https://registry.yarnpkg.com/sanitize-html/-/sanitize-html-2.17.4.tgz#7db8b73b0024ccf543978c2a44da8223c4740cb1"
integrity sha512-2HW7v2ol/uAM7sX4hbD8Z59OGWmAPrvjL8E71UWlBcj6m+kcF6ilQBLny+cIgY214QJeJT5tQuxKKqX0SQqjGQ==