Compare commits

..

4 Commits

Author SHA1 Message Date
Joris K
cce68035ca feat(web-core): add UiOverridden component (#10840) 2026-11-19 11:37:38 +01:00
Thomas Moraine
948d4a23e5 docs(updater.md): link to replace your xoa from the updater page (#10471)
* docs(updater): link to Replace your XOA for getting a newer OS

The updater keeps Xen Orchestra up to date but doesn't refresh the
appliance's underlying OS/kernel/runtime; point readers to the
"Replace your XOA" guide for that.

* docs(updater): turn OS updates note into a warning

Stress that keeping XOA's OS up to date is critical given its privileged
access, and that reboots shouldn't be postponed but scheduled outside
backup windows.

* docs(updater): make OS warning title actionable

* docs(updater): emphasize not postponing XOA reboots
2026-11-19 11:29:56 +01:00
OlivierFL
68634c8c01 test(web): map @core-test to the web-core test helpers (#10831) 2026-11-19 10:29:44 +01:00
Killian
36cb16e508 fix(xen-api,xo-server): reconnect a pool whose event loop failed (#10814)
After a short network interruption, a pool could disappear from XO and its server stay in "connecting" until it was disabled and enabled again.

The cause is a chain of three things:

    xo-server processed the metrics of a VM, host or PIF whose owner had been removed in the meantime (the cached records are refreshed type by type), and threw Cannot read properties of undefined (reading '$type') from the flush of the objects collection. The owner is already gone from XO, so the metrics are now skipped.
    xo-collection stopped flushing when a listener threw: the remaining batches and finish were never emitted and the buffer was emitted again at the next flush. Every batch and finish are now emitted whatever the listeners do, then the first failure is rethrown.
    xen-api swallowed the rejection of its event loop, so nothing restarted it and the cache froze on a connection which still looked alive; the session stayed open, disconnected was never emitted and the auto-reconnection never started. It now logs the error and disconnects, so the owner of the connection reconnects with a fresh cache.
2026-11-19 10:05:07 +01:00
50 changed files with 1076 additions and 943 deletions

View File

@@ -0,0 +1,19 @@
<template>
<ComponentStory
v-slot="{ settings }"
:params="[
slot().help('Label displayed next to the dot, leave empty to only display the dot'),
setting('defaultSlot').widget(text()).preset('Overridden'),
]"
>
<UiOverridden v-if="settings.defaultSlot">{{ settings.defaultSlot }}</UiOverridden>
<UiOverridden v-else />
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { setting, slot } from '@/libs/story/story-param.ts'
import { text } from '@/libs/story/story-widget.ts'
import UiOverridden from '@core/components/ui/overridden/UiOverridden.vue'
</script>

View File

@@ -14,7 +14,7 @@
- [useItemCounter](../lib/composables/item-counter.composable.md)
- [useRouteQuery](../lib/composables/route-query.composable.md)
- [useTable](../lib/composables/table.composable.md)
- [useTree](../lib/composables/tree.composable.md)
- [useTree](../lib/packages/tree/README.md)
# Directives

View File

@@ -1,6 +1,46 @@
# Tests
Testing uses **Vitest 4** with a single `unit` project (see `vitest.config.ts`): every test matches `**/*.unit.test.ts` and runs on `happy-dom`, CLI-only, no browser. Conventions follow the [XO 6 test docs](../../web/docs/tests.md).
These pages hold the unit-testing conventions shared by `@xen-orchestra/web-core` and `@xen-orchestra/web` (XO 6). What only XO 6 has — its factories, its remote-resource mocks, its readers of app components, its pages — is in the [XO 6 test docs](../../web/docs/tests.md).
**Start with [Assert behavior, not implementation](./tests/assert-behavior.md)** — it is the rule the rest of this guide serves.
## Which package tests what
A behaviour is tested once, in the package that owns it:
- What a web-core component, composable, store or util does **on its own** — a select opening its options, a side panel opening on a selection, a store re-expanding on a resize — is tested in web-core.
- An XO 6 test covers what the app decides, and asserts a state it sets on a web-core component through that component's props. A test still green once the app code is removed tests web-core: write it in web-core instead, when web-core has no test for that behaviour yet.
## What to test first in web-core
1. **Logic** — `lib/utils/*.util.ts`, `lib/composables/*.composable.ts`, `lib/packages/*`, `lib/stores/*`
2. **`Vts*` building blocks with behaviour** — props, slots and variants → rendered output, emits, derived state (responsive classes, sorting, fallbacks)
3. **`Ui*` components** — their real branches only (a conditional slot, a derived label), never their styling
Every component gets tests in the medium term; until then, a change to a component adds the tests of what it touches.
## Shared test helpers
| Helper kind | Lives in | Imported as |
| --------------------------------------------------------------------------------------------- | ------------------------------ | -------------- |
| Generic — knows only web-core components or Vue (`mountComposable`, `createGlobalTestConfig`) | `web-core/test/` | `@core-test/…` |
| Domain-aware — knows an XO object, an XO 6 module, a remote resource | `@xen-orchestra/web/src/test/` | `@/test/…` |
XO 6 tests import the generic helpers through `@core-test` too, so a helper exists once for both packages: a generic one found in `src/test/` moves to `web-core/test/` when it is next touched. The exception is the mount setup: XO 6 keeps its own `createGlobalTestConfig` and `mountComposable` in `src/test/`, which install the app configuration (form validation, real routes) and take options, and its tests import those. Never add a domain-aware helper to web-core.
## Writing a test
- [Assert behavior, not implementation](./tests/assert-behavior.md) — the one rule that outranks the others
- [File layout and structure](./tests/file-structure.md) — where a test lives, how it is named, how it is organized
- [Setup: prefer helpers over `beforeEach`](./tests/setup-helpers.md) — local helpers, auto-unmount
- [Mocking dependencies](./tests/mocking.md) — the typed `vi.mock` form, shared mock modules
- [Testing pure utilities](./tests/testing-utilities.md) — `*.util.ts`, called directly
- [Testing composables](./tests/testing-composables.md) — mounting in a Vue context, reactivity, `useI18n`
- [Testing components](./tests/testing-components.md) — `mount`, querying rendered output, translations, what `happy-dom` cannot do
## Setup in web-core
Testing uses **Vitest 4** with a single `unit` project (see `vitest.config.ts`): every test matches `**/*.unit.test.ts` and runs on `happy-dom`, CLI-only, no browser.
| Path | Role |
| ----------------------------------- | ----------------------------------------------------------------------------------------------------- |
@@ -14,7 +54,7 @@ Testing uses **Vitest 4** with a single `unit` project (see `vitest.config.ts`):
Test files sit next to the code they test, as `lib/**/*.unit.test.ts`. Shared test infrastructure lives in `test/`, outside `lib/`. The shared `scripts/npmignore` keeps all of it out of the published package.
`@xen-orchestra/web` and `@xen-orchestra/lite` type-check `web-core/lib` as part of their own sources: their tsconfigs exclude the web-core test files, which they would otherwise check without the Vitest globals.
`@xen-orchestra/web` and `@xen-orchestra/lite` type-check `web-core/lib` as part of their own sources: their app tsconfigs exclude its `*.unit.test.ts`, which they would otherwise check without the Vitest globals. How XO 6 imports `web-core/test/` is in its [test runner](../../web/docs/tests/running-tests.md) page.
`test.alias` maps `placement.js` to its ESM build: the package only declares a `module` entry, which the Node-style resolution used by Vitest ignores.

View File

@@ -1,24 +1,25 @@
# Assert behavior, not implementation
**This is the rule the rest of the guide serves.** A test earns its place by failing when behavior breaks, and staying green through any refactor that preserves it.
**This is the rule the rest of the guide serves**, in `@xen-orchestra/web-core` and `@xen-orchestra/web` alike. A test earns its place by failing when behavior breaks, and staying green through any refactor that preserves it.
- Assert concrete outputs and contracts (`input → output`). Never assert _how_ the result was reached — which helper ran, in which order, how many times.
- Every test must assert something meaningful. Never re-assert a mock's own return value: `getHostById.mockReturnValue(host)` followed by `expect(…).toBe(host)` tests the mock, not the code.
- Every test must assert something meaningful. Never re-assert a mock's own return value: `getItemById.mockReturnValue(item)` followed by `expect(…).toBe(item)` tests the mock, not the code.
- **When a value is produced by a helper, build the expected value with that same helper** instead of copying its output as a literal. `objectIcon(type, state)` owns the icon-name format and `t(key)` owns the wording of a translation; what the code under test decides is _which_ icon and _which_ key. Assert that decision:
```typescript
// ✗ pins a format the code under test does not own — renaming the icon scheme or rewording a
// translation then breaks the test even though the behavior is unchanged
expect(displayData.vmIcon).toBe('object:vm:running')
expect(wrapper.vm.powerState.text).toBe('Running')
expect(wrapper.vm.icon).toBe('object:vm:running')
expect(wrapper.vm.label).toBe('Enabled')
// ✓ asserts the decision: the running VM icon, the running status label
expect(displayData.vmIcon).toBe(objectIcon('vm', 'running'))
expect(wrapper.vm.powerState.text).toBe(t('vm:status:running'))
// ✓ asserts the decision: the running icon, the enabled label
expect(wrapper.vm.icon).toBe(objectIcon('vm', 'running'))
expect(wrapper.vm.label).toBe(t('enabled'))
```
- A component test takes that `t` from `src/test/i18n.ts`, the very instance `createGlobalTestConfig()` installs; a composable test calls `useI18n()` inside the `setup` callback (see [Testing composables](./testing-composables.md)).
- A component test takes that `t` from the very instance its mount installs: `t` of `@core-test/i18n.ts` in web-core (XO 6: see [Translations](../../../web/docs/tests/testing-components.md#translations)); a composable test calls `useI18n()` inside the `setup` callback (see [Testing composables](./testing-composables.md)).
- This is not tautological, because the helper is not the code under test: `objectIcon` and the translation files have their own tests. A test _of_ `objectIcon` does assert literals — that is where its format is pinned, once.
- Values that are literals in production stay literals in the test. `powerState.icon` is written as `'status:running-circle'` in the source, so `expect(wrapper.vm.powerState.icon).toBe('status:running-circle')` is the right assertion; there is no helper to defer to.
- Values that are literals in production stay literals in the test. `statusIcon` is written as `'status:running-circle'` in the source, so `expect(wrapper.vm.statusIcon).toBe('status:running-circle')` is the right assertion; there is no helper to defer to.
- Environment-dependent values — a relative timestamp, a formatted date — are derived the way production derives them (`formatDateTime` from `@core/utils/time.util.ts`), and the test says so.
- Every mock couples the test to the mocked surface, which is why the boundary stays tight — see [Mocking dependencies](./mocking.md).
- Test each behaviour in the package that owns it: what a web-core component, composable or store does on its own is tested in web-core, never from an XO 6 test — see [Which package tests what](../tests.md#which-package-tests-what).

View File

@@ -0,0 +1,40 @@
# File layout and structure
## File layout and naming
- A test file lives **next to** the file it covers, named `<source-name>.unit.test.ts`.
- `to-variants.util.ts` → `to-variants.util.unit.test.ts`
- `menu-popup.composable.ts` → `menu-popup.composable.unit.test.ts`
- `VtsSuccessStateHero.vue` → `VtsSuccessStateHero.unit.test.ts` (the `.vue` is dropped)
- Shared test infrastructure lives apart from the code: `test/` in web-core (alias `@core-test`), `src/test/` in XO 6 (alias `@/test`) — see [Shared test helpers](../tests.md#shared-test-helpers).
## Structuring a test file
- **One `describe` block per function or exposed property**, labeled with its exact name (`describe('formatItemCount')`, `describe('status')`). A component test has no such members: group with `describe` only to separate genuinely distinct behaviors, otherwise flat `it`s read better.
- Use `it` (not `test`).
- The name completes the sentence the `it` starts: a **present-tense assertion**, lowercase, no trailing period, and **without a redundant prefix** — the `describe` label already carries the function name. `it('formats the selected count with the total')` reads as one sentence; `it('formatItemCount formats …')` stutters.
```typescript
describe('formatItemCount', () => {
it('formats the selected count with the total', () => {
expect(formatItemCount({ selected: 2, total: 8 })).toBe('2 / 8')
})
it('falls back to zero for missing counts', () => {
expect(formatItemCount({})).toBe('0 / 0')
})
})
```
## Do not import from `vitest`
`globals: true` (in the package's `vitest.config.ts` / `vite.config.ts`) together with `"types": ["vitest/globals"]` make `describe`, `it`, `expect`, `vi` and `beforeEach` available globally. **Never** add `import { ... } from 'vitest'`.
Those types are declared in `tsconfig.vitest.json`, not in `tsconfig.app.json`, so they are ambient in test files only. A `expect()` left behind in production code is a type error rather than a runtime `ReferenceError` in the browser.
The two projects split on the file name:
| Project | Covers | Test globals |
| ---------------------- | ----------------------------------------------------------------------------------------- | ------------ |
| `tsconfig.app.json` | everything **except** `*.unit.test.ts` and the test infrastructure (`test/`, `src/test/`) | no |
| `tsconfig.vitest.json` | everything, tests included; XO 6 also includes `web-core/test/` for `@core-test` | yes |

View File

@@ -0,0 +1,35 @@
# Mocking dependencies
Keep the mock boundary tight: **mock only what reaches outside the code under test** (a remote resource, a store fed by the network, an overlay a unit test cannot answer), and let pure utilities and icon helpers run for real.
Use the **typed** mock form — `vi.mock(import('<module>'), …)` — so a rename breaks type-check instead of silently leaving a stale mock. Create the stub functions with `vi.hoisted` (a plain `const fn = vi.fn()` referenced in the factory throws, because the mock is hoisted above imports), and reset them in `beforeEach`:
```typescript
const { sendCtrlAltDel } = vi.hoisted(() => ({
sendCtrlAltDel: vi.fn(),
}))
vi.mock(import('@core/composables/remote-console.composable.ts'), () => ({
useRemoteConsole: (() => ({ sendCtrlAltDel })) as unknown as typeof useRemoteConsole,
}))
beforeEach(() => {
sendCtrlAltDel.mockReset()
})
```
Note the cast: the typed form checks the factory return against the **whole** module, so a partial mock of a large export needs `as unknown as typeof useX` (with an `import type { useX }`).
When several test files mock the same module with the same shape, the mock lives once in the package's test infrastructure (`test/` in web-core, `src/test/` in XO 6) and the test file only points `vi.mock` to it; its exported state is read and changed by the tests, and reset in `beforeEach`:
```typescript
vi.mock(import('@core/composables/remote-console.composable.ts'), () => import('@core-test/mock-remote-console.ts'))
beforeEach(() => {
remoteConsoleMock.reset()
})
```
`vi.mock` is hoisted: it cannot be wrapped in a helper, so one `vi.mock(path, () => import(...))` line per file is the convention, not a duplication.
The XO 6 shared mocks (remote-resource collections, modals, overlays) and the network stub are listed in [XO 6 mocking](../../../web/docs/tests/mocking.md).

View File

@@ -0,0 +1,36 @@
# Setup: prefer helpers over `beforeEach`
Reserve `beforeEach` for **mock resets only**. Repeated setup goes into small local helper/factory functions at the top of the file.
A component or composable mounted with different props or fixtures across a file gets one helper taking them — never a `mount(...)` call repeated per test:
```typescript
function mountSuccessStateHero({ title }: { title?: string } = {}) {
return mount(VtsSuccessStateHero, {
global: createGlobalTestConfig(),
slots: { default: 'Message', ...(title !== undefined && { title }) },
})
}
```
A composable helper returns the mounted state, read with no `.value`:
```typescript
function mountLevel({ isPopup = true, horizontal = false } = {}) {
return mountComposable(() => useMenuLevel({ isPopup, horizontal })).wrapper.vm
}
```
A helper returning `wrapper.vm` serves a **reactivity** test too, as long as it accepts the source as a `ref` (`MaybeRefOrGetter`): `wrapper.vm` keeps following the updates. Only a test that must call a function returned by the composable, or build its expected value, _inside_ the `setup` callback stays inline (see [Testing composables](./testing-composables.md)).
Because mocks are read lazily, calling `getX.mockReturnValue(...)` in the test body _before_ invoking the helper still takes effect.
This applies to **navigation into the result** too, not only to mounting. An expression such as `result.items[0]`, repeated across a `describe` block, is repeated setup — give it a helper and assert on a named local, rather than re-deriving it in every test.
The exception is a **reactivity** test: it must keep reading through the mounted `vm` after reassigning the source ref. A helper returning a snapshot of the first item would defeat the test.
A helper used by a second test file moves to the package's test infrastructure — see [Shared test helpers](../tests.md#shared-test-helpers).
## Unmounting
Each package's `setup.ts` calls `enableAutoUnmount(afterEach)`, so every wrapper is unmounted after the test that created it. Never unmount by hand for cleanup, and never mount in `beforeAll`: that wrapper would be torn down after the first test. The one `wrapper.unmount()` allowed is the act of a test asserting what `onUnmounted` does.

View File

@@ -0,0 +1,112 @@
# Testing components
Components run in the same `unit` project as everything else: `@vue/test-utils` `mount` on `happy-dom`, **no browser needed**. Mount with the package's `createGlobalTestConfig()` (`@core-test/create-global-test-config.ts` in web-core, `@/test/global-test-config.ts` in XO 6), and give the repeated mount a helper (see [Setup](./setup-helpers.md)):
```typescript
import VtsSuccessStateHero from '@core/components/success-state-hero/VtsSuccessStateHero.vue'
import UiAlert from '@core/components/ui/alert/UiAlert.vue'
import { createGlobalTestConfig } from '@core-test/create-global-test-config.ts'
import { mount } from '@vue/test-utils'
function mountSuccessStateHero() {
return mount(VtsSuccessStateHero, {
global: createGlobalTestConfig(),
slots: { default: 'Message' },
})
}
it('renders the message in a success alert', () => {
const alert = mountSuccessStateHero().getComponent(UiAlert)
expect(alert.props('accent')).toBe('success')
expect(alert.text()).toBe('Message')
})
```
Where the test file lives and how it groups its tests: see [File layout and structure](./file-structure.md).
## What a web-core component test covers
A web-core component is tested for its **contract with its consumers**: what each prop, slot and variant renders, what it emits on a user action, the state it derives (responsive classes, a sort, a fallback). Not its styling — see [What `happy-dom` cannot do](#what-happy-dom-cannot-do).
- A variant is asserted through the class `toVariants` gives it, since that class is the contract the CSS reads — never through a style.
- A child web-core component is asserted through its props (`getComponent(UiAlert).props('accent')`), not the DOM it renders: that child has its own test.
- A responsive state is driven with `(window as unknown as HappyDomWindow).happyDOM.setViewport({ width })` before mounting (`import type { Window as HappyDomWindow } from 'happy-dom'`).
## Keep components thin
A component should not carry much complex logic. Non-trivial computation (series, aggregation, formatting rules) belongs in a `*.util.ts` or a composable, tested directly — that is cheaper and covers more branches than mounting. A component that is awkward to test is telling you to **extract**, not to write a heavier component test, and never to skip the test.
What is left to assert at the component level is what it renders: labels, formatted values, conditional rows, empty states.
### Extracting from a tested component
The extraction is a refactor, so the tests come **first** and are what proves it changed nothing:
1. Write the tests against the component **as it stands**, and run them green.
2. Extract.
3. Re-run those tests **unchanged**.
4. Move the ones the extraction made redundant down next to the new util/composable, and delete them from the component test.
Step 3 is the gate. A test that has to be edited to pass is reporting a behavior change — say so, do not absorb it into the diff. Tests written only _after_ an extraction describe the new code and cannot catch what the extraction broke, which is the whole risk being taken.
Step 4 is selective. A test that only exercised the logic now living in the util moves; a test asserting something the component alone does — rendering, conditional rows, empty states, feeding the util's output into the template — stays.
## Assert what the user reads, not the markup
`wrapper.text()` concatenates the whole subtree **with no separators**, so `'8 B'` and `'Disabled'` run together. It is fine for `toContain` on a single component, but it cannot express "this label has this value". Query instead:
```typescript
// every key/value row: `VtsKeyValuePair` renders a semantic `dt.label` and `dd.value`
const rows = wrapper.findAll('.vts-tabular-key-value-row')
const labelledValues = Object.fromEntries(rows.map(row => [row.get('dt.label').text(), row.get('dd.value').text()]))
expect(labelledValues).toEqual({ [t('name')]: 'Item 1', [t('status')]: t('enabled') })
```
Prefer this shape, one assertion covering every row a user sees: it fails loudly when a value lands under the wrong label. Assert against **class names and semantic elements**, never a positional chain of child indexes.
The class must exist for the component's own CSS: **never add a class only for a test**, and remove one whose CSS is gone. Without a styled class, query the component (`getComponent`), a styled class of a child component, or the text the user reads.
A query a second test file needs becomes a shared reader (see [Shared test helpers](../tests.md#shared-test-helpers)); XO 6 already has many, listed in [XO 6 components](../../../web/docs/tests/testing-components.md).
### Never spell out a translation
A rendered label or a translated value is wording the component does not own, so [asserting behavior](./assert-behavior.md) means naming the **key**, not the English string, through the `t` of the very instance the mount installs:
```typescript
// ✗ rewording the translation breaks the test although the component still picks the same key
expect(wrapper.get('.value').text()).toBe('None')
// ✓ asserts the decision: the value falls back to the "none" wording
expect(wrapper.get('.value').text()).toBe(t('none'))
```
A mistyped key does not pass quietly — `t` returns a marker for a key the locale has no entry for, which matches no rendered text.
Where the line falls:
| Value | Assert as |
| ---------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| a label, or a value that is itself a translation | `t('key')` — including a plural, `t('n-warnings', 2)` |
| a formatted date | `formatDateTime(timestamp)` from `@core/utils/time.util.ts`, as the component does |
| a string the component composes from several translations | a template literal of those `t(…)` calls |
| data reaching the component (a name, an id, an IP, a tag) | the literal — it is the test's own input |
| a number the component formats (`'8 B'`, `'4 GiB'`, `'2'`) | the literal — deriving it would copy the template |
## What `happy-dom` cannot do
There is no layout engine, and Vitest's `css` option is off, so component styles are never loaded. Out of reach:
- `toBeVisible()` and anything depending on real visibility — assert presence/absence instead (`expect(wrapper.find('.foo').exists()).toBe(false)`)
- `getComputedStyle` assertions on design tokens (color, padding, `flex-direction`)
- real event dispatch — `trigger()` simulates events
- canvas (ECharts), `ResizeObserver`, `IntersectionObserver` — stub the component that needs them
`happy-dom` also **lacks some browser APIs entirely**. `EventSource` is one: mounting a component that opens an SSE subscription throws `ReferenceError: EventSource is not defined`. It surfaces as an _unhandled rejection_, so Vitest **exits non-zero while reporting every test as passed** — do not read a green test list as success. Mock the subscribing module ([Mocking dependencies](./mocking.md)) so the subscription is never opened.
Never claim a component is untestable because there is no browser: its behaviour is testable here, only its appearance is not.
### Styling and visual non-regression (planned)
Appearance will be covered by a separate `visual` project, not by unit tests: Vitest browser mode with Playwright, `*.visual.test.ts` files mounting each variant and state of a component in light and dark, `expect.element(…).toMatchScreenshot()` against committed baselines, run by a `test:visual` script outside `yarn test`. Until it exists, a unit test never asserts a style, and a component's variant matrix is covered through its classes.

View File

@@ -0,0 +1,49 @@
# Testing composables
A composable that relies on a Vue context (`useI18n`, `inject`, an effect scope, plugins) must run **inside a mounted component**: a throwaway component whose `setup` calls it, mounted with the package's global test config. `mountComposable` (`@core-test/mount-composable.ts`) does it and returns `{ wrapper }`; XO 6 has its own, on its global test config (see [XO 6 composables](../../../web/docs/tests/testing-composables.md)). `mountComposable` renders nothing, so a composable needing rendered elements (a `useTemplateRef` target, as `useMenuPopup`) is the one case mounted by hand, with a component rendering them. A composable needing no Vue context is called directly, like a [utility](./testing-utilities.md).
Because the real i18n instance is installed, translations resolve to actual strings, and the assertion builds its expected label with `t` instead of hard-coding the wording — see [Assert behavior](./assert-behavior.md).
The composable result becomes the component state, so `wrapper.vm` exposes it with refs **already unwrapped** — no `.value`. Read through it rather than destructuring it: a destructured value is a snapshot and stops following updates.
The wrapper is unmounted after the test, so `onUnmounted` and `onScopeDispose` cleanup runs and no watcher of a previous test can re-fire in the next one.
## Reactivity
To test that a composable reacts to its source, pass a `ref` and reassign it:
```typescript
const source = ref(createItem({ status: 'running' }))
const { wrapper } = mountComposable(() => useItemStatus(source))
expect(wrapper.vm.icon).toBe('status:running-circle')
source.value = createItem({ status: 'halted' })
expect(wrapper.vm.icon).toBe('status:halted-circle')
```
## Composables whose returned function calls `useI18n` / `inject`
`useI18n()` must be called synchronously during a component `setup()`. If a composable returns a function that _itself_ calls `useI18n`, you cannot call that function from the test body after the mount has returned — it throws `Must be called at the top of a 'setup' function`. Invoke it **inside** the `setup` callback instead:
```typescript
const startTimeInSeconds = 1660000000
const { wrapper } = mountComposable(() => {
const { locale } = useI18n()
return {
relativeStartTime: useItemUtils(createItem()).getRelativeStartTime(startTimeInSeconds),
expectedRelativeTime: getRelativeTime(new Date(startTimeInSeconds * 1000), locale.value),
}
})
expect(wrapper.vm.relativeStartTime).toBe(wrapper.vm.expectedRelativeTime)
```
Note the object literal: `setup()` returns the component **bindings**, so the callback must hand back an object. A lone ref is not component state and would not surface on `wrapper.vm`. Anything the assertion needs — the `t`, a `locale`, an expected value — is returned alongside, which is why the callback body is a block rather than a bare object.
The expected value is **derived the way production derives it** ([Assert behavior](./assert-behavior.md)): `getRelativeTime` owns the wording, and what the composable decides is which date to hand it. `expect(typeof …).toBe('string')` would pass for any string, including one built from a start time read as milliseconds instead of seconds — it asserts the type, not the behavior. Where a value is environment-dependent, name the helper production uses and call it with the same input; never assert merely that the value is non-empty or differs from some other label.
Functions that only touch refs/computed can be called on the returned object as usual.

View File

@@ -0,0 +1,21 @@
# Testing pure utilities
Utility functions (`*.util.ts`) are pure — import and call them directly, and assert `input → output`. No mounting, no mocks.
```typescript
describe('toVariants', () => {
it('renders a `true` value as the bare key', () => {
expect(toVariants({ disabled: true })).toEqual(['disabled'])
})
it('drops falsy values', () => {
expect(toVariants({ accent: undefined, disabled: false, size: '' })).toEqual([])
})
})
```
Cover the meaningful edge cases: empty input, missing samples (`NaN` propagation), `null` data, and boundary rounding.
> **Logic extracted from a component is tested here**, not through the component — see [Keep components thin](./testing-components.md#keep-components-thin).
> **A util more than one consumer needs lives once.** Generic logic belongs in `web-core/lib/utils/` (or a shared `@vates/*` package), tested there; an app or a module never forks it. Where XO 6 keeps its own shared utils, see [XO 6 utilities](../../../web/docs/tests/testing-utilities.md).

View File

@@ -1,29 +0,0 @@
<template>
<div class="vts-flag-legend">
<VtsIcon name="fa:circle" size="current" class="dot" />
<span class="typo-body-regular-small">
<slot />
</span>
</div>
</template>
<script setup lang="ts">
import VtsIcon from '@core/components/icon/VtsIcon.vue'
defineSlots<{
default(): any
}>()
</script>
<style lang="postcss" scoped>
.vts-flag-legend {
display: flex;
align-items: center;
gap: 0.8rem;
color: var(--color-info-txt-base);
.dot {
font-size: 0.8rem;
}
}
</style>

View File

@@ -1,11 +1,11 @@
<template>
<UiTableCell align="center" class="vts-flag-cell">
<VtsIcon v-if="flagged" name="fa:circle" size="current" class="dot" />
<UiOverridden v-if="flagged" />
</UiTableCell>
</template>
<script setup lang="ts">
import VtsIcon from '@core/components/icon/VtsIcon.vue'
import UiOverridden from '@core/components/ui/overridden/UiOverridden.vue'
import UiTableCell from '@core/components/ui/table-cell/UiTableCell.vue'
defineProps<{
@@ -16,10 +16,5 @@ defineProps<{
<style lang="postcss" scoped>
.vts-flag-cell {
width: 4rem;
.dot {
font-size: 0.8rem;
color: var(--color-info-txt-base);
}
}
</style>

View File

@@ -0,0 +1,21 @@
import UiOverridden from '@core/components/ui/overridden/UiOverridden.vue'
import { createGlobalTestConfig } from '@core-test/create-global-test-config.ts'
import { mount } from '@vue/test-utils'
function mountOverridden(label?: string) {
return mount(UiOverridden, {
slots: label === undefined ? {} : { default: label },
global: createGlobalTestConfig(),
})
}
it('renders only the dot when no label is given', () => {
const wrapper = mountOverridden()
expect(wrapper.text()).toBe('')
expect(wrapper.find('.typo-body-regular-small').exists()).toBe(false)
})
it('reads the label it is given', () => {
expect(mountOverridden('Added').text()).toBe('Added')
})

View File

@@ -0,0 +1,32 @@
<!-- v1 -->
<template>
<span class="ui-overridden">
<VtsIcon name="fa:circle" size="current" class="icon" />
<span v-if="slots.default" class="typo-body-regular-small">
<slot />
</span>
</span>
</template>
<script lang="ts" setup>
import VtsIcon from '@core/components/icon/VtsIcon.vue'
const slots = defineSlots<{
default?(): any
}>()
</script>
<style lang="postcss" scoped>
.ui-overridden {
display: inline-flex;
align-items: center;
gap: 0.8rem;
height: 2.4rem;
color: var(--color-info-txt-base);
white-space: nowrap;
.icon {
font-size: 0.8rem;
}
}
</style>

View File

@@ -1,8 +1,8 @@
# Testing
This guide documents the unit-testing conventions used in `@xen-orchestra/web`, as established across the `pool`, `host` and `vm` modules. Follow it when adding tests for a new module, composable, utility or component.
This guide documents what is specific to the unit tests of `@xen-orchestra/web` (XO 6). The conventions shared with `@xen-orchestra/web-core` — assert behavior, file layout, setup helpers, mocking, utilities, composables, components — live in the [web-core test docs](../../web-core/docs/tests.md): read them first.
**Start with [Assert behavior, not implementation](./tests/assert-behavior.md)** — it is the rule the rest of this guide serves.
**Start with [Assert behavior, not implementation](../../web-core/docs/tests/assert-behavior.md)** — it is the rule the rest of this guide serves.
## What to test first
@@ -12,26 +12,24 @@ A fixed priority, not a preference:
2. **Composables and utilities** (`*.composable.ts`, `*.util.ts`) — top priority
3. **Pages** (`src/pages/**`) — lowest, and deliberately thin: assert which components render, never their values
Testing a page is a different job from testing a component, and the component is the more valuable one. A component should not carry much complex logic — when it does, extract that into a composable or utility and test it there.
Testing a page is a different job from testing a component, and the component is the more valuable one (see [Keep components thin](../../web-core/docs/tests/testing-components.md#keep-components-thin)).
### Only the app's own behaviour
An XO 6 test covers what the app decides, never what `@xen-orchestra/web-core` does on its own: a side panel opening on a selection, a store re-expanding on a resize, a select opening its options all belong to the web-core tests. A web-core component may be rendered beside the code under test when the app's rule depends on it, but the assertion must be about that rule: a test that still passes once the app's code is removed is testing web-core and is deleted, not written. A state the app sets on a web-core component (`busy`, `disabled`, `selected`, a table `state`…) is asserted through that component's props (`getUiButton(wrapper, label).props('busy')`), never through the DOM it renders for it; a user action clicks the real `<button>` (`getButton(wrapper, label)`). A composable member that only forwards to a web-core store gets no test of its own. Selects: see [Testing components](./tests/testing-components.md#selects).
An XO 6 test covers what the app decides, never what `@xen-orchestra/web-core` does on its own: that is tested in web-core (see [Which package tests what](../../web-core/docs/tests.md#which-package-tests-what)). A web-core component may be rendered beside the code under test when the app's rule depends on it, but the assertion must be about that rule. A state the app sets on a web-core component (`busy`, `disabled`, `selected`, a table `state`…) is asserted through that component's props (`getUiButton(wrapper, label).props('busy')`), never through the DOM it renders for it; a user action clicks the real `<button>` (`getButton(wrapper, label)`). A composable member that only forwards to a web-core store gets no test of its own. Selects: see [Testing components](./tests/testing-components.md#selects).
## Getting started
## Shared conventions (web-core docs)
- [Assert behavior, not implementation](../../web-core/docs/tests/assert-behavior.md)
- [File layout and structure](../../web-core/docs/tests/file-structure.md)
- [Shared test helpers](../../web-core/docs/tests.md#shared-test-helpers) — generic helpers in `web-core/test/` (`@core-test`), domain-aware ones in `src/test/`
## XO 6 specifics
- [Assert behavior, not implementation](./tests/assert-behavior.md) — the one rule that outranks the others
- [Test runner](./tests/running-tests.md) — Vitest setup and the commands to run a suite
## Writing a test
- [File layout and structure](./tests/file-structure.md) — where a test lives, how it is named, how it is organized
- [Setup: prefer helpers over `beforeEach`](./tests/setup-helpers.md) — local helpers, and the shared `use<X>EnhancedData` ones
- [Test data factories](./tests/factories.md) — the `src/test/create*` factories and how to use them
## What you are testing
- [Testing pure utilities](./tests/testing-utilities.md) — `*.util.ts`, called directly
- [Testing composables](./tests/testing-composables.md) — `mountComposable`, reactivity, `useI18n`
- [Testing components](./tests/testing-components.md) — `mount`, querying rendered output, and what `happy-dom` cannot do
- [Mocking dependencies](./tests/mocking.md) — the typed `vi.mock` form, and the network stub
- [Setup helpers](./tests/setup-helpers.md) — local storage, the shared `use<X>EnhancedData` helpers
- [Test data factories](./tests/factories.md) — the `src/test/create*` factories and helpers
- [Utilities](./tests/testing-utilities.md) — where XO 6 keeps shared utils
- [Composables](./tests/testing-composables.md) — `mountComposable`, `mountComposableWithI18n`
- [Components](./tests/testing-components.md) — the `src/test/` readers, tables, charts, legends, routing, selects, pages
- [Mocking](./tests/mocking.md) — the shared remote-resource mocks, and the network stub

File diff suppressed because one or more lines are too long

View File

@@ -1,44 +0,0 @@
# File layout and structure
## File layout and naming
- A test file lives **next to** the file it covers, named `<source-name>.unit.test.ts`.
- `xo-host.util.ts` → `xo-host.util.unit.test.ts`
- `use-pool-enhanced-data.composable.ts` → `use-pool-enhanced-data.composable.unit.test.ts`
- `VmSystemGraphics.vue` → `VmSystemGraphics.unit.test.ts` (the `.vue` is dropped)
- Shared test data **factories** and helpers live in `src/test/`.
## Structuring a test file
- **One `describe` block per function or exposed property**, labeled with its exact name (`describe('getHostInfo')`, `describe('powerState')`). A component test has no such members: group with `describe` only to separate genuinely distinct behaviors, otherwise flat `it`s read better.
- Use `it` (not `test`).
- The name completes the sentence the `it` starts: a **present-tense assertion**, lowercase, no trailing period, and **without a redundant prefix** — the `describe` label already carries the function name. `it('formats the core count with its socket count')` reads as one sentence; `it('getHostCoreSocketInfo formats …')` stutters.
```typescript
describe('getHostCoreSocketInfo', () => {
it('formats the core count with its socket count', () => {
const host = createHost({ cpus: { cores: 8, sockets: 2 } })
expect(getHostCoreSocketInfo(host)).toBe('8 (2)')
})
it('falls back to zero for missing core and socket counts', () => {
const host = createHost({ cpus: {} })
expect(getHostCoreSocketInfo(host)).toBe('0 (0)')
})
})
```
## Do not import from `vitest`
`globals: true` (in `vite.config.ts`) together with `"types": ["vitest/globals"]` make `describe`, `it`, `expect`, `vi` and `beforeEach` available globally. **Never** add `import { ... } from 'vitest'`.
Those types are declared in `tsconfig.vitest.json`, not in `tsconfig.app.json`, so they are ambient in test files only. A `expect()` left behind in production code is a type error rather than a runtime `ReferenceError` in the browser.
The two projects split on the file name:
| Project | Covers | Test globals |
| ---------------------- | ------------------------------------------------------ | ------------ |
| `tsconfig.app.json` | everything **except** `*.unit.test.ts` and `src/test/` | no |
| `tsconfig.vitest.json` | everything, tests included | yes |

View File

@@ -1,43 +1,10 @@
# Mocking dependencies
# Mocking (XO 6)
Keep the mock boundary tight: **mock only the remote-resource collections / stores** a composable depends on, and let pure utilities and icon helpers run for real.
The typed `vi.mock` form, `vi.hoisted` and shared mock modules are in [Mocking dependencies](../../../web-core/docs/tests/mocking.md). In XO 6, **mock only the remote-resource collections / stores** a composable depends on.
Use the **typed** mock form — `vi.mock(import('<module>'), …)` — so a rename breaks type-check instead of silently leaving a stale mock. Create the stub functions with `vi.hoisted` (a plain `const fn = vi.fn()` referenced in the factory throws, because the mock is hoisted above imports), and reset them in `beforeEach`:
The shared mock modules of XO 6 live in `src/test/`. `mock-xo-vm-collection.ts` stands for `useXoVmCollection`: `vmCollectionMock.areVmsReady` is true after a reset; set it to false to hold the collection as still loading.
```typescript
const { getHostById, isMasterHost } = vi.hoisted(() => ({
getHostById: vi.fn(),
isMasterHost: vi.fn(),
}))
vi.mock(import('@/modules/host/remote-resources/use-xo-host-collection.ts'), () => ({
useXoHostCollection: (() => ({ getHostById, isMasterHost })) as unknown as typeof useXoHostCollection,
}))
beforeEach(() => {
getHostById.mockReset()
isMasterHost.mockReset()
})
```
Note the cast: the typed form checks the factory return against the **whole** module, so a partial mock of a large export needs `as unknown as typeof useX` (with an `import type { useX }`).
When several test files mock the same remote resource (a collection or a single resource) with the same shape, the mock lives once in `src/test/` and the test file only points `vi.mock` to it; its exported state is read and changed by the tests, and reset in `beforeEach`:
```typescript
vi.mock(
import('@/modules/vm/remote-resources/use-xo-vm-collection.ts'),
() => import('@/test/mock-xo-vm-collection.ts')
)
beforeEach(() => {
vmCollectionMock.reset()
})
```
`vmCollectionMock.areVmsReady` is true after a reset; set it to false to hold the collection as still loading.
Collections always read together share one mock module exporting each of their composables: `mock-xo-collections.ts` stands for the pool, host, SR, network, PBD, PIF and VM template collections. Each `vi.mock` of these modules points to it (`vi.mock` is hoisted, it cannot be wrapped in a helper), and `xoCollectionsMock.reset()` resets them all. Its pool collection also answers `getPoolById`, `hasPoolById` and `useGetPoolById` from `pools`, its host collection `getHostById` from `hosts`, its SR and network collections `getSrById` and `getNetworkById`, its PBD collection `pbdsBySr` from `pbds`, and `arePoolsReady`, `areSrsReady`, `areNetworksReady` and `areTemplatesReady` (true after a reset) let a test hold that collection as still loading. `seedV2vListPool` (`seed-v2v-list-pool.ts`) seeds the pool of a V2V list and what it offers; `xoCollectionsMock.startLoadingPools()` empties the pools and clears `arePoolsReady`.
Collections always read together share one mock module exporting each of their composables: `mock-xo-collections.ts` stands for the pool, host, SR, network, PBD, PIF and VM template collections. Each `vi.mock` of these modules points to it, and `xoCollectionsMock.reset()` resets them all. Its pool collection also answers `getPoolById`, `hasPoolById` and `useGetPoolById` from `pools`, its host collection `getHostById` from `hosts`, its SR and network collections `getSrById` and `getNetworkById`, its PBD collection `pbdsBySr` from `pbds`, and `arePoolsReady`, `areSrsReady`, `areNetworksReady` and `areTemplatesReady` (true after a reset) let a test hold that collection as still loading. `seedV2vListPool` (`seed-v2v-list-pool.ts`) seeds the pool of a V2V list and what it offers; `xoCollectionsMock.startLoadingPools()` empties the pools and clears `arePoolsReady`.
The same goes for `mock-xo-v2v-vm-rows-collections.ts`, the VM, task and VM snapshot collections the V2V VM rows are built from: `v2vVmRowsCollectionsMock` holds `vms`, `tasks`, `snapshots` and their `are…Ready` flags (true after a reset; set one to false to hold that collection as still loading). Its VMs are those of `mock-xo-vm-collection.ts`, which it re-exports and resets.

View File

@@ -1,10 +1,8 @@
# Test runner
Testing uses **Vitest 4** with a single `unit` project (see `vite.config.ts`): every test matches `**/*.unit.test.ts` and runs on `happy-dom`, CLI-only, no browser.
XO 6 runs the same setup as web-core ([Setup in web-core](../../../web-core/docs/tests.md#setup-in-web-core)), configured in `vite.config.ts` (`test`).
Utilities, composables **and components** all run there — mounting a component needs `@vue/test-utils`, not a browser. Only real-CSS and layout assertions are out of reach; see [Testing components](./testing-components.md).
`test.alias` in that config maps `placement.js` to its ESM build: the package only declares a `module` entry, which the Node-style resolution used by Vitest ignores, so any component pulling in a menu fails to resolve it otherwise.
`test.alias` in that config maps `placement.js` to its ESM build: the package only declares a `module` entry, which the Node-style resolution used by Vitest ignores, so any component pulling in a menu fails to resolve it otherwise. It also maps `@core-test` to `web-core/test/`, the generic helpers shared with the web-core tests (see [Shared test helpers](../../../web-core/docs/tests.md#shared-test-helpers)); `tsconfig.vitest.json` declares the same path.
## Running tests

View File

@@ -1,36 +1,10 @@
# Setup: prefer helpers over `beforeEach`
# Setup helpers (XO 6)
Reserve `beforeEach` for **mock resets only**. Repeated setup goes into small local helper/factory functions at the top of the file:
A composable mounted with different fixture overrides across a file gets one helper taking those overrides — never a `mountComposable(...)` call repeated per test:
```typescript
function mountVmUtils(overrides: Partial<FrontXoVm> = {}) {
return mountComposable(() => useXoVmUtils(createVm(overrides))).wrapper.vm
}
it('is true while a state-changing operation is pending', () => {
const result = mountVmUtils({ current_operations: { task1: VM_OPERATIONS.CLEAN_REBOOT } })
expect(result.isChangingState).toBe(true)
})
```
A helper returning `wrapper.vm` serves a **reactivity** test too, as long as it accepts the source as a `ref` (`MaybeRefOrGetter`): `wrapper.vm` keeps following the updates. Only a test that must call a function returned by the composable, or build its expected value, _inside_ the `setup` callback stays inline (see [Testing composables](./testing-composables.md)).
Because mocks are read lazily, calling `getX.mockReturnValue(...)` in the test body _before_ invoking the helper still takes effect.
This applies to **navigation into the result** too, not only to mounting. An expression such as `result.filterableServers[0]`, repeated across a `describe` block, is repeated setup — give it a helper and assert on a named local, rather than re-deriving it in every test.
The exception is a **reactivity** test: it must keep reading through the mounted `vm` after reassigning the source ref. A helper returning a snapshot of the first item would defeat the test.
## Unmounting
`src/test/setup.ts` calls `enableAutoUnmount(afterEach)`, so every wrapper — `mount` or `mountComposable` — is unmounted after the test that created it. Never unmount by hand for cleanup, and never mount in `beforeAll`: that wrapper would be torn down after the first test. The one `wrapper.unmount()` allowed is the act of a test asserting what `onUnmounted` does.
The shared rules — helpers over `beforeEach`, auto-unmount — are in [Setup](../../../web-core/docs/tests/setup-helpers.md). XO 6 adds:
## Local storage
`src/test/setup.ts` clears `localStorage` before each test, so every test starts with an empty storage. Never clear it again in a test file: store what a test needs in its own setup (e.g. `seedV2vMigrationList`).
`src/test/setup.ts` stubs `fetch` (see [Mocking](./mocking.md#network)), calls `enableAutoUnmount(afterEach)` and clears `localStorage` before each test, so every test starts with an empty storage. Never clear it again in a test file: store what a test needs in its own setup (e.g. `seedV2vMigrationList`).
## Shared helpers: `use<X>EnhancedData`
@@ -50,6 +24,6 @@ it('maps poolName from the server pool label', () => {
})
```
Types are inferred from the composable itself, so `filterableServer` is a `ServerFilterableData` and `mountFirstDisplayData()` a `ServerDisplayData` — no annotation at the call site. `mountEnhancedData` returns the mounted instance, for the reactivity test.
Types are inferred from the composable itself, so `filterableServer` is a `PoolFilterableData` and `mountFirstDisplayData()` a `PoolDisplayData` — no annotation at the call site. `mountEnhancedData` returns the mounted instance, for the reactivity test.
Adding a new `use<X>EnhancedData` test means three lines of wiring, not three copied helpers.

View File

@@ -1,6 +1,6 @@
# Testing components
# Components (XO 6)
Components run in the same `unit` project as everything else: `@vue/test-utils` `mount` on `happy-dom`, **no browser needed**. Mount with `createGlobalTestConfig()` so the real `vue-i18n` instance, the app form validation messages (`RegleVuePlugin` with `formValidationConfig`, as in `main.ts`) and a fresh Pinia are installed, and give the repeated mount a helper (see [Setup](./setup-helpers.md)):
The shared rules — keep components thin, extract under unchanged tests, assert what the user reads, never spell out a translation, what `happy-dom` cannot do — are in [Testing components](../../../web-core/docs/tests/testing-components.md). In XO 6, mount with `createGlobalTestConfig()` so the real `vue-i18n` instance, the app form validation messages (`RegleVuePlugin` with `formValidationConfig`, as in `main.ts`) and a fresh Pinia are installed:
```typescript
import VmSystemGraphics from '@/modules/vm/components/system/VmSystemGraphics.vue'
@@ -23,47 +23,9 @@ it('shows VGA as enabled when the VM uses the "std" adapter', () => {
})
```
The test file sits next to the component, named `<ComponentName>.unit.test.ts` (no `.vue`). Group with `describe` only when the component has several distinct behaviors to separate; a small component reads better as flat `it`s.
## Reading rendered values
## Keep components thin
A component should not carry much complex logic. Non-trivial computation (chart series, aggregation, formatting rules) belongs in a `*.util.ts` or a composable, tested directly — that is cheaper and covers more branches than mounting. A component that is awkward to test is telling you to **extract**, not to write a heavier component test, and never to skip the test.
What is left to assert at the component level is what it renders: labels, formatted values, conditional rows, empty states.
### Extracting from a tested component
The extraction is a refactor, so the tests come **first** and are what proves it changed nothing:
1. Write the tests against the component **as it stands**, and run them green.
2. Extract.
3. Re-run those tests **unchanged**.
4. Move the ones the extraction made redundant down next to the new util/composable, and delete them from the component test.
Step 3 is the gate. A test that has to be edited to pass is reporting a behavior change — say so, do not absorb it into the diff. Tests written only _after_ an extraction describe the new code and cannot catch what the extraction broke, which is the whole risk being taken.
Step 4 is selective. A test that only exercised the logic now living in the util moves; a test asserting something the component alone does — rendering, conditional rows, empty states, feeding the util's output into the template — stays.
## Assert what the user reads, not the markup
`wrapper.text()` concatenates the whole subtree **with no separators**, so `'8 B'` and `'Disabled'` run together. It is fine for `toContain` on a single component, but it cannot express "this label has this value". Query instead:
```typescript
// every card title, in order
expect(wrapper.findAll('.ui-title').map(title => title.text())).toEqual([t('graphics-display')])
// a key/value row: the markup is semantic, so label and value are addressable
const rows = wrapper.findAll('.vts-tabular-key-value-row')
const labelledValues = Object.fromEntries(rows.map(row => [row.get('dt.label').text(), row.get('dd.value').text()]))
expect(labelledValues).toEqual({ [t('vga')]: t('disabled'), [t('video-ram')]: '8 B' })
```
Prefer this shape: one assertion covering every row a user sees, and it fails loudly when a value lands under the wrong label. Assert against **class names and semantic elements**, never a positional chain of child indexes.
The class must exist for the component's own CSS: **never add a class only for a test**, and remove one whose CSS is gone. Without a styled class, query the component (`getComponent`), a styled class of a child component, or the text the user reads.
`src/test/find-rendered-values.ts` does exactly that reduction, so a card test does not re-roll it:
A label/value row is read through one query covering every row a user sees ([Assert what the user reads](../../../web-core/docs/tests/testing-components.md#assert-what-the-user-reads-not-the-markup)). `src/test/find-rendered-values.ts` does that reduction, so a card test does not re-roll it:
| Helper | Reads |
| ---------------------------- | ------------------------------------------------------------------ |
@@ -107,29 +69,9 @@ expect(findTableRows(wrapper)).toEqual([
`findTableRows` reads cells rather than each row's whole text for the same reason the helpers above split label from value: `row.text()` concatenates the columns, so a patch named `XSAPATCH-1` at version `1.0` and one named `XSAPATCH-11` at version `.0` read identically.
### Never spell out a translation
### Translations
A rendered label or a translated value is wording the component does not own, so [asserting behavior](./assert-behavior.md) means naming the **key**, not the English string. `src/test/i18n.ts` exposes the `t` of the very instance `createGlobalTestConfig()` installs:
```typescript
// ✗ rewording the translation breaks the test although the component still picks the same key
expect(findLabelledValues(wrapper)).toEqual({ 'Suspend storage repository': 'None' })
// ✓ asserts the decision: the suspend-SR row, falling back to the "none" wording
expect(findLabelledValues(wrapper)).toEqual({ [t('suspend-storage-repository')]: t('none') })
```
A mistyped key does not pass quietly — `t` returns a `⟨key⟩` marker for a key the locale has no entry for, which matches no rendered text.
Where the line falls:
| Value | Assert as |
| ---------------------------------------------------------- | ---------------------------------------------------------------------------------- |
| a label, or a value that is itself a translation | `t('key')` — including a plural, `t('n-vcpus', 2)` |
| a formatted date | `formatDateTime(timestamp)` from `@core/utils/time.util.ts`, as the component does |
| a string the component composes from several translations | a template literal of those `t(…)` calls |
| data reaching the component (a name, an id, an IP, a tag) | the literal — it is the test's own input |
| a number the component formats (`'8 B'`, `'4 GiB'`, `'2'`) | the literal — deriving it would copy the template |
`src/test/i18n.ts` exposes the `t` and `n` of the very instance `createGlobalTestConfig()` installs: import them to build an expected label (see [Never spell out a translation](../../../web-core/docs/tests/testing-components.md#never-spell-out-a-translation)).
## Tables
@@ -222,7 +164,7 @@ Three things shape those assertions:
`createGlobalTestConfig()` installs a router on **every** mount, built by `src/test/create-test-router.ts` over the **real generated routes** on an in-memory history. Two unrelated things need it:
- A component rendering `RouterLink`. Without a router the link resolves to a plain element and its scoped slot (`isActive`, `href`) is never invoked, so the markup renders **empty instead of failing** — a tab bar silently becomes no tabs, and an assertion on it passes vacuously.
- Anything reaching `useUiStore` (`VtsStateHero`, `VtsKeyValueRow`, `TabItem`…). That store calls `useRouter()`/`useRoute()` in its setup, so a router-less mount logs two `injection "Symbol(router)" not found` warnings, and reading `uiStore.hasUi` would throw on `route.query`.
- Anything reaching `useUiStore` (`VtsStateHero`, `VtsKeyValueRow`, `UiTabItem`…). That store calls `useRouter()`/`useRoute()` in its setup, so a router-less mount logs two `injection "Symbol(router)" not found` warnings, and reading `uiStore.hasUi` would throw on `route.query`.
Because the routes are the real ones, `href` assertions are real paths (`/vm/vm-42/system`) rather than a stub's echo of its own prop. Page components are swapped for an empty one: a test never renders a page, and installing a router runs an initial navigation that would otherwise import the whole page module graph.
@@ -236,8 +178,8 @@ const wrapper = mount(VmHeader, { props: { vm }, global: createGlobalTestConfig(
expect(
wrapper
.findAll('.tab-item')
.filter(tab => tab.classes('active'))
.findAllComponents(UiTabItem)
.filter(tab => tab.props('active'))
.map(tab => tab.text())
).toEqual([t('system')])
```
@@ -246,21 +188,14 @@ Pushing before mounting is what makes the active tab assertable; without a push
## Selects
How `FormSelect` and `VtsSelect` render and open their options belongs to the web-core tests, never to an XO 6 one:
How `VtsSelect` renders and opens its options belongs to the web-core tests, never to an XO 6 one; XO 6's `FormSelect` wraps it:
- A component that only passes select bindings on is mounted with `createGlobalTestConfig({ stubs: { FormSelect: true } })`, given `createSelectBindings`, and read with `findSelectStubLabels`.
- The options a form builds (their labels, their custom properties) are read by mounting the form with `mountWithSelect`, rendering a `VtsSelect` for its select, then `openSelect` and `findSelectOptionLabels`; `findShownSelections` reads the selection each select shows.
## What `happy-dom` cannot do
## Remote-resource collections
There is no layout engine, and Vitest's `css` option is off, so component styles are never loaded. Out of reach:
- `toBeVisible()` and anything depending on real visibility — assert presence/absence instead (`expect(wrapper.find('.foo').exists()).toBe(false)`)
- `getComputedStyle` assertions on design tokens (color, padding, `flex-direction`)
- real event dispatch — `trigger()` simulates events
- canvas (ECharts), `ResizeObserver`, `IntersectionObserver` — for a chart card, stub the chart (see [Chart cards](#chart-cards))
`happy-dom` also **lacks some browser APIs entirely**. `EventSource` is one: mounting a component that reaches a remote-resource collection opens an SSE subscription and throws `ReferenceError: EventSource is not defined`. It surfaces as an _unhandled rejection_, so Vitest **exits non-zero while reporting every test as passed** — do not read a green test list as success. Mock the collection ([Mocking dependencies](./mocking.md)) so the subscription is never opened.
A remote-resource collection opens an SSE subscription, which `happy-dom` cannot ([What `happy-dom` cannot do](../../../web-core/docs/tests/testing-components.md#what-happy-dom-cannot-do)): mock it with its `src/test/` module ([Mocking](./mocking.md)).
## Pages

View File

@@ -1,8 +1,8 @@
# Testing composables
# Composables (XO 6)
A composable that relies on a Vue context (`useI18n`, `inject`, an effect scope, plugins) must run **inside a mounted component**. Use the helpers from `src/test/mount-composable.ts`, which mount a throwaway component with `createGlobalTestConfig()`: the real `vue-i18n` instance, the app form validation messages, a fresh Pinia and a router.
The shared rules — mounting in a Vue context, reactivity, a returned function calling `useI18n` — are in [Testing composables](../../../web-core/docs/tests/testing-composables.md). XO 6 mounts with the helpers of `src/test/mount-composable.ts`, which mount a throwaway component with `createGlobalTestConfig()`: the real `vue-i18n` instance, the app form validation messages, a fresh Pinia and a router.
Because the real i18n instance is installed, translations resolve to actual strings, and the assertion builds its expected label with `t` instead of hard-coding the wording — see [Assert behavior](./assert-behavior.md). `mountComposableWithI18n` mounts the composable, spreads its result, adds the `t` of the mounted component and returns `wrapper.vm`:
`mountComposableWithI18n` mounts the composable, spreads its result, adds the `t` of the mounted component and returns `wrapper.vm`:
```typescript
import { mountComposableWithI18n } from '@/test/mount-composable.ts'
@@ -16,47 +16,3 @@ expect(result.powerState.text).toBe(result.t('vm:status:running'))
`mountComposable` does the same without `t` and returns `{ wrapper }`, for a test that needs neither the translation nor a returned object spread.
Both take the options of `createGlobalTestConfig()` as a second argument, e.g. `{ router }` for a composable that navigates (build it with `createTestRouter()` and assert on `router.currentRoute.value`), or `{ provide }` for a composable injecting what a parent component provides.
The composable result becomes the component state, so `wrapper.vm` exposes it with refs **already unwrapped** — no `.value`. Read through it rather than destructuring it: a destructured value is a snapshot and stops following updates.
The wrapper is unmounted after the test, so `onUnmounted` and `onScopeDispose` cleanup runs and no watcher of a previous test can re-fire in the next one.
## Reactivity
To test that a composable reacts to its source, pass a `ref` and reassign it:
```typescript
const vm = ref(createVm({ power_state: VM_POWER_STATE.RUNNING }))
const { wrapper } = mountComposable(() => useXoVmUtils(vm))
expect(wrapper.vm.powerState.icon).toBe('status:running-circle')
vm.value = createVm({ power_state: VM_POWER_STATE.HALTED })
expect(wrapper.vm.powerState.icon).toBe('status:halted-circle')
```
## Composables whose returned function calls `useI18n` / `inject`
`useI18n()` must be called synchronously during a component `setup()`. If a composable returns a function that _itself_ calls `useI18n` (e.g. `useXoHostUtils(host).getRelativeStartTime`), you cannot call that function from the test body after `mountComposable` has returned — it throws `Must be called at the top of a 'setup' function`. Invoke it **inside** the `mountComposable` callback instead:
```typescript
const startTimeInSeconds = 1660000000
const { wrapper } = mountComposable(() => {
const { locale } = useI18n()
return {
relativeStartTime: useXoHostUtils(createHost()).getRelativeStartTime(startTimeInSeconds),
expectedRelativeTime: getRelativeTime(new Date(startTimeInSeconds * 1000), locale.value),
}
})
expect(wrapper.vm.relativeStartTime).toBe(wrapper.vm.expectedRelativeTime)
```
Note the object literal: `setup()` returns the component **bindings**, so the callback must hand back an object. A lone ref is not component state and would not surface on `wrapper.vm`. Anything the assertion needs — the `t`, a `locale`, an expected value — is returned alongside, which is why the callback body is a block rather than a bare object.
The expected value is **derived the way production derives it** ([Assert behavior](./assert-behavior.md)): `getRelativeTime` owns the wording, and what the composable decides is which date to hand it. `expect(typeof …).toBe('string')` would pass for any string, including one built from a start time read as milliseconds instead of seconds — it asserts the type, not the behavior. Where a value is environment-dependent, name the helper production uses and call it with the same input; never assert merely that the value is non-empty or differs from some other label.
Functions that only touch refs/computed (e.g. `getPowerState`) can be called on the returned object as usual.

View File

@@ -1,26 +1,7 @@
# Testing pure utilities
# Utilities (XO 6)
Utility functions (`*.util.ts`) are pure — import and call them directly, and assert `input → output`. No mounting, no mocks.
How to test a util is in [Testing pure utilities](../../../web-core/docs/tests/testing-utilities.md). XO 6 adds where its utils live:
```typescript
describe('buildCpuUsageSeries', () => {
it('averages the usage across all cpus at each index', () => {
const data = createHostStats({ stats: { cpus: { cpu0: [10, 20], cpu1: [30, 40] } } })
expect(buildCpuUsageSeries(data)).toEqual([
{ timestamp: 990_000, value: 20 },
{ timestamp: 1_000_000, value: 30 },
])
})
it('returns an empty array for null data', () => {
expect(buildCpuUsageSeries(null)).toEqual([])
})
})
```
Cover the meaningful edge cases: empty input, missing samples (`NaN` propagation), `null` data, and boundary rounding.
> **Prefer extracting pure logic into a util.** When a `<script setup>` holds non-trivial logic (chart series, formatting, aggregation), pull it into `modules/<mod>/utils/*.util.ts` and unit-test that — a component should not carry much complex logic. This is how the Pool and Host dashboard chart logic was made testable (`xo-pool-dashboard.util.ts`, `xo-host-dashboard.util.ts`). What remains in the component is then rendering, covered by [Testing components](./testing-components.md).
> **A util extracted from a module component goes to `modules/<mod>/utils/*.util.ts`.** This is how the Pool and Host dashboard chart logic was made testable (`xo-pool-dashboard.util.ts`, `xo-host-dashboard.util.ts`).
> **Logic more than one module needs goes to `src/shared/utils/`,** not copied per module. `shared/utils/chart-stats.util.ts` holds what the VM, host and pool dashboards all do — building timestamps, averaging cpu usage, deriving used memory, summing a bidirectional series, rounding an axis maximum — and is tested once, there. A `modules/<mod>/utils/*.util.ts` earns its place only for logic no other module has (`buildHostLoadAverageSeries`: hosts alone report a load average). Never add a module function that just forwards to the shared one: the component calls the shared function itself, passing the stats path it reads and the axis step it wants.

View File

@@ -12,7 +12,7 @@
</VtsRow>
</tbody>
</VtsTable>
<VtsFlagLegend v-if="flaggedRows.length > 0">{{ t('vdis-must-be-migrated') }}</VtsFlagLegend>
<UiOverridden v-if="flaggedRows.length > 0">{{ t('vdis-must-be-migrated') }}</UiOverridden>
<VtsErrorList v-if="showErrors && flaggedRows.length > 0">
<li v-for="row in flaggedRows" :key="row.vdi.id">
{{ t('vdi-destination-sr-required', { name: row.vdi.name_label }) }}
@@ -28,9 +28,9 @@ import { useXoVbdCollection } from '@/modules/vbd/remote-resources/use-xo-vbd-co
import { getVdiIcon } from '@/modules/vdi/utils/xo-vdi.util.ts'
import type { VmMigrateVdiRow } from '@/modules/vm/form/migrate/use-vm-migrate-mapping-form.ts'
import VtsErrorList from '@core/components/error-list/VtsErrorList.vue'
import VtsFlagLegend from '@core/components/table/VtsFlagLegend.vue'
import VtsRow from '@core/components/table/VtsRow.vue'
import VtsTable from '@core/components/table/VtsTable.vue'
import UiOverridden from '@core/components/ui/overridden/UiOverridden.vue'
import { usePagination } from '@core/composables/pagination.composable.ts'
import { useTableState } from '@core/composables/table-state.composable.ts'
import { useFormSelect } from '@core/packages/form-select'

View File

@@ -12,7 +12,7 @@
</VtsRow>
</tbody>
</VtsTable>
<VtsFlagLegend v-if="flaggedRows.length > 0">{{ t('vifs-must-be-reassigned') }}</VtsFlagLegend>
<UiOverridden v-if="flaggedRows.length > 0">{{ t('vifs-must-be-reassigned') }}</UiOverridden>
<VtsErrorList v-if="showErrors && flaggedRows.length > 0">
<li v-for="row in flaggedRows" :key="row.vif.id">
{{ t('vif-destination-network-required', { name: row.sourceNetwork?.name_label ?? row.vif.MAC }) }}
@@ -26,9 +26,9 @@ import type { FrontXoNetwork } from '@/modules/network/remote-resources/use-xo-n
import { useXoPifCollection } from '@/modules/pif/remote-resources/use-xo-pif-collection.ts'
import type { VmMigrateVifRow } from '@/modules/vm/form/migrate/use-vm-migrate-mapping-form.ts'
import VtsErrorList from '@core/components/error-list/VtsErrorList.vue'
import VtsFlagLegend from '@core/components/table/VtsFlagLegend.vue'
import VtsRow from '@core/components/table/VtsRow.vue'
import VtsTable from '@core/components/table/VtsTable.vue'
import UiOverridden from '@core/components/ui/overridden/UiOverridden.vue'
import { usePagination } from '@core/composables/pagination.composable.ts'
import { useTableState } from '@core/composables/table-state.composable.ts'
import { useFormSelect } from '@core/packages/form-select'

View File

@@ -14,7 +14,7 @@ import type { Router } from 'vue-router'
*
* The router is not only for components rendering `RouterLink`: the shared
* `useUiStore` calls `useRouter()`/`useRoute()` in its setup, so every component
* reaching that store (`VtsStateHero`, `VtsKeyValueRow`, `TabItem`…) needs one —
* reaching that store (`VtsStateHero`, `VtsKeyValueRow`, `UiTabItem`…) needs one —
* without it the injections miss, and reading `uiStore.hasUi` would throw.
*
* Pass a `router` to navigate before mounting, which is what makes an active

View File

@@ -5,6 +5,6 @@ import i18n from '@core/i18n.ts'
* so a test can build an expected value the way the component does — asserting
* *which* key or format was chosen instead of pinning the EN wording and the
* locale-formatted output it does not own (see
* [Assert behavior](../../docs/tests/assert-behavior.md)).
* [Assert behavior](../../../web-core/docs/tests/assert-behavior.md)).
*/
export const { t, n } = i18n.global

View File

@@ -1,7 +1,21 @@
{
"extends": "./tsconfig.app.json",
"include": [
"env.d.ts",
"./src/**/*",
"./src/**/*.vue",
"../web-core/env.d.ts",
"../web-core/lib/**/*",
"../web-core/lib/**/*.vue",
"../web-core/test/**/*"
],
"exclude": ["../web-core/lib/**/*.unit.test.ts", "../web-core/lib/**/*.unit.spec.ts"],
"compilerOptions": {
"types": ["vitest/globals"]
"types": ["vitest/globals"],
"paths": {
"@/*": ["./src/*"],
"@core/*": ["../web-core/lib/*"],
"@core-test/*": ["../web-core/test/*"]
}
}
}

View File

@@ -45,6 +45,7 @@ export default defineConfig(({ mode }) => {
globals: true,
setupFiles: ['./src/test/setup.ts'],
alias: {
'@core-test': fileURLToPath(new URL('../web-core/test', import.meta.url)),
// `placement.js` only declares a `module` entry, which the Node-style resolution used by Vitest ignores
'placement.js': fileURLToPath(new URL('../../node_modules/placement.js/dist/index.es.js', import.meta.url)),
},

View File

@@ -76,6 +76,7 @@
- [REST API] `GET /rest/v0/tasks/{id}?wait=true` now returns when a backup, metadata backup or restore ends, instead of waiting until the task is interrupted (PR [#10778](https://github.com/vatesfr/xen-orchestra/pull/10778))
- [Backups] A backup job that fails as a whole is now marked as failed in its task, instead of staying pending until XO restarts (PR [#10778](https://github.com/vatesfr/xen-orchestra/pull/10778))
- [REST API/Tasks] Aborting a running backup task that can't be aborted now fails with `forbidden operation` instead of `no such task` (with `sync=true`: 403 instead of 404) (PR [#10778](https://github.com/vatesfr/xen-orchestra/pull/10778))
- [Servers] Fix a pool disappearing from XO, its server stuck in "connecting" until it is disabled and enabled again, after a short network interruption (PR [#10814](https://github.com/vatesfr/xen-orchestra/pull/10814))
### Packages to release
@@ -110,6 +111,7 @@
- @xen-orchestra/web-core minor
- @xen-orchestra/xapi major
- xen-api major
- xo-collection major
- xo-server minor
- xo-server-audit minor
- xo-server-load-balancer patch

View File

@@ -157,7 +157,7 @@ useDirectChannel = false
Changing the mode is only supported forward : from direct OpenFlow Protocol channel to XAPI Plugin communication.
A migration script is provided to automatically convert the traffic rules.
See [SDN controller: migrate from the default mode](../manage-your-infrastructure/sdn-controller/advanced.md#migration-path) for details.
See [SDN Controller: OpenFlow rules](../manage-your-infrastructure/networking/sdn_controller.md#migration-path) for details.
## Custom certificate authority

View File

@@ -9,6 +9,14 @@ All updates are pushed through the updater, which is the central piece that keep
It also allows you to change your current version into another (Free, Starter, Enterprise or Premium) **without downloading a new XOA**.
:::warning Keep the XOA OS up to date
The updater keeps Xen Orchestra itself up to date, including the Node.js runtime when needed, and the appliance's OS automatically installs security updates as soon as they're available.
Since XOA has privileged access to your whole infrastructure, keeping its OS up to date is critical. Some updates, such as a new kernel, only take effect after a reboot: **don't postpone it**. Rebooting XOA doesn't affect your VMs, but schedule it outside your backup windows, as running backup jobs will likely hang.
For a newer base system, [replace your XOA](migrate_to_new_xoa.md) with a freshly deployed one.
:::
:::tip
By design, the updater is only available in XOA. If you are using XO from the sources, [update with `git` and rebuild](installation/install-from-sources.md#updating).
:::

View File

@@ -87,7 +87,7 @@ A rule is simple to express: allow or block, a protocol (ARP, ICMP, IP, TCP or U
<UiShot light="/img/xo6/traffic-rule-new-light.png" dark="/img/xo6/traffic-rule-new-dark.png" alt="The new traffic rule form: policy, protocol, direction, IP range, and the network or VIF it applies to" url="https://your-xo/v6/#/traffic-rule/new" />
:::warning Prerequisites
Traffic rules are enforced by the [SDN Controller plugin](sdn-controller/setup.md): it must be loaded, and switched to the **XAPI plugin** mode ([`useDirectChannel = false`](../getting-started/configuration.md#sdn-controller-mode)). XO 6 shows a notification guiding you through the switch, and a [migration script](sdn-controller/advanced.md#migration-path) converts existing rules.
Traffic rules are enforced by the [SDN Controller plugin](networking/sdn_controller.md): it must be loaded, and switched to the **XAPI plugin** mode ([`useDirectChannel = false`](../getting-started/configuration.md#sdn-controller-mode)). XO 6 shows a notification guiding you through the switch, and a [migration script](networking/sdn_controller.md#migration-path) converts existing rules.
:::
Everything is also available through the [REST API](../automation/restapi.md), where rules can additionally be updated in place, making network policies easy to automate.

View File

@@ -0,0 +1,9 @@
{
"label": "Networking",
"position": 4,
"link": {
"type": "generated-index",
"slug": "/category/networking",
"description": "Networks and software-defined networking"
}
}

View File

@@ -0,0 +1,384 @@
---
sidebar_position: 1
---
# SDN controller
<InterfaceNote>Private networks are currently created and managed from XO 5. Traffic rules moved ahead in [XO 6](../management.md#traffic-rules), with more capabilities than the XO 5 equivalent.</InterfaceNote>
:::tip
Be sure to enable the plugin on only one XOA instance.
:::
The SDN Controller enables a user to **create pool-wide and cross-pool private networks** and more. It's available as a Xen Orchestra plugin (included in XOA Premium).
## Global Private Networks
Interconnect your VMs and hosts within a dedicated and secured private network, even across different pools all around the world. This is a great way to protect "private links" (eg between applications and databases, management networks etc.) without any complicated deployment.
<Schema label="One private network spanning two sites" legend={[["#6aabf0", "XO"], ["#8e83fe", "XCP-ng"], ["#5ac8c8", "private network tunnels"]]} maxWidth="640px">
<svg viewBox="0 0 640 260" role="img" aria-label="The SDN controller in Xen Orchestra builds encrypted GRE or VxLAN tunnels between the hosts of two pools in different locations, forming a single private network for the VMs">
<rect x="280" y="10" width="80" height="34" rx="8" fill="rgba(106,171,240,0.12)" stroke="#6aabf0"/>
<text x="320" y="27" fontSize="12.5" fill="#6aabf0" textAnchor="middle">XO</text>
<text x="320" y="39" fontSize="8.5" fill="#7a8699" textAnchor="middle">SDN controller</text>
<g className="schema-flow" stroke="#7a8699" strokeWidth="1.3" strokeDasharray="5 4">
<line x1="292" y1="44" x2="160" y2="70"/>
<line x1="348" y1="44" x2="480" y2="70"/>
</g>
<g fill="none" stroke="rgba(255,255,255,0.22)" strokeDasharray="6 5">
<rect x="25" y="70" width="270" height="160" rx="10"/>
<rect x="345" y="70" width="270" height="160" rx="10"/>
</g>
<g fontSize="12" fill="#7a8699">
<text x="41" y="92">Pool 1 · Paris</text>
<text x="361" y="92">Pool 2 · Amsterdam</text>
</g>
<g fill="rgba(142,131,254,0.1)" stroke="#8e83fe" strokeOpacity="0.8">
<rect x="45" y="102" width="115" height="86" rx="6"/>
<rect x="175" y="102" width="115" height="86" rx="6"/>
<rect x="365" y="102" width="115" height="86" rx="6"/>
<rect x="495" y="102" width="115" height="86" rx="6"/>
</g>
<g fontSize="10" fill="#8e83fe" textAnchor="middle">
<text x="102" y="119">Host 1</text>
<text x="232" y="119">Host 2</text>
<text x="422" y="119">Host 3</text>
<text x="552" y="119">Host 4</text>
</g>
<g fill="rgba(86,194,136,0.14)" stroke="#56c288">
<rect x="60" y="132" width="85" height="34" rx="4"/>
<rect x="190" y="132" width="85" height="34" rx="4"/>
<rect x="380" y="132" width="85" height="34" rx="4"/>
<rect x="510" y="132" width="85" height="34" rx="4"/>
</g>
<g fontSize="10.5" fill="#c6d2e1" textAnchor="middle">
<text x="102" y="152">VM</text>
<text x="232" y="152">VM</text>
<text x="422" y="152">VM</text>
<text x="552" y="152">VM</text>
</g>
<g className="schema-flow" stroke="#5ac8c8" strokeWidth="1.6" strokeDasharray="5 4">
<line x1="102" y1="188" x2="102" y2="210"/>
<line x1="232" y1="188" x2="232" y2="210"/>
<line x1="422" y1="188" x2="422" y2="210"/>
<line x1="552" y1="188" x2="552" y2="210"/>
<line x1="102" y1="210" x2="552" y2="210"/>
</g>
<text x="320" y="203" fontSize="9" fill="#5ac8c8" textAnchor="middle">WAN</text>
<text x="320" y="248" fontSize="9.5" fill="#7a8699" textAnchor="middle">encrypted GRE / VxLAN tunnels · one L2 network for all these VMs</text>
</svg>
</Schema>
### How does it work?
Please read the [dedicated devblog on the SDN Controller](https://xen-orchestra.com/blog/xo-sdn-controller/) and its [extension for cross-pool private networks](https://xen-orchestra.com/blog/devblog-3-extending-the-sdn-controller/).
:::warning
As VxLAN and GRE are protocols using extra encapsulation, they require extra bits on a network packet. If you create a Global Private Network with a default MTU at `1500`, you won't be able to use it "as is" in your VMs, unless you configure a smaller MTU for each virtual interface, in your VM operating system (eg: `1400`).
If you want something entirely transparent for your VMs, then you'll need to create a network with a MTU of `1546` for GRE or `1550` for VxLAN. However, larger MTU will require capable network equipments.
:::
### Network creation
In the network creation view:
- Select a `pool`
- Select `Private network`
- Select an interface on which to create the network's tunnels
- Select the encapsulation: a choice is offered between `GRE` and `VxLAN`, if `VxLAN` is chosen, then port 4789 must be open for UDP traffic on all the network's hosts (see [the requirements](#vxlan))
- Choose if the network should be encrypted or not (see [the requirements](#encryption) to use encryption)
- Select other `pool`s to add them to the network if desired
- For each added `pool`: select an interface on which to create the tunnels
- Create the network
- Have fun! ☺
<UiShot light="/img/xo5/sdn-controller.png" alt="Creating a private network: interface, encapsulation, encryption, and the pools to join" url="https://your-xo/v5/#/new/network" />
:::tip
- All hosts in a private network must be able to reach the other hosts' management interface and all hosts must be able to reach one another on the interface selected for private networks creation.
> The term ‘management interface’ is used to indicate the IP-enabled NIC that carries the management traffic.
- Only 1 encrypted GRE network and 1 encrypted VxLAN network per pool can exist at a time due to Open vSwitch limitation.
:::
### Configuration
Like all other xo-server plugins, it can be configured directly via the web interface, see [the plugin documentation](../plugins/plugins.md).
The plugin's configuration contains:
- `cert-dir`: The path where the plugin will look for the certificates to create SSL connections with the hosts.
If none is provided, the plugin will create its own self-signed certificates.
- `override-certs`: Enable to uninstall the existing SDN controller CA certificate in order to replace it with the plugin's one.
### Requirements
### VxLAN
### Encryption
To be able to encrypt the networks, the `openvswitch-ipsec` package must be installed on all the hosts:
<Terminal shell title="on every host of the network">{`
yum install openvswitch-ipsec --enablerepo=xcp-ng-testing
systemctl enable ipsec
systemctl enable openvswitch-ipsec
systemctl start ipsec
systemctl start openvswitch-ipsec
`}</Terminal>
## OpenFlow rules
Traffic rules let you allow or block traffic per VIF, or network-wide. There are currently two backends:
- One where the SDN Controller plugin talks directly to Open vSwitch through the OpenFlow protocol
- A newer one using a XAPI plugin on XCP-ng side that directly configures Open vSwitch
At this time, the two options are covered until we can fully deprecate the older, direct OpenFlow implementation.
Where the UI lives:
- **XO 5**: per-VIF rules only, from the VM **Network** tab (described [below](#openflow-protocol))
- **XO 6**: the full experience, network-wide **and** per-VIF rules, with a consolidated pool view: see [Traffic rules in XO 6](../management.md#traffic-rules). It requires the XAPI plugin backend.
### OpenFlow Protocol
:::warning
This feature requires opening the OpenFlow port (TCP 6653). This is done automatically by XAPI.
:::
Limitations:
- Only on the physical host's management network (neither bond nor VLAN)
- Only supports per-VIF rules
For now, this is the default mode in Xen Orchestra.
Please see the [devblog about OpenFlow rules](https://xen-orchestra.com/blog/vms-vif-network-traffic-control/).
In the VM network tab a new column has been added: _Network rules_.
- The _Add rule_ button display a form to add a new rule choosing to:
- enable/disable the matching traffic
- for a specific protocol (optional)
- on a specific port (optional)
- matching a specific IP or IP range (optional)
- coming from the VIF / going to the VIF / both
- The _Show rules_ button allow to display all rules for a VIF.
- When the rules are display a button to delete a rule is available.
<UiDetail src="/img/xo5/add-rule.png" alt="The Add rule form: allow or deny, protocol, port, IP range, direction" width={480} />
<UiDetail src="/img/xo5/show-rules.png" alt="All the rules of a VIF, with a delete button for each" width={700} />
### XAPI Plugin
:::warning
A few caveats:
- This is still in BETA and should not be used in production yet.
- This will only work on XCP-ng, not on XenServer hosts.
- This is not enabled by default, and requires a configuration change for `xo-server`. See [the configuration page](../../getting-started/configuration.md#sdn-controller-mode) to know more.
:::
:::tip
This is the backend used by the [XO 6 traffic rules UI](../management.md#traffic-rules) (since XO 6.5): network-wide and per-VIF rules, with a consolidated view in the pool **Traffic rules** tab. The rules can also be managed through the [REST API](../../automation/restapi.md), including in-place updates (since XO 6.7).
:::
- Works on any network:
- Networks bound to physical interface as well as bonds
- VLAN on top of any network
- Private networks and cross-pool private networks
- Per VIF rules
- Network-wide rules
To setup a per-VIF rule using the UI, follow the [openflow instructions](#openflow-protocol) above, as the UI is the same and only the backend changes.
Here, we describe how to use `xo-cli` to configure rules. First, make sure to register xo-cli to your XOA instance as documented in [its documentation](../../core-concepts/architecture.md#xo-cli).
- Add per-VIF rules: `xo-cli sdnController.addRule vifId=<VIF_UUID> <parameters>`
- Delete per-VIF rules: `xo-cli sdnController.deleteRule vifId=<VIF_UUID> <parameters>`
- Add new network-wide rules: `xo-cli sdnController.addNetworkRule networkId=<NETWORK_UUID> <parameters>`
- Delete network-wide rules: `xo-cli sdnController.deleteNetworkRule networkId=<NETWORK_UUID> <parameters>`
Parameters:
- _ipRange_: An IP or range of IPs in CIDR notation (for example `192.168.1.0/24`). An IP does not need `/32`.
- _direction_:
- _to_: means the parameters for **port** and **ipRange** are to be used as destination.
- _from_: means they will be used as source.
- _from/to_ or _to/from_: 2 rules will be created (one per direction).
- _protocol_: IP, TCP, UDP, ICMP or ARP (case-insensitive).
- _port_: required for TCP/UDP protocol. Use `json:22` so the number is passed as an integer.
- _allow_: true or false. If set to false the packets are dropped.
- _priority_ (optional): the OpenFlow priority of the rule, an integer from 1 to 65535 (XAPI reserves 0), refused when `useDirectChannel` is enabled. A rule without one has the OpenFlow default, 32768. When several rules of a network match a packet, network-wide and per-VIF rules alike, the one with the **highest** priority applies: a rule of priority 30 applies before a rule of priority 20. Two rules of a network can't be given the same priority. To delete a rule that has a priority, you must pass that priority to `sdnController.deleteRule` or `sdnController.deleteNetworkRule` as well.
:::tip
Leave room between the priorities of your rules (for example 100, 110, 120…) rather than numbering them one after the other (101, 102, 103…): a new rule can then go between two existing ones without renumbering them.
:::
Some examples:
<Terminal shell title="per-VIF rules">{`
xo-cli sdnController.addRule vifId=15f1a9ec-4348-0cca-d2b8-e536db043298 direction=from ipRange=1.1.1.3 protocol=tcp port=json:4242 allow=false priority=json:100
xo-cli sdnController.deleteRule vifId=15f1a9ec-4348-0cca-d2b8-e536db043298 direction=from ipRange=1.1.1.3 protocol=tcp port=json:4242 priority=json:100
xo-cli sdnController.addRule vifId=e9a7914a-9518-82e2-7052-42cb16cc9724 direction=to ipRange=1.1.1.2 protocol=icmp allow=false priority=json:110
xo-cli sdnController.deleteRule vifId=e9a7914a-9518-82e2-7052-42cb16cc9724 direction=to ipRange=1.1.1.2 protocol=icmp priority=json:110
`}</Terminal>
<Terminal shell title="network-wide rules">{`
xo-cli sdnController.addNetworkRule networkId=9334aa83-6960-62e5-a463-5acc05295af4 direction=to ipRange=1.1.1.2 protocol=icmp allow=false priority=json:200
xo-cli sdnController.deleteNetworkRule networkId=9334aa83-6960-62e5-a463-5acc05295af4 direction=to ipRange=1.1.1.2 protocol=icmp priority=json:200
xo-cli sdnController.addNetworkRule networkId=9334aa83-6960-62e5-a463-5acc05295af4 direction=from ipRange=1.1.1.2 protocol=tcp allow=false port=json:4242 priority=json:210
xo-cli sdnController.deleteNetworkRule networkId=9334aa83-6960-62e5-a463-5acc05295af4 direction=from ipRange=1.1.1.2 protocol=tcp port=json:4242 priority=json:210
`}</Terminal>
### Migration path
OpenFlow Protocol and XAPI Plugin modes implement traffic rules in slightly different ways.
Because of this mismatch, the two modes are not directly interchangeable and you must either
1. Re‑create the rules from scratch, or
2. Use the provided migration script to translate an existing set of rules.
:::note
The migration is forward only.
You can go from OpenFlow Protocol to XAPI Plugin in a semi‑automatic manner, but to revert existing rules will be deleted first.
:::
#### What the migration script does
- Back up the current rules in the OpenFlow Protocol format in `rules-channel.json` file.
- Translate those rules into the XAPI Plugin format.
If you ever need to go back to the original configuration, the same script can restore the rules from the backup.
Existing rules will first be removed before restoring the saved ones.
#### How to use the script
The migration script is available as [sdn-migration.py (download script)](../../../static/sh/sdn-migration.py).
<Terminal shell title="migrate the rules (backup written to rules-channel.json)">{`
# Export current rules to rules-channel.json and convert to XAPI format
python3 sdn-migration.py migrate
# (Optional) Restore original rules (from rules-channel.json file)
python3 sdn-migration.py restore
`}</Terminal>
## OpenSSL 3 + SDN upgrade path
With OpenSSL 3 arriving in XCP-ng 8.3, the certificates previously generated by the Xen Orchestra SDN Controller plugin will no longer work. **You must regenerate the certificates before updating your XCP-ng pools.** The steps below only cover certificate regeneration: updating your XCP-ng pools is a separate operation that you perform as you normally would, after the certificates are in place.
:::warning
We remind you that the self-signed certificates generated by Xen Orchestra’s SDN Controller plugin are a workaround. **They are neither safe nor recommended**. You should provide your own certificates.
:::
### Are you impacted?
This only applies to you if you meet **all of the following requirements:**
- One of your pools is using our **Global Private Network** (VxLAN or GRE tunnels) or the **VIF Traffic Rules**.
- The SDN Controller plugin is enabled in **Xen Orchestra → Settings → Plugins**.
- You’re not providing your own certificates.
- You’re using the `override-cert` option (shown when clicking the `+` button of the SDN Controller plugin).
:::info
Standard networks and VLAN are not related to the SDN Controller and are **not impacted**.
:::
#### How to check if your pools use these features?
To check if you’re using **Global Private Networks**, you can use one of the methods below.
##### Method 1: Use a script
We provide a script to run from a host that has access to your pool. To run the script, you will need the following:
- A machine to run it that has access to your pools. Your XOA may be a good place.
- The list of the addresses of your pool masters.
- (optional) If your infrastructure is on the bigger side, it may be better to have ssh agents configured with keys to avoid the need to pass all the passwords.
[check-sdn-features.sh (download script)](../../../static/sh/check-sdn-features.sh)
Copy the file to where you want to run the script, then run this:
<Terminal shell title="check every pool master">{`
bash check-sdn-features.sh <pool-master-ip1> [pool-master-ip2] [pool-master-ip3] ...
`}</Terminal>
The script will connect to those masters and check:
- if an SDN Controller is connected
- if there are tunnels
- if there are traffic rules configured
It will then print a summary letting you know if there are using features that require a manual intervention.
##### Method 2: Check manually
Alternatively, you can check manually in Xen Orchestra’s interface:
- For **Global Private Networks**: Go to the **Pool → Network** tab, and check for tunnelX PIFs, note that the search field is looking at the name of the network (not the PIF) so you can’t filter with that.
- For **VIF Traffic Rules**: Go to the **VM → Network** tab and look for the “eye” icon under the traffic rule column.
### Manual Regeneration Procedure
If you did the previous check and confirm you’re using the SDN Controller features, you will unfortunately need a manual intervention before the March XCP-ng 8.3 update.
There are 3 cases here:
- You’re using the `latest` channel of Xen Orchestra Appliance.
- You’re using the `stable` channel of Xen Orchestra Appliance.
- You run Xen Orchestra from sources.
:::warning
We recommend doing this right before updating Xen Orchestra Appliance, or you’ll need to restart the `xo-server` again manually.
:::
#### Latest Channel
This is the simplest case. We have updated the self-signed certificates to work with the incoming OpenSSL 3. All you need is to remove the current certificates, start the update, and you’re good to go. The certificates will be regenerated and copied over to your hosts.
:::tip
We suggest doing a backup of the certificates in case anything goes wrong:
<Terminal shell title="back up the current certificates, on your XOA">{`
today=$(date +%Y%m%d)
sudo mkdir /var/lib/xo-server/data/sdn-controller/$today-backup
sudo mv /var/lib/xo-server/data/sdn-controller/*.pem /var/lib/xo-server/data/sdn-controller/$today-backup
`}</Terminal>
:::
Finally, update your XOA. On next restart, `xo-server` will regenerate the certificates and push them to your hosts automatically. You can then update your XCP-ng pools as you normally would.
#### Stable Channel
The update present in the `latest` channel will probably be available later than the XCP-ng 8.3 update (March 2026) that will include OpenSSL 3. In that case, you need to actually generate certificates yourself, then restart `xo-server`.
We provide a helper script to run on your XOA VM:
[regenerate-certs.sh (download script)](../../../static/sh/regenerate-certs.sh)
<Terminal shell title="regenerate the certificates, on your XOA">{`
sudo bash -e ./regenerate-certs.sh
# if you have available updates, just update XOA, otherwise:
sudo systemctl restart xo-server
`}</Terminal>
Once `xo-server` is back up, the new certificates are pushed to your hosts. You can then update your XCP-ng pools as you normally would.
#### Running from sources
If you have auto-updates from master, you likely already are in a case similar to people using the `latest` channel and already have the updated certificate generation.
1. You need to find where your xo-server's data folder lives.
2. Move or remove your certificates.
3. Restart xo-server.
If for any reason you’re pinning xen-orchestra to a specific release, you can use the `regenerate-certs.sh` as an insipration. However, be sure to adjust it to your installation (xo-server’s data folder, permission…). Then, you can restart `xo-server` with your distribution service manager.
Once `xo-server` is back up, the new certificates are pushed to your hosts. You can then update your XCP-ng pools as you normally would.

View File

@@ -29,6 +29,6 @@ Other plugins are documented with the feature they serve:
- [Backup reports](../../backups-and-dr/backup_reports.md), to get notified about your backup jobs,
- [Netbox](../advanced.md#netbox), to synchronize your infrastructure with Netbox,
- [Performance alerts](../advanced.md#performance-alerts), to be warned when a resource crosses a usage threshold,
- [SDN controller](../sdn-controller/how-it-works.md), for private networks and traffic rules,
- [SDN controller](../networking/sdn_controller.md), for private networks and traffic rules,
- [Usage reports](../manage_infrastructure.md#usage-reports), to receive regular reports on the usage of your resources,
- [Web hooks](../advanced.md#web-hooks), to call your own services when Xen Orchestra events happen.

View File

@@ -1,9 +0,0 @@
{
"label": "SDN controller",
"position": 4,
"link": {
"type": "generated-index",
"slug": "/category/sdn-controller",
"description": "Pool-wide and cross-pool private networks, and traffic rules, with the SDN controller plugin. Start with how it works, then set it up."
}
}

View File

@@ -1,227 +0,0 @@
---
sidebar_position: 4
---
# Reference and advanced configuration
This page gathers what you only need in specific cases: the optional XAPI plugin mode for traffic rules, the migration to it, and the certificate regeneration required by OpenSSL 3 on XCP-ng 8.3. For a first setup, start with [How it works](./how-it-works.md) and [Set up the SDN controller](./setup.md).
## XAPI plugin mode for traffic rules {#xapi-plugin}
By default, the SDN controller sets [traffic rules](./traffic-rules.md) by talking directly to Open vSwitch through the OpenFlow protocol. In the XAPI plugin mode, it goes through a XAPI plugin on the XCP-ng side, which configures Open vSwitch itself.
:::warning
A few caveats:
- This is still in **beta** and should not be used in production yet.
- It only works on XCP-ng, not on XenServer hosts.
- It's not enabled by default: it requires a configuration change for `xo-server` (`useDirectChannel = false`). See [the configuration page](../../getting-started/configuration.md#sdn-controller-mode).
- Switching is forward only: going back to the default mode deletes the rules. See [Migrate from the default mode](#migration-path).
:::
:::tip
This is the mode used by the [XO 6 traffic rules interface](../management.md#traffic-rules) (since XO 6.5): network-wide and per-VIF rules, with a consolidated view in the pool **Traffic rules** tab.
:::
Compared to [the default mode](./traffic-rules.md), it:
- works on any network:
- Networks bound to physical interface as well as bonds
- VLAN on top of any network
- Private networks and cross-pool private networks
- supports per-VIF **and** network-wide rules;
- supports rule priorities.
### Manage the rules {#xapi-plugin-rules}
- From the **XO 6** interface: see [Traffic rules in XO 6](../management.md#traffic-rules).
- From the **XO 5** interface: per-VIF rules only, exactly as in [the default mode](./traffic-rules.md#add-a-rule): only the backend changes.
- From the [REST API](../../automation/restapi.md), which can also update rules in place (since XO 6.7).
- From `xo-cli`, described below.
### Manage the rules with xo-cli {#xo-cli}
First, register xo-cli to your XOA instance as documented in [its documentation](../../core-concepts/architecture.md#xo-cli). Then:
- Add per-VIF rules: `xo-cli sdnController.addRule vifId=<VIF_UUID> <parameters>`
- Delete per-VIF rules: `xo-cli sdnController.deleteRule vifId=<VIF_UUID> <parameters>`
- Add new network-wide rules: `xo-cli sdnController.addNetworkRule networkId=<NETWORK_UUID> <parameters>`
- Delete network-wide rules: `xo-cli sdnController.deleteNetworkRule networkId=<NETWORK_UUID> <parameters>`
Parameters:
- _ipRange_: An IP or range of IPs in CIDR notation (for example `192.168.1.0/24`). An IP does not need `/32`.
- _direction_:
- _to_: means the parameters for **port** and **ipRange** are to be used as destination.
- _from_: means they will be used as source.
- _from/to_ or _to/from_: 2 rules will be created (one per direction).
- _protocol_: IP, TCP, UDP, ICMP or ARP (case-insensitive).
- _port_: required for TCP/UDP protocol. Use `json:22` so the number is passed as an integer.
- _allow_: true or false. If set to false the packets are dropped.
- _priority_ (optional): the OpenFlow priority of the rule, an integer from 1 to 65535 (XAPI reserves 0), refused when `useDirectChannel` is enabled. A rule without one has the OpenFlow default, 32768. When several rules of a network match a packet, network-wide and per-VIF rules alike, the one with the **highest** priority applies: a rule of priority 30 applies before a rule of priority 20. Two rules of a network can't be given the same priority. To delete a rule that has a priority, you must pass that priority to `sdnController.deleteRule` or `sdnController.deleteNetworkRule` as well.
:::tip
Leave room between the priorities of your rules (for example 100, 110, 120…) rather than numbering them one after the other (101, 102, 103…): a new rule can then go between two existing ones without renumbering them.
:::
Some examples:
<Terminal shell title="per-VIF rules">{`
xo-cli sdnController.addRule vifId=15f1a9ec-4348-0cca-d2b8-e536db043298 direction=from ipRange=1.1.1.3 protocol=tcp port=json:4242 allow=false priority=json:100
xo-cli sdnController.deleteRule vifId=15f1a9ec-4348-0cca-d2b8-e536db043298 direction=from ipRange=1.1.1.3 protocol=tcp port=json:4242 priority=json:100
xo-cli sdnController.addRule vifId=e9a7914a-9518-82e2-7052-42cb16cc9724 direction=to ipRange=1.1.1.2 protocol=icmp allow=false priority=json:110
xo-cli sdnController.deleteRule vifId=e9a7914a-9518-82e2-7052-42cb16cc9724 direction=to ipRange=1.1.1.2 protocol=icmp priority=json:110
`}</Terminal>
<Terminal shell title="network-wide rules">{`
xo-cli sdnController.addNetworkRule networkId=9334aa83-6960-62e5-a463-5acc05295af4 direction=to ipRange=1.1.1.2 protocol=icmp allow=false priority=json:200
xo-cli sdnController.deleteNetworkRule networkId=9334aa83-6960-62e5-a463-5acc05295af4 direction=to ipRange=1.1.1.2 protocol=icmp priority=json:200
xo-cli sdnController.addNetworkRule networkId=9334aa83-6960-62e5-a463-5acc05295af4 direction=from ipRange=1.1.1.2 protocol=tcp allow=false port=json:4242 priority=json:210
xo-cli sdnController.deleteNetworkRule networkId=9334aa83-6960-62e5-a463-5acc05295af4 direction=from ipRange=1.1.1.2 protocol=tcp port=json:4242 priority=json:210
`}</Terminal>
## Migrate from the default mode {#migration-path}
The default (OpenFlow) mode and the XAPI plugin mode implement traffic rules in slightly different ways, so their rules are not directly interchangeable. When you [switch to the XAPI plugin mode](../../getting-started/configuration.md#sdn-controller-mode), you must either:
1. Re-create the rules from scratch, or
2. Use the provided migration script to translate an existing set of rules.
:::note
The migration is forward only. You can go from the default mode to the XAPI plugin mode semi-automatically. Going back restores the backed-up rules, but deletes the existing ones first.
:::
### What the migration script does
- Back up the current rules of the default mode in the `rules-channel.json` file.
- Translate those rules into the XAPI plugin mode format.
If you ever need to go back to the original configuration, the same script can restore the rules from the backup.
Existing rules will first be removed before restoring the saved ones.
### How to use the script
The migration script is available as [sdn-migration.py (download script)](../../../static/sh/sdn-migration.py).
<Terminal shell title="migrate the rules (backup written to rules-channel.json)">{`
# Export current rules to rules-channel.json and convert to XAPI format
python3 sdn-migration.py migrate
# (Optional) Restore original rules (from rules-channel.json file)
python3 sdn-migration.py restore
`}</Terminal>
## OpenSSL 3 and certificates {#openssl-3-sdn-upgrade-path}
With OpenSSL 3 arriving in XCP-ng 8.3, the certificates previously generated by the Xen Orchestra SDN Controller plugin will no longer work. **You must regenerate the certificates before updating your XCP-ng pools.** The steps below only cover certificate regeneration: updating your XCP-ng pools is a separate operation that you perform as you normally would, after the certificates are in place.
:::warning
We remind you that the self-signed certificates generated by Xen Orchestra’s SDN Controller plugin are a workaround. **They are neither safe nor recommended**. You should provide your own certificates.
:::
### Are you impacted?
This only applies to you if you meet **all of the following requirements:**
- One of your pools is using our **Global Private Network** (VxLAN or GRE tunnels) or the **VIF Traffic Rules**.
- The SDN Controller plugin is enabled in **Xen Orchestra → Settings → Plugins**.
- You’re not providing your own certificates.
- You’re using the `override-cert` option (shown when clicking the `+` button of the SDN Controller plugin).
:::info
Standard networks and VLAN are not related to the SDN Controller and are **not impacted**.
:::
#### How to check if your pools use these features?
To check if you’re using **Global Private Networks**, you can use one of the methods below.
##### Method 1: Use a script
We provide a script to run from a host that has access to your pool. To run the script, you will need the following:
- A machine to run it that has access to your pools. Your XOA may be a good place.
- The list of the addresses of your pool masters.
- (optional) If your infrastructure is on the bigger side, it may be better to have ssh agents configured with keys to avoid the need to pass all the passwords.
[check-sdn-features.sh (download script)](../../../static/sh/check-sdn-features.sh)
Copy the file to where you want to run the script, then run this:
<Terminal shell title="check every pool master">{`
bash check-sdn-features.sh <pool-master-ip1> [pool-master-ip2] [pool-master-ip3] ...
`}</Terminal>
The script will connect to those masters and check:
- if an SDN Controller is connected
- if there are tunnels
- if there are traffic rules configured
It will then print a summary letting you know if there are using features that require a manual intervention.
##### Method 2: Check manually
Alternatively, you can check manually in Xen Orchestra’s interface:
- For **Global Private Networks**: Go to the **Pool → Network** tab, and check for tunnelX PIFs, note that the search field is looking at the name of the network (not the PIF) so you can’t filter with that.
- For **VIF Traffic Rules**: Go to the **VM → Network** tab and look for the “eye” icon under the traffic rule column.
### Manual Regeneration Procedure
If you did the previous check and confirm you’re using the SDN Controller features, you will unfortunately need a manual intervention before the March XCP-ng 8.3 update.
There are 3 cases here:
- You’re using the `latest` channel of Xen Orchestra Appliance.
- You’re using the `stable` channel of Xen Orchestra Appliance.
- You run Xen Orchestra from sources.
:::warning
We recommend doing this right before updating Xen Orchestra Appliance, or you’ll need to restart the `xo-server` again manually.
:::
#### Latest Channel
This is the simplest case. We have updated the self-signed certificates to work with the incoming OpenSSL 3. All you need is to remove the current certificates, start the update, and you’re good to go. The certificates will be regenerated and copied over to your hosts.
:::tip
We suggest doing a backup of the certificates in case anything goes wrong:
<Terminal shell title="back up the current certificates, on your XOA">{`
today=$(date +%Y%m%d)
sudo mkdir /var/lib/xo-server/data/sdn-controller/$today-backup
sudo mv /var/lib/xo-server/data/sdn-controller/*.pem /var/lib/xo-server/data/sdn-controller/$today-backup
`}</Terminal>
:::
Finally, update your XOA. On next restart, `xo-server` will regenerate the certificates and push them to your hosts automatically. You can then update your XCP-ng pools as you normally would.
#### Stable Channel
The update present in the `latest` channel will probably be available later than the XCP-ng 8.3 update (March 2026) that will include OpenSSL 3. In that case, you need to actually generate certificates yourself, then restart `xo-server`.
We provide a helper script to run on your XOA VM:
[regenerate-certs.sh (download script)](../../../static/sh/regenerate-certs.sh)
<Terminal shell title="regenerate the certificates, on your XOA">{`
sudo bash -e ./regenerate-certs.sh
# if you have available updates, just update XOA, otherwise:
sudo systemctl restart xo-server
`}</Terminal>
Once `xo-server` is back up, the new certificates are pushed to your hosts. You can then update your XCP-ng pools as you normally would.
#### Running from sources
If you have auto-updates from master, you likely already are in a case similar to people using the `latest` channel and already have the updated certificate generation.
1. You need to find where your xo-server's data folder lives.
2. Move or remove your certificates.
3. Restart xo-server.
If for any reason you’re pinning xen-orchestra to a specific release, you can use the `regenerate-certs.sh` as an insipration. However, be sure to adjust it to your installation (xo-server’s data folder, permission…). Then, you can restart `xo-server` with your distribution service manager.
Once `xo-server` is back up, the new certificates are pushed to your hosts. You can then update your XCP-ng pools as you normally would.

View File

@@ -1,213 +0,0 @@
---
sidebar_position: 1
---
# How it works
This page explains what the SDN controller does and how it builds its networks. Read it before [setting up the controller](./setup.md): the requirements and the choices you make at creation (encapsulation, encryption, MTU, preferred center) follow from it.
## What is the SDN controller?
An SDN controller (Software-Defined Networking controller) manages software network switches from a central place. Each XCP-ng host runs its own virtual switch, Open vSwitch (OVS). A single OVS bridge works well on its own, but to build a network that spans several hosts, someone has to configure all their bridges together, and keep them consistent when hosts and VMs come and go.
In Xen Orchestra, that someone is the **SDN controller plugin**. On XOA, it requires a Vates VMS subscription that includes it. It runs inside `xo-server`, so there is no extra appliance to deploy, and it provides:
- **Private networks**, pool-wide or cross-pool: one isolated layer 2 network for VMs spread across several hosts, and even across pools in different locations.
- **Encryption** of these networks, with IPsec.
- **Traffic rules**: allow or block traffic per VIF, or network-wide. They are covered on their own page: [Traffic rules](./traffic-rules.md).
<Schema label="One private network spanning two sites" legend={[["#6aabf0", "XO"], ["#8e83fe", "XCP-ng"], ["#5ac8c8", "private network tunnels"]]} maxWidth="640px">
<svg viewBox="0 0 640 260" role="img" aria-label="The SDN controller in Xen Orchestra builds encrypted GRE or VxLAN tunnels between the hosts of two pools in different locations, forming a single private network for the VMs">
<rect x="280" y="10" width="80" height="34" rx="8" fill="rgba(106,171,240,0.12)" stroke="#6aabf0"/>
<text x="320" y="27" fontSize="12.5" fill="#6aabf0" textAnchor="middle">XO</text>
<text x="320" y="39" fontSize="8.5" fill="#7a8699" textAnchor="middle">SDN controller</text>
<g className="schema-flow" stroke="#7a8699" strokeWidth="1.3" strokeDasharray="5 4">
<line x1="292" y1="44" x2="160" y2="70"/>
<line x1="348" y1="44" x2="480" y2="70"/>
</g>
<g fill="none" stroke="rgba(255,255,255,0.22)" strokeDasharray="6 5">
<rect x="25" y="70" width="270" height="160" rx="10"/>
<rect x="345" y="70" width="270" height="160" rx="10"/>
</g>
<g fontSize="12" fill="#7a8699">
<text x="41" y="92">Pool 1 · Paris</text>
<text x="361" y="92">Pool 2 · Amsterdam</text>
</g>
<g fill="rgba(142,131,254,0.1)" stroke="#8e83fe" strokeOpacity="0.8">
<rect x="45" y="102" width="115" height="86" rx="6"/>
<rect x="175" y="102" width="115" height="86" rx="6"/>
<rect x="365" y="102" width="115" height="86" rx="6"/>
<rect x="495" y="102" width="115" height="86" rx="6"/>
</g>
<g fontSize="10" fill="#8e83fe" textAnchor="middle">
<text x="102" y="119">Host 1</text>
<text x="232" y="119">Host 2</text>
<text x="422" y="119">Host 3</text>
<text x="552" y="119">Host 4</text>
</g>
<g fill="rgba(86,194,136,0.14)" stroke="#56c288">
<rect x="60" y="132" width="85" height="34" rx="4"/>
<rect x="190" y="132" width="85" height="34" rx="4"/>
<rect x="380" y="132" width="85" height="34" rx="4"/>
<rect x="510" y="132" width="85" height="34" rx="4"/>
</g>
<g fontSize="10.5" fill="#c6d2e1" textAnchor="middle">
<text x="102" y="152">VM</text>
<text x="232" y="152">VM</text>
<text x="422" y="152">VM</text>
<text x="552" y="152">VM</text>
</g>
<g className="schema-flow" stroke="#5ac8c8" strokeWidth="1.6" strokeDasharray="5 4">
<line x1="102" y1="188" x2="102" y2="210"/>
<line x1="232" y1="188" x2="232" y2="210"/>
<line x1="422" y1="188" x2="422" y2="210"/>
<line x1="552" y1="188" x2="552" y2="210"/>
<line x1="102" y1="210" x2="552" y2="210"/>
</g>
<text x="320" y="203" fontSize="9" fill="#5ac8c8" textAnchor="middle">WAN</text>
<text x="320" y="248" fontSize="9.5" fill="#7a8699" textAnchor="middle">encrypted GRE / VxLAN tunnels · one L2 network for all these VMs</text>
</svg>
</Schema>
## What is a private network? {#private-network}
Without the SDN controller, XCP-ng can only create a private network on a single host: VMs of that host can talk to each other, but the network can't follow a VM migrated to another host, and it disappears if the host goes down.
A private network created by the SDN controller is:
- **reachable** by all the hosts of its pools, and by the VMs plugged into it, wherever they run;
- **isolated**: nothing outside the network can reach it;
- **self-maintained**: it follows the changes of the pools (hosts added, rebooted or removed, VMs started, stopped or migrated) without any action on your side.
Typical uses are links that should never be exposed: between an application and its database, a management or backup network, or a cluster interconnect spread across two sites.
## How a private network is built {#how-it-is-built}
To build a private network, the controller uses two connections:
- **XAPI**, to the pool master: it creates the network object of the pool and a tunnel on each host. A tunnel is a virtual PIF, carried over a physical interface you choose (the _transport_ interface).
- **OVSDB**, to the Open vSwitch database of **each host**, over TLS on port `6640`: it adds to the network's bridge the ports and interfaces that connect the hosts to each other. The host listens passively, and the controller's CA certificate is installed on the pool through XAPI, so only a controller signed by that CA can connect.
The hosts are then connected with **GRE** or **VxLAN** tunnels, in a **star topology**: one host is elected **star center**, and every other host has a single tunnel to it. A star is simpler and more robust than a full mesh: a mesh would create loops, and would require the Spanning Tree Protocol to break them.
<Schema label="A pool-wide private network: XAPI to the master, OVSDB to every host, tunnels to the star center" legend={[["#6aabf0", "XAPI"], ["#7a8699", "OVSDB (TLS, port 6640)"], ["#5ac8c8", "GRE / VxLAN tunnels"]]} maxWidth="660px">
<svg viewBox="0 0 660 340" role="img" aria-label="The SDN controller in Xen Orchestra talks to the pool master over XAPI and to the Open vSwitch database of every host over OVSDB. Hosts 1, 3, 4 and 5 each have a single GRE or VxLAN tunnel to host 2, the elected star center">
<rect x="30" y="157" width="120" height="50" rx="8" fill="rgba(106,171,240,0.12)" stroke="#6aabf0"/>
<text x="90" y="179" fontSize="12.5" fill="#6aabf0" textAnchor="middle">XO</text>
<text x="90" y="194" fontSize="9" fill="#7a8699" textAnchor="middle">SDN controller</text>
<g fill="none" stroke="#7a8699" strokeWidth="1.1">
<polyline points="90,157 90,16 580,16 580,70"/>
<line x1="150" y1="174" x2="245" y2="106"/>
<line x1="150" y1="184" x2="385" y2="184"/>
<line x1="150" y1="196" x2="245" y2="266"/>
<polyline points="90,207 90,330 580,330 580,294"/>
</g>
<line x1="150" y1="164" x2="245" y2="92" stroke="#6aabf0" strokeWidth="1.6"/>
<text x="168" y="120" fontSize="10" fill="#6aabf0">XAPI</text>
<text x="97" y="140" fontSize="9.5" fill="#7a8699">OVSDB</text>
<text x="97" y="232" fontSize="9.5" fill="#7a8699">OVSDB</text>
<g transform="translate(0,22)">
<rect x="215" y="15" width="430" height="275" rx="10" fill="rgba(255,255,255,0.02)" stroke="rgba(255,255,255,0.22)" strokeDasharray="6 5"/>
<text x="631" y="280" fontSize="12" fill="#7a8699" textAnchor="end">Pool</text>
<g className="schema-flow" stroke="#5ac8c8" strokeWidth="1.8" strokeDasharray="5 4">
<line x1="355" y1="92" x2="400" y2="138"/>
<line x1="525" y1="92" x2="480" y2="138"/>
<line x1="355" y1="228" x2="400" y2="182"/>
<line x1="525" y1="228" x2="480" y2="182"/>
</g>
<g fill="rgba(142,131,254,0.1)" stroke="#8e83fe" strokeOpacity="0.8">
<rect x="245" y="48" width="110" height="44" rx="6"/>
<rect x="525" y="48" width="110" height="44" rx="6"/>
<rect x="245" y="228" width="110" height="44" rx="6"/>
<rect x="525" y="228" width="110" height="44" rx="6"/>
</g>
<rect x="385" y="138" width="110" height="44" rx="6" fill="rgba(90,200,200,0.12)" stroke="#5ac8c8" strokeWidth="1.6"/>
<g fontSize="11" fill="#c6d2e1" textAnchor="middle">
<text x="300" y="68">Host 1</text>
<text x="580" y="74">Host 3</text>
<text x="440" y="157">Host 2</text>
<text x="300" y="254">Host 4</text>
<text x="580" y="254">Host 5</text>
</g>
<text x="300" y="82" fontSize="9" fill="#7a8699" textAnchor="middle">pool master</text>
<text x="440" y="172" fontSize="9" fill="#5ac8c8" textAnchor="middle">star center</text>
</g>
</svg>
</Schema>
With VxLAN, each private network also gets its own VxLAN Network Identifier (VNI), so that Open vSwitch can carry the traffic of several networks in the same tunnels without mixing them.
## How the network is maintained {#maintenance}
Once the star is built, most changes need nothing from the controller: when a VM starts, stops or migrates, or a VIF is plugged or unplugged, Open vSwitch handles it on its own. Same when a host stops or a tunnel is unplugged: OVS removes the corresponding ports and interfaces.
The controller steps in for the rest:
- **A host is added to a pool**, or **a stopped host starts again**: the controller creates or plugs its tunnel and connects it to the star center.
- **The star center goes down**, or its tunnel is unplugged: since every tunnel goes through it, the controller **elects a new star center** among the hosts still available, and rebuilds the star around it.
By default, the first available host is elected. You can give a network a **preferred center** when you create it: the controller elects that host whenever it is available. It's useful to put the center on your most reliable host, or on the site that has the most VMs on the network.
## Cross-pool private networks {#cross-pool}
A private network can span several pools, even in different locations, as long as their hosts can reach one another. Each pool gets its own network object (they share the same private network UUID), and the controller keeps **a single star** across all of them: one star center for the whole private network, and one tunnel from every other host of every pool to it.
<Schema label="A cross-pool private network: one star center for all the pools" legend={[["#8e83fe", "XCP-ng hosts"], ["#5ac8c8", "GRE / VxLAN tunnels"]]} maxWidth="660px">
<svg viewBox="0 0 660 280" role="img" aria-label="Three pools share one private network. Host 4, in pool 2, is the star center, and each of the six other hosts of the three pools has a single tunnel to it">
<g fill="none" stroke="rgba(255,255,255,0.22)" strokeDasharray="6 5">
<rect x="15" y="12" width="190" height="255" rx="10"/>
<rect x="235" y="12" width="190" height="255" rx="10"/>
<rect x="455" y="12" width="190" height="255" rx="10"/>
</g>
<g fontSize="12" fill="#7a8699" textAnchor="middle">
<text x="110" y="256">Pool 1</text>
<text x="330" y="256">Pool 2</text>
<text x="550" y="256">Pool 3</text>
</g>
<g className="schema-flow" stroke="#5ac8c8" strokeWidth="1.8" strokeDasharray="5 4">
<line x1="158" y1="70" x2="282" y2="122"/>
<line x1="158" y1="182" x2="282" y2="140"/>
<line x1="330" y1="62" x2="330" y2="113"/>
<line x1="330" y1="200" x2="330" y2="149"/>
<line x1="502" y1="70" x2="378" y2="122"/>
<line x1="502" y1="182" x2="378" y2="140"/>
</g>
<g fill="rgba(142,131,254,0.1)" stroke="#8e83fe" strokeOpacity="0.8">
<rect x="62" y="52" width="96" height="34" rx="6"/>
<rect x="62" y="166" width="96" height="34" rx="6"/>
<rect x="282" y="28" width="96" height="34" rx="6"/>
<rect x="282" y="200" width="96" height="34" rx="6"/>
<rect x="502" y="52" width="96" height="34" rx="6"/>
<rect x="502" y="166" width="96" height="34" rx="6"/>
</g>
<rect x="276" y="113" width="108" height="36" rx="6" fill="rgba(90,200,200,0.12)" stroke="#5ac8c8" strokeWidth="1.6"/>
<g fontSize="11" fill="#c6d2e1" textAnchor="middle">
<text x="110" y="73">Host 1</text>
<text x="110" y="187">Host 2</text>
<text x="330" y="49">Host 3</text>
<text x="330" y="128">Host 4</text>
<text x="330" y="221">Host 5</text>
<text x="550" y="73">Host 6</text>
<text x="550" y="187">Host 7</text>
</g>
<text x="330" y="142" fontSize="9" fill="#5ac8c8" textAnchor="middle">star center</text>
</svg>
</Schema>
For the hosts and the VMs, nothing differs from a pool-wide private network: VMs on the network reach each other whatever their pool, and keep doing so when they migrate between hosts or pools of the network. If the star center goes down, a new one is elected among all the hosts of all the pools, and the star is rebuilt around it.
:::tip
In a cross-pool network, all the traffic between two sites goes through the star center. Set the [preferred center](#maintenance) on a host of the site that hosts most of the VMs, to keep most of the traffic local.
:::
## Encryption {#encryption}
The tunnels of a private network can be encrypted with **IPsec**, so that its traffic can cross networks you don't trust, such as the Internet between two sites. Open vSwitch handles it on each host (the `openvswitch-ipsec` package), with a pre-shared key that the controller generates for each tunnel.
## Encapsulation and MTU {#mtu}
GRE and VxLAN both wrap each packet of the private network into a new packet, sent over the transport interface. This encapsulation adds a header to every packet: with the default MTU of `1500` on the transport interface, the private network can't carry full-size `1500`-byte packets. Either the VMs use a smaller MTU, or the transport network carries larger packets. The [setup page](./setup.md#mtu) gives the values.
## Next step
You are ready to [set up the SDN controller](./setup.md).

View File

@@ -1,88 +0,0 @@
---
sidebar_position: 2
---
# Set up the SDN controller
<InterfaceNote>Private networks are currently created and managed from XO 5. Traffic rules moved ahead in [XO 6](../management.md#traffic-rules), with more capabilities than the XO 5 equivalent.</InterfaceNote>
This page takes you from the requirements to your first private network. If you haven't yet, read [How it works](./how-it-works.md) first: it explains the choices you'll make below.
## Requirements {#requirements}
Check these before you start: the encapsulation, the encryption and the MTU are chosen when you create a network.
### Xen Orchestra {#requirements-xo}
- On XOA, the SDN controller plugin requires a **Vates VMS subscription** that includes it.
- **Enable the plugin on only one Xen Orchestra instance.** Two controllers managing the same pools would fight over the same Open vSwitch bridges.
### Network connectivity {#connectivity}
- Xen Orchestra must reach the **management interface** of every host of the network, on TCP port `6640` (OVSDB). The management interface is the IP-enabled NIC that carries the management traffic.
- All the hosts of the network must reach one another on the **interface you select for the tunnels** (the transport interface). For a cross-pool network, this includes the hosts of the other pools.
### VxLAN {#vxlan}
If you choose the **VxLAN** encapsulation, port `4789` must be open for **UDP** traffic on all the hosts of the network. GRE has no port to open, but it must not be filtered between the hosts (IP protocol 47).
### Encryption {#encryption}
To encrypt a network, the `openvswitch-ipsec` package must be installed and running on **all** its hosts:
<Terminal shell title="on every host of the network">{`
yum install openvswitch-ipsec --enablerepo=xcp-ng-testing
systemctl enable ipsec
systemctl enable openvswitch-ipsec
systemctl start ipsec
systemctl start openvswitch-ipsec
`}</Terminal>
Due to an Open vSwitch limitation, a pool can have **at most 1 encrypted GRE network and 1 encrypted VxLAN network** at a time.
### MTU {#mtu}
GRE and VxLAN add a header to every packet (see [Encapsulation and MTU](./how-it-works.md#mtu)). Pick one of these two options before creating the network:
| Option | Network MTU | What it requires |
| ---------------------------- | ------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
| Keep the default | `1500` | Configure a smaller MTU (for example `1400`) on the network interface of each VM, in its operating system. |
| Transparent for the VMs | `1546` (GRE) or `1550` (VxLAN) | Nothing in the VMs, but every network equipment between the hosts must carry these larger packets (jumbo frames). |
## Step 1: configure and enable the plugin {#configuration}
The plugin must be configured and loaded before you can create a private network. Like all xo-server plugins, it's configured from **Settings → Plugins** in XO 5: see [the plugin documentation](../plugins/plugins.md).
The plugin's configuration contains:
- `cert-dir`: the path of a directory containing `client-cert.pem`, `client-key.pem` and `ca-cert.pem`, used to create the TLS connections with the hosts. If none is provided, the plugin creates its own self-signed certificates.
- `override-certs`: enable to uninstall the SDN controller CA certificate already installed on the pools, and replace it with the plugin's one.
:::warning
The self-signed certificates generated by the plugin are a convenience, **neither safe nor recommended** for production: provide your own certificates with `cert-dir`. If you used the self-signed certificates before updating to XCP-ng 8.3, see [OpenSSL 3 and certificates](./advanced.md#openssl-3-sdn-upgrade-path).
:::
Once configured, load the plugin. On load, it installs its CA certificate on your pools and connects to their hosts.
## Step 2: create a private network {#network-creation}
In XO 5, go to **New → Network**, then:
1. Select a **pool**.
1. Enable **Private network**.
1. Select the **interface** on which to create the network's tunnels (the transport interface, see [the requirements](#connectivity)).
1. Give the network a **name**, and optionally a description.
1. Set the **MTU** you chose in [the requirements](#mtu).
1. Select the **encapsulation**: `GRE` or `VxLAN` (for VxLAN, see [the requirements](#vxlan)).
1. Choose whether the network is **encrypted** (see [the requirements](#encryption)).
1. Optionally, select a **preferred center**: the host to elect first as [star center](./how-it-works.md#maintenance).
1. For a cross-pool network, click **Add pool** for each other pool, and select for each one the interface on which to create its tunnels.
1. Create the network.
<UiShot light="/img/xo5/sdn-controller.png" alt="Creating a private network: interface, encapsulation, encryption, and the pools to join" url="https://your-xo/v5/#/new/network" />
The network now appears in each of its pools, and you can plug your VMs' VIFs into it like into any other network.
## Next step
To control which traffic is allowed on your networks and VIFs, see [Traffic rules](./traffic-rules.md).

View File

@@ -1,48 +0,0 @@
---
sidebar_position: 3
---
# Traffic rules
Traffic rules let you allow or block traffic on a VM's virtual interface (VIF), without touching anything inside the guest: for example to isolate VMs that share a subnet or a VLAN. They are enforced by the SDN controller, which writes them as OpenFlow rules into the Open vSwitch of the hosts.
This page covers the **default mode**, available as soon as the [SDN controller plugin is enabled](./setup.md#configuration). An optional mode, with more capabilities but still in beta, is described in [Reference and advanced configuration](./advanced.md#xapi-plugin).
## Requirements and limitations {#requirements}
In the default mode, the SDN controller talks directly to Open vSwitch through the OpenFlow protocol:
- Xen Orchestra must reach the hosts on **TCP port `6653`** (OpenFlow). XAPI opens this port automatically.
- Rules are set **per VIF** only.
- Rules only work on VIFs of the host's **physical management network**: not on a bond, nor on a VLAN.
## Add a rule {#add-a-rule}
In XO 5, go to the **Network** tab of a VM. Each VIF has a **Network rules** column:
- The **Add rule** button opens a form to create a rule, where you choose:
- whether to **allow or block** the matching traffic;
- a **protocol** (optional);
- a **port** (optional);
- an **IP address or IP range** (optional);
- the **direction**: coming from the VIF, going to the VIF, or both.
- The **Show rules** button displays all the rules of the VIF, with a button to delete each of them.
<UiDetail src="/img/xo5/add-rule.png" alt="The Add rule form: allow or deny, protocol, port, IP range, direction" width={480} />
<UiDetail src="/img/xo5/show-rules.png" alt="All the rules of a VIF, with a delete button for each" width={700} />
For more background, see the [devblog about VIF traffic rules](https://xen-orchestra.com/blog/vms-vif-network-traffic-control/).
## Going further {#going-further}
The default mode covers per-VIF rules on the management network. If you need any of the following, look at the [XAPI plugin mode](./advanced.md#xapi-plugin):
- **network-wide** rules;
- rules on **bonds, VLANs and private networks**;
- **rule priorities**;
- the [XO 6 traffic rules](../management.md#traffic-rules) interface, with a consolidated view of all the rules of a pool.
:::warning
The XAPI plugin mode is still in **beta**, only works on XCP-ng, and switching to it can't be undone without deleting your rules. Read [its caveats](./advanced.md#xapi-plugin) before switching.
:::

View File

@@ -51,7 +51,7 @@ sidebar_position: 5
| **NFS** | Network File System | File-based **SR** backed by an NFS export. |
| **QCOW2** | QEMU Copy On Write v2 | Disk format lifting the 2 TiB **VHD** limit (up to 16 TiB per disk), generally available since XO 6.5 and recent XCP-ng releases. |
| **SR-IOV** | Single Root I/O Virtualization | Passing a virtual function of a physical NIC to a **VM** for near-native I/O. |
| **Traffic rules** | | Firewall-like rules applied to networks and **VIFs** through the [SDN controller](../manage-your-infrastructure/sdn-controller/traffic-rules.md). |
| **Traffic rules** | | Firewall-like rules applied to networks and **VIFs** through the [SDN controller](../manage-your-infrastructure/networking/sdn_controller.md). |
| **VHD** | Virtual Hard Disk | Historical disk and backup format of the platform, limited to 2 TiB per disk (see **QCOW2**). |
| **VLAN** | Virtual LAN | Logical LAN segment; often tied to **PIF** tagging in XAPI. |
| **XVA** | XenServer Virtual Appliance | Archive format for a complete VM export, used by [full backups](../backups-and-dr/backup-types/full_backups.md). |

View File

@@ -87,7 +87,7 @@ export default {
from: ['/backups', '/xo5/backups'],
},
{
to: '/backups-and-dr/backups-in-xo6',
to: '/backups-and-dr/backups-in-xo6',
from: '/xo6/backups',
},
{
@@ -236,17 +236,8 @@ export default {
from: ['/xo5/rolling_snapshots', '/rolling_snapshots'],
},
{
to: '/category/sdn-controller',
from: '/category/networking',
},
{
to: '/manage-your-infrastructure/sdn-controller/setup',
from: [
'/sdn_controller',
'/xo5/sdn_controller',
'/manage-your-infrastructure/sdn_controller',
'/manage-your-infrastructure/networking/sdn_controller',
],
to: '/manage-your-infrastructure/networking/sdn_controller',
from: ['/sdn_controller', '/xo5/sdn_controller', '/manage-your-infrastructure/sdn_controller'],
},
{
to: '/getting-started/requirements#host-compatibility-list',

View File

@@ -1006,8 +1006,23 @@ export class Xapi extends EventEmitter {
}
// manually run events watching if set to `false` in constructor
//
// `_watchEvents` only returns on a failure it does not handle (e.g. an exception thrown by a listener of
// the objects collection) and nothing restarts it: the cache would stay frozen on a connection which still
// looks alive. Disconnect instead: reconnecting is up to the owner of this connection, which listens to
// `disconnected` (xo-server does) and rebuilds what its listeners derived from the cache. Recovering in place
// would keep whatever state the failing listener left half-updated. An owner which does not reconnect (the
// backup worker, the proxy) sees its next call fail instead of waiting forever on a frozen cache.
watchEvents() {
ignoreErrors.call(this._watchEvents())
ignoreErrors.call(
this._watchEvents().catch(error => {
console.warn(`${this._humanId}: the event loop failed, disconnecting`, error)
this._watchEventsError = error
return this.disconnect().catch(disconnectError => {
console.warn(`${this._humanId}: failed to disconnect after the event loop failed`, disconnectError)
})
})
)
}
async watchTask(ref) {

View File

@@ -0,0 +1,29 @@
import { once } from 'node:events'
import { mock, test } from 'node:test'
import { strict as assert } from 'node:assert'
import { Xapi } from './index.mjs'
test('watchEvents() disconnects when an objects listener throws', async () => {
const warn = mock.method(console, 'warn', () => {})
const error = new Error('listener failure')
const xapi = new Xapi({ url: 'https://user:password@192.0.2.1', watchEvents: false })
xapi._sessionOpenWithFailover = async () => {}
await xapi.connect()
xapi._pool = { $ref: 'OpaqueRef:pool' }
xapi._types = ['pool']
xapi._sessionCall = async () => 'token' // event.inject
xapi._roCall = async () => ({ 'OpaqueRef:pool': { uuid: 'pool-uuid', other_config: {} } }) // pool.get_all_records
xapi.objects.on('add', () => {
throw error
})
// fails instead of hanging when nothing disconnects
const disconnected = once(xapi, 'disconnected', { signal: AbortSignal.timeout(2000) })
xapi.watchEvents()
await disconnected
assert.equal(xapi.status, 'disconnected')
assert.equal(warn.mock.calls[0].arguments[1], error)
})

View File

@@ -18,7 +18,7 @@
"preferGlobal": false,
"main": "dist/collection",
"engines": {
"node": ">=6"
"node": ">=15"
},
"dependencies": {
"kindof": "^2.0.0",

View File

@@ -259,6 +259,10 @@ export class Collection extends EventEmitter {
// Events buffering
// -----------------------------------------------------------------
// A listener which throws must not leave the buffer behind, nor skip the other batches and `finish`: the
// flush emits everything, then throws the failure (an `AggregateError` if several), so that the caller
// still sees it. The listeners registered after the failing one for the same batch still miss it, that is
// how `emit` works.
bufferEvents() {
++this._buffering
@@ -290,9 +294,18 @@ export class Collection extends EventEmitter {
data[buffer[key]][key] = this._items[key]
}
const errors = []
const emit = (event, items) => {
try {
this.emit(event, items)
} catch (error) {
errors.push(error)
}
}
forOwn(data, (items, action) => {
if (!isEmpty(items)) {
this.emit(action, items)
emit(action, items)
}
})
@@ -300,9 +313,16 @@ export class Collection extends EventEmitter {
//
// This name has been chosen because it is used in Node writable
// streams when the data has been successfully committed.
this.emit('finish')
emit('finish')
this._buffer = createObject(null)
if (errors.length === 1) {
throw errors[0]
}
if (errors.length > 1) {
throw new AggregateError(errors, 'several listeners failed while flushing the buffered events')
}
}
}

View File

@@ -259,6 +259,68 @@ describe('Collection', function () {
})
})
describe('#bufferEvents()', function () {
it('flushes everything and rethrows when a listener throws', function () {
const error = new Error('listener failure')
const events = []
col.once('add', () => {
throw error
})
col.on('remove', items => events.push(['remove', Object.keys(items)]))
col.on('finish', () => events.push(['finish']))
const flush = col.bufferEvents()
col.add('foo', 1)
col.remove('bar')
assert.throws(flush, error)
assert.deepEqual(events, [['remove', ['bar']], ['finish']])
// the failed flush must not leave its entries in the buffer
const added = []
col.on('add', items => added.push(Object.keys(items)))
const flush2 = col.bufferEvents()
col.add('baz', 2)
flush2()
assert.deepEqual(added, [['baz']])
})
it('empties the buffer when a finish listener throws', function () {
const error = new Error('listener failure')
col.once('finish', () => {
throw error
})
const flush = col.bufferEvents()
col.add('foo', 1)
assert.throws(flush, error)
const added = []
col.on('add', items => added.push(Object.keys(items)))
const flush2 = col.bufferEvents()
col.add('baz', 2)
flush2()
assert.deepEqual(added, [['baz']])
})
it('throws an AggregateError when several listeners throw', function () {
const addError = new Error('add failure')
const removeError = new Error('remove failure')
col.once('add', () => {
throw addError
})
col.once('remove', () => {
throw removeError
})
const flush = col.bufferEvents()
col.add('foo', 1)
col.remove('bar')
assert.throws(flush, { name: 'AggregateError', errors: [addError, removeError] })
})
})
describe('deduplicates events', function () {
forEach(
{

View File

@@ -191,3 +191,24 @@ describe('disconnectXenServer', function () {
assert.deepEqual({ ...xenServers._serverIdsByPool }, { 'pool-2': 'server-2' })
})
})
describe('_onXenAdd', function () {
it('ignores the metrics of an owner which is gone', function () {
const { xenServers } = createXenServers()
// the owner was removed, but `_onXenRemove` left the metrics registered
const dependents = { __proto__: null, 'OpaqueRef:metrics': 'vm-1' }
const metrics = { $id: 'metrics-1', $ref: 'OpaqueRef:metrics', $type: 'VM_metrics' }
assert.doesNotThrow(() =>
xenServers._onXenAdd(
{ 'metrics-1': metrics },
{ __proto__: null },
{ __proto__: null },
'server-1',
dependents,
{}
)
)
assert.deepEqual({ ...dependents }, {})
})
})

View File

@@ -288,6 +288,11 @@ export default class XenServers {
return serverId
}
// `dependents` maps the ref of a metrics object to the id of the object which owns it. `_onXenRemove`
// does not clean it, so the owner may be gone when its metrics are processed, e.g. when the cached records
// are refreshed: each type gets its own `get_all_records` snapshot, taken at a different time, so an owner
// can be destroyed between the snapshot of its metrics and its own. Its removal already dropped its XO
// object, nothing is left to rebuild, and throwing here would end the event loop of the whole pool.
_onXenAdd(newXapiObjects, xapiIdsToXo, toRetry, conId, dependents, xapiObjects) {
const conflicts = this._objectConflicts
const objects = this._app._objects
@@ -319,7 +324,12 @@ export default class XenServers {
const dependent = dependents[$ref]
if (dependent !== undefined) {
delete dependents[$ref]
return handleObject(xapiObjects[dependent], dependent)
const owner = xapiObjects[dependent]
if (owner === undefined) {
return
}
return handleObject(owner, dependent)
}
try {
@@ -670,6 +680,12 @@ export default class XenServers {
await this.updateXenServer(server.id, { status: 'disconnected' })
}
// a failed event loop leaves no other trace, the next successful connection clears it
const { watchEventsError } = xapi
if (watchEventsError !== undefined) {
await this.updateXenServer(server.id, { error: serializeError(watchEventsError) })
}
// deliberate disconnections set `enabled` to false beforehand, in
// which case the loop stops on its own
this._autoReconnectXenServer(server.id)