Compare commits

..

3 Commits

73 changed files with 960 additions and 813 deletions

View File

@@ -101,21 +101,6 @@ 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
@@ -350,7 +335,6 @@ export interface Xapi {
checkLimits?: (limits: Record<string, number>, vm: XenApiVmWrapped) => Promise<void>
): Promise<void>
editVif(id: XoVif['id'], props: EditVifProps): Promise<void>
editNetwork(id: XoNetwork['id'], props: EditNetworkProps): Promise<void>
startVm(
id: XoVm['id'],
opts?: {

View File

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

View File

@@ -4,6 +4,9 @@
- [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))
- [VM/Network] Add a link to the pool network in the VIF side panel and table (PR [#10686](https://github.com/vatesfr/xen-orchestra/pull/10686))
- [VIF] Add a VIF page with general and network information, linked from the VM network table and the VIF side panel (PR [#10686](https://github.com/vatesfr/xen-orchestra/pull/10686))
- [Host] Add possibility to enable SSH on XCP-ng 9 hosts, and to disable it with auto-enable if XAPI goes down. The SSH status is shown in the host dashboard and System tab (PR [#10974](https://github.com/vatesfr/xen-orchestra/pull/10974))
## **0.28.0** (2026/12/01)

View File

@@ -19,7 +19,7 @@ const props = defineProps<{
id?: I
}>()
const route = useRoute<'/pool/[uuid]' | '/host/[uuid]' | '/vm/[uuid]'>()
const route = useRoute<'/pool/[uuid]' | '/host/[uuid]' | '/vm/[uuid]' | '/vif/[uuid]'>()
const id = computed(() => props.id ?? (route.params.uuid as I))

View File

@@ -8,6 +8,11 @@
</template>
</VtsKeyValueRow>
<VtsKeyValueRow :label="t('ip-address')" :value="host.address" copy />
<VtsKeyValueRow v-if="isSshManageable" :label="t('ssh')">
<template #value>
<VtsStatus :status="host.ssh_enabled ?? false" />
</template>
</VtsKeyValueRow>
<VtsKeyValueRow :label="t('started')" :value="isRunning ? relativeStartTime : undefined" />
<VtsKeyValueRow :label="t('master')">
<template #value>
@@ -49,7 +54,7 @@
<script lang="ts" setup>
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import { useHostUtils } from '@/modules/host/composables/host-utils.composable.ts'
import { getHostCoreSocketInfo, getHostManufacturerInfo } from '@/modules/host/utils/host.util.ts'
import { getHostCoreSocketInfo, getHostManufacturerInfo, isHostSshManageable } from '@/modules/host/utils/host.util.ts'
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
import { useHostStore } from '@/stores/xen-api/host.store.ts'
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
@@ -57,6 +62,7 @@ import VtsIcon from '@core/components/icon/VtsIcon.vue'
import VtsKeyValueList from '@core/components/key-value-list/VtsKeyValueList.vue'
import VtsKeyValueRow from '@core/components/key-value-row/VtsKeyValueRow.vue'
import VtsQuickInfoCard from '@core/components/quick-info-card/VtsQuickInfoCard.vue'
import VtsStatus from '@core/components/status/VtsStatus.vue'
import VtsTag from '@core/components/tag/VtsTag.vue'
import UiLink from '@core/components/ui/link/UiLink.vue'
import UiTagsList from '@core/components/ui/tag/UiTagsList.vue'
@@ -84,6 +90,8 @@ const manufacturerInfo = computed(() => getHostManufacturerInfo(host))
const coreSocketInfo = computed(() => getHostCoreSocketInfo(host))
const isSshManageable = computed(() => isHostSshManageable(host))
const ram = computed(() => {
const memory = getHostMemory(host)

View File

@@ -5,6 +5,11 @@
</UiTitle>
<VtsTabularKeyValueList>
<VtsTabularKeyValueRow :label="t('ip-address')" :value="host.address" copy />
<VtsTabularKeyValueRow v-if="isSshManageable" :label="t('ssh')">
<template #value>
<VtsStatus :status="host.ssh_enabled ?? false" />
</template>
</VtsTabularKeyValueRow>
<VtsTabularKeyValueRow :label="t('remote-syslog')" :value="host.logging.syslog_destination" />
<VtsTabularKeyValueRow :label="t('iscsi-iqn')" :value="host.iscsi_iqn" copy />
<VtsTabularKeyValueRow :label="t('multi-pathing')">
@@ -18,16 +23,20 @@
<script setup lang="ts">
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import { isHostSshManageable } from '@/modules/host/utils/host.util.ts'
import VtsStatus from '@core/components/status/VtsStatus.vue'
import VtsTabularKeyValueList from '@core/components/tabular-key-value-list/VtsTabularKeyValueList.vue'
import VtsTabularKeyValueRow from '@core/components/tabular-key-value-row/VtsTabularKeyValueRow.vue'
import UiCard from '@core/components/ui/card/UiCard.vue'
import UiTitle from '@core/components/ui/title/UiTitle.vue'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
defineProps<{
const { host } = defineProps<{
host: XenApiHost
}>()
const { t } = useI18n()
const isSshManageable = computed(() => isHostSshManageable(host))
</script>

View File

@@ -85,6 +85,7 @@
<script setup lang="ts">
import PifRow from '@/components/pif/PifRow.vue'
import type { XenApiNetwork } from '@/libs/xen-api/xen-api.types.ts'
import { useNetworkUtils } from '@/modules/network/composables/network-utils.composable.ts'
import { useNetworkDelete } from '@/modules/network/composables/use-network-delete.composable.ts'
import { usePifStore } from '@/stores/xen-api/pif.store.ts'
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
@@ -108,6 +109,7 @@ const emit = defineEmits<{
}>()
const { getPifsByNetworkRef } = usePifStore().subscribe()
const { getNetworkVlan } = useNetworkUtils()
const { t } = useI18n()
@@ -115,13 +117,7 @@ const { deleteNetworks, isDeletingNetworks } = useNetworkDelete(() => (network !
const pifs = computed(() => (network !== undefined ? getPifsByNetworkRef(network.$ref) : []))
const networkVlan = computed(() => {
if (pifs.value.length === 0) {
return
}
return pifs.value[0].VLAN !== -1 ? pifs.value[0].VLAN.toString() : t('none')
})
const networkVlan = computed(() => (network !== undefined ? getNetworkVlan(network) : undefined))
const networkNbd = computed(() => (network?.purpose[0] ? t('on') : t('off')))

View File

@@ -20,6 +20,10 @@ export function createHostOperations(xenApi: XenApi) {
const restartAgent = (hostRef: HostRef) => xenApi.call('host.restart_agent', [hostRef])
const enableSsh = (hostRef: HostRef) => xenApi.call('host.enable_ssh', [hostRef])
const setSshAutoMode = (hostRef: HostRef, value: boolean) => xenApi.call('host.set_ssh_auto_mode', [hostRef, value])
const clearHost = async (hostRef: HostRef, force: boolean) => {
await disable(hostRef)
@@ -41,6 +45,8 @@ export function createHostOperations(xenApi: XenApi) {
powerOn,
destroy,
restartAgent,
enableSsh,
setSshAutoMode,
cleanReboot: async (hostRef: HostRef, forceReboot: boolean) => {
await clearHost(hostRef, forceReboot)

View File

@@ -164,6 +164,7 @@ export interface XenApiHost extends XenApiRecord<'host'> {
multipathing: boolean
enabled: boolean
PGPUs: XenApiPgpu['$ref'][]
ssh_enabled?: boolean
}
export interface XenApiSr extends XenApiRecord<'sr'> {

View File

@@ -13,6 +13,10 @@
<HostRestartToolstackButton :host />
<HostDisableButton v-if="displayDisableButton" :host />
<HostEnableButton v-else :host />
<template v-if="isSshManageable">
<HostDisableSshButton v-if="host.ssh_enabled" :host />
<HostEnableSshButton v-else :host />
</template>
<HostDetachButton :host />
<HostForgetButton :host />
<VtsDivider v-if="layout !== 'sections'" type="stretch" />
@@ -23,12 +27,15 @@
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import HostDetachButton from '@/modules/host/components/actions/detach/HostDetachButton.vue'
import HostDisableButton from '@/modules/host/components/actions/disable/HostDisableButton.vue'
import HostDisableSshButton from '@/modules/host/components/actions/disable-ssh/HostDisableSshButton.vue'
import HostDownloadButton from '@/modules/host/components/actions/download/HostDownloadButton.vue'
import HostEnableButton from '@/modules/host/components/actions/enable/HostEnableButton.vue'
import HostEnableSshButton from '@/modules/host/components/actions/enable-ssh/HostEnableSshButton.vue'
import HostForgetButton from '@/modules/host/components/actions/forget/HostForgetButton.vue'
import HostPowerStateActions from '@/modules/host/components/actions/HostPowerStateActions.vue'
import HostRestartToolstackButton from '@/modules/host/components/actions/restart-toolstack/HostRestartToolstackButton.vue'
import type { HostQuickAction } from '@/modules/host/composables/host-quick-actions.composable.ts'
import { isHostSshManageable } from '@/modules/host/utils/host.util.ts'
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
import VtsDivider from '@core/components/divider/VtsDivider.vue'
import VtsChangeStateMenuItem from '@core/components/menu/VtsChangeStateMenuItem.vue'
@@ -54,4 +61,6 @@ const { getHostPowerState } = useHostMetricsStore().subscribe()
const isHostHalted = computed(() => getHostPowerState(host) === HOST_POWER_STATE.HALTED)
const displayDisableButton = computed(() => host.enabled || isHostHalted.value)
const isSshManageable = computed(() => isHostSshManageable(host))
</script>

View File

@@ -0,0 +1,52 @@
<template>
<MenuItem
v-tooltip="!canDisableSsh && disableSshErrorMessage"
accent="neutral"
:busy="isDisablingSsh"
:disabled="!canDisableSsh"
icon="action:disable"
@click="disableSsh()"
>
{{ t('action:disable-ssh') }}
<i class="em-dash-prefix">{{ t('auto-enable-if-xapi-goes-down') }}</i>
</MenuItem>
</template>
<script lang="ts" setup>
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import { useHostDisableSshJob } from '@/modules/host/jobs/host-disable-ssh.job.ts'
import MenuItem from '@core/components/menu/MenuItem.vue'
import { useActionModal } from '@core/composables/modals/use-action-modal.ts'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import { useI18n } from 'vue-i18n'
const { host } = defineProps<{
host: XenApiHost
}>()
const { t } = useI18n()
const { open: openActionModal } = useActionModal()
const {
run,
canRun: canDisableSsh,
isRunning: isDisablingSsh,
errorMessage: disableSshErrorMessage,
} = useHostDisableSshJob(() => host)
function disableSsh() {
return openActionModal({
props: {
accent: 'info',
action: 'disable-ssh',
object: 'host',
hostName: host.name_label,
icon: 'status:info-picto',
},
events: {
onConfirm: () => run({ detached: true }),
},
})
}
</script>

View File

@@ -7,7 +7,7 @@
icon="action:disable"
@click="disableHost()"
>
{{ t('action:disable') }}
{{ t('action:disable-host') }}
</MenuItem>
</template>

View File

@@ -0,0 +1,51 @@
<template>
<MenuItem
v-tooltip="!canEnableSsh && enableSshErrorMessage"
accent="neutral"
:busy="isEnablingSsh"
:disabled="!canEnableSsh"
icon="status:success-circle"
@click="enableSsh()"
>
{{ t('action:enable-ssh') }}
</MenuItem>
</template>
<script lang="ts" setup>
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import { useHostEnableSshJob } from '@/modules/host/jobs/host-enable-ssh.job.ts'
import MenuItem from '@core/components/menu/MenuItem.vue'
import { useActionModal } from '@core/composables/modals/use-action-modal.ts'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import { useI18n } from 'vue-i18n'
const { host } = defineProps<{
host: XenApiHost
}>()
const { t } = useI18n()
const { open: openActionModal } = useActionModal()
const {
run,
canRun: canEnableSsh,
isRunning: isEnablingSsh,
errorMessage: enableSshErrorMessage,
} = useHostEnableSshJob(() => host)
function enableSsh() {
return openActionModal({
props: {
accent: 'info',
action: 'enable-ssh',
object: 'host',
hostName: host.name_label,
icon: 'status:info-picto',
},
events: {
onConfirm: () => run({ detached: true }),
},
})
}
</script>

View File

@@ -7,7 +7,7 @@
icon="status:success-circle"
@click="enableHost()"
>
{{ t('action:enable') }}
{{ t('action:enable-host') }}
</MenuItem>
</template>

View File

@@ -0,0 +1,34 @@
import { hostArg } from '@/modules/host/jobs/host-args.ts'
import { isHostSshManageable } from '@/modules/host/utils/host.util.ts'
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
import { useXenApiStore } from '@/stores/xen-api.store.ts'
import { defineJob, JobError, JobRunningError } from '@core/packages/job'
import { useI18n } from 'vue-i18n'
export const useHostDisableSshJob = defineJob('host.disable-ssh', [hostArg], () => {
const xapi = useXenApiStore().getXapi()
const { t } = useI18n()
const { isHostRunning } = useHostMetricsStore().subscribe()
return {
run: host => xapi.host.setSshAutoMode(host.$ref, true),
validate: (isRunning, host) => {
if (host === undefined) {
throw new JobError(t('job:host-disable-ssh:missing-host'))
}
if (isRunning) {
throw new JobRunningError(t('job:host-disable-ssh:in-progress'))
}
if (!isHostSshManageable(host)) {
throw new JobError(t('job:host-disable-ssh:unsupported-version'))
}
if (!isHostRunning(host)) {
throw new JobError(t('job:host-disable-ssh:bad-power-state'))
}
},
}
})

View File

@@ -0,0 +1,34 @@
import { hostArg } from '@/modules/host/jobs/host-args.ts'
import { isHostSshManageable } from '@/modules/host/utils/host.util.ts'
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
import { useXenApiStore } from '@/stores/xen-api.store.ts'
import { defineJob, JobError, JobRunningError } from '@core/packages/job'
import { useI18n } from 'vue-i18n'
export const useHostEnableSshJob = defineJob('host.enable-ssh', [hostArg], () => {
const xapi = useXenApiStore().getXapi()
const { t } = useI18n()
const { isHostRunning } = useHostMetricsStore().subscribe()
return {
run: host => xapi.host.enableSsh(host.$ref),
validate: (isRunning, host) => {
if (host === undefined) {
throw new JobError(t('job:host-enable-ssh:missing-host'))
}
if (isRunning) {
throw new JobRunningError(t('job:host-enable-ssh:in-progress'))
}
if (!isHostSshManageable(host)) {
throw new JobError(t('job:host-enable-ssh:unsupported-version'))
}
if (!isHostRunning(host)) {
throw new JobError(t('job:host-enable-ssh:bad-power-state'))
}
},
}
})

View File

@@ -3,6 +3,7 @@ import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import { objectIcon } from '@core/icons'
import { HOST_POWER_STATE } from '@vates/types'
import { castArray } from 'lodash-es'
import { coerce, satisfies } from 'semver'
export type HostState = Lowercase<HOST_POWER_STATE> | 'disabled'
@@ -45,6 +46,9 @@ export const getHostState = (host: XenApiHost | undefined, powerState: HOST_POWE
return host.enabled ? 'running' : 'disabled'
}
export const isHostSshManageable = (host: XenApiHost) =>
satisfies(coerce(host.software_version.product_version) ?? '', '>=8.99')
export const getHostIcon = (host: XenApiHost | undefined, powerState: HOST_POWER_STATE) =>
objectIcon('host', getHostState(host, powerState))

View File

@@ -2,9 +2,12 @@ import type { XenApiNetwork } from '@/libs/xen-api/xen-api.types.ts'
import { usePifMetricsStore } from '@/stores/xen-api/pif-metrics.store.ts'
import { usePifStore } from '@/stores/xen-api/pif.store.ts'
import { getConnectionStatus } from '@core/utils/connection.util.ts'
import { useI18n } from 'vue-i18n'
export function useNetworkUtils() {
const { records: pifs } = usePifStore().subscribe()
const { t } = useI18n()
const { records: pifs, getPifsByNetworkRef } = usePifStore().subscribe()
const { getPifCarrier } = usePifMetricsStore().subscribe()
function getNetworkStatus(network: XenApiNetwork) {
@@ -13,5 +16,15 @@ export function useNetworkUtils() {
return getConnectionStatus(networkPifs.map(pif => pif.currently_attached && getPifCarrier(pif)))
}
return { getNetworkStatus }
function getNetworkVlan(network: XenApiNetwork) {
const networkPifs = getPifsByNetworkRef(network.$ref)
if (networkPifs.length === 0) {
return
}
return networkPifs[0].VLAN !== -1 ? networkPifs[0].VLAN.toString() : t('none')
}
return { getNetworkStatus, getNetworkVlan }
}

View File

@@ -0,0 +1,72 @@
<template>
<div class="breadcrumb-container">
<UiBreadcrumb :size>
<UiLink v-if="vm" :size :to="{ name: '/vm/[uuid]/dashboard', params: { uuid: vm.uuid } }">
<VtsObjectIcon type="vm" :state="vmPowerState" size="current" />
{{ vm.name_label }}
</UiLink>
<UiLink v-if="vm && network" :size :to="{ name: '/vm/[uuid]/network', params: { uuid: vm.uuid } }">
{{ t('network') }}
</UiLink>
<span>
<VtsIcon name="object:vif" size="current" />
{{ t('vif-device', { device: vif.device }) }}
</span>
</UiBreadcrumb>
</div>
<UiHeadBar icon="object:vif">
{{ t('vif-device', { device: vif.device }) }}
</UiHeadBar>
<TabList :label="t('vif-device', { device: vif.device })">
<RouterTab :to="{ name: '/vif/[uuid]/general', params: { uuid: vif.uuid } }">
{{ t('general') }}
</RouterTab>
</TabList>
</template>
<script setup lang="ts">
import RouterTab from '@/components/RouterTab.vue'
import type { XenApiVif } from '@/libs/xen-api/xen-api.types.ts'
import { useNetworkStore } from '@/stores/xen-api/network.store.ts'
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
import VtsIcon from '@core/components/icon/VtsIcon.vue'
import VtsObjectIcon from '@core/components/object-icon/VtsObjectIcon.vue'
import TabList from '@core/components/tab-list/TabList.vue'
import UiBreadcrumb from '@core/components/ui/breadcrumb/UiBreadcrumb.vue'
import UiHeadBar from '@core/components/ui/head-bar/UiHeadBar.vue'
import UiLink from '@core/components/ui/link/UiLink.vue'
import { useUiStore } from '@core/stores/ui.store.ts'
import { toLower } from 'lodash-es'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { vif } = defineProps<{ vif: XenApiVif }>()
const { t } = useI18n()
const uiStore = useUiStore()
const size = computed(() => (uiStore.isSmall ? 'small' : 'medium'))
const { getByOpaqueRef: getVmByOpaqueRef } = useVmStore().subscribe()
const { getByOpaqueRef: getNetworkByOpaqueRef } = useNetworkStore().subscribe()
const vm = computed(() => getVmByOpaqueRef(vif.VM))
const network = computed(() => getNetworkByOpaqueRef(vif.network))
const vmPowerState = computed(() => toLower(vm.value?.power_state))
</script>
<style lang="postcss" scoped>
.breadcrumb-container {
min-height: 5.6rem;
padding: 1.2rem 1.6rem;
display: flex;
gap: 1.6rem;
align-items: center;
border-bottom: 0.1rem solid var(--color-neutral-border);
background-color: var(--color-neutral-background-primary);
justify-content: space-between;
overflow-y: auto;
}
</style>

View File

@@ -22,12 +22,16 @@
</div>
</template>
<script lang="ts" setup>
import type { XenApiNetwork, XenApiVif, XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
<script setup lang="ts">
import type { XenApiVif, XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import { getPoolNetworkRoute } from '@/modules/network/utils/network.util.ts'
import { useVifConnection } from '@/modules/vif/composables/use-vif-connection.composable.ts'
import { useVifDelete } from '@/modules/vif/composables/use-vif-delete.composable.ts'
import { useVifEdit } from '@/modules/vif/composables/use-vif-edit.composable.ts'
import { useVifUtils } from '@/modules/vif/composables/vif-utils.composable.ts'
import { getVifRoute } from '@/modules/vif/utils/vif.util.ts'
import { useNetworkStore } from '@/stores/xen-api/network.store.ts'
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
import { useVifStore } from '@/stores/xen-api/vif.store.ts'
import { useVmGuestMetricsStore } from '@/stores/xen-api/vm-guest-metrics.store.ts'
import VtsRow from '@core/components/table/VtsRow.vue'
@@ -38,16 +42,18 @@ import { usePagination } from '@core/composables/pagination.composable.ts'
import { useRouteQuery } from '@core/composables/route-query.composable.ts'
import { useSearchFilter } from '@core/composables/search-filter.composable.ts'
import { useTableState } from '@core/composables/table-state.composable.ts'
import { icon } from '@core/icons'
import { useMapper } from '@core/packages/mapper'
import { type ActionItem } from '@core/tables/column-definitions/action-column.ts'
import { useVifColumns } from '@core/tables/column-sets/vif-columns.ts'
import { CONNECTION_ACTION } from '@core/types/connection.ts'
import { useVifNetworkColumns } from '@core/tables/column-sets/vif-network-columns.ts'
import { renderBodyCell } from '@core/tables/helpers/render-body-cell.ts'
import { CONNECTION_ACTION, CONNECTION_STATUS } from '@core/types/connection.ts'
import { getUniqueIpAddressesForDevice } from '@core/utils/ip-address.utils.ts'
import { logicNot } from '@vueuse/math'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { vifs, vm } = defineProps<{
const { vifs: rawVifs, vm } = defineProps<{
vifs: XenApiVif[]
vm: XenApiVm
}>()
@@ -56,17 +62,29 @@ defineSlots<{
'title-actions'(): any
}>()
const { isReady, hasError } = useVifStore().subscribe()
const { getByOpaqueRef: getNetworkByOpaqueRef } = useNetworkStore().subscribe()
const { getByOpaqueRef: getGuestMetricsByOpaqueRef } = useVmGuestMetricsStore().subscribe()
const { isReady, hasError } = useVifStore().subscribe()
const { pool } = usePoolStore().subscribe()
const { t } = useI18n()
const { goToVifEdit } = useVifEdit()
const selectedVifId = useRouteQuery('id')
const getNetworkName = (networkRef: XenApiNetwork['$ref']) => getNetworkByOpaqueRef(networkRef)?.name_label ?? ''
const getNetworkName = (vif: XenApiVif) => getNetworkByOpaqueRef(vif.network)?.name_label ?? ''
const { items: filteredVifs, searchBindings } = useSearchFilter(
() => rawVifs,
vif => [...Object.values(vif), getNetworkName(vif)]
)
const state = useTableState({
busy: logicNot(isReady),
error: hasError,
empty: () =>
rawVifs.length === 0 ? t('no-vif-detected') : filteredVifs.value.length === 0 ? { type: 'no-result' } : false,
})
const getIpAddresses = (vif: XenApiVif) => {
const networks = getGuestMetricsByOpaqueRef(vm.guest_metrics)?.networks
@@ -74,25 +92,20 @@ const getIpAddresses = (vif: XenApiVif) => {
return getUniqueIpAddressesForDevice(networks, vif.device)
}
const { items: filteredVifs, searchBindings } = useSearchFilter(
() => vifs,
vif => [...Object.values(vif), getNetworkName(vif.network)]
)
const state = useTableState({
busy: logicNot(isReady),
error: hasError,
empty: () =>
vifs.length === 0 ? t('no-vif-detected') : filteredVifs.value.length === 0 ? { type: 'no-result' } : false,
})
const { pageRecords: paginatedVifs, paginationBindings } = usePagination('vifs', filteredVifs)
const { HeadCells, BodyCells } = useVifColumns({
const { HeadCells, BodyCells } = useVifNetworkColumns({
body: (vif: XenApiVif) => {
const name = computed(() => getNetworkName(vif.network))
const ipAddresses = computed(() => getIpAddresses(vif))
const network = computed(() => getNetworkByOpaqueRef(vif.network))
const poolNetworkRoute = computed(() =>
pool.value && network.value ? getPoolNetworkRoute(pool.value.uuid, network.value.uuid) : undefined
)
const { lockingModeLabel } = useVifUtils(() => vif)
const {
connectVifs,
disconnectVifs,
@@ -133,13 +146,26 @@ const { HeadCells, BodyCells } = useVifColumns({
)
return {
network: r => r({ label: name.value }),
vif: r =>
r({
label: t('vif'),
to: getVifRoute(vif.uuid),
icon: icon('object:vif'),
}),
network: r =>
network.value
? r({
label: network.value.name_label,
to: poolNetworkRoute.value,
icon: icon('object:network'),
})
: renderBodyCell(),
device: r => r(t('vif-device', { device: vif.device })),
status: r => r(vif.currently_attached ? 'connected' : 'disconnected'),
status: r => r(vif.currently_attached ? CONNECTION_STATUS.CONNECTED : CONNECTION_STATUS.DISCONNECTED),
ipsAddresses: r => r(ipAddresses.value),
macAddresses: r => r(vif.MAC),
mtu: r => r(vif.MTU),
lockingMode: r => r(vif.locking_mode),
lockingMode: r => r(lockingModeLabel.value),
actions: r =>
r({
onClick: () => (selectedVifId.value = vif.uuid),

View File

@@ -0,0 +1,88 @@
<template>
<UiCard>
<UiTitle>
{{ t('general-information') }}
</UiTitle>
<VtsTabularKeyValueList>
<VtsTabularKeyValueRow :label="t('name')" :value="vifDevice" />
<VtsTabularKeyValueRow :label="t('uuid')">
<template #value>
<VtsCodeSnippet :content="vif.uuid" />
</template>
</VtsTabularKeyValueRow>
<VtsTabularKeyValueRow :label="t('network')">
<template v-if="network" #value>
<UiLink size="medium" :to="networkTo" icon="object:network">
{{ network.name_label }}
</UiLink>
</template>
</VtsTabularKeyValueRow>
<VtsTabularKeyValueRow :label="t('device')" :value="vifDevice" />
<VtsTabularKeyValueRow :label="t('vif-status')">
<template #value>
<VtsStatus :status="vifStatus" />
</template>
</VtsTabularKeyValueRow>
<VtsTabularKeyValueRow :label="t('vlan')" :value="networkVlan" />
<VtsTabularKeyValueRow :label="t('mtu')" :value="String(vif.MTU)" />
<VtsTabularKeyValueRow :label="t('rate-limit')" :value="rateLimit" />
<VtsTabularKeyValueRow :label="t('locking-mode')" :value="lockingModeLabel">
<template v-if="vif.locking_mode === VIF_LOCKING_MODE.DISABLED" #value>
<VtsStatus status="disabled" />
</template>
</VtsTabularKeyValueRow>
<VtsTabularKeyValueRow :label="t('check-summing')">
<template #value>
<VtsStatus :status="txChecksumming" />
</template>
</VtsTabularKeyValueRow>
</VtsTabularKeyValueList>
</UiCard>
</template>
<script setup lang="ts">
import type { XenApiVif } from '@/libs/xen-api/xen-api.types.ts'
import { useNetworkUtils } from '@/modules/network/composables/network-utils.composable.ts'
import { getPoolNetworkRoute } from '@/modules/network/utils/network.util.ts'
import { useVifUtils } from '@/modules/vif/composables/vif-utils.composable.ts'
import { useNetworkStore } from '@/stores/xen-api/network.store.ts'
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
import VtsCodeSnippet from '@core/components/code-snippet/VtsCodeSnippet.vue'
import VtsStatus from '@core/components/status/VtsStatus.vue'
import VtsTabularKeyValueList from '@core/components/tabular-key-value-list/VtsTabularKeyValueList.vue'
import VtsTabularKeyValueRow from '@core/components/tabular-key-value-row/VtsTabularKeyValueRow.vue'
import UiCard from '@core/components/ui/card/UiCard.vue'
import UiLink from '@core/components/ui/link/UiLink.vue'
import UiTitle from '@core/components/ui/title/UiTitle.vue'
import { CONNECTION_STATUS } from '@core/types/connection.ts'
import { VIF_LOCKING_MODE } from '@vates/types'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { vif } = defineProps<{ vif: XenApiVif }>()
const { t } = useI18n()
const { getByOpaqueRef: getNetworkByOpaqueRef } = useNetworkStore().subscribe()
const { pool } = usePoolStore().subscribe()
const { lockingModeLabel, rateLimit: rawRateLimit, txChecksumming } = useVifUtils(() => vif)
const { getNetworkVlan } = useNetworkUtils()
const network = computed(() => getNetworkByOpaqueRef(vif.network))
const networkTo = computed(() =>
pool.value && network.value ? getPoolNetworkRoute(pool.value.uuid, network.value.uuid) : undefined
)
const networkVlan = computed(() => (network.value !== undefined ? getNetworkVlan(network.value) : undefined))
const vifStatus = computed(() =>
vif.currently_attached ? CONNECTION_STATUS.CONNECTED : CONNECTION_STATUS.DISCONNECTED
)
const vifDevice = computed(() => t('vif-device', { device: vif.device }))
const rateLimit = computed(() =>
rawRateLimit.value !== undefined ? `${rawRateLimit.value} ${t('bytes:kbs')}` : undefined
)
</script>

View File

@@ -0,0 +1,55 @@
<template>
<UiCard>
<UiTitle>
{{ t('vif-network-info') }}
</UiTitle>
<VtsTabularKeyValueList>
<VtsTabularKeyValueRow :label="t('ip-addresses')">
<template v-if="ipAddresses.length" #value>
<div class="ip-list">
<span v-for="ip in ipAddresses" :key="ip">{{ ip }}</span>
</div>
</template>
</VtsTabularKeyValueRow>
<VtsTabularKeyValueRow :label="t('mac-address')" :value="vif.MAC" />
</VtsTabularKeyValueList>
</UiCard>
</template>
<script setup lang="ts">
import type { XenApiVif } from '@/libs/xen-api/xen-api.types.ts'
import { useVmGuestMetricsStore } from '@/stores/xen-api/vm-guest-metrics.store.ts'
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
import VtsTabularKeyValueList from '@core/components/tabular-key-value-list/VtsTabularKeyValueList.vue'
import VtsTabularKeyValueRow from '@core/components/tabular-key-value-row/VtsTabularKeyValueRow.vue'
import UiCard from '@core/components/ui/card/UiCard.vue'
import UiTitle from '@core/components/ui/title/UiTitle.vue'
import { getUniqueIpAddressesForDevice } from '@core/utils/ip-address.utils.ts'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { vif } = defineProps<{ vif: XenApiVif }>()
const { t } = useI18n()
const { getByOpaqueRef: getVmByOpaqueRef } = useVmStore().subscribe()
const { getByOpaqueRef: getGuestMetricsByOpaqueRef } = useVmGuestMetricsStore().subscribe()
const ipAddresses = computed(() => {
const vm = getVmByOpaqueRef(vif.VM)
if (vm === undefined) {
return []
}
return getUniqueIpAddressesForDevice(getGuestMetricsByOpaqueRef(vm.guest_metrics)?.networks, vif.device)
})
</script>
<style scoped lang="postcss">
.ip-list {
display: flex;
flex-direction: column;
gap: 0.4rem;
}
</style>

View File

@@ -1,5 +1,5 @@
<template>
<VtsSidePanel :has-selection="!!vif" class="vm-vifs-side-panel" @close="emit('close')">
<VtsSidePanel :has-selection="!!vif" class="vif-side-panel" @close="emit('close')">
<template v-if="vif" #actions>
<VifEditButton :vif />
<VifConnectionToggleButton v-if="vm" :vif :vm />
@@ -8,15 +8,19 @@
<template v-if="vif" #default>
<!-- VIF -->
<UiPanelCard>
<UiPanelCardTitle :id="vif.uuid" size="medium" :label="t('vif')" />
<UiPanelCardTitle :id="vif.uuid" size="medium" :to="vifTo" :label="t('vif')" icon="object:vif" />
<VtsCardRowList>
<!-- NETWORK -->
<VtsCardRowKeyValue>
<template #key>
{{ t('network') }}
</template>
<template #value>{{ network?.name_label }}</template>
<template v-if="network?.name_label" #addons>
<template #value>
<UiLink v-if="network" size="small" :to="networkTo" icon="object:network">
{{ network.name_label }}
</UiLink>
</template>
<template v-if="network" #addons>
<VtsCopyButton :value="network.name_label" />
</template>
</VtsCardRowKeyValue>
@@ -68,7 +72,7 @@
{{ t('locking-mode') }}
</template>
<template #value>
{{ vif.locking_mode }}
{{ lockingModeLabel }}
</template>
</VtsCardRowKeyValue>
<!-- TX CHECK SUMMING -->
@@ -77,12 +81,12 @@
{{ t('check-summing') }}
</template>
<template #value>
{{ isTxChecksummingEnabled(vif) }}
{{ txChecksumming }}
</template>
</VtsCardRowKeyValue>
</VtsCardRowList>
</UiPanelCard>
<!-- VIF NETWORK INFORMATION -->
<!-- NETWORK INFORMATION -->
<UiPanelCard>
<UiPanelCardTitle size="medium" :label="t('network-information')" />
<VtsCardRowList>
@@ -110,11 +114,14 @@
<script setup lang="ts">
import type { XenApiVif } from '@/libs/xen-api/xen-api.types.ts'
import { getPoolNetworkRoute } from '@/modules/network/utils/network.util.ts'
import VifConnectionToggleButton from '@/modules/vif/components/actions/connection/VifConnectionToggleButton.vue'
import VifDeleteButton from '@/modules/vif/components/actions/delete/VifDeleteButton.vue'
import VifEditButton from '@/modules/vif/components/actions/edit/VifEditButton.vue'
import { isTxChecksummingEnabled } from '@/modules/vif/utils/vif-tx-checksumming.util.ts'
import { useVifUtils } from '@/modules/vif/composables/vif-utils.composable.ts'
import { getVifRoute } from '@/modules/vif/utils/vif.util.ts'
import { useNetworkStore } from '@/stores/xen-api/network.store.ts'
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
import { useVmGuestMetricsStore } from '@/stores/xen-api/vm-guest-metrics.store.ts'
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
@@ -122,8 +129,10 @@ import VtsCardRowList from '@core/components/card/VtsCardRowList.vue'
import VtsCopyButton from '@core/components/copy-button/VtsCopyButton.vue'
import VtsSidePanel from '@core/components/panel/VtsSidePanel.vue'
import VtsStatus from '@core/components/status/VtsStatus.vue'
import UiLink from '@core/components/ui/link/UiLink.vue'
import UiPanelCard from '@core/components/ui/panel-card/UiPanelCard.vue'
import UiPanelCardTitle from '@core/components/ui/panel-card-title/UiPanelCardTitle.vue'
import { CONNECTION_STATUS } from '@core/types/connection.ts'
import { getUniqueIpAddressesForDevice } from '@core/utils/ip-address.utils.ts'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
@@ -141,8 +150,13 @@ const { t } = useI18n()
const { getByOpaqueRef: getNetworkByOpaqueRef } = useNetworkStore().subscribe()
const { getByOpaqueRef: getGuestMetricsByOpaqueRef } = useVmGuestMetricsStore().subscribe()
const { getByOpaqueRef: getVmByOpaqueRef } = useVmStore().subscribe()
const { pool } = usePoolStore().subscribe()
const { lockingModeLabel, rateLimit, txChecksumming } = useVifUtils(() => vif)
const vm = computed(() => (vif !== undefined ? getVmByOpaqueRef(vif.VM) : undefined))
const vifTo = computed(() => (vif !== undefined ? getVifRoute(vif.uuid) : undefined))
const ipAddresses = computed(() => {
if (vif === undefined) {
return []
@@ -159,19 +173,15 @@ const ipAddresses = computed(() => {
const network = computed(() => (vif !== undefined ? getNetworkByOpaqueRef(vif.network) : undefined))
const status = computed(() => (vif?.currently_attached ? 'connected' : 'disconnected'))
const networkTo = computed(() =>
pool.value && network.value ? getPoolNetworkRoute(pool.value.uuid, network.value.uuid) : undefined
)
const rateLimit = computed(() => {
if (vif?.qos_algorithm_type !== 'ratelimit') {
return undefined
}
return vif.qos_algorithm_params.kbps
})
const status = computed(() => (vif?.currently_attached ? CONNECTION_STATUS.CONNECTED : CONNECTION_STATUS.DISCONNECTED))
</script>
<style scoped lang="postcss">
.vm-vifs-side-panel {
.vif-side-panel {
.value:empty::before {
content: '-';
}

View File

@@ -5,7 +5,7 @@ export function useVifEdit() {
const router = useRouter()
function goToVifEdit(vif: XenApiVif) {
return router.push({ name: '/vif/[uuid]/edit', params: { uuid: vif.uuid } })
return router.push({ name: '/vif/edit', query: { vifUuid: vif.uuid } })
}
return { goToVifEdit }

View File

@@ -0,0 +1,22 @@
import type { XenApiVif } from '@/libs/xen-api/xen-api.types.ts'
import { isTxChecksummingEnabled } from '@/modules/vif/utils/vif-tx-checksumming.util.ts'
import { getVifRateLimit } from '@/modules/vif/utils/vif.util.ts'
import { useVifLockingModeLabel } from '@core/composables/vif-locking-mode-label.composable.ts'
import { toComputed } from '@core/utils/to-computed.util.ts'
import { computed, type MaybeRefOrGetter } from 'vue'
export function useVifUtils(rawVif: MaybeRefOrGetter<XenApiVif | undefined>) {
const vif = toComputed(rawVif)
const lockingModeLabel = useVifLockingModeLabel(() => vif.value?.locking_mode)
const rateLimit = computed(() => (vif.value !== undefined ? getVifRateLimit(vif.value) : undefined))
const txChecksumming = computed(() => vif.value !== undefined && isTxChecksummingEnabled(vif.value))
return {
lockingModeLabel,
rateLimit,
txChecksumming,
}
}

View File

@@ -1,18 +1,19 @@
import type { XenApiVif } from '@/libs/xen-api/xen-api.types.ts'
import { useVifForm } from '@/modules/vif/form/use-vif-form-base.ts'
import { isTxChecksummingEnabled } from '@/modules/vif/utils/vif-tx-checksumming.util.ts'
import { getVifRateLimit } from '@/modules/vif/utils/vif.util.ts'
import { useI18n } from 'vue-i18n'
export function useEditVifForm(vif: XenApiVif) {
const { t } = useI18n()
const { kbps } = vif.qos_algorithm_params
const kbps = getVifRateLimit(vif)
return useVifForm(
{
network: vif.network,
mac: vif.MAC,
rateLimit: vif.qos_algorithm_type === 'ratelimit' && kbps !== undefined ? Number(kbps) : undefined,
rateLimit: kbps !== undefined ? Number(kbps) : undefined,
allowedIps: [...vif.ipv4_allowed, ...vif.ipv6_allowed].join('; '),
txChecksumming: isTxChecksummingEnabled(vif),
},

View File

@@ -3,6 +3,7 @@ import { vifArg } from '@/modules/vif/jobs/vif-args.ts'
import type { VifPayload } from '@/modules/vif/jobs/vif-create.job.ts'
import { editVifPayloadArg } from '@/modules/vif/jobs/vif-edit-args.ts'
import { isTxChecksummingEnabled } from '@/modules/vif/utils/vif-tx-checksumming.util.ts'
import { getVifRateLimit } from '@/modules/vif/utils/vif.util.ts'
import { useXenApiStore } from '@/stores/xen-api.store.ts'
import { defineJob, JobError, JobRunningError } from '@core/packages/job'
import { VIF_LOCKING_MODE } from '@vates/types'
@@ -91,7 +92,7 @@ export const useVifEditJob = defineJob('vif.edit', [vifArg, editVifPayloadArg],
}
const kbps = payload.qos_algorithm_params?.kbps
const currentKbps = vif.qos_algorithm_type === 'ratelimit' ? vif.qos_algorithm_params.kbps : undefined
const currentKbps = getVifRateLimit(vif)
if (kbps !== currentKbps) {
await xapi.vif.setRateLimit(vif.$ref, kbps === undefined ? null : Number(kbps))

View File

@@ -0,0 +1,13 @@
import type { XenApiVif } from '@/libs/xen-api/xen-api.types.ts'
import type { RouteLocationAsRelative } from 'vue-router'
export function getVifRoute(vifId: XenApiVif['uuid']): RouteLocationAsRelative {
return {
name: '/vif/[uuid]/general',
params: { uuid: vifId },
}
}
export function getVifRateLimit(vif: XenApiVif) {
return vif.qos_algorithm_type === 'ratelimit' ? vif.qos_algorithm_params.kbps : undefined
}

View File

@@ -0,0 +1,29 @@
<template>
<ObjectNotFoundWrapper :is-ready :uuid-checker="hasUuid">
<template v-if="vif">
<VifHeader v-if="uiStore.hasUi" :vif />
<RouterView v-slot="{ Component }">
<component :is="Component" :vif />
</RouterView>
</template>
</ObjectNotFoundWrapper>
</template>
<script lang="ts" setup>
import ObjectNotFoundWrapper from '@/components/ObjectNotFoundWrapper.vue'
import type { XenApiVif } from '@/libs/xen-api/xen-api.types.ts'
import VifHeader from '@/modules/vif/components/VifHeader.vue'
import { useVifStore } from '@/stores/xen-api/vif.store.ts'
import { useDefaultTab } from '@core/composables/default-tab.composable.ts'
import { useUiStore } from '@core/stores/ui.store.ts'
import { computed } from 'vue'
import { useRoute } from 'vue-router'
useDefaultTab('/vif/[uuid]', 'general')
const route = useRoute<'/vif/[uuid]'>()
const uiStore = useUiStore()
const { getByUuid, hasUuid, isReady } = useVifStore().subscribe()
const vif = computed(() => getByUuid(route.params.uuid as XenApiVif['uuid']))
</script>

View File

@@ -0,0 +1,30 @@
<template>
<div class="scroll-container">
<VtsColumns extra-space-around>
<VtsColumn>
<VifGeneralInfoCard :vif />
</VtsColumn>
<VtsColumn>
<VifNetworkInfoCard :vif />
</VtsColumn>
</VtsColumns>
</div>
</template>
<script setup lang="ts">
import type { XenApiVif } from '@/libs/xen-api/xen-api.types.ts'
import VifGeneralInfoCard from '@/modules/vif/components/cards/VifGeneralInfoCard.vue'
import VifNetworkInfoCard from '@/modules/vif/components/cards/VifNetworkInfoCard.vue'
import VtsColumn from '@core/components/column/VtsColumn.vue'
import VtsColumns from '@core/components/columns/VtsColumns.vue'
defineProps<{ vif: XenApiVif }>()
</script>
<style lang="postcss" scoped>
.scroll-container {
flex: 1;
min-height: 0;
overflow-y: auto;
}
</style>

View File

@@ -52,14 +52,14 @@ import { type RouteLocationRaw, useRoute, useRouter } from 'vue-router'
const { t } = useI18n()
const router = useRouter()
const route = useRoute<'/vif/[uuid]/edit'>()
const route = useRoute()
const { isReady: areVifsReady, getByUuid: getVifByUuid } = useVifStore().subscribe()
const { getByOpaqueRef: getVmByOpaqueRef } = useVmStore().subscribe()
const vifUuid = computed(() => route.params.uuid as XenApiVif['uuid'])
const vifUuid = computed(() => route.query.vifUuid as XenApiVif['uuid'] | undefined)
const vif = computed(() => getVifByUuid(vifUuid.value))
const vif = computed(() => (vifUuid.value === undefined ? undefined : getVifByUuid(vifUuid.value)))
const vm = computed(() => (vif.value === undefined ? undefined : getVmByOpaqueRef(vif.value.VM)))

View File

@@ -1227,11 +1227,25 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/vif/[uuid]/edit': RouteRecordInfo<
'/vif/[uuid]/edit',
'/vif/:uuid/edit',
'/vif/[uuid]': RouteRecordInfo<
'/vif/[uuid]',
'/vif/:uuid',
{ uuid: ParamValue<true> },
{ uuid: ParamValue<false> },
| '/vif/[uuid]/general'
>,
'/vif/[uuid]/general': RouteRecordInfo<
'/vif/[uuid]/general',
'/vif/:uuid/general',
{ uuid: ParamValue<true> },
{ uuid: ParamValue<false> },
| never
>,
'/vif/edit': RouteRecordInfo<
'/vif/edit',
'/vif/edit',
Record<never, never>,
Record<never, never>,
| never
>,
'/vif/new': RouteRecordInfo<
@@ -2368,9 +2382,22 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/pages/vif/[uuid]/edit.vue': {
'src/pages/vif/[uuid].vue': {
routes:
| '/vif/[uuid]/edit'
| '/vif/[uuid]'
| '/vif/[uuid]/general'
views:
| 'default'
}
'src/pages/vif/[uuid]/general.vue': {
routes:
| '/vif/[uuid]/general'
views:
| never
}
'src/pages/vif/edit.vue': {
routes:
| '/vif/edit'
views:
| never
}

View File

@@ -1,11 +1,9 @@
import {
Body,
Delete,
Example,
Extension,
Get,
Middlewares,
Patch,
Path,
Put,
Query,
@@ -18,9 +16,8 @@ import {
} from 'tsoa'
import { inject } from 'inversify'
import { provide } from 'inversify-binding-decorators'
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 { Request as ExRequest } from 'express'
import type { XoAlarm, XoMessage, XoNetwork, XoTask } from '@vates/types'
import { AlarmService } from '../alarms/alarm.service.mjs'
import { escapeUnsafeComplexMatcher } from '../helpers/utils.helper.mjs'
@@ -29,8 +26,6 @@ import { network, networkIds, partialNetworks } from '../open-api/oa-examples/ne
import {
badRequestResp,
forbiddenOperationResp,
internalServerErrorResp,
invalidParameters as invalidParametersResp,
noContentResp,
notFoundResp,
unauthorizedResp,
@@ -41,60 +36,7 @@ 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, 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)
}
}
import { acl } from '../middlewares/acl.middleware.mjs'
@Route('networks')
@Security('*')
@@ -152,56 +94,6 @@ export class NetworkController extends XapiXoController<XoNetwork> {
return this.getObject(id as XoNetwork['id'])
}
/**
* Partial update of a network: only the fields present in the body are modified.
*
* Changing `MTU` unplugs and replugs the network's PIFs and the VIFs of its running VMs: their
* traffic is briefly interrupted.
* `nbd` and `insecureNbd` are mutually exclusive; setting one to `false` only removes that purpose.
* `automatic` adds the network to new VMs automatically; `defaultIsLocked` blocks the traffic of
* VIFs with no allowed IP.
* A body with none of the fields below is refused with a 422, whether or not the network exists.
*
* Required privilege per field provided in the body:
* - resource: network, action: update:&lt;field&gt;
* - and with `nbd: true`, also resource: network, action: update:insecureNbd (it removes the
* insecure NBD purpose); with `insecureNbd: true`, also action: update:nbd (it removes the NBD purpose)
*
* @example id "9fe12ca3-d75d-cfb0-492e-cfd2bc6c568f"
* @example body { "name_label": "backups", "MTU": 9000, "insecureNbd": true }
*/
@Extension('x-mcp-exposure', 'confirm')
@Patch('{id}')
@Middlewares([
json(),
refuseEmptyUpdate,
acl({
resource: 'network',
actions: updateNetworkActions,
objectId: 'params.id',
}),
])
@SuccessResponse(noContentResp.status, noContentResp.description)
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
@Response(notFoundResp.status, notFoundResp.description)
@Response(invalidParametersResp.status, invalidParametersResp.description)
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
async updateNetwork(@Path() id: string, @Body() body: UpdateNetworkRequestBody): Promise<void> {
const networkId = id as XoNetwork['id']
const { automatic, defaultIsLocked, insecureNbd, MTU, name_description, name_label, nbd } = body
// forward only the declared fields: the ACL above checked their privileges and the NBD purpose each one removes
await this.getXapi(networkId).editNetwork(networkId, {
automatic,
defaultIsLocked,
insecureNbd,
MTU,
name_description,
name_label,
nbd,
})
}
/**
* Required privilege:
* - resource: network, action: delete

View File

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

View File

@@ -1,62 +1,10 @@
import { invalidParameters } from 'xo-common/api-errors.js'
import type { CreateBondedNetworkBody, CreateInternalNetworkBody, CreateNetworkBody } from '../pools/pool.type.mjs'
import type { AuthenticatedRequest, ReplaceKey } from '../helpers/helper.type.mjs'
import type { NextFunction, Response as ExResponse } from 'express'
import type { ReplaceKey } from '../helpers/helper.type.mjs'
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
@@ -64,12 +12,9 @@ export class NetworkService {
this.#restApi = restApi
}
// body must come from normalizeNetworkCreateBody
async create(
poolId: XoPool['id'],
body: (ReplaceKey<CreateNetworkBody, 'pif', 'pifId'> | CreateBondedNetworkBody | CreateInternalNetworkBody) & {
name: string
}
body: ReplaceKey<CreateNetworkBody, 'pif', 'pifId'> | CreateBondedNetworkBody | CreateInternalNetworkBody
): Promise<XoNetwork['id']> {
const { nbd, insecureNbd, ...rest } = body
if (nbd && insecureNbd) {

View File

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

View File

@@ -95,12 +95,7 @@ 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,
networkCreateAclObject,
normalizeNetworkCreateBody,
refuseInvalidNetworkCreateBody,
} from '../networks/network.service.mjs'
import { NetworkService } 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'
@@ -185,8 +180,8 @@ export class PoolController extends XapiXoController<XoPool> {
*
* @example id "355ee47d-ff4c-4924-3db2-fd86ae629676"
* @example body {
* "name_label": "awes0me_network",
* "name_description": "random description",
* "name": "awes0me_network",
* "description": "random description",
* "pif": "ad15b2c8-3d9a-194e-c43a-e3dcda74b256",
* "vlan": 0
* }
@@ -197,11 +192,10 @@ 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: networkCreateAclObject },
{ resource: 'network', action: 'create', object: ({ req }) => req.body },
]),
])
@Tags('networks')
@@ -217,8 +211,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 }
@@ -242,8 +236,8 @@ export class PoolController extends XapiXoController<XoPool> {
*
* @example id "355ee47d-ff4c-4924-3db2-fd86ae629676"
* @example body {
* "name_label": "awes0me_bonded_network",
* "name_description": "random description",
* "name": "awes0me_bonded_network",
* "description": "random description",
* "pifIds": ["ad15b2c8-3d9a-194e-c43a-e3dcda74b256", "7b6bed50-26b2-bd27-8f3a-1b5a81989a92"],
* "bondMode": "lacp"
* }
@@ -254,10 +248,9 @@ 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: networkCreateAclObject },
{ resource: 'network', action: 'create', object: ({ req }) => req.body },
]),
])
@Tags('networks')
@@ -273,8 +266,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 }
@@ -298,8 +291,8 @@ export class PoolController extends XapiXoController<XoPool> {
*
* @example id "355ee47d-ff4c-4924-3db2-fd86ae629676"
* @example body {
* "name_label": "awes0me_internal_network",
* "name_description": "random description"
* "name": "awes0me_internal_network",
* "description": "random description"
* }
*/
@Example(taskLocation)
@@ -308,10 +301,9 @@ 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: networkCreateAclObject },
{ resource: 'network', action: 'create', object: ({ req }) => req.body },
]),
])
@Tags('networks')
@@ -327,9 +319,8 @@ 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, networkBody)
const networkId = await this.#networkService.create(poolId, body)
return { id: networkId }
}

View File

@@ -12,28 +12,13 @@ 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 = {
/**
* @deprecated use `name_label`
*/
name?: string
name_label?: string
/**
* @deprecated use `name_description`
*/
name: string
description?: string
name_description?: string
/**
* @deprecated use `MTU`
*/
mtu?: number
/**
* @default 1500
*/
MTU?: number
mtu?: number
nbd?: boolean
/**
* NBD in clear, only on a network dedicated to backups. Mutually exclusive with `nbd`

View File

@@ -172,6 +172,18 @@ These classes MUST be used to ensure the typography is consistent across all com
>
> `<div class="typo-body-regular` />
## Component MUST use the z-index variables
A z-index only means something compared to the others: a menu, a select dropdown and a modal can all show at the same time. To keep them in the right order, each layer is a variable of the [z-index file](../../lib/assets/css/_z-indexes.pcss), from bottom to top:
- `--z-index-panel`: the sidebar, the side panels and the mobile menu laid over the page, and the backdrop under them
- `--z-index-popup`: the popups opened from the page (menus), which stay under an overlay opened from one of their items
- `--z-index-overlay-backdrop` and `--z-index-overlay`: the overlays (modals, drawers) and their backdrop
- `--z-index-overlay-popup`: the popups above the overlays: the menus opened from the current overlay, and the select dropdowns, which close as soon as something else is clicked
- `--z-index-tooltip`: the tooltips, above everything
Use the variable of the layer the element belongs to rather than a number. If none fits, add a layer to the file.
## New CSS features support
We try to keep up to date with new CSS features and use them when they address a problem or specific integration use case.

View File

@@ -65,6 +65,7 @@ Testing uses **Vitest 5** with a single `unit` project (see `vitest.config.ts`):
| `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 |
| `test/find-title.ts` | `findTitle`: the `.title` of a `VtsSuccessStateHero` or a list item, `undefined` without one (also used by XO 6) |
| `test/create-task-item.ts` | `createTaskItem`: a `Task` as the task lists display it, with the given overrides (also used by XO 6) |
| `test/overlay.ts` | `registerOverlay(key?)`: an open overlay in the store of the last mounted wrapper, on top of those already open; `provideOverlayKey(key)`: what that overlay provides to its content, nothing without a key |
| `tsconfig.vitest.json` | Type-checks test files with the Vitest globals and the `@core-test` alias |
| `tsconfig.app.json` | Type-checks the library, test files excluded |

View File

@@ -0,0 +1,8 @@
:root {
--z-index-panel: 1010;
--z-index-popup: 1011;
--z-index-overlay-backdrop: 1015;
--z-index-overlay: 1016;
--z-index-overlay-popup: 1020;
--z-index-tooltip: 999999;
}

View File

@@ -3,6 +3,7 @@
@import '_fonts.pcss';
@import '_context.pcss';
@import '_shadows.pcss';
@import '_z-indexes.pcss';
@import '_typography.pcss';
:root {

View File

@@ -14,6 +14,6 @@ defineSlots<{
.vts-backdrop {
position: fixed;
inset: 0;
z-index: 1010;
z-index: var(--z-index-panel);
}
</style>

View File

@@ -99,7 +99,7 @@ const className = computed(() => [
height: 100%;
background-color: var(--color-neutral-background-secondary);
width: v-bind('sidebar.cssWidth');
z-index: 1010;
z-index: var(--z-index-panel);
transition: v-bind(slideTransition);
&.bordered {

View File

@@ -0,0 +1,35 @@
import MenuList from '@core/components/menu/MenuList.vue'
import { createGlobalTestConfig } from '@core-test/create-global-test-config.ts'
import { provideOverlayKey, registerOverlay } from '@core-test/overlay.ts'
import { mount } from '@vue/test-utils'
import { nextTick } from 'vue'
function mountMenuList(overlayKey?: symbol) {
return mount(MenuList, {
global: createGlobalTestConfig({ provide: provideOverlayKey(overlayKey) }),
slots: { default: 'Item' },
})
}
function isRaisedAboveOverlays(wrapper: ReturnType<typeof mountMenuList>) {
return wrapper.get('.menu-list').classes('in-current-overlay')
}
it('rises above the topmost overlay when opened from it', async () => {
const overlayKey = Symbol('overlay')
const wrapper = mountMenuList(overlayKey)
registerOverlay(overlayKey)
await nextTick()
expect(isRaisedAboveOverlays(wrapper)).toBe(true)
})
it('stays under an overlay opened over the page it belongs to', async () => {
const wrapper = mountMenuList()
registerOverlay()
await nextTick()
expect(isRaisedAboveOverlays(wrapper)).toBe(false)
})

View File

@@ -7,7 +7,7 @@
:id="menuId"
ref="menu"
:aria-orientation="horizontal ? 'horizontal' : undefined"
:class="{ horizontal, border: !noBorder }"
:class="{ horizontal, border: !noBorder, 'in-current-overlay': isInCurrentOverlay }"
class="menu-list"
role="menu"
v-bind="$attrs"
@@ -98,7 +98,7 @@ provide(IK_MENU_LEVEL, level)
provide(IK_IN_MENU, true)
const { placementSide, close } = useMenuPopup(menu, {
const { placementSide, isInCurrentOverlay, close } = useMenuPopup(menu, {
isOpen,
anchor: anchorElement,
placement: () => placement ?? defaultPlacement.value,
@@ -153,9 +153,13 @@ defineExpose({ focusFirstItem })
color: var(--color-neutral-txt-primary);
border-radius: 0.4rem;
background-color: var(--color-neutral-background-primary);
z-index: 1011;
z-index: var(--z-index-popup);
overflow: auto;
&.in-current-overlay {
z-index: var(--z-index-overlay-popup);
}
&.horizontal {
flex-direction: row;
}

View File

@@ -144,7 +144,7 @@ provide(IK_MOBILE_MENU, { openSubmenu })
.vts-mobile-menu {
position: fixed;
inset: 0;
z-index: 1010;
z-index: var(--z-index-panel);
border: none;
border-radius: 0;

View File

@@ -163,6 +163,16 @@ const textMappingsByObject: TextMappingByObject = {
message: t('modal:host-emergency-shutdown-message'),
action: t('action:emergency-shutdown-host'),
},
'enable-ssh': {
title: t('modal:confirm-host-enable-ssh', { host: hostName }),
message: t('modal:host-enable-ssh-message'),
action: t('action:enable-ssh'),
},
'disable-ssh': {
title: t('modal:confirm-host-disable-ssh', { host: hostName }),
message: t('modal:host-disable-ssh-message'),
action: t('action:disable-ssh'),
},
},
}

View File

@@ -70,7 +70,7 @@ watch([rootElement, () => overlayStore.overlays.map(overlay => overlay.key)], ([
.backdrop {
position: fixed;
inset: 0;
z-index: 1015;
z-index: var(--z-index-overlay-backdrop);
background-color: var(--color-opacity-primary);
pointer-events: none;
@@ -88,7 +88,7 @@ watch([rootElement, () => overlayStore.overlays.map(overlay => overlay.key)], ([
.overlays {
position: fixed;
inset: 0;
z-index: 1016;
z-index: var(--z-index-overlay);
/* The container only positions the stacked modals; each modal catches its own
clicks, so an empty container must let clicks through. */

View File

@@ -134,7 +134,7 @@ function handleClose() {
}
&.mobile .panel {
z-index: 1010;
z-index: var(--z-index-panel);
position: fixed;
width: 100dvw;
height: 100dvh;

View File

@@ -79,7 +79,7 @@ function toggleSelectAll(value: boolean) {
.dropdown-list {
max-height: 36.2rem;
overflow: auto;
z-index: 1020;
z-index: var(--z-index-overlay-popup);
.select-all-buttons {
display: flex;

View File

@@ -129,7 +129,7 @@ defineExpose({
min-width: v-bind(minWidth);
max-height: 36.2rem; /* 8 Dropdown items */
overflow: auto;
z-index: 1020;
z-index: var(--z-index-overlay-popup);
.search-container {
background-color: var(--color-neutral-background-primary);

View File

@@ -315,7 +315,7 @@ watch(isOpen, open => {
min-width: 32rem;
max-width: calc(100vw - 3.2rem);
height: 44.6rem;
z-index: 1020;
z-index: var(--z-index-overlay-popup);
:deep(.container) {
flex: 1 1 0;

View File

@@ -68,7 +68,7 @@ watch(content, () => updatePlacement(), { flush: 'post' })
color: var(--color-neutral-background-primary);
border-radius: 0.4rem;
background-color: var(--color-neutral-txt-primary);
z-index: 999999;
z-index: var(--z-index-tooltip);
[data-placement^='top'] {
margin-bottom: 0.7rem;

View File

@@ -1,8 +1,9 @@
import { IK_OVERLAY_KEY } from '@core/packages/overlay/injection-keys.ts'
import { useOverlayStore } from '@core/packages/overlay/use-overlay-store.ts'
import { placeOverlay } from '@core/utils/placement.util.ts'
import { onClickOutside, useEventListener } from '@vueuse/core'
import type { Options } from 'placement.js'
import { type MaybeRefOrGetter, ref, type Ref, toValue, watch } from 'vue'
import { computed, inject, type MaybeRefOrGetter, ref, type Ref, toValue, watch } from 'vue'
type MenuPopupOptions = {
isOpen: Ref<boolean>
@@ -21,6 +22,10 @@ export function useMenuPopup(
const overlayStore = useOverlayStore()
const overlayKey = inject(IK_OVERLAY_KEY, undefined)
const isInCurrentOverlay = computed(() => overlayKey !== undefined && overlayStore.isCurrent(overlayKey.value))
let overlayCountOnOpen = 0
let stopClickOutside: (() => void) | undefined
@@ -106,5 +111,5 @@ export function useMenuPopup(
{ capture: true }
)
return { placementSide, close }
return { placementSide, isInCurrentOverlay, close }
}

View File

@@ -1,11 +1,14 @@
import { useMenuPopup } from '@core/composables/menu-popup.composable.ts'
import { useOverlayStore } from '@core/packages/overlay/use-overlay-store.ts'
import { createGlobalTestConfig } from '@core-test/create-global-test-config.ts'
import { mountWithSetupResult } from '@core-test/mount-with-setup.ts'
import { provideOverlayKey, registerOverlay } from '@core-test/overlay.ts'
import { h, nextTick, ref, useTemplateRef } from 'vue'
type PopupOptions = Partial<Pick<Parameters<typeof useMenuPopup>[1], 'closesOnClickOutside' | 'hasOpenSubmenu'>>
type PopupOptions = Partial<Pick<Parameters<typeof useMenuPopup>[1], 'closesOnClickOutside' | 'hasOpenSubmenu'>> & {
overlayKey?: symbol
}
async function mountOpenPopup(options: PopupOptions = {}) {
async function mountOpenPopup({ overlayKey, ...options }: PopupOptions = {}) {
const onClosed = vi.fn()
const isOpen = ref(false)
@@ -31,7 +34,12 @@ async function mountOpenPopup(options: PopupOptions = {}) {
]),
}
},
{ attachTo: document.body }
{
attachTo: document.body,
global: createGlobalTestConfig({
provide: provideOverlayKey(overlayKey),
}),
}
)
isOpen.value = true
@@ -48,18 +56,6 @@ function pressEscape() {
return event
}
function registerModal() {
useOverlayStore().register({
key: Symbol('modal'),
component: { render: () => null },
props: {},
status: 'idle',
lastTrigger: undefined,
returnFocusTarget: null,
abort: () => {},
})
}
describe('useMenuPopup', () => {
it('places the menu against its anchor and exposes the side it ends up on', async () => {
const { popup } = await mountOpenPopup()
@@ -91,7 +87,7 @@ describe('useMenuPopup', () => {
it('leaves Escape to a modal opened after it', async () => {
const { isOpen } = await mountOpenPopup()
registerModal()
registerOverlay()
const event = pressEscape()
await nextTick()
@@ -127,3 +123,32 @@ describe('useMenuPopup', () => {
}
)
})
describe('isInCurrentOverlay', () => {
it('is false for a menu opened from the page', async () => {
const { popup } = await mountOpenPopup()
registerOverlay()
expect(popup.isInCurrentOverlay.value).toBe(false)
})
it('is true for a menu opened from the topmost modal', async () => {
const modalKey = Symbol('modal')
const { popup } = await mountOpenPopup({ overlayKey: modalKey })
registerOverlay(modalKey)
expect(popup.isInCurrentOverlay.value).toBe(true)
})
it('turns false once a modal opens over the one of the menu', async () => {
const modalKey = Symbol('modal')
const { popup } = await mountOpenPopup({ overlayKey: modalKey })
registerOverlay(modalKey)
registerOverlay()
expect(popup.isInCurrentOverlay.value).toBe(false)
})
})

View File

@@ -0,0 +1,19 @@
import { useMapper } from '@core/packages/mapper'
import { VIF_LOCKING_MODE } from '@vates/types'
import type { MaybeRefOrGetter } from 'vue'
import { useI18n } from 'vue-i18n'
export function useVifLockingModeLabel(lockingMode: MaybeRefOrGetter<VIF_LOCKING_MODE | undefined>) {
const { t } = useI18n()
return useMapper<VIF_LOCKING_MODE, string>(
lockingMode,
{
[VIF_LOCKING_MODE.DISABLED]: t('disabled'),
[VIF_LOCKING_MODE.LOCKED]: t('locked'),
[VIF_LOCKING_MODE.NETWORK_DEFAULT]: t('network-default'),
[VIF_LOCKING_MODE.UNLOCKED]: t('unlocked'),
},
VIF_LOCKING_MODE.NETWORK_DEFAULT
)
}

View File

@@ -83,6 +83,7 @@
"action:disable-host": "Disable host",
"action:disable-host-and-evacuate-vms": "Disable host and evacuate VMs",
"action:disable-load-at-startup": "Disable load at startup",
"action:disable-ssh": "Disable SSH",
"action:discard": "Discard",
"action:disconnect": "Disconnect",
"action:disconnect-n": "Disconnect {n}",
@@ -108,6 +109,7 @@
"action:enable-host": "Enable host",
"action:enable-light-mode": "Enable light mode",
"action:enable-load-at-startup": "Enable load at startup",
"action:enable-ssh": "Enable SSH",
"action:export": "Export",
"action:export-content": "Export content",
"action:export-n-vms": "Export 1 VM | Export {n} VMs",
@@ -273,6 +275,7 @@
"at-least-one-enabled": "At least one enabled",
"attach-vdi": "Attach existing VDI",
"auto-collapse-completed-tasks": "Auto-collapse completed tasks",
"auto-enable-if-xapi-goes-down": "Auto-enable if XAPI goes down",
"auto-generated": "Automatically generated",
"auto-power": "Auto power",
"available": "Available",
@@ -756,8 +759,16 @@
"job:host-detach:in-progress": "Host detach in progress…",
"job:host-detach:master-host": "Master host cannot be detached",
"job:host-detach:missing-host": "No host to detach",
"job:host-disable-ssh:bad-power-state": "@:host-not-running",
"job:host-disable-ssh:in-progress": "@:action:disable-ssh in progress…",
"job:host-disable-ssh:missing-host": "@:host-missing",
"job:host-disable-ssh:unsupported-version": "@:xcp-ng-9-required",
"job:host-disable:bad-power-state": "@:host-not-running",
"job:host-disable:missing-host": "@:host-missing",
"job:host-enable-ssh:bad-power-state": "@:host-not-running",
"job:host-enable-ssh:in-progress": "@:action:enable-ssh in progress…",
"job:host-enable-ssh:missing-host": "@:host-missing",
"job:host-enable-ssh:unsupported-version": "@:xcp-ng-9-required",
"job:host-enable:missing-host": "@:host-missing",
"job:host-evacuate:in-progress": "Host evacuation in progress…",
"job:host-forget:bad-power-state": "Host is running",
@@ -1017,8 +1028,10 @@
"modal:backup-repository-forget-title": "You are about to forget a backup repository | You are about to forget {n} backup repositories",
"modal:confirm-host-detach?": "Are you sure you want to detach {host}?",
"modal:confirm-host-disable-and-evacuate-vms?": "Are you sure you want to disable {host} and evacuate its VMs?",
"modal:confirm-host-disable-ssh": "Disable SSH on {host}, auto-enable if XAPI goes down",
"modal:confirm-host-disable?": "Are you sure you want to disable {host}?",
"modal:confirm-host-emergency-shutdown?": "Are you sure you want to make an emergency shutdown of {host}?",
"modal:confirm-host-enable-ssh": "Enable SSH on {host}",
"modal:confirm-host-enable?": "Are you sure you want to enable {host}?",
"modal:confirm-host-force-reboot?": "Are you sure you want to force reboot {host}?",
"modal:confirm-host-forget?": "Are you sure you want to forget {host}?",
@@ -1032,8 +1045,10 @@
"modal:host-detach-message": "This host will be detached from the pool and its local storage reset. Make sure no VMs are still running on it and that anything you need from its local storage has been backed up.",
"modal:host-disable-and-evacuate-vms-message": "The host will be disabled and its running VMs will be automatically migrated to other hosts in the pool, with no interruption as long as resources allow.",
"modal:host-disable-message": "The host will be marked unavailable for starting or receiving new VMs. Already-running VMs are not affected.",
"modal:host-disable-ssh-message": "SSH will be turned off and emergency access turned back on (the default). Open SSH sessions are not closed. While XAPI responds on this host, SSH stays off. If XAPI stops responding, SSH is turned on automatically so you can repair the host, and turned off again once XAPI responds. SSH also accepts connections for a short time at each boot, until XAPI has started.",
"modal:host-emergency-shutdown-message": "This will power off the host. Its running VMs will be suspended, without migration, before the host shuts down. VMs that cannot be suspended will be shut down.",
"modal:host-enable-message": "The host becomes available again for starting or receiving VMs.",
"modal:host-enable-ssh-message": "SSH will accept connections on this host until you disable it.",
"modal:host-force-reboot-message": "The host is about to reboot. Its running VMs will be migrated to other hosts when possible, but those that can't be will be forcibly shut down. Data loss may occur.",
"modal:host-forget-message": "This will permanently remove the host from the pool database. Only do this if the host is physically gone or unrecoverable - if it can come back online, use Detach instead. This action cannot be undone.",
"modal:host-reboot-message": "The host is about to reboot. Its running VMs will be migrated to other hosts and won't be moved back to it automatically afterwards.",
@@ -1605,6 +1620,7 @@
"sr-required": "Storage repository is required.",
"sr-usage-exceeds-80-percent": "Storage usage has exceeded 80% of total capacity. Performance may be impacted, consider freeing up space.",
"sr-usage-exceeds-90-percent": "Storage usage has exceeded 90% of total capacity. Free up space immediately to avoid service disruption.",
"ssh": "SSH",
"ssh-account": "SSH account",
"ssh-key": "SSH key",
"ssh-keys": "SSH keys",
@@ -1981,6 +1997,7 @@
"writing-speed": "Writing speed",
"xapi-plugin": "XAPI plugin",
"xcp-ng": "XCP-ng",
"xcp-ng-9-required": "Requires XCP-ng 9 or later",
"xen-orchestra": "Xen Orchestra",
"xo": "XO",
"xo-5": "XO-5",

View File

@@ -83,6 +83,7 @@
"action:disable-host": "Désactiver l'hôte",
"action:disable-host-and-evacuate-vms": "Désactiver l'hôte et évacuer les VMs",
"action:disable-load-at-startup": "Désactiver le chargement au démarrage",
"action:disable-ssh": "Désactiver SSH",
"action:discard": "Abandonner",
"action:disconnect": "Déconnecter",
"action:disconnect-n": "Déconnecter {n}",
@@ -108,6 +109,7 @@
"action:enable-host": "Activer l'hôte",
"action:enable-light-mode": "Activer le mode clair",
"action:enable-load-at-startup": "Activer le chargement au démarrage",
"action:enable-ssh": "Activer SSH",
"action:export": "Exporter",
"action:export-content": "Exporter le contenu",
"action:export-n-vms": "Exporter 1 VM | Exporter {n} VMs",
@@ -273,6 +275,7 @@
"at-least-one-enabled": "Au moins un activé",
"attach-vdi": "Attacher un VDI existant",
"auto-collapse-completed-tasks": "Replier automatiquement les tâches terminées",
"auto-enable-if-xapi-goes-down": "Réactivation automatique si la XAPI ne répond plus",
"auto-generated": "Généré automatiquement",
"auto-power": "Démarrage automatique",
"available": "Disponible",
@@ -756,8 +759,16 @@
"job:host-detach:in-progress": "Détachement de l'hôte en cours…",
"job:host-detach:master-host": "L'hôte primaire ne peut pas être détaché",
"job:host-detach:missing-host": "Aucun hôte à détacher",
"job:host-disable-ssh:bad-power-state": "@:host-not-running",
"job:host-disable-ssh:in-progress": "Désactivation de SSH en cours…",
"job:host-disable-ssh:missing-host": "@:host-missing",
"job:host-disable-ssh:unsupported-version": "@:xcp-ng-9-required",
"job:host-disable:bad-power-state": "@:host-not-running",
"job:host-disable:missing-host": "@:host-missing",
"job:host-enable-ssh:bad-power-state": "@:host-not-running",
"job:host-enable-ssh:in-progress": "Activation de SSH en cours…",
"job:host-enable-ssh:missing-host": "@:host-missing",
"job:host-enable-ssh:unsupported-version": "@:xcp-ng-9-required",
"job:host-enable:missing-host": "@:host-missing",
"job:host-evacuate:in-progress": "Évacuation de l'hôte en cours…",
"job:host-forget:bad-power-state": "L'hôte est en cours d'exécution",
@@ -1017,8 +1028,10 @@
"modal:backup-repository-forget-title": "Vous êtes sur le point d'oublier un dépôt de sauvegarde | Vous êtes sur le point d'oublier {n} dépôts de sauvegarde",
"modal:confirm-host-detach?": "Êtes-vous sûr de vouloir détacher {host} ?",
"modal:confirm-host-disable-and-evacuate-vms?": "Êtes-vous sûr de vouloir désactiver {host} et évacuer ses VMs ?",
"modal:confirm-host-disable-ssh": "Désactiver SSH sur {host}, réactivation automatique si la XAPI ne répond plus",
"modal:confirm-host-disable?": "Êtes-vous sûr de vouloir désactiver {host} ?",
"modal:confirm-host-emergency-shutdown?": "Êtes-vous sûr de vouloir effectuer un arrêt d'urgence de {host} ?",
"modal:confirm-host-enable-ssh": "Activer SSH sur {host}",
"modal:confirm-host-enable?": "Êtes-vous sûr de vouloir activer {host} ?",
"modal:confirm-host-force-reboot?": "Êtes-vous sûr de vouloir forcer le redémarrage de {host} ?",
"modal:confirm-host-forget?": "Êtes-vous sûr de vouloir oublier {host} ?",
@@ -1032,8 +1045,10 @@
"modal:host-detach-message": "Cet hôte sera détaché du pool et son stockage local réinitialisé. Assurez-vous qu'aucune VM n'est encore en cours d'exécution et que tout ce dont vous avez besoin sur son stockage local a été sauvegardé.",
"modal:host-disable-and-evacuate-vms-message": "L'hôte sera désactivé et ses VMs en cours d'exécution seront automatiquement migrées vers d'autres hôtes du pool, sans interruption si les ressources le permettent.",
"modal:host-disable-message": "L'hôte sera marqué comme indisponible pour le démarrage ou la réception de nouvelles VMs. Les VMs déjà en cours d’exécution ne sont pas affectées.",
"modal:host-disable-ssh-message": "SSH sera désactivé et l'accès de secours réactivé (comportement par défaut). Les sessions SSH ouvertes ne sont pas fermées. Tant que la XAPI répond sur cet hôte, SSH reste désactivé. Si la XAPI ne répond plus, SSH est activé automatiquement pour vous permettre de réparer l'hôte, puis désactivé à nouveau dès que la XAPI répond. SSH accepte aussi des connexions pendant un court instant à chaque démarrage, jusqu'au lancement de la XAPI.",
"modal:host-emergency-shutdown-message": "L'hôte va être éteint. Ses VMs en cours d'exécution seront suspendues, sans migration, avant l'arrêt de l'hôte. Les VMs qui ne peuvent pas être suspendues seront arrêtées.",
"modal:host-enable-message": "L'hôte redevient disponible pour démarrer ou recevoir des VMs.",
"modal:host-enable-ssh-message": "SSH acceptera les connexions sur cet hôte jusqu'à ce que vous le désactiviez.",
"modal:host-force-reboot-message": "L'hôte est sur le point de redémarrer. Ses VMs en cours d'exécution seront migrées vers d'autres hôtes lorsque cela sera possible, mais celles qui ne peuvent pas l'être seront arrêtées de force. Une perte de données peut survenir.",
"modal:host-forget-message": "Cela supprimera définitivement l'hôte de la base de données du pool. Ne faites cela que si l'hôte est physiquement absent ou irrécupérable - s'il peut revenir en ligne, utilisez à la place Détacher. Cette action ne peut pas être annulée.",
"modal:host-reboot-message": "L'hôte va redémarrer. Ses VMs en cours d'exécution seront migrées vers d'autres hôtes et ne reviendront pas automatiquement dessus après l'opération.",
@@ -1605,6 +1620,7 @@
"sr-required": "Le dépôt de stockage est requis.",
"sr-usage-exceeds-80-percent": "L'utilisation du stockage dépasse 80 % de la capacité totale. Les performances peuvent être impactées, pensez à libérer de l'espace.",
"sr-usage-exceeds-90-percent": "L'utilisation du stockage dépasse 90 % de la capacité totale. Libérez de l'espace immédiatement pour éviter toute interruption de service.",
"ssh": "SSH",
"ssh-account": "Compte SSH",
"ssh-key": "Clé SSH",
"ssh-keys": "Clés SSH",
@@ -1981,6 +1997,7 @@
"writing-speed": "Vitesse d'écriture",
"xapi-plugin": "plugin XAPI",
"xcp-ng": "XCP-ng",
"xcp-ng-9-required": "Nécessite XCP-ng 9 ou une version ultérieure",
"xen-orchestra": "Xen Orchestra",
"xo": "XO",
"xo-5": "XO-5",

View File

@@ -1,23 +0,0 @@
import { defineColumns } from '@core/packages/table/define-columns.ts'
import { useActionColumn } from '@core/tables/column-definitions/action-column.ts'
import { useAddressColumn } from '@core/tables/column-definitions/address-column.ts'
import { useLinkColumn } from '@core/tables/column-definitions/link-column.ts'
import { useNumberColumn } from '@core/tables/column-definitions/number-column.ts'
import { useStatusColumn } from '@core/tables/column-definitions/status-column.ts'
import { useTextColumn } from '@core/tables/column-definitions/text-column.ts'
import { useI18n } from 'vue-i18n'
export const useVifColumns = defineColumns(() => {
const { t } = useI18n()
return {
network: useLinkColumn({ headerLabel: () => t('network'), flexible: true }),
device: useTextColumn({ headerLabel: () => t('device') }),
status: useStatusColumn({ headerLabel: () => t('status') }),
ipsAddresses: useAddressColumn({ headerLabel: () => t('ip-addresses') }),
macAddresses: useAddressColumn({ headerLabel: () => t('mac-addresses') }),
mtu: useNumberColumn({ headerLabel: () => t('mtu') }),
lockingMode: useTextColumn({ headerLabel: () => t('locking-mode') }),
actions: useActionColumn({}),
}
})

View File

@@ -14,6 +14,8 @@ export type HostActions =
| 'restart-toolstack'
| 'detach'
| 'emergency-shutdown'
| 'enable-ssh'
| 'disable-ssh'
export type VmBlockedOperations =
| 'clean_shutdown'

View File

@@ -20,6 +20,7 @@
"@regle/rules": "^1.26.0",
"@regle/schemas": "^1.20.2",
"@types/d3-time-format": "^4.0.3",
"@vates/types": "^3.2.0",
"@vueuse/core": "^14.0.0",
"@vueuse/math": "^14.0.0",
"@vueuse/router": "^14.0.0",

View File

@@ -0,0 +1,22 @@
import { IK_OVERLAY_KEY } from '@core/packages/overlay/injection-keys.ts'
import { useOverlayStore } from '@core/packages/overlay/use-overlay-store.ts'
import { computed } from 'vue'
// Registers an overlay of that key in the store of the last mounted wrapper, on top of the overlays already open
export function registerOverlay(key = Symbol('overlay')) {
useOverlayStore().register({
key,
component: { render: () => null },
props: {},
status: 'idle',
lastTrigger: undefined,
returnFocusTarget: null,
abort: () => {},
})
}
// What the overlay of that key provides to its content, for the `provide` of `createGlobalTestConfig`; nothing without a
// key, as for content of the page
export function provideOverlayKey(key: symbol | undefined) {
return key === undefined ? {} : { [IK_OVERLAY_KEY]: computed(() => key) }
}

View File

@@ -27,8 +27,9 @@ import { useXoNetworkCollection } from '@/modules/network/remote-resources/use-x
import { getPoolNetworkRoute } from '@/modules/network/utils/xo-network.util.ts'
import { useVifConnection } from '@/modules/vif/composables/use-vif-connection.composable.ts'
import { useVifDelete } from '@/modules/vif/composables/use-vif-delete.composable.ts'
import { useXoVifUtils } from '@/modules/vif/composables/xo-vif-utils.composable.ts'
import { type FrontXoVif, useXoVifCollection } from '@/modules/vif/remote-resources/use-xo-vif-collection.ts'
import { getVifTrafficRoute } from '@/modules/vif/utils/xo-vif.util.ts'
import { getVifRoute } from '@/modules/vif/utils/xo-vif.util.ts'
import { type FrontXoVm, useXoVmCollection } from '@/modules/vm/remote-resources/use-xo-vm-collection.ts'
import VtsRow from '@core/components/table/VtsRow.vue'
import VtsTable from '@core/components/table/VtsTable.vue'
@@ -97,6 +98,8 @@ const { HeadCells, BodyCells } = useVifNetworkColumns({
network.value ? getPoolNetworkRoute(network.value.$pool, network.value.id) : undefined
)
const { lockingModeLabel } = useXoVifUtils(() => vif)
const { deleteVifs, canDeleteVifs, isDeletingVifs } = useVifDelete(() => [vif])
const {
@@ -140,7 +143,7 @@ const { HeadCells, BodyCells } = useVifNetworkColumns({
vif: r =>
r({
label: t('vif'),
to: getVifTrafficRoute(vif.id),
to: getVifRoute(vif.id),
icon: icon('object:vif'),
}),
network: r =>
@@ -156,7 +159,7 @@ const { HeadCells, BodyCells } = useVifNetworkColumns({
ipsAddresses: r => r(ipAddresses.value),
macAddresses: r => r(vif.MAC),
mtu: r => r(vif.MTU),
lockingMode: r => r(vif.lockingMode),
lockingMode: r => r(lockingModeLabel.value),
actions: r =>
r({
onClick: () => (selectedVifId.value = vif.id),

View File

@@ -75,7 +75,7 @@ const { networkVlan } = useXoNetworkUtils(network)
const vifStatus = computed(() => (vif.attached ? CONNECTION_STATUS.CONNECTED : CONNECTION_STATUS.DISCONNECTED))
const vifDevice = computed(() => `${t('vif')}${vif.device}`)
const vifDevice = computed(() => t('vif-device', { device: vif.device }))
const rateLimit = computed(() => (vif.rateLimit !== undefined ? `${vif.rateLimit} kB/s` : undefined))
const rateLimit = computed(() => (vif.rateLimit !== undefined ? `${vif.rateLimit} ${t('bytes:kbs')}` : undefined))
</script>

View File

@@ -71,7 +71,7 @@
{{ t('locking-mode') }}
</template>
<template #value>
{{ vif.lockingMode }}
{{ lockingModeLabel }}
</template>
</VtsCardRowKeyValue>
<!-- TX CHECK SUMMING -->
@@ -116,8 +116,9 @@ import { useXoNetworkCollection } from '@/modules/network/remote-resources/use-x
import { getPoolNetworkRoute } from '@/modules/network/utils/xo-network.util.ts'
import VifConnectionToggleButton from '@/modules/vif/components/actions/connection/VifConnectionToggleButton.vue'
import VifDeleteButton from '@/modules/vif/components/actions/delete/VifDeleteButton.vue'
import { useXoVifUtils } from '@/modules/vif/composables/xo-vif-utils.composable.ts'
import type { FrontXoVif } from '@/modules/vif/remote-resources/use-xo-vif-collection.ts'
import { getVifTrafficRoute } from '@/modules/vif/utils/xo-vif.util.ts'
import { getVifRoute } from '@/modules/vif/utils/xo-vif.util.ts'
import { type FrontXoVm, useXoVmCollection } from '@/modules/vm/remote-resources/use-xo-vm-collection.ts'
import VtsCardRowKeyValue from '@core/components/card/VtsCardRowKeyValue.vue'
import VtsCardRowList from '@core/components/card/VtsCardRowList.vue'
@@ -145,8 +146,9 @@ const { t } = useI18n()
const { useGetNetworkById } = useXoNetworkCollection()
const { getVmById } = useXoVmCollection()
const { lockingModeLabel } = useXoVifUtils(() => vif)
const vifTo = computed(() => (vif !== undefined ? getVifTrafficRoute(vif.id) : undefined))
const vifTo = computed(() => (vif !== undefined ? getVifRoute(vif.id) : undefined))
const ipAddresses = computed(() => {
if (vif === undefined) {

View File

@@ -1,25 +1,12 @@
import type { FrontXoVif } from '@/modules/vif/remote-resources/use-xo-vif-collection.ts'
import { useMapper } from '@core/packages/mapper'
import { useVifLockingModeLabel } from '@core/composables/vif-locking-mode-label.composable.ts'
import { toComputed } from '@core/utils/to-computed.util.ts'
import { VIF_LOCKING_MODE } from '@vates/types'
import type { MaybeRefOrGetter } from 'vue'
import { useI18n } from 'vue-i18n'
export function useXoVifUtils(rawVif: MaybeRefOrGetter<FrontXoVif>) {
const { t } = useI18n()
export function useXoVifUtils(rawVif: MaybeRefOrGetter<FrontXoVif | undefined>) {
const vif = toComputed(rawVif)
const lockingModeLabel = useMapper(
() => vif.value.lockingMode,
{
[VIF_LOCKING_MODE.DISABLED]: t('disabled'),
[VIF_LOCKING_MODE.LOCKED]: t('locked'),
[VIF_LOCKING_MODE.NETWORK_DEFAULT]: t('network-default'),
[VIF_LOCKING_MODE.UNLOCKED]: t('unlocked'),
},
VIF_LOCKING_MODE.NETWORK_DEFAULT
)
const lockingModeLabel = useVifLockingModeLabel(() => vif.value?.lockingMode)
return {
lockingModeLabel,

View File

@@ -1,7 +1,7 @@
import type { FrontXoVif } from '@/modules/vif/remote-resources/use-xo-vif-collection.ts'
import type { RouteLocationAsRelative } from 'vue-router'
export function getVifTrafficRoute(vifId: FrontXoVif['id']): RouteLocationAsRelative {
export function getVifRoute(vifId: FrontXoVif['id']): RouteLocationAsRelative {
return {
name: '/vif/[id]/general',
params: { id: vifId },

View File

@@ -15,8 +15,6 @@
- [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
@@ -26,8 +24,8 @@
- [Backup] Correctly cleanup the snapshot of a VM without any backed up disk: only a CDROM or only `[NOBAK]` disks (PR [#10789](https://github.com/vatesfr/xen-orchestra/pull/10789))
- [SDN Controller] Network traffic rules are now enforced on VMs started after the rule was created, when a pool's first traffic rule is a network rule: only VIF rules used to set up the SDN controller's event handling, so such network rules were recorded but never (re)applied (PR [#10917](https://github.com/vatesfr/xen-orchestra/pull/10917))
- [Layout] The page no longer slides sideways to show the closed side panel or "My tasks" when the keyboard focus moves past the last element of the page, and their content can no longer be reached while they are closed (PR [#10973](https://github.com/vatesfr/xen-orchestra/pull/10973))
- [Network] Saving a network's settings no longer unplugs and replugs all its VIFs and PIFs when its MTU is unchanged (PR [#XXXX](https://github.com/vatesfr/xen-orchestra/pull/XXXX))
- [Network] When one of a network's new settings fails to apply, the settings already changed are restored instead of being left half-applied (PR [#XXXX](https://github.com/vatesfr/xen-orchestra/pull/XXXX))
- [VIF] Display the locking mode as a translated label in the VIF table, side panel and page, and name VIFs "VIF #0" instead of "VIF0" (PR [#10686](https://github.com/vatesfr/xen-orchestra/pull/10686))
- [Query builder] Clicking the "…" button of a filter or a group shows its menu (Duplicate, Turn into group, Delete), which was hidden behind the query builder window (PR [#10975](https://github.com/vatesfr/xen-orchestra/pull/10975))
### Packages to release
@@ -46,10 +44,8 @@
<!--packages-start-->
- @vates/task minor
- @vates/types minor
- @xen-orchestra/acl minor
- @xen-orchestra/backups minor
- @xen-orchestra/rest-api minor
- @xen-orchestra/vmware-explorer patch
- @xen-orchestra/web minor
- @xen-orchestra/web-core minor

View File

@@ -108,7 +108,7 @@ In practice, a Storage administrator can create and delete SRs, manage virtual d
| Resource | Access |
| --------- | ------------------------------------------------------------------------------------------------ |
| `network` | Every action (`*`): read, create, delete, update tags, `other_config`, name, description, MTU, NBD, `automatic` and default locking mode. |
| `network` | Every action (`*`): read, create, delete, update tags and `other_config`. |
| `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`, `update:automatic`, `update:defaultIsLocked`, `update:insecureNbd`, `update:MTU`, `update:name_description`, `update:name_label`, `update:nbd` |
| `network` | `read`, `create`, `delete`, `update:tags`,`update:other_config` |
| `pif` | `read`, `update:management` |
| `pbd` | `read`, `plug`, `unplug` |
| `pci` | `read` |

View File

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

View File

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

View File

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