mirror of
https://github.com/vatesfr/xen-orchestra.git
synced 2026-12-03 05:42:41 -06:00
Compare commits
14 Commits
feat_apt_u
...
feat/rest-
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
576d0670d5 | ||
|
|
8eaa4c507a | ||
|
|
f22c27b863 | ||
|
|
3e8658c906 | ||
|
|
7b7fab8366 | ||
|
|
22bcc37439 | ||
|
|
5ca2958d2a | ||
|
|
205ae67940 | ||
|
|
addfdd5475 | ||
|
|
5512fc65a6 | ||
|
|
1f8f265afc | ||
|
|
c0e7843274 | ||
|
|
c893471c5e | ||
|
|
6f91a90299 |
@@ -835,12 +835,3 @@ export type XoaPackageUpdate = {
|
||||
/** undefined: the package is not installed yet */
|
||||
installedVersion?: string
|
||||
}
|
||||
|
||||
/** a Debian package of the XO appliance with a newer version available */
|
||||
export interface UpgradablePackage {
|
||||
name: string
|
||||
version: string
|
||||
installedVersion: string
|
||||
release: string
|
||||
description: string
|
||||
}
|
||||
|
||||
@@ -703,17 +703,6 @@ export type XoOpenmetricsPlugin = BaseXoPlugin<
|
||||
XoOpenmetricsPluginConfigurationSchema
|
||||
>
|
||||
|
||||
// ===================================================================
|
||||
// package-manager
|
||||
|
||||
/** not configurable: xo-server sends no `configurationSchema` */
|
||||
export type XoPackageManagerPlugin = Omit<
|
||||
BaseXoPlugin<'package-manager', Record<string, never>, never>,
|
||||
'configurationSchema'
|
||||
> & {
|
||||
configurationSchema?: undefined
|
||||
}
|
||||
|
||||
// ===================================================================
|
||||
// perf-alert
|
||||
|
||||
|
||||
@@ -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?: {
|
||||
|
||||
@@ -33,7 +33,6 @@ import type {
|
||||
XoLoadBalancerPlugin,
|
||||
XoNetboxPlugin,
|
||||
XoOpenmetricsPlugin,
|
||||
XoPackageManagerPlugin,
|
||||
XoPerfAlertPlugin,
|
||||
XoSdnControllerPlugin,
|
||||
XoTestPluginPlugin,
|
||||
@@ -505,7 +504,6 @@ export type XoPlugin =
|
||||
| XoLoadBalancerPlugin
|
||||
| XoNetboxPlugin
|
||||
| XoOpenmetricsPlugin
|
||||
| XoPackageManagerPlugin
|
||||
| XoPerfAlertPlugin
|
||||
| XoSdnControllerPlugin
|
||||
| XoTestPluginPlugin
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
}
|
||||
|
||||
@@ -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)
|
||||
)
|
||||
}
|
||||
|
||||
|
||||
@@ -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 }))
|
||||
}
|
||||
|
||||
@@ -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', () => {
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
@@ -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) {
|
||||
|
||||
13
@xen-orchestra/lite/src/route-map.d.ts
vendored
13
@xen-orchestra/lite/src/route-map.d.ts
vendored
@@ -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'
|
||||
|
||||
@@ -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>
|
||||
```
|
||||
@@ -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>
|
||||
@@ -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`
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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 },
|
||||
]
|
||||
)
|
||||
})
|
||||
})
|
||||
|
||||
@@ -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 }
|
||||
)
|
||||
}
|
||||
|
||||
@@ -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')
|
||||
|
||||
@@ -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 |
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
@@ -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">
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -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)
|
||||
})
|
||||
@@ -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"
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<template>
|
||||
<UiInfo
|
||||
v-tooltip="iconOnly ? currentStatus.text : false"
|
||||
class="vts-status"
|
||||
:accent="currentStatus.accent"
|
||||
:role="iconOnly ? 'img' : undefined"
|
||||
:aria-label="iconOnly ? currentStatus.text : undefined"
|
||||
@@ -73,3 +74,13 @@ const currentStatus = useMapper<Status, { text: string; accent: InfoAccent }>(
|
||||
false
|
||||
)
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
.ui-info.vts-status {
|
||||
align-items: center;
|
||||
|
||||
:deep(.icon) {
|
||||
transform: none;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<!-- v9 -->
|
||||
<template>
|
||||
<div class="ui-checkbox">
|
||||
<label :class="classNames" class="checkbox-label" v-bind="wrapperAttrs">
|
||||
<label :class="[classNames, { 'has-label': slots.default }]" class="checkbox-label" v-bind="wrapperAttrs">
|
||||
<input
|
||||
v-model="checkboxModel"
|
||||
:disabled="isDisabled"
|
||||
@@ -79,6 +79,14 @@ const attrs = useAttrs()
|
||||
align-items: center;
|
||||
gap: 0.4rem;
|
||||
|
||||
&.has-label {
|
||||
align-items: flex-start;
|
||||
|
||||
.fake-checkbox {
|
||||
margin-block-start: 0.4rem;
|
||||
}
|
||||
}
|
||||
|
||||
.fake-checkbox {
|
||||
--checkbox-mark-color: var(--color-neutral-background-primary);
|
||||
position: relative;
|
||||
|
||||
@@ -36,13 +36,14 @@ const isDisabled = useDisabled(() => disabled)
|
||||
.ui-radio-button {
|
||||
--radio-dot-color: var(--color-neutral-background-primary);
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
align-items: flex-start;
|
||||
gap: 0.8rem;
|
||||
|
||||
.radio {
|
||||
position: relative;
|
||||
display: inline-flex;
|
||||
flex-shrink: 0;
|
||||
margin-block-start: 0.4rem;
|
||||
border-radius: 50%;
|
||||
color: var(--radio-color);
|
||||
transition:
|
||||
|
||||
@@ -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,
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -95,7 +95,7 @@ function handleBackdropClick() {
|
||||
display: flex;
|
||||
flex: 1;
|
||||
min-height: 0;
|
||||
overflow-x: hidden;
|
||||
overflow-x: clip;
|
||||
}
|
||||
|
||||
.header {
|
||||
|
||||
@@ -1049,7 +1049,6 @@
|
||||
"s3-endpoint-sample": "مثال: s3.us-west-1.amazonaws.com",
|
||||
"scan-pifs": "فحص PIF",
|
||||
"schedule": "الجدول الزمني",
|
||||
"schedules": "الجداول الزمنية",
|
||||
"secret": "السر",
|
||||
"secure-boot": "الإقلاع الآمن",
|
||||
"see-details": "عرض التفاصيل",
|
||||
|
||||
@@ -1190,7 +1190,6 @@
|
||||
"s3-endpoint-sample": "Příklad: s3.us-west-1.amazonaws.com",
|
||||
"scan-pifs": "Skenovat fyzická rozhraní",
|
||||
"schedule": "Plán",
|
||||
"schedules": "Plány",
|
||||
"secret": "Tajemství",
|
||||
"secure-boot": "Secure boot",
|
||||
"see-details": "Viz podrobnosti",
|
||||
|
||||
@@ -1117,7 +1117,6 @@
|
||||
"s3-endpoint-sample": "Eksempel: s3.us-west-1.amazonaws.com",
|
||||
"scan-pifs": "Skan PIF'er",
|
||||
"schedule": "Tidsplan",
|
||||
"schedules": "Tidsplaner",
|
||||
"secret": "Hemmelighed",
|
||||
"secure-boot": "Secure boot",
|
||||
"see-details": "Se detaljer",
|
||||
|
||||
@@ -745,7 +745,6 @@
|
||||
"s3-backup-repository": "S3-Backupdepot",
|
||||
"scan-pifs": "PIFs scannen",
|
||||
"schedule": "Zeitplan",
|
||||
"schedules": "Zeitpläne",
|
||||
"secure-boot": "Secure Boot",
|
||||
"see-details": "Details anzeigen",
|
||||
"select-compression": "Kompression auswählen",
|
||||
|
||||
@@ -216,8 +216,6 @@
|
||||
"action:turn-into-group": "Turn into group",
|
||||
"action:unload": "Unload",
|
||||
"action:update": "Update",
|
||||
"action:upgrade": "Upgrade",
|
||||
"action:upgrade-all": "Upgrade all",
|
||||
"action:use-query-builder": "Use query builder",
|
||||
"actions": "Actions",
|
||||
"active-mapping": "Active mapping",
|
||||
@@ -795,8 +793,6 @@
|
||||
"job:network-delete:has-n-pif-connected": "The network has one PIF connected | The network has {n} PIFs connected",
|
||||
"job:network-delete:has-n-vif-attached": "The network has one VIF attached | The network has {n} VIFs attached",
|
||||
"job:network-delete:missing-network": "No network to delete",
|
||||
"job:package-refresh:in-progress": "Package list update in progress…",
|
||||
"job:package-upgrade:in-progress": "A package upgrade is in progress…",
|
||||
"job:pbd-plug:missing-pbd": "No PBDs to connect",
|
||||
"job:pbd-plug:pbd-connected": "One or several PBDs are already connected",
|
||||
"job:pbd-unplug:missing-pbd": "No PBDs to disconnect",
|
||||
@@ -1069,6 +1065,7 @@
|
||||
"multi-pathing": "Multi-pathing",
|
||||
"multiple-schedules": "Multiple schedules",
|
||||
"multiple-schedules-advice": "We advise splitting a backup job with multiple schedules into multiple backup jobs with one schedule each.",
|
||||
"multiple-schedules-split-in-xo5": "Multiple schedules: split into one job per schedule in XO 5",
|
||||
"must-be-at-least-n": "Must be at least {n}.",
|
||||
"n-blocking": "1 blocking | {n} blocking",
|
||||
"n-bonded-networks": "1 bonded network | {n} bonded networks",
|
||||
@@ -1308,7 +1305,6 @@
|
||||
"other-properties": "Other properties",
|
||||
"ova": "OVA",
|
||||
"overridden": "Overridden",
|
||||
"package": "Package",
|
||||
"page-not-found": "This page is not to be found…",
|
||||
"page-please-wait": "Hold tight, astronaut! The page is getting ready to take off.{newline}We're just aligning the thrusters and calibrating the systems. It won't be long now, stay tuned!",
|
||||
"pagination:all": "@:all",
|
||||
@@ -1320,11 +1316,6 @@
|
||||
"patch-name": "Patch name",
|
||||
"patches": "Patches",
|
||||
"patches-up-to-date": "Patches up to date",
|
||||
"patches:n-available": "{n} patch available | {n} patches available",
|
||||
"patches:plugin-not-loaded": "The {plugin} plugin must be loaded to manage the patches of the XO appliance.",
|
||||
"patches:reboot-required": "Some installed patches require a reboot of the XO appliance to take effect.",
|
||||
"patches:upgrade-all": "Upgrade all patches?",
|
||||
"patches:upgrade-all-confirm": "{n} patch will be installed. | {n} patches will be installed.",
|
||||
"path": "Path",
|
||||
"path-in-bucket": "Path in bucket",
|
||||
"path-in-container": "Path in container",
|
||||
@@ -1517,7 +1508,6 @@
|
||||
"save-xo-config": "Save XO config",
|
||||
"scan-pifs": "Scan PIFs",
|
||||
"schedule": "Schedule",
|
||||
"schedules": "Schedules",
|
||||
"scope": "Scope",
|
||||
"scope-preview": "Scope preview",
|
||||
"scope-type": "Scope type",
|
||||
@@ -1576,6 +1566,7 @@
|
||||
"snapshot-mode:with-memory-description": "Includes the VM's memory state. The VM will be briefly suspended during the snapshot.",
|
||||
"snapshot-revert-snapshot-before": "Take a snapshot of the VM before reverting",
|
||||
"snapshot-revert-warning": "This will restore the VM to the selected snapshot state. Any changes made since then (data, configuration, and disk state) will be lost. This action cannot be undone.",
|
||||
"snapshot-settings-disabled-offline-backup": "Snapshot settings are disabled because offline backup shuts down the VMs instead of taking a snapshot.",
|
||||
"snapshot-synchronisation": "Snapshot synchronisation",
|
||||
"snapshot-vdis": "Snapshot VDIs",
|
||||
"snapshots": "Snapshots",
|
||||
|
||||
@@ -817,7 +817,6 @@
|
||||
"s3-backup-repository": "Repositorio S3 de salvaguardas",
|
||||
"scan-pifs": "Escanear PIFs",
|
||||
"schedule": "Planificación",
|
||||
"schedules": "Planificaciones",
|
||||
"secure-boot": "Arranque seguro",
|
||||
"see-details": "Ver detalles",
|
||||
"select-compression": "Elige modo de compression",
|
||||
|
||||
@@ -1049,7 +1049,6 @@
|
||||
"s3-endpoint-sample": "مثال: s3.us-west-1.amazonaws.com",
|
||||
"scan-pifs": "اسکن PIFها",
|
||||
"schedule": "زمانبندی",
|
||||
"schedules": "زمانبندیها",
|
||||
"secret": "رمز",
|
||||
"secure-boot": "بوت امن",
|
||||
"see-details": "مشاهده جزئیات",
|
||||
|
||||
@@ -1049,7 +1049,6 @@
|
||||
"s3-endpoint-sample": "Esimerkki: s3.us-west-1.amazonaws.com",
|
||||
"scan-pifs": "Skannaa PIF:t",
|
||||
"schedule": "Aikataulu",
|
||||
"schedules": "Aikataulut",
|
||||
"secret": "Salaisuus",
|
||||
"secure-boot": "Suojattu käynnistys",
|
||||
"see-details": "Katso tiedot",
|
||||
|
||||
@@ -216,8 +216,6 @@
|
||||
"action:turn-into-group": "Transformer en groupe",
|
||||
"action:unload": "Décharger",
|
||||
"action:update": "Mettre à jour",
|
||||
"action:upgrade": "Mettre à niveau",
|
||||
"action:upgrade-all": "Tout mettre à niveau",
|
||||
"action:use-query-builder": "Constructeur de requête",
|
||||
"actions": "Actions",
|
||||
"active-mapping": "Correspondance active",
|
||||
@@ -795,8 +793,6 @@
|
||||
"job:network-delete:has-n-pif-connected": "Le réseau a un PIF connecté | Le réseau a {n} PIFs connectés",
|
||||
"job:network-delete:has-n-vif-attached": "Le réseau a un VIF attaché | Le réseau a {n} VIFs attachés",
|
||||
"job:network-delete:missing-network": "Aucun réseau à supprimer",
|
||||
"job:package-refresh:in-progress": "Mise à jour de la liste des paquets en cours…",
|
||||
"job:package-upgrade:in-progress": "Une mise à niveau de paquets est en cours…",
|
||||
"job:pbd-plug:missing-pbd": "Aucun PBD à connecter",
|
||||
"job:pbd-plug:pbd-connected": "Un ou plusieurs PBDs sont déjà connectés",
|
||||
"job:pbd-unplug:missing-pbd": "Aucun PBD à déconnecter",
|
||||
@@ -1069,6 +1065,7 @@
|
||||
"multi-pathing": "Multi-pathing",
|
||||
"multiple-schedules": "Plusieurs planifications",
|
||||
"multiple-schedules-advice": "Nous vous conseillons de diviser un job de sauvegarde à plusieurs planifications en plusieurs jobs ayant chacun une seule planification.",
|
||||
"multiple-schedules-split-in-xo5": "Plusieurs planifications : diviser en un job par planification dans XO 5",
|
||||
"must-be-at-least-n": "Doit être au moins {n}.",
|
||||
"n-blocking": "0 bloquante | 1 bloquante | {n} bloquantes",
|
||||
"n-bonded-networks": "1 réseau lié | {n} réseaux liés",
|
||||
@@ -1308,7 +1305,6 @@
|
||||
"other-properties": "Autres propriétés",
|
||||
"ova": "OVA",
|
||||
"overridden": "Personnalisé",
|
||||
"package": "Paquet",
|
||||
"page-not-found": "Cette page est introuvable…",
|
||||
"page-please-wait": "Accrochez-vous, astronaute ! La page est sur le point de décoller.{newline}Nous alignons les propulseurs et calibrons les systèmes. Plus que quelques instants, restez à l'écoute !",
|
||||
"pagination:all": "Tous",
|
||||
@@ -1320,11 +1316,6 @@
|
||||
"patch-name": "Nom du patch",
|
||||
"patches": "Patches",
|
||||
"patches-up-to-date": "Patches à jour",
|
||||
"patches:n-available": "{n} patch disponible | {n} patches disponibles",
|
||||
"patches:plugin-not-loaded": "Le plugin {plugin} doit être chargé pour gérer les patches de l'appliance XO.",
|
||||
"patches:reboot-required": "Certains patches installés nécessitent un redémarrage de l'appliance XO pour être appliqués.",
|
||||
"patches:upgrade-all": "Installer tous les patches ?",
|
||||
"patches:upgrade-all-confirm": "{n} patch va être installé. | {n} patches vont être installés.",
|
||||
"path": "Chemin",
|
||||
"path-in-bucket": "Chemin dans le bucket",
|
||||
"path-in-container": "Chemin dans le conteneur",
|
||||
@@ -1517,7 +1508,6 @@
|
||||
"save-xo-config": "Sauvegarder la config XO",
|
||||
"scan-pifs": "Scan PIFs",
|
||||
"schedule": "Planification",
|
||||
"schedules": "Planifications",
|
||||
"scope": "Périmètre",
|
||||
"scope-preview": "Aperçu du périmètre",
|
||||
"scope-type": "Type de périmètre",
|
||||
@@ -1576,6 +1566,7 @@
|
||||
"snapshot-mode:with-memory-description": "Inclut l'état de la mémoire de la VM. La VM sera brièvement suspendue pendant le snapshot.",
|
||||
"snapshot-revert-snapshot-before": "Créer un instantané de la VM avant la restauration",
|
||||
"snapshot-revert-warning": "La VM sera restaurée à l'état de l'instantané sélectionné. Tous les changements effectués depuis (données, configuration et état des disques) seront perdus. Cette action est irréversible.",
|
||||
"snapshot-settings-disabled-offline-backup": "Les paramètres de snapshot sont désactivés car la sauvegarde hors ligne éteint les VMs au lieu de faire un snapshot.",
|
||||
"snapshot-synchronisation": "Synchronisation des snapshots",
|
||||
"snapshot-vdis": "VDIs snapshot",
|
||||
"snapshots": "Instantanés",
|
||||
|
||||
@@ -1049,7 +1049,6 @@
|
||||
"s3-endpoint-sample": "Esempio: s3.us-west-1.amazonaws.com",
|
||||
"scan-pifs": "Scansiona PIF",
|
||||
"schedule": "Pianificazione",
|
||||
"schedules": "Pianificazioni",
|
||||
"secret": "Segreto",
|
||||
"secure-boot": "Secure boot",
|
||||
"see-details": "Vedi i dettagli",
|
||||
|
||||
@@ -1049,7 +1049,6 @@
|
||||
"s3-endpoint-sample": "例: s3.us-west-1.amazonaws.com",
|
||||
"scan-pifs": "PIF をスキャン",
|
||||
"schedule": "スケジュール",
|
||||
"schedules": "スケジュール",
|
||||
"secret": "シークレット",
|
||||
"secure-boot": "セキュアブート",
|
||||
"see-details": "詳細を表示",
|
||||
|
||||
@@ -1049,7 +1049,6 @@
|
||||
"s3-endpoint-sample": "예: s3.us-west-1.amazonaws.com",
|
||||
"scan-pifs": "PIF 검색",
|
||||
"schedule": "일정",
|
||||
"schedules": "일정",
|
||||
"secret": "시크릿",
|
||||
"secure-boot": "보안 부팅",
|
||||
"see-details": "상세 보기",
|
||||
|
||||
@@ -1049,7 +1049,6 @@
|
||||
"s3-endpoint-sample": "Eksempel: s3.us-west-1.amazonaws.com",
|
||||
"scan-pifs": "Skann PIF-er",
|
||||
"schedule": "Tidsplan",
|
||||
"schedules": "Tidsplaner",
|
||||
"secret": "Hemmelighet",
|
||||
"secure-boot": "Sikker oppstart",
|
||||
"see-details": "Se detaljer",
|
||||
|
||||
@@ -1190,7 +1190,6 @@
|
||||
"s3-endpoint-sample": "Voorbeeld: s3.us-west-1.amazonaws.com",
|
||||
"scan-pifs": "Scan PIF's",
|
||||
"schedule": "Planning",
|
||||
"schedules": "Schema's",
|
||||
"secret": "Secret",
|
||||
"secure-boot": "Beveiligd opstarten",
|
||||
"see-details": "Zie details",
|
||||
|
||||
@@ -1049,7 +1049,6 @@
|
||||
"s3-endpoint-sample": "Przykład: s3.us-west-1.amazonaws.com",
|
||||
"scan-pifs": "Skanuj PIF",
|
||||
"schedule": "Harmonogram",
|
||||
"schedules": "Harmonogramy",
|
||||
"secret": "Sekret",
|
||||
"secure-boot": "Secure boot",
|
||||
"see-details": "Zobacz szczegóły",
|
||||
|
||||
@@ -1049,7 +1049,6 @@
|
||||
"s3-endpoint-sample": "Exemplo: s3.us-west-1.amazonaws.com",
|
||||
"scan-pifs": "Escanear PIFs",
|
||||
"schedule": "Agendamento",
|
||||
"schedules": "Agendamentos",
|
||||
"secret": "Segredo",
|
||||
"secure-boot": "Secure boot",
|
||||
"see-details": "Veja os detalhes",
|
||||
|
||||
@@ -726,7 +726,6 @@
|
||||
"s3-backup-repository": "Repositório de cópias de segurança do S3",
|
||||
"scan-pifs": "Digitalizar PIFs",
|
||||
"schedule": "Calendário",
|
||||
"schedules": "Calendários",
|
||||
"secure-boot": "Arranque seguro",
|
||||
"see-details": "Veja os detalhes",
|
||||
"select-compression": "Selecione um tipo de compressão",
|
||||
|
||||
@@ -1049,7 +1049,6 @@
|
||||
"s3-endpoint-sample": "Пример: s3.us-west-1.amazonaws.com",
|
||||
"scan-pifs": "Сканировать PIFs",
|
||||
"schedule": "Расписание",
|
||||
"schedules": "Расписания",
|
||||
"secret": "Секрет",
|
||||
"secure-boot": "Безопасная загрузка",
|
||||
"see-details": "Подробнее",
|
||||
|
||||
@@ -1017,7 +1017,6 @@
|
||||
"s3-backup-repository": "S3 repozitár záloh",
|
||||
"scan-pifs": "Skenovať PIFs",
|
||||
"schedule": "Plán",
|
||||
"schedules": "Plány",
|
||||
"secret": "Tajomstvo",
|
||||
"secure-boot": "Secure boot",
|
||||
"see-details": "Zobraziť podrobnosti",
|
||||
|
||||
@@ -940,7 +940,6 @@
|
||||
"s3-backup-repository": "S3 säkerhetskopieringsförvar",
|
||||
"scan-pifs": "Skanna PIF",
|
||||
"schedule": "Schema",
|
||||
"schedules": "Schema",
|
||||
"secure-boot": "Säker boot",
|
||||
"see-details": "Se detaljer",
|
||||
"select-compression": "Välj komprimering",
|
||||
|
||||
@@ -984,7 +984,6 @@
|
||||
"s3-backup-repository": "S3 yedek deposu",
|
||||
"scan-pifs": "PIF'leri tara",
|
||||
"schedule": "Zamanlama",
|
||||
"schedules": "Zamanlamalar",
|
||||
"secure-boot": "Güvenli önyükleme",
|
||||
"see-details": "Ayrıntıları gör",
|
||||
"select-compression": "Sıkıştırma seçin",
|
||||
|
||||
@@ -1049,7 +1049,6 @@
|
||||
"s3-endpoint-sample": "Приклад: s3.us-west-1.amazonaws.com",
|
||||
"scan-pifs": "Сканувати PIFs",
|
||||
"schedule": "Розклад",
|
||||
"schedules": "Розклади",
|
||||
"secret": "Секрет",
|
||||
"secure-boot": "Безпечне завантаження",
|
||||
"see-details": "Переглянути деталі",
|
||||
|
||||
@@ -987,7 +987,6 @@
|
||||
"s3-backup-repository": "S3备份仓库",
|
||||
"scan-pifs": "扫描PIF",
|
||||
"schedule": "计划",
|
||||
"schedules": "计划",
|
||||
"secure-boot": "安全启动",
|
||||
"see-details": "查看详情",
|
||||
"select-compression": "选择压缩方式",
|
||||
|
||||
@@ -1,16 +0,0 @@
|
||||
import { defineColumns } from '@core/packages/table/define-columns.ts'
|
||||
import { useButtonColumn } from '@core/tables/column-definitions/button-column.ts'
|
||||
import { useTextColumn } from '@core/tables/column-definitions/text-column.ts'
|
||||
import { useTruncatedTextColumn } from '@core/tables/column-definitions/truncated-text-column.ts'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
export const useUpgradablePackageColumns = defineColumns(() => {
|
||||
const { t } = useI18n()
|
||||
|
||||
return {
|
||||
name: useTextColumn({ headerLabel: () => t('package') }),
|
||||
version: useTextColumn({ headerLabel: () => t('version') }),
|
||||
description: useTruncatedTextColumn({ headerLabel: () => t('description') }),
|
||||
upgrade: useButtonColumn({ buttonVariant: 'secondary', buttonSize: 'small' }),
|
||||
}
|
||||
})
|
||||
10
@xen-orchestra/web-core/test/can-focus-input.ts
Normal file
10
@xen-orchestra/web-core/test/can-focus-input.ts
Normal 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
|
||||
}
|
||||
@@ -24,13 +24,14 @@ it('shows no message without info nor error', () => {
|
||||
expect(findMessages(mountCheckbox())).toEqual([])
|
||||
})
|
||||
|
||||
it('shows the info, then the error', () => {
|
||||
it('shows the info as its description, then the error', () => {
|
||||
const wrapper = mountCheckbox({
|
||||
info: 'The VMs will be shut down',
|
||||
error: { content: 'Select at least one option', accent: 'danger' },
|
||||
})
|
||||
|
||||
expect(findMessages(wrapper)).toEqual(['The VMs will be shut down', 'Select at least one option'])
|
||||
expect(wrapper.get('.ui-rich-checkbox .description').text()).toBe('The VMs will be shut down')
|
||||
expect(findMessages(wrapper)).toEqual(['Select at least one option'])
|
||||
})
|
||||
|
||||
it('is checked according to its model', () => {
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
<template>
|
||||
<div class="backup-job-form-checkbox">
|
||||
<UiCheckbox v-model="model" accent="brand">
|
||||
<UiRichCheckbox v-if="info" v-model="model" accent="brand" :description="info">
|
||||
{{ label }}
|
||||
</UiRichCheckbox>
|
||||
<UiCheckbox v-else v-model="model" accent="brand">
|
||||
{{ label }}
|
||||
</UiCheckbox>
|
||||
<UiInfo v-if="info" accent="info" wrap>
|
||||
{{ info }}
|
||||
</UiInfo>
|
||||
<UiInfo v-if="errorMessage !== undefined" accent="danger" wrap>
|
||||
{{ errorMessage }}
|
||||
</UiInfo>
|
||||
@@ -17,6 +17,7 @@ import { formatErrorMessage } from '@/modules/backup-job/utils/backup-job-error-
|
||||
import type { InputWrapperMessage } from '@core/components/input-wrapper/VtsInputWrapper.vue'
|
||||
import UiCheckbox from '@core/components/ui/checkbox/UiCheckbox.vue'
|
||||
import UiInfo from '@core/components/ui/info/UiInfo.vue'
|
||||
import UiRichCheckbox from '@core/components/ui/rich-checkbox/UiRichCheckbox.vue'
|
||||
import { computed } from 'vue'
|
||||
|
||||
const { error } = defineProps<{
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
</span>
|
||||
</template>
|
||||
<template #period>
|
||||
<span class="typo-body-bold">{{ period }}</span>
|
||||
<span class="period typo-body-bold">{{ period }}</span>
|
||||
</template>
|
||||
<template #keep>
|
||||
<span class="keep">
|
||||
@@ -62,6 +62,10 @@ const errorMessage = computed(() => formatErrorMessage(error))
|
||||
width: 10rem;
|
||||
}
|
||||
|
||||
.period {
|
||||
margin-inline-end: -1.2rem;
|
||||
}
|
||||
|
||||
.keep {
|
||||
flex: 0 0 18rem;
|
||||
width: 18rem;
|
||||
|
||||
@@ -1,5 +1,30 @@
|
||||
<template>
|
||||
<UiRichRadioButtonGroup
|
||||
v-if="hasDescription"
|
||||
class="backup-job-form-radio"
|
||||
accent="brand"
|
||||
:vertical="vertical || uiStore.isSmall"
|
||||
>
|
||||
<template #label>
|
||||
<UiLabel accent="neutral" required>{{ label }}</UiLabel>
|
||||
</template>
|
||||
<UiRichRadioButton
|
||||
v-for="option of options"
|
||||
:key="option.value"
|
||||
v-model="model"
|
||||
accent="brand"
|
||||
:value="option.value"
|
||||
:description="option.description"
|
||||
:disabled
|
||||
>
|
||||
{{ option.label }}
|
||||
</UiRichRadioButton>
|
||||
<template v-if="slots.info" #info>
|
||||
<slot name="info" />
|
||||
</template>
|
||||
</UiRichRadioButtonGroup>
|
||||
<UiRadioButtonGroup
|
||||
v-else
|
||||
class="backup-job-form-radio"
|
||||
accent="brand"
|
||||
:gap="vertical || uiStore.isSmall ? 'narrow' : 'wide'"
|
||||
@@ -8,12 +33,17 @@
|
||||
<template #label>
|
||||
<UiLabel accent="neutral" required>{{ label }}</UiLabel>
|
||||
</template>
|
||||
<div v-for="option of options" :key="option.value" class="option">
|
||||
<UiRadioButton v-model="model" accent="brand" :value="option.value">
|
||||
{{ option.label }}
|
||||
</UiRadioButton>
|
||||
<UiInfo v-if="option.description" accent="info" wrap>{{ option.description }}</UiInfo>
|
||||
</div>
|
||||
<UiRadioButton
|
||||
v-for="option of options"
|
||||
:key="option.value"
|
||||
v-model="model"
|
||||
class="radio-button"
|
||||
accent="brand"
|
||||
:value="option.value"
|
||||
:disabled
|
||||
>
|
||||
{{ option.label }}
|
||||
</UiRadioButton>
|
||||
<template v-if="slots.info" #info>
|
||||
<slot name="info" />
|
||||
</template>
|
||||
@@ -22,16 +52,19 @@
|
||||
|
||||
<script setup lang="ts" generic="TValue extends string">
|
||||
import type { BackupJobFormOption } from '@/modules/backup-job/types/backup-job-form.type.ts'
|
||||
import UiInfo from '@core/components/ui/info/UiInfo.vue'
|
||||
import UiLabel from '@core/components/ui/label/UiLabel.vue'
|
||||
import UiRadioButton from '@core/components/ui/radio-button/UiRadioButton.vue'
|
||||
import UiRadioButtonGroup from '@core/components/ui/radio-button-group/UiRadioButtonGroup.vue'
|
||||
import UiRichRadioButton from '@core/components/ui/rich-radio-button/UiRichRadioButton.vue'
|
||||
import UiRichRadioButtonGroup from '@core/components/ui/rich-radio-button-group/UiRichRadioButtonGroup.vue'
|
||||
import { useUiStore } from '@core/stores/ui.store.ts'
|
||||
import { computed } from 'vue'
|
||||
|
||||
defineProps<{
|
||||
const { options } = defineProps<{
|
||||
label: string
|
||||
options: BackupJobFormOption<TValue>[]
|
||||
vertical?: boolean
|
||||
disabled?: boolean
|
||||
}>()
|
||||
|
||||
const model = defineModel<TValue>({ required: true })
|
||||
@@ -41,14 +74,19 @@ const slots = defineSlots<{
|
||||
}>()
|
||||
|
||||
const uiStore = useUiStore()
|
||||
|
||||
const hasDescription = computed(() => options.some(option => option.description !== undefined))
|
||||
</script>
|
||||
|
||||
<style lang="postcss" scoped>
|
||||
.backup-job-form-radio {
|
||||
.option {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.4rem;
|
||||
:deep(.group.gap--wide) {
|
||||
flex-wrap: wrap;
|
||||
row-gap: 0.8rem;
|
||||
}
|
||||
|
||||
.radio-button {
|
||||
white-space: nowrap;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -3,13 +3,13 @@
|
||||
<BackupJobFormRow>
|
||||
<div class="field">
|
||||
<UiLabel :accent="hasError ? 'danger' : 'neutral'" required>{{ label }}</UiLabel>
|
||||
<UiInput v-model.number="model" :accent="hasError ? 'danger' : 'neutral'" type="number" required />
|
||||
<UiInput v-model.number="model" :accent="hasError ? 'danger' : 'neutral'" type="number" required :disabled />
|
||||
</div>
|
||||
</BackupJobFormRow>
|
||||
|
||||
<div class="messages">
|
||||
<UiInfo accent="info" wrap>{{ t('value-by-default', { value: 1 }) }}</UiInfo>
|
||||
<div class="ephemeral typo-body-regular-small">
|
||||
<div class="ephemeral typo-body-regular">
|
||||
<span>{{ t('ephemeral-snapshot-mode:title') }}</span>
|
||||
<ul>
|
||||
<li>{{ t('ephemeral-snapshot-mode:incremental') }}</li>
|
||||
@@ -34,6 +34,7 @@ import { useI18n } from 'vue-i18n'
|
||||
const { error } = defineProps<{
|
||||
label: string
|
||||
error?: InputWrapperMessage
|
||||
disabled?: boolean
|
||||
}>()
|
||||
|
||||
const model = defineModel<number | undefined>({ required: true })
|
||||
@@ -66,7 +67,6 @@ const hasError = computed(() => errorMessage.value !== undefined)
|
||||
|
||||
.ephemeral {
|
||||
padding-inline-start: 2.4rem;
|
||||
color: var(--color-neutral-txt-secondary);
|
||||
|
||||
ul {
|
||||
padding-inline-start: 2rem;
|
||||
|
||||
@@ -37,5 +37,14 @@ const { t } = useI18n()
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.6rem;
|
||||
|
||||
:deep(.ui-subtitle) {
|
||||
margin-block-start: 1.6rem;
|
||||
}
|
||||
|
||||
:deep(.vts-tabular-key-value-list) {
|
||||
grid-template-columns: minmax(min-content, 28rem) 1fr;
|
||||
row-gap: 0.8rem;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -8,6 +8,11 @@
|
||||
:label="t('compression-type')"
|
||||
:value="compressionLabel"
|
||||
/>
|
||||
<VtsTabularKeyValueRow v-if="!isMirror" :label="t('offline-backup')">
|
||||
<template #value>
|
||||
<VtsStatus :status="form.formData.offlineBackup" />
|
||||
</template>
|
||||
</VtsTabularKeyValueRow>
|
||||
</VtsTabularKeyValueList>
|
||||
|
||||
<template v-if="isIncremental && !isMirror">
|
||||
@@ -33,22 +38,15 @@
|
||||
</VtsTabularKeyValueList>
|
||||
</template>
|
||||
|
||||
<template v-if="!isMirror">
|
||||
<template v-if="!isMirror && !form.formData.offlineBackup">
|
||||
<UiSubtitle>{{ t('snapshot') }}</UiSubtitle>
|
||||
<VtsTabularKeyValueList>
|
||||
<VtsTabularKeyValueRow :label="t('offline-backup')">
|
||||
<template #value>
|
||||
<VtsStatus :status="form.formData.offlineBackup" />
|
||||
</template>
|
||||
</VtsTabularKeyValueRow>
|
||||
<template v-if="!form.formData.offlineBackup">
|
||||
<VtsTabularKeyValueRow :label="t('snapshot-mode')" :value="snapshotModeLabel" />
|
||||
<VtsTabularKeyValueRow :label="t('snapshot-synchronisation')" :value="snapshotSyncLabel" />
|
||||
<VtsTabularKeyValueRow
|
||||
:label="t('minimum-snapshots-to-retain')"
|
||||
:value="form.formData.snapshotRetention?.toString()"
|
||||
/>
|
||||
</template>
|
||||
<VtsTabularKeyValueRow :label="t('snapshot-mode')" :value="snapshotModeLabel" />
|
||||
<VtsTabularKeyValueRow :label="t('snapshot-synchronisation')" :value="snapshotSyncLabel" />
|
||||
<VtsTabularKeyValueRow
|
||||
:label="t('minimum-snapshots-to-retain')"
|
||||
:value="form.formData.snapshotRetention?.toString()"
|
||||
/>
|
||||
</VtsTabularKeyValueList>
|
||||
</template>
|
||||
</template>
|
||||
|
||||
@@ -119,27 +119,39 @@ function findMessages(wrapper: VueWrapper) {
|
||||
return wrapper.findAll('.ui-info').map(message => message.text())
|
||||
}
|
||||
|
||||
function getEnableToggle(wrapper: VueWrapper) {
|
||||
return wrapper.get('.general .ui-toggle')
|
||||
function findStatusRadios(wrapper: VueWrapper) {
|
||||
return wrapper.findAll('.general .ui-radio-button')
|
||||
}
|
||||
|
||||
function findCheckedStatus(wrapper: VueWrapper) {
|
||||
return findStatusRadios(wrapper)
|
||||
.filter(radio => radio.get<HTMLInputElement>('input').element.checked)
|
||||
.map(radio => radio.text())
|
||||
}
|
||||
|
||||
it('enables the job by default', () => {
|
||||
const toggle = getEnableToggle(mountSourceStep())
|
||||
const wrapper = mountSourceStep()
|
||||
|
||||
expect(toggle.text()).toBe(t('action:enable'))
|
||||
expect(toggle.get<HTMLInputElement>('input').element.checked).toBe(true)
|
||||
expect(findStatusRadios(wrapper).map(radio => radio.text())).toEqual([t('action:enable'), t('action:disable')])
|
||||
expect(findCheckedStatus(wrapper)).toEqual([t('action:enable')])
|
||||
})
|
||||
|
||||
it('shows a disabled job as disabled', () => {
|
||||
expect(getEnableToggle(mountSourceStep({ enabled: false })).get<HTMLInputElement>('input').element.checked).toBe(
|
||||
false
|
||||
)
|
||||
expect(findCheckedStatus(mountSourceStep({ enabled: false }))).toEqual([t('action:disable')])
|
||||
})
|
||||
|
||||
it('disables the job', async () => {
|
||||
const wrapper = mountSourceStep()
|
||||
|
||||
await findStatusRadios(wrapper)[1].get('input').setValue(true)
|
||||
|
||||
expect(findCheckedStatus(wrapper)).toEqual([t('action:disable')])
|
||||
})
|
||||
|
||||
it('offers the data source, the backup mode and the scope of a VM backup', () => {
|
||||
const wrapper = mountSourceStep()
|
||||
|
||||
expect(findRadioLabels(wrapper)).toEqual([t('data-source'), t('backup-mode'), t('scope-type')])
|
||||
expect(findRadioLabels(wrapper)).toEqual([t('status'), t('data-source'), t('backup-mode'), t('scope-type')])
|
||||
expect(findLabels(wrapper, BackupJobFormSelect)).toEqual([])
|
||||
expect(findLabels(wrapper, BackupJobFormCheckbox)).toEqual([])
|
||||
})
|
||||
@@ -153,14 +165,14 @@ it('selects the source proxy and backup repository of a mirror backup', () => {
|
||||
it('offers the options of a metadata backup, without backup mode', () => {
|
||||
const wrapper = mountSourceStep({ dataSource: 'metadata' })
|
||||
|
||||
expect(findRadioLabels(wrapper)).toEqual([t('data-source'), t('scope-type')])
|
||||
expect(findRadioLabels(wrapper)).toEqual([t('status'), t('data-source'), t('scope-type')])
|
||||
expect(findLabels(wrapper, BackupJobFormCheckbox)).toEqual([t('save-xo-config'), t('save-pools-metadata')])
|
||||
})
|
||||
|
||||
it('selects no scope for a metadata backup saving the XO config only', () => {
|
||||
const wrapper = mountSourceStep({ dataSource: 'metadata', saveXoConfig: true, savePoolsMetadata: false })
|
||||
|
||||
expect(findRadioLabels(wrapper)).toEqual([t('data-source')])
|
||||
expect(findRadioLabels(wrapper)).toEqual([t('status'), t('data-source')])
|
||||
})
|
||||
|
||||
it('tells that the replications are excluded from the VM selection', () => {
|
||||
|
||||
@@ -1,15 +1,15 @@
|
||||
<template>
|
||||
<div class="backup-job-source-step">
|
||||
<div class="general">
|
||||
<BackupJobFormRow>
|
||||
<BackupJobFormRow class="name-status">
|
||||
<BackupJobFormTextInput v-bind="bindings.name" />
|
||||
<BackupJobFormRadio
|
||||
:label="bindings.enabled.label"
|
||||
:options="bindings.enabled.options"
|
||||
:model-value="bindings.enabled.modelValue ? 'enabled' : 'disabled'"
|
||||
@update:model-value="value => bindings.enabled['onUpdate:modelValue'](value === 'enabled')"
|
||||
/>
|
||||
</BackupJobFormRow>
|
||||
<UiToggle
|
||||
:model-value="bindings.enabled.modelValue"
|
||||
@update:model-value="value => bindings.enabled['onUpdate:modelValue'](value ?? false)"
|
||||
>
|
||||
{{ t('action:enable') }}
|
||||
</UiToggle>
|
||||
</div>
|
||||
<BackupJobFormRadio v-bind="bindings.dataSource" />
|
||||
<div v-if="!isMetadata" class="mode">
|
||||
@@ -95,7 +95,6 @@ import VtsIcon from '@core/components/icon/VtsIcon.vue'
|
||||
import VtsOption from '@core/components/select/VtsOption.vue'
|
||||
import UiInfo from '@core/components/ui/info/UiInfo.vue'
|
||||
import UiLabel from '@core/components/ui/label/UiLabel.vue'
|
||||
import UiToggle from '@core/components/ui/toggle/UiToggle.vue'
|
||||
import { computed } from 'vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
@@ -142,6 +141,10 @@ const isSourceBackupRepositoryMissing = computed(
|
||||
gap: 2.4rem;
|
||||
}
|
||||
|
||||
.name-status {
|
||||
column-gap: 8rem;
|
||||
}
|
||||
|
||||
.mode {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
useBackupJobTransferForm,
|
||||
} from '@/modules/backup-job/form/use-backup-job-transfer-form.ts'
|
||||
import type { useXoVmCollection } from '@/modules/vm/remote-resources/use-xo-vm-collection.ts'
|
||||
import { findAllGenericComponents } from '@/test/find-generic-components.ts'
|
||||
import { createGlobalTestConfig } from '@/test/global-test-config.ts'
|
||||
import { t } from '@/test/i18n.ts'
|
||||
import { mockModule } from '@/test/spy-on-module.ts'
|
||||
@@ -106,9 +107,14 @@ it('offers the snapshot mode, its synchronisation and its retention', () => {
|
||||
expect(wrapper.findComponent(BackupJobFormSnapshotRetention).exists()).toBe(true)
|
||||
})
|
||||
|
||||
it('takes no snapshot for an offline backup', () => {
|
||||
it('disables the snapshot settings of an offline backup', () => {
|
||||
const wrapper = mountTransferStep({ offlineBackup: true })
|
||||
|
||||
expect(findRadioLabels(wrapper)).not.toContain(t('snapshot-mode'))
|
||||
expect(wrapper.findComponent(BackupJobFormSnapshotRetention).exists()).toBe(false)
|
||||
const disabledRadioLabels = findAllGenericComponents(wrapper, 'BackupJobFormRadio')
|
||||
.filter(radio => radio.props('disabled'))
|
||||
.map(radio => radio.props('label'))
|
||||
|
||||
expect(wrapper.text()).toContain(t('snapshot-settings-disabled-offline-backup'))
|
||||
expect(disabledRadioLabels).toEqual([t('snapshot-mode'), t('snapshot-synchronisation')])
|
||||
expect(wrapper.findComponent(BackupJobFormSnapshotRetention).props('disabled')).toBe(true)
|
||||
})
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
</BackupJobFormRow>
|
||||
|
||||
<BackupJobFormRadio v-if="!isIncremental && !isMirror" v-bind="bindings.compression" />
|
||||
|
||||
<BackupJobFormCheckbox v-if="!isMirror" v-bind="bindings.offlineBackup" />
|
||||
</div>
|
||||
|
||||
<div v-if="isIncremental && !isMirror" class="section">
|
||||
@@ -40,19 +42,22 @@
|
||||
<div v-if="!isMirror" class="section">
|
||||
<UiTitle>{{ t('snapshot') }}</UiTitle>
|
||||
|
||||
<BackupJobFormCheckbox v-bind="bindings.offlineBackup" />
|
||||
<UiInfo v-if="bindings.offlineBackup.modelValue" accent="warning" wrap>
|
||||
{{ t('snapshot-settings-disabled-offline-backup') }}
|
||||
</UiInfo>
|
||||
|
||||
<template v-if="!bindings.offlineBackup.modelValue">
|
||||
<BackupJobFormRadio v-bind="bindings.snapshotMode" vertical />
|
||||
<BackupJobFormRadio v-bind="bindings.snapshotMode" vertical :disabled="bindings.offlineBackup.modelValue" />
|
||||
|
||||
<BackupJobFormRadio v-bind="bindings.snapshotSync" />
|
||||
<BackupJobFormRadio v-bind="bindings.snapshotSync" :disabled="bindings.offlineBackup.modelValue" />
|
||||
|
||||
<BackupJobFormRow v-if="bindings.snapshotSync.modelValue === 'smart'">
|
||||
<BackupJobFormSelect v-bind="bindings.snapshotSyncTag" />
|
||||
</BackupJobFormRow>
|
||||
<BackupJobFormRow v-if="bindings.snapshotSync.modelValue === 'smart'">
|
||||
<BackupJobFormSelect v-bind="bindings.snapshotSyncTag" />
|
||||
</BackupJobFormRow>
|
||||
|
||||
<BackupJobFormSnapshotRetention v-bind="bindings.snapshotRetention" />
|
||||
</template>
|
||||
<BackupJobFormSnapshotRetention
|
||||
v-bind="bindings.snapshotRetention"
|
||||
:disabled="bindings.offlineBackup.modelValue"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -40,6 +40,7 @@ import { useXoBackupJobTypeLabels } from '@/modules/backup-job/composables/use-x
|
||||
import type { FrontAnyXoBackupJob } from '@/modules/backup-job/remote-resources/use-xo-backup-job-collection.ts'
|
||||
import { getBackupJobHealthCheckStatus } from '@/modules/backup-job/utils/xo-backup-job.util.ts'
|
||||
import { useXoBackupLogCollection } from '@/modules/backup-log/remote-resources/use-xo-backup-log-collection.ts'
|
||||
import { useXoScheduleCollection } from '@/modules/schedule/remote-resources/use-xo-schedule-collection.ts'
|
||||
import { useXoRoutes } from '@/shared/remote-resources/use-xo-routes.ts'
|
||||
import VtsQueryBuilder from '@core/components/query-builder/VtsQueryBuilder.vue'
|
||||
import VtsRow from '@core/components/table/VtsRow.vue'
|
||||
@@ -73,6 +74,8 @@ const { buildXo5Route } = useXoRoutes()
|
||||
|
||||
const { areBackupLogsReady } = useXoBackupLogCollection()
|
||||
|
||||
const { schedulesByJobId } = useXoScheduleCollection()
|
||||
|
||||
const { items: queryFilteredBackupJobs, searchBindings } = useQueryBuilderFilter('backup-jobs', () => backupJobs)
|
||||
|
||||
const { filteredBackupJobs, statusSelectId, lastRunsStatusSelectId, lastDaysStatusSelectId } =
|
||||
@@ -122,6 +125,7 @@ const { HeadCells, BodyCells } = useBackupJobColumns({
|
||||
const modeLabel = useXoBackupJobModeLabel(() => backupJob)
|
||||
const lastRuns = useXoBackupJobLastRuns(() => backupJob)
|
||||
const healthCheckStatus = computed(() => getBackupJobHealthCheckStatus(backupJob))
|
||||
const hasMultipleSchedules = computed(() => (schedulesByJobId.value.get(backupJob.id)?.length ?? 0) > 1)
|
||||
|
||||
const { isEnabled, moreActions, deleteAction } = useXoBackupJobActions(() => backupJob)
|
||||
|
||||
@@ -136,6 +140,9 @@ const { HeadCells, BodyCells } = useBackupJobColumns({
|
||||
label: backupJob.name ?? t('untitled'),
|
||||
href: jobOverviewHref.value,
|
||||
icon: 'object:backup-job',
|
||||
rightIcon: hasMultipleSchedules.value
|
||||
? { icon: 'status:warning-circle', tooltip: t('multiple-schedules-split-in-xo5') }
|
||||
: undefined,
|
||||
}),
|
||||
type: r => r(typeLabels.value[0] ?? '', { extraCount: typeLabels.value.length - 1 }),
|
||||
mode: r => r(modeLabel.value),
|
||||
|
||||
@@ -9,7 +9,6 @@ import { mockXoRoutes } from '@/test/mock-xo-routes.ts'
|
||||
import VtsDivider from '@core/components/divider/VtsDivider.vue'
|
||||
import VtsStatus from '@core/components/status/VtsStatus.vue'
|
||||
import UiLink from '@core/components/ui/link/UiLink.vue'
|
||||
import UiPanelCardTitle from '@core/components/ui/panel-card-title/UiPanelCardTitle.vue'
|
||||
import { formatDateTime } from '@core/utils/time.util.ts'
|
||||
import { mount, type VueWrapper } from '@vue/test-utils'
|
||||
|
||||
@@ -72,12 +71,11 @@ it('shows the status of each schedule when there are several', () => {
|
||||
expect(statuses.map(status => status.props('status'))).toEqual([true, false])
|
||||
})
|
||||
|
||||
it('counts the schedules and separates them', () => {
|
||||
it('separates the schedules', () => {
|
||||
const wrapper = mountSchedulesCard([
|
||||
createSchedule({ id: 'schedule-1' as FrontXoSchedule['id'] }),
|
||||
createSchedule({ id: 'schedule-2' as FrontXoSchedule['id'] }),
|
||||
])
|
||||
|
||||
expect(wrapper.getComponent(UiPanelCardTitle).props('counter')).toBe(2)
|
||||
expect(wrapper.findAllComponents(VtsDivider)).toHaveLength(1)
|
||||
})
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<template>
|
||||
<UiPanelCard class="backup-job-schedules-card">
|
||||
<UiPanelCardTitle size="medium" :label="t('schedules')" :counter="schedules.length" />
|
||||
<UiPanelCardTitle size="medium" :label="t('schedule')" />
|
||||
<VtsCardRowList class="content">
|
||||
<template v-for="({ schedule, nextRun }, index) in schedulesWithNextRun" :key="schedule.id">
|
||||
<VtsDivider v-if="index > 0" class="divider" type="stretch" />
|
||||
|
||||
@@ -205,6 +205,11 @@ export function useBackupJobSourceForm(formData: BackupJobSourceFormData) {
|
||||
{ label: dataSourceLabels.value.metadata, value: 'metadata' },
|
||||
])
|
||||
|
||||
const statusOptions = computed<BackupJobFormOption<'enabled' | 'disabled'>[]>(() => [
|
||||
{ label: t('action:enable'), value: 'enabled' },
|
||||
{ label: t('action:disable'), value: 'disabled' },
|
||||
])
|
||||
|
||||
const modeLabels = computed<Record<BackupJobMode, string>>(() => ({
|
||||
delta: t('incremental'),
|
||||
full: t('full'),
|
||||
@@ -255,7 +260,7 @@ export function useBackupJobSourceForm(formData: BackupJobSourceFormData) {
|
||||
|
||||
const bindings = reactive({
|
||||
name: useField('name', () => ({ label: t('name'), required: true })),
|
||||
enabled: useField('enabled'),
|
||||
enabled: useField('enabled', () => ({ label: t('status'), options: statusOptions.value })),
|
||||
dataSource: useField('dataSource', () => ({ label: t('data-source'), options: dataSourceOptions.value })),
|
||||
mode: useField('mode', () => ({ label: t('backup-mode'), options: modeOptions.value })),
|
||||
saveXoConfig: useField('saveXoConfig', () => ({ label: t('save-xo-config') })),
|
||||
|
||||
@@ -180,6 +180,7 @@ export function useBackupJobTransferForm(
|
||||
const { id: snapshotSyncTagSelectId } = useFormSelect('snapshotSyncTag', vmTags, {
|
||||
searchable: true,
|
||||
required: true,
|
||||
disabled: () => formData.offlineBackup,
|
||||
})
|
||||
|
||||
const bindings = reactive({
|
||||
|
||||
@@ -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>
|
||||
|
||||
@@ -2,10 +2,10 @@
|
||||
<UiHeadBar icon="object:pool">
|
||||
{{ pool.name_label }}
|
||||
<template #actions>
|
||||
<PoolAddHostButton :pool-id="pool.id" />
|
||||
<UiLink size="medium" :to="{ name: '/vm/new', query: { poolid: pool.id } }" icon="fa:plus">
|
||||
{{ t('new-vm') }}
|
||||
</UiLink>
|
||||
<PoolAddHostButton :pool-id="pool.id" />
|
||||
</template>
|
||||
</UiHeadBar>
|
||||
<TabList :label="pool.name_label">
|
||||
|
||||
@@ -34,9 +34,6 @@
|
||||
<RouterLink v-slot="{ isExactActive, href }" :to="{ name: '/(site)/vms' }" custom>
|
||||
<UiTabItem :active="isExactActive" :href tag="a">{{ t('vms') }}</UiTabItem>
|
||||
</RouterLink>
|
||||
<RouterLink v-slot="{ isExactActive, href }" :to="{ name: '/(site)/patches' }" custom>
|
||||
<UiTabItem :active="isExactActive" :href tag="a">{{ t('patches') }}</UiTabItem>
|
||||
</RouterLink>
|
||||
</TabList>
|
||||
</template>
|
||||
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
<template>
|
||||
<UiTitle>{{ t('patches:n-available', packages.length) }}</UiTitle>
|
||||
|
||||
<VtsTable :state :pagination-bindings sticky="right">
|
||||
<thead>
|
||||
<tr>
|
||||
<HeadCells />
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
<VtsRow v-for="upgradablePackage of paginatedPackages" :key="upgradablePackage.name">
|
||||
<BodyCells :item="upgradablePackage" />
|
||||
</VtsRow>
|
||||
</tbody>
|
||||
</VtsTable>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import { useXoPackageUpgradeJob } from '@/modules/xoa/jobs/xo-package-upgrade.job.ts'
|
||||
import VtsRow from '@core/components/table/VtsRow.vue'
|
||||
import VtsTable from '@core/components/table/VtsTable.vue'
|
||||
import UiTitle from '@core/components/ui/title/UiTitle.vue'
|
||||
import { usePagination } from '@core/composables/pagination.composable.ts'
|
||||
import { useTableState } from '@core/composables/table-state.composable.ts'
|
||||
import { useUpgradablePackageColumns } from '@core/tables/column-sets/upgradable-package-columns.ts'
|
||||
import type { UpgradablePackage } from '@vates/types'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
const { packages, busy, error } = defineProps<{
|
||||
packages: UpgradablePackage[]
|
||||
busy: boolean
|
||||
error: boolean
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
const { pageRecords: paginatedPackages, paginationBindings } = usePagination('upgradable-packages', () => packages)
|
||||
|
||||
const state = useTableState({
|
||||
busy: () => busy,
|
||||
error: () => error,
|
||||
empty: () => (packages.length === 0 ? { type: 'all-done', message: t('patches-up-to-date') } : false),
|
||||
})
|
||||
|
||||
const { HeadCells, BodyCells } = useUpgradablePackageColumns({
|
||||
body: (upgradablePackage: UpgradablePackage) => {
|
||||
// the job is shared by all rows (one apt operation at a time): rows are disabled, not busy
|
||||
const { run, canRun } = useXoPackageUpgradeJob(upgradablePackage.name)
|
||||
|
||||
return {
|
||||
name: r => r(upgradablePackage.name),
|
||||
version: r => r(`${upgradablePackage.installedVersion} → ${upgradablePackage.version}`),
|
||||
description: r => r(upgradablePackage.description),
|
||||
upgrade: r => r(t('action:upgrade'), () => run(), { disabled: !canRun.value }),
|
||||
}
|
||||
},
|
||||
})
|
||||
</script>
|
||||
@@ -1,32 +0,0 @@
|
||||
<template>
|
||||
<UiModal accent="warning" icon="status:warning-picto" @confirm="emit('confirm')" @dismiss="emit('cancel')">
|
||||
<template #title>{{ t('patches:upgrade-all') }}</template>
|
||||
|
||||
<template #content>
|
||||
{{ t('patches:upgrade-all-confirm', count) }}
|
||||
</template>
|
||||
|
||||
<template #buttons>
|
||||
<VtsOverlayCancelButton @click="emit('cancel')">{{ t('action:go-back') }}</VtsOverlayCancelButton>
|
||||
<VtsOverlayConfirmButton>{{ t('action:upgrade-all') }}</VtsOverlayConfirmButton>
|
||||
</template>
|
||||
</UiModal>
|
||||
</template>
|
||||
|
||||
<script lang="ts" setup>
|
||||
import VtsOverlayCancelButton from '@core/components/overlay/VtsOverlayCancelButton.vue'
|
||||
import VtsOverlayConfirmButton from '@core/components/overlay/VtsOverlayConfirmButton.vue'
|
||||
import UiModal from '@core/components/ui/modal/UiModal.vue'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
defineProps<{
|
||||
count: number
|
||||
}>()
|
||||
|
||||
const emit = defineEmits<{
|
||||
confirm: []
|
||||
cancel: []
|
||||
}>()
|
||||
|
||||
const { t } = useI18n()
|
||||
</script>
|
||||
@@ -1,24 +0,0 @@
|
||||
import { useXoPackageUpdates } from '@/modules/xoa/remote-resources/use-xo-package-updates.ts'
|
||||
import { fetchPost } from '@/shared/utils/fetch.util.ts'
|
||||
import { defineJob, JobRunningError } from '@core/packages/job'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
/**
|
||||
* Refresh the package indexes of the appliance, then reload the upgradable packages
|
||||
*/
|
||||
export const useXoPackageRefreshJob = defineJob('package.refresh', [], () => {
|
||||
const { t } = useI18n()
|
||||
const { $context } = useXoPackageUpdates()
|
||||
|
||||
return {
|
||||
async run() {
|
||||
await fetchPost('plugins/package-manager/updates/actions/refresh')
|
||||
await $context.forceReload()
|
||||
},
|
||||
validate(isRunning) {
|
||||
if (isRunning) {
|
||||
throw new JobRunningError(t('job:package-refresh:in-progress'))
|
||||
}
|
||||
},
|
||||
}
|
||||
})
|
||||
@@ -1,42 +0,0 @@
|
||||
import type { FrontXoTask } from '@/modules/task/remote-resources/use-xo-task-collection.ts'
|
||||
import { useXoPackageUpdates } from '@/modules/xoa/remote-resources/use-xo-package-updates.ts'
|
||||
import { useXoTaskUtils } from '@/shared/composables/xo-task-utils.composable.ts'
|
||||
import { fetchPost } from '@/shared/utils/fetch.util.ts'
|
||||
import { defineJob, defineJobArg, JobRunningError } from '@core/packages/job'
|
||||
import { useI18n } from 'vue-i18n'
|
||||
|
||||
// apt runs one operation at a time: the package is not part of the identity
|
||||
const xoPackageNameArg = defineJobArg<string | undefined>({
|
||||
identify: false,
|
||||
toArray: false,
|
||||
})
|
||||
|
||||
/**
|
||||
* Upgrade one package, or all upgradable packages when the package name is undefined
|
||||
*/
|
||||
export const useXoPackageUpgradeJob = defineJob('package.upgrade', [xoPackageNameArg], () => {
|
||||
const { t } = useI18n()
|
||||
const { monitorTask } = useXoTaskUtils()
|
||||
const { $context } = useXoPackageUpdates()
|
||||
|
||||
return {
|
||||
async run(packageName) {
|
||||
const endpoint =
|
||||
packageName === undefined
|
||||
? 'plugins/package-manager/updates/actions/upgrade'
|
||||
: `plugins/package-manager/updates/${encodeURIComponent(packageName)}/actions/upgrade`
|
||||
|
||||
try {
|
||||
const { taskId } = await fetchPost<{ taskId: FrontXoTask['id'] }>(endpoint)
|
||||
await monitorTask(taskId)
|
||||
} finally {
|
||||
await $context.forceReload()
|
||||
}
|
||||
},
|
||||
validate(isRunning) {
|
||||
if (isRunning) {
|
||||
throw new JobRunningError(t('job:package-upgrade:in-progress'))
|
||||
}
|
||||
},
|
||||
}
|
||||
})
|
||||
@@ -1,27 +0,0 @@
|
||||
import { BASE_URL } from '@/shared/utils/fetch.util.ts'
|
||||
import { defineRemoteResource } from '@core/packages/remote-resource/define-remote-resource.ts'
|
||||
import type { UpgradablePackage } from '@vates/types'
|
||||
import { computed } from 'vue'
|
||||
|
||||
export type XoPackageUpdates = {
|
||||
packages: UpgradablePackage[]
|
||||
isRebootRequired: boolean
|
||||
}
|
||||
|
||||
// served by the `package-manager` plugin
|
||||
export const useXoPackageUpdates = defineRemoteResource({
|
||||
url: `${BASE_URL}/plugins/package-manager/updates`,
|
||||
initialData: (): XoPackageUpdates => ({ packages: [], isRebootRequired: false }),
|
||||
// listing calls apt on the appliance: only reload after a refresh or an upgrade
|
||||
pollingIntervalMs: false,
|
||||
// the default merge would mutate `packages` in place (same reference, not reactive) and never shrink it
|
||||
onDataReceived: async (updates, receivedUpdates: XoPackageUpdates) => {
|
||||
updates.value = receivedUpdates
|
||||
},
|
||||
state: (updates, context) => ({
|
||||
upgradablePackages: computed(() => updates.value.packages),
|
||||
isRebootRequired: computed(() => updates.value.isRebootRequired),
|
||||
arePackageUpdatesReady: context.isReady,
|
||||
hasPackageUpdatesFetchError: context.hasError,
|
||||
}),
|
||||
})
|
||||
@@ -1,122 +0,0 @@
|
||||
<template>
|
||||
<div class="container">
|
||||
<div class="actions">
|
||||
<UiButton
|
||||
accent="brand"
|
||||
variant="secondary"
|
||||
size="medium"
|
||||
left-icon="fa:rotate-left"
|
||||
:disabled="!isPackageManagerLoaded || !canRefresh"
|
||||
:busy="isRefreshing"
|
||||
@click="refresh()"
|
||||
>
|
||||
{{ t('action:update') }}
|
||||
</UiButton>
|
||||
<UiButton
|
||||
accent="brand"
|
||||
variant="primary"
|
||||
size="medium"
|
||||
:disabled="!isPackageManagerLoaded || !canUpgrade || upgradablePackages.length === 0"
|
||||
:busy="isUpgrading"
|
||||
@click="openUpgradeAllModal()"
|
||||
>
|
||||
{{ t('action:upgrade-all') }}
|
||||
</UiButton>
|
||||
</div>
|
||||
<UiAlert v-if="isPackageManagerLoaded === false" accent="danger">
|
||||
<I18nT keypath="patches:plugin-not-loaded" scope="global">
|
||||
<template #plugin>
|
||||
<UiLink size="small" :to="getPluginRoute(PACKAGE_MANAGER_PLUGIN_ID)">{{ PACKAGE_MANAGER_PLUGIN_ID }}</UiLink>
|
||||
</template>
|
||||
</I18nT>
|
||||
</UiAlert>
|
||||
<VtsBanner v-if="isRebootRequired" accent="warning">
|
||||
{{ t('patches:reboot-required') }}
|
||||
</VtsBanner>
|
||||
<UiCard v-if="isPackageManagerLoaded">
|
||||
<UpgradablePackagesTable
|
||||
:packages="upgradablePackages"
|
||||
:busy="!arePackageUpdatesReady"
|
||||
:error="hasPackageUpdatesFetchError"
|
||||
/>
|
||||
</UiCard>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup lang="ts">
|
||||
import {
|
||||
type FrontXoPlugin,
|
||||
useXoPluginCollection,
|
||||
} from '@/modules/plugin/remote-resources/use-xo-plugin-collection.ts'
|
||||
import { getPluginRoute, isPluginLoaded } from '@/modules/plugin/utils/xo-plugin.util.ts'
|
||||
import UpgradablePackagesTable from '@/modules/xoa/components/UpgradablePackagesTable.vue'
|
||||
import { useXoPackageRefreshJob } from '@/modules/xoa/jobs/xo-package-refresh.job.ts'
|
||||
import { useXoPackageUpgradeJob } from '@/modules/xoa/jobs/xo-package-upgrade.job.ts'
|
||||
import { useXoPackageUpdates } from '@/modules/xoa/remote-resources/use-xo-package-updates.ts'
|
||||
import VtsBanner from '@core/components/banner/VtsBanner.vue'
|
||||
import UiAlert from '@core/components/ui/alert/UiAlert.vue'
|
||||
import UiButton from '@core/components/ui/button/UiButton.vue'
|
||||
import UiCard from '@core/components/ui/card/UiCard.vue'
|
||||
import UiLink from '@core/components/ui/link/UiLink.vue'
|
||||
import { useOverlay } from '@core/packages/overlay/use-overlay.ts'
|
||||
import { computed, watch } from 'vue'
|
||||
import { I18nT, useI18n } from 'vue-i18n'
|
||||
|
||||
const { t } = useI18n()
|
||||
|
||||
// the routes of the plugin only exist while it is loaded
|
||||
const PACKAGE_MANAGER_PLUGIN_ID = 'package-manager' as FrontXoPlugin['id']
|
||||
|
||||
const { getPluginById, arePluginsReady } = useXoPluginCollection()
|
||||
|
||||
// undefined until the plugins are fetched
|
||||
const isPackageManagerLoaded = computed(() => {
|
||||
if (!arePluginsReady.value) {
|
||||
return undefined
|
||||
}
|
||||
const plugin = getPluginById(PACKAGE_MANAGER_PLUGIN_ID)
|
||||
return plugin !== undefined && isPluginLoaded(plugin)
|
||||
})
|
||||
|
||||
const { upgradablePackages, isRebootRequired, arePackageUpdatesReady, hasPackageUpdatesFetchError, $context } =
|
||||
useXoPackageUpdates()
|
||||
|
||||
// the packages were fetched before the plugin was loaded from the plugins page
|
||||
watch(isPackageManagerLoaded, (isLoaded, wasLoaded) => {
|
||||
if (isLoaded === true && wasLoaded === false) {
|
||||
void $context.forceReload()
|
||||
}
|
||||
})
|
||||
|
||||
const { run: refresh, canRun: canRefresh, isRunning: isRefreshing } = useXoPackageRefreshJob()
|
||||
|
||||
const { run: upgradeAll, canRun: canUpgrade, isRunning: isUpgrading } = useXoPackageUpgradeJob(undefined)
|
||||
|
||||
const { open } = useOverlay({
|
||||
component: () => import('@/modules/xoa/components/modal/PackageUpgradeAllModal.vue'),
|
||||
events: {
|
||||
onConfirm: () => upgradeAll({ detached: true }),
|
||||
onCancel: true,
|
||||
},
|
||||
})
|
||||
|
||||
function openUpgradeAllModal() {
|
||||
return open({ props: { count: upgradablePackages.value.length } })
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped lang="postcss">
|
||||
.container {
|
||||
height: fit-content;
|
||||
gap: 0.8rem;
|
||||
margin: 0.8rem;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
|
||||
.actions {
|
||||
display: flex;
|
||||
justify-content: flex-end;
|
||||
gap: 0.8rem;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
15
@xen-orchestra/web/src/route-map.d.ts
vendored
15
@xen-orchestra/web/src/route-map.d.ts
vendored
@@ -37,7 +37,6 @@ declare module 'vue-router/auto-routes' {
|
||||
Record<never, never>,
|
||||
| '/(site)/dashboard'
|
||||
| '/(site)/hosts'
|
||||
| '/(site)/patches'
|
||||
| '/(site)/pools'
|
||||
| '/(site)/tasks'
|
||||
| '/(site)/vms'
|
||||
@@ -56,13 +55,6 @@ declare module 'vue-router/auto-routes' {
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/(site)/patches': RouteRecordInfo<
|
||||
'/(site)/patches',
|
||||
'/patches',
|
||||
Record<never, never>,
|
||||
Record<never, never>,
|
||||
| never
|
||||
>,
|
||||
'/(site)/pools': RouteRecordInfo<
|
||||
'/(site)/pools',
|
||||
'/pools',
|
||||
@@ -549,7 +541,6 @@ declare module 'vue-router/auto-routes' {
|
||||
| '/(site)'
|
||||
| '/(site)/dashboard'
|
||||
| '/(site)/hosts'
|
||||
| '/(site)/patches'
|
||||
| '/(site)/pools'
|
||||
| '/(site)/tasks'
|
||||
| '/(site)/vms'
|
||||
@@ -568,12 +559,6 @@ declare module 'vue-router/auto-routes' {
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/pages/(site)/patches.vue': {
|
||||
routes:
|
||||
| '/(site)/patches'
|
||||
views:
|
||||
| never
|
||||
}
|
||||
'src/pages/(site)/pools.vue': {
|
||||
routes:
|
||||
| '/(site)/pools'
|
||||
|
||||
@@ -11,8 +11,12 @@
|
||||
|
||||
- [Backups] A backup job running in the xo-server process (`backups.disableWorkers`) can be aborted from its task (tasks view, REST API, or the "run schedule" action): the reads and writes stop, the partial backups are removed and the VMs are reported as interrupted (PR [#10875](https://github.com/vatesfr/xen-orchestra/pull/10875))
|
||||
- [@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))
|
||||
- [Plugins/package-manager] New plugin to list and upgrade the Debian packages of the XO appliance with apt: REST routes restricted to administrators, upgrades run in XO tasks, package indexes refreshed every 12 hours (PR [#9659](https://github.com/vatesfr/xen-orchestra/pull/9659))
|
||||
- [XO6/Patches] New "Patches" tab on the site page: update the package list, upgrade all packages or a single one, and see when the appliance needs a reboot, once the package-manager plugin is loaded (PR [#9659](https://github.com/vatesfr/xen-orchestra/pull/9659))
|
||||
- [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
|
||||
|
||||
@@ -20,6 +24,10 @@
|
||||
|
||||
- [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 +47,16 @@
|
||||
|
||||
- @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-package-manager minor
|
||||
- xo-server-sdn-controller patch
|
||||
- xo-web minor
|
||||
|
||||
<!--packages-end-->
|
||||
|
||||
145
docs/docs/backups-and-dr/backup_chain_repair.md
Normal file
145
docs/docs/backups-and-dr/backup_chain_repair.md
Normal 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).
|
||||
@@ -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
|
||||
|
||||
@@ -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` |
|
||||
|
||||
BIN
docs/static/img/xo5/backup-log-broken-chain.png
vendored
Normal file
BIN
docs/static/img/xo5/backup-log-broken-chain.png
vendored
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 84 KiB |
BIN
docs/static/img/xo5/delete-vm-backups.png
vendored
Normal file
BIN
docs/static/img/xo5/delete-vm-backups.png
vendored
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 38 KiB |
BIN
docs/static/img/xo6/vm-snapshot-delete.png
vendored
Normal file
BIN
docs/static/img/xo6/vm-snapshot-delete.png
vendored
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 24 KiB |
@@ -1,14 +0,0 @@
|
||||
Lists and upgrades the Debian packages of the XO appliance (apt only). Once loaded, the following REST routes are
|
||||
available to administrators:
|
||||
|
||||
| Route | Description |
|
||||
| --------------------------------------------------------------------- | ------------------------------------------------------------ |
|
||||
| `GET /rest/v0/plugins/package-manager/updates` | Upgradable packages (from the local indexes) and reboot flag |
|
||||
| `POST /rest/v0/plugins/package-manager/updates/actions/refresh` | `apt-get update` |
|
||||
| `POST /rest/v0/plugins/package-manager/updates/actions/upgrade` | Upgrade all packages, returns a task |
|
||||
| `POST /rest/v0/plugins/package-manager/updates/:name/actions/upgrade` | Upgrade one package, returns a task |
|
||||
|
||||
Upgrades never prompt: a configuration file which has been modified locally is kept as is, and the version shipped by
|
||||
the package is written next to it with a `.dpkg-dist` suffix, to be merged by hand.
|
||||
|
||||
The full apt output is in `/var/log/apt/term.log`.
|
||||
@@ -1 +0,0 @@
|
||||
../../scripts/npmignore
|
||||
@@ -1,37 +0,0 @@
|
||||
<!-- DO NOT EDIT MANUALLY, THIS FILE HAS BEEN GENERATED -->
|
||||
|
||||
# xo-server-package-manager
|
||||
|
||||
> XO Server plugin for managing system packages (apt) on the XO appliance
|
||||
|
||||
## Usage
|
||||
|
||||
Lists and upgrades the Debian packages of the XO appliance (apt only). Once loaded, the following REST routes are
|
||||
available to administrators:
|
||||
|
||||
| Route | Description |
|
||||
| --------------------------------------------------------------------- | ------------------------------------------------------------ |
|
||||
| `GET /rest/v0/plugins/package-manager/updates` | Upgradable packages (from the local indexes) and reboot flag |
|
||||
| `POST /rest/v0/plugins/package-manager/updates/actions/refresh` | `apt-get update` |
|
||||
| `POST /rest/v0/plugins/package-manager/updates/actions/upgrade` | Upgrade all packages, returns a task |
|
||||
| `POST /rest/v0/plugins/package-manager/updates/:name/actions/upgrade` | Upgrade one package, returns a task |
|
||||
|
||||
Upgrades never prompt: a configuration file which has been modified locally is kept as is, and the version shipped by
|
||||
the package is written next to it with a `.dpkg-dist` suffix, to be merged by hand.
|
||||
|
||||
The full apt output is in `/var/log/apt/term.log`.
|
||||
|
||||
## Contributions
|
||||
|
||||
Contributions are _very_ welcomed, either on the documentation or on
|
||||
the code.
|
||||
|
||||
You may:
|
||||
|
||||
- report any [issue](https://github.com/vatesfr/xen-orchestra/issues)
|
||||
you've encountered;
|
||||
- fork and create a pull request.
|
||||
|
||||
## License
|
||||
|
||||
[AGPL-3.0-or-later](https://spdx.org/licenses/AGPL-3.0-or-later) © [Vates SAS](https://vates.fr)
|
||||
@@ -1,50 +0,0 @@
|
||||
{
|
||||
"name": "xo-server-package-manager",
|
||||
"version": "0.1.0",
|
||||
"license": "AGPL-3.0-or-later",
|
||||
"description": "XO Server plugin for managing system packages (apt) on the XO appliance",
|
||||
"type": "module",
|
||||
"keywords": [
|
||||
"xen-orchestra",
|
||||
"xo-server",
|
||||
"plugin",
|
||||
"package-manager",
|
||||
"apt",
|
||||
"upgrade"
|
||||
],
|
||||
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/packages/xo-server-package-manager",
|
||||
"bugs": "https://github.com/vatesfr/xen-orchestra/issues",
|
||||
"repository": {
|
||||
"directory": "packages/xo-server-package-manager",
|
||||
"type": "git",
|
||||
"url": "https://github.com/vatesfr/xen-orchestra.git"
|
||||
},
|
||||
"author": {
|
||||
"name": "Vates SAS",
|
||||
"url": "https://vates.fr"
|
||||
},
|
||||
"main": "dist/index.mjs",
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
},
|
||||
"dependencies": {
|
||||
"@vates/types": "^2.5.0",
|
||||
"@xen-orchestra/log": "^0.7.1",
|
||||
"xo-common": "^0.11.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^20.0.0",
|
||||
"rimraf": "^6.0.1",
|
||||
"typescript": "^5.0.0"
|
||||
},
|
||||
"scripts": {
|
||||
"build": "tsc",
|
||||
"clean": "rimraf dist/",
|
||||
"dev": "yarn run clean && tsc --watch",
|
||||
"prebuild": "yarn run clean",
|
||||
"prepublishOnly": "yarn run build",
|
||||
"test": "cd dist && node --test",
|
||||
"test-integration": "cd dist && node --test apt.integ.mjs"
|
||||
},
|
||||
"private": true
|
||||
}
|
||||
@@ -1,51 +0,0 @@
|
||||
/**
|
||||
* Integration tests of the apt wrapper
|
||||
*
|
||||
* Requires a Debian system with apt and root access, upgrades one real package
|
||||
*
|
||||
* Run: sudo node --test dist/apt.integ.mjs
|
||||
*/
|
||||
import assert from 'node:assert/strict'
|
||||
import { describe, it } from 'node:test'
|
||||
import { checkAptAvailable, listUpgradablePackages, upgradePackages } from './apt.mjs'
|
||||
|
||||
describe('apt', () => {
|
||||
it('checkAptAvailable does not throw on a Debian system', async () => {
|
||||
await checkAptAvailable()
|
||||
})
|
||||
|
||||
it('listUpgradablePackages returns packages with all fields', async () => {
|
||||
for (const pkg of await listUpgradablePackages()) {
|
||||
assert.ok(pkg.name !== '')
|
||||
assert.ok(pkg.version !== '', `version of ${pkg.name}`)
|
||||
assert.ok(pkg.installedVersion !== '', `installed version of ${pkg.name}`)
|
||||
assert.ok(pkg.release !== '', `release of ${pkg.name}`)
|
||||
assert.equal(typeof pkg.description, 'string')
|
||||
}
|
||||
})
|
||||
|
||||
it('upgrades a single package and reports progress', async t => {
|
||||
const packages = await listUpgradablePackages()
|
||||
const target = packages.find(p => p.name === 'tzdata') ?? packages.find(p => p.name === 'distro-info-data')
|
||||
if (target === undefined) {
|
||||
t.skip('no safe package to upgrade')
|
||||
return
|
||||
}
|
||||
|
||||
const progresses: number[] = []
|
||||
await upgradePackages({ packageName: target.name, onProgress: percentage => progresses.push(percentage) })
|
||||
|
||||
assert.equal(progresses.at(-1), 100)
|
||||
assert.equal(
|
||||
(await listUpgradablePackages()).find(p => p.name === target.name),
|
||||
undefined
|
||||
)
|
||||
})
|
||||
|
||||
it('rejects an invalid package name', async () => {
|
||||
await assert.rejects(
|
||||
upgradePackages({ packageName: '-oAPT::foo=bar', onProgress: () => {} }),
|
||||
/invalid package name/
|
||||
)
|
||||
})
|
||||
})
|
||||
@@ -1,185 +0,0 @@
|
||||
import type { UpgradablePackage } from '@vates/types'
|
||||
import { createLogger } from '@xen-orchestra/log'
|
||||
import { execFile, spawn } from 'node:child_process'
|
||||
import { access } from 'node:fs/promises'
|
||||
import { promisify } from 'node:util'
|
||||
import {
|
||||
type AptStatus,
|
||||
getOverallPercentage,
|
||||
parseDescriptions,
|
||||
parseStatusFdLine,
|
||||
parseUpgradableList,
|
||||
} from './parse.mjs'
|
||||
|
||||
const log = createLogger('xo:xo-server-package-manager:apt')
|
||||
|
||||
const execFileAsync = promisify(execFile)
|
||||
|
||||
const APT_GET_PATH = '/usr/bin/apt-get'
|
||||
const APT_PATH = '/usr/bin/apt'
|
||||
const APT_CACHE_PATH = '/usr/bin/apt-cache'
|
||||
const REBOOT_REQUIRED_PATH = '/var/run/reboot-required'
|
||||
|
||||
// `apt-get update` fetches the indexes from the mirrors
|
||||
const UPDATE_TIMEOUT = 5 * 60e3
|
||||
// a stalled mirror is already covered by apt's own acquire timeout: this is for a hung maintainer script
|
||||
const UPGRADE_TIMEOUT = 60 * 60e3
|
||||
|
||||
// Debian policy: lowercase alphanumerics, `+`, `-` and `.`, starting with an alphanumeric
|
||||
// apt names the packages of a foreign architecture `name:arch`
|
||||
const PACKAGE_NAME_RE = /^[a-z0-9][a-z0-9+.-]+(:[a-z0-9-]+)?$/
|
||||
|
||||
// `LC_ALL=C`: `parseUpgradableList()` and `upgradePackages()` match apt's English output
|
||||
const APT_ENV = { ...process.env, DEBIAN_FRONTEND: 'noninteractive', LC_ALL: 'C' }
|
||||
|
||||
async function exec(cmd: string, args: string[], { timeout = 0 } = {}): Promise<string> {
|
||||
try {
|
||||
const { stdout } = await execFileAsync(cmd, args, { env: APT_ENV, maxBuffer: 10 * 1024 * 1024, timeout })
|
||||
return stdout
|
||||
} catch (err) {
|
||||
const error = new Error(`${cmd} ${args.join(' ')} failed`)
|
||||
error.cause = err
|
||||
Object.assign(error, { stderr: (err as { stderr?: string }).stderr })
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
export async function checkAptAvailable(): Promise<void> {
|
||||
try {
|
||||
await access(APT_GET_PATH)
|
||||
} catch (err) {
|
||||
const error = new Error(`${APT_GET_PATH} not found, this plugin requires a Debian-based system`)
|
||||
error.cause = err
|
||||
throw error
|
||||
}
|
||||
}
|
||||
|
||||
export function isValidPackageName(name: string): boolean {
|
||||
return PACKAGE_NAME_RE.test(name)
|
||||
}
|
||||
|
||||
export async function isRebootRequired(): Promise<boolean> {
|
||||
try {
|
||||
await access(REBOOT_REQUIRED_PATH)
|
||||
return true
|
||||
} catch (error) {
|
||||
// dpkg creates this file when an upgraded package needs a reboot
|
||||
if ((error as NodeJS.ErrnoException).code !== 'ENOENT') {
|
||||
log.warn('failed to check whether a reboot is required', { error, path: REBOOT_REQUIRED_PATH })
|
||||
}
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Refresh the package indexes (`apt-get update`)
|
||||
*/
|
||||
export async function refreshPackageIndexes(): Promise<void> {
|
||||
await exec(APT_GET_PATH, ['update', '-q'], { timeout: UPDATE_TIMEOUT })
|
||||
}
|
||||
|
||||
/**
|
||||
* List upgradable packages from the local indexes, see `refreshPackageIndexes()`
|
||||
*/
|
||||
export async function listUpgradablePackages(): Promise<UpgradablePackage[]> {
|
||||
const upgradablePackages = parseUpgradableList(await exec(APT_PATH, ['list', '--upgradable']))
|
||||
if (upgradablePackages.length === 0) {
|
||||
return []
|
||||
}
|
||||
|
||||
const descriptions = parseDescriptions(await exec(APT_CACHE_PATH, ['show', ...upgradablePackages.map(p => p.name)]))
|
||||
return upgradablePackages.map(pkg => ({ ...pkg, description: descriptions.get(pkg.name) ?? '' }))
|
||||
}
|
||||
|
||||
/**
|
||||
* Upgrade one package, or all upgradable packages if `packageName` is undefined
|
||||
*
|
||||
* `apt-get upgrade` never installs new dependencies: a package which needs one stays upgradable until it is upgraded
|
||||
* on its own.
|
||||
*/
|
||||
export async function upgradePackages({
|
||||
packageName,
|
||||
onProgress,
|
||||
onStatus,
|
||||
}: {
|
||||
readonly packageName?: string
|
||||
readonly onProgress: (percentage: number) => void
|
||||
readonly onStatus?: (status: AptStatus) => void
|
||||
}): Promise<void> {
|
||||
const args = [
|
||||
'-y',
|
||||
'-q',
|
||||
// keep the local version of modified config files instead of prompting
|
||||
'-o',
|
||||
'Dpkg::Options::=--force-confdef',
|
||||
'-o',
|
||||
'Dpkg::Options::=--force-confold',
|
||||
'-o',
|
||||
'APT::Status-Fd=3',
|
||||
]
|
||||
if (packageName === undefined) {
|
||||
args.push('upgrade')
|
||||
} else {
|
||||
if (!isValidPackageName(packageName)) {
|
||||
throw new Error(`invalid package name: ${packageName}`)
|
||||
}
|
||||
// unlike `upgrade`, `install` can remove a conflicting package: abort instead
|
||||
args.push('install', '--only-upgrade', '--no-remove', packageName)
|
||||
}
|
||||
|
||||
// the full output is already logged by apt in /var/log/apt/term.log
|
||||
const child = spawn(APT_GET_PATH, args, {
|
||||
env: APT_ENV,
|
||||
stdio: ['ignore', 'ignore', 'pipe', 'pipe'],
|
||||
// SIGTERM after the timeout
|
||||
timeout: UPGRADE_TIMEOUT,
|
||||
})
|
||||
|
||||
let stderr = ''
|
||||
child.stderr!.setEncoding('utf8').on('data', (chunk: string) => {
|
||||
stderr += chunk
|
||||
})
|
||||
|
||||
let hasDownloaded = false
|
||||
let pendingStatus = ''
|
||||
const statusFd = child.stdio[3] as NodeJS.ReadableStream
|
||||
statusFd.setEncoding('utf8')
|
||||
statusFd.on('data', (chunk: string) => {
|
||||
const lines = (pendingStatus + chunk).split('\n')
|
||||
pendingStatus = lines.pop()!
|
||||
for (const line of lines) {
|
||||
const status = parseStatusFdLine(line)
|
||||
if (status !== undefined) {
|
||||
hasDownloaded ||= status.phase === 'download'
|
||||
onProgress(getOverallPercentage(status, hasDownloaded))
|
||||
onStatus?.(status)
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
const exitCode = await new Promise<number | null>((resolve, reject) => {
|
||||
child.on('error', reject)
|
||||
child.on('close', resolve)
|
||||
// killed by the timeout: the hung dpkg keeps the pipes open, `close` would never fire
|
||||
child.on('exit', code => {
|
||||
if (child.killed) {
|
||||
resolve(code)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
if (exitCode !== 0) {
|
||||
let message: string
|
||||
if (child.killed) {
|
||||
message = `apt-get killed after ${UPGRADE_TIMEOUT / 60e3} minutes, run \`dpkg --configure -a\` on the appliance if it was interrupted`
|
||||
} else if (stderr.includes('Could not get lock') || stderr.includes('Unable to acquire')) {
|
||||
message = 'another package operation is in progress'
|
||||
} else {
|
||||
message = `apt-get failed with exit code ${exitCode}`
|
||||
}
|
||||
const error = new Error(message)
|
||||
Object.assign(error, { packageName, stderr })
|
||||
throw error
|
||||
}
|
||||
onProgress(100)
|
||||
}
|
||||
@@ -1,3 +0,0 @@
|
||||
declare module 'xo-common/api-errors.js' {
|
||||
export function invalidParameters(message?: string, errors?: unknown): Error
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user