Compare commits

..

17 Commits

Author SHA1 Message Date
Olivier Lambert
86cdc3d973 fix(xo-server/backups): never replicate to an SR of a disconnected pool
The SRs matched by the expression of a backup job now include the stale
SRs of a disconnected pool, which cannot receive anything: they are
skipped, as when they were not kept.
2026-11-17 21:46:05 +01:00
Olivier Lambert
208a3d6e4f fix(xo-server,rest-api): keep the objects of a failed reconnection, skip stale hosts
- a failed attempt to reconnect a lost server, e.g. which times out while
  fetching its objects, removed the objects it had already replaced: they
  are now kept, flagged, like the others, until the next connection
- the missing patches of every pool (XOA and pool dashboards) failed as
  soon as a pool was stale: its hosts are now counted as failed, and a
  host whose XAPI cannot be found no longer fails the others
2026-11-17 21:46:05 +01:00
Olivier Lambert
6b775fb52c chore: changelog 2026-11-17 21:46:05 +01:00
Olivier Lambert
e41e31ef44 feat(xo-server): keep the objects of a lost pool, flagged as stale
When XO loses a pool, it removed all its objects, which made the pool vanish
from the UI even during a short outage. They are now kept with a `$lastSeen`
property (timestamp of the last successful event fetch) until the pool is
reconnected, and replaced by the fresh objects on reconnection.

- the objects are flagged after `xapiMarkDisconnectedDelay`, lowered from 5
  minutes to 30 seconds since flagging is not destructive, or on an
  unexpected disconnection
- they are removed on a deliberate disconnection, and anyway after the new
  `xapiStaleObjectsMaxAge` setting (1 hour)
- actions on a stale object fail with `the pool of object X is disconnected,
  last seen at …`
- the timeout to fetch the objects of a pool on connection, which reused
  `xapiMarkDisconnectedDelay`, is the new `xapiObjectsFetchTimeout` setting
  (5 minutes)
- the load balancer, perf alert, usage report and Netbox plugins skip stale
  objects
2026-11-17 21:46:05 +01:00
Joris K
3cd440dbdf feat(xo6/host): show the host actions in host tables and side panels (#10821) 2026-11-17 18:07:09 +01:00
Thierry Goettelmann
94f44bfc0e test(web-core): set up Vitest unit test runner (#10818) 2026-11-17 17:27:19 +01:00
OlivierFL
8f62424762 feat(xo6): V2V migration wizard (#10816) 2026-11-17 15:55:23 +01:00
GeraldineFromVates
f37ffc34ca feat(rest-api): add move_management_ip action (#10669)
XO-3150

Add POST /rest/v0/hosts/:id/actions/move_management_ip to move the management IP configuration (IP, netmask, gateway, DNS) of a host to another PIF, then remove it from the previous management PIF.
2026-11-17 14:32:34 +01:00
Joris K
3ac17cbb6b feat(xo6/lite/web-core): show the main VM and host actions in their header (#10815) 2026-11-17 11:08:37 +01:00
Mathieu
1ac84b488c fix(vmware-explorer): read the network cards from the whole config (#10781)
Introduced by 56ffcdb
2026-11-16 18:21:39 +01:00
Bastien Nollet
8fe26d1c2c test(xen-orchestra/log): fix flaky test (#10812)
Fix flaky test that was failing ~40% of the time, which repeatedly failed the CI. (see: https://github.com/vatesfr/xen-orchestra/actions/runs/43883203086/attempts/1?pr=10809, it failed twice before succeeding)

Introduced by 8fb6a9d
2026-11-16 18:21:30 +01:00
Olivier Lambert
3c6d3e66e4 feat(xo-server-audit): forward records to a remote syslog server (#10618)
* feat(xo-server-audit): forward records to a remote syslog server

Add an optional `syslog` section to the plugin configuration (target,
facility, and certificate options for TLS). Each new record is sent as JSON
in an RFC 5424 message over UDP, TCP or TLS, so that audit records can be
collected by a SIEM. Records stay stored in XO, forwarding is best effort with
a bounded buffer.

Since records can now leave XO, known sensitive values (created API tokens,
credentials and encryption keys in URLs, one-time download/upload links) are
redacted before storing the records, which keeps their hashes verifiable.

See https://feedback.vates.tech/posts/88

* chore: add PR link to changelog

* fix(xo-server-audit): report connection errors to host names with several addresses

Connecting to a host name resolving to several addresses (e.g. IPv4 and
IPv6) fails with an AggregateError without message, which was displayed as
an empty error by the plugin test. Use the messages of its errors instead.

* fix(xo-server-audit): replace checkCertificate by ignoreUnauthorized

xo-web displays a missing boolean as disabled whatever its default, so
`checkCertificate` (enabled by default) was displayed as disabled while
certificates were checked. Use the same option as transport-email instead,
disabled by default.

* fix(xo-server-audit): rename syslog target to uri

xo-web considers an object with a `target` property as an event, so the
whole `syslog` section could not be edited in the plugin form. Use `uri`,
like the LDAP plugin.

* feat(xo-server-audit): use @vates/syslog

Use the shared syslog client instead of the plugin's own sender, and expose
its framing option (octet-counting is required by some servers, e.g. the
syslog() driver of syslog-ng).

* refactor(xo-server-audit): redact records with @vates/obfuscate

The redaction is also needed by the support bundle (#10737), so the generic
parts move to @vates/obfuscate:

- isExportSensitiveParam() and redact(), from #10737, with options for the
  replacement and to also redact the URLs of the other strings
- redactUrls(): credentials and sensitive query parameters of URLs, in any
  string (e.g. an error message)

Only the XO specific checks stay in the plugin: methods whose result is a
secret and one-time download/upload URLs. Keys like apiKey, privateKey or
secret are now also redacted, whatever the type of their values.

* fix(xo-server-audit): keep recording when syslog cannot be set up at startup

- a configuration change with unusable syslog settings (e.g. an unreadable
  certificate authority) is still rejected, with the reason
- at startup, the error is logged and only the forwarding is disabled, the
  records are still stored, and the test button shows the error
- rename ignoreUnauthorized to allowUnauthorized, like elsewhere in XO
2026-11-16 16:16:22 +01:00
Joris K
c8d016d8bd fix(xo6/lite/web-core): fix the double scrollbar in side panels (#10807) 2026-11-16 15:07:13 +01:00
Olivier Lambert
8dbf5a5ace feat(xo-server): stream local ISOs from the browser through live mount (#10426)
* fix(mixins/live-mount): leave the firewall alone without root on iptables-legacy

As non-root, iptables-legacy fails on the xtables lock (`can't open lock
file /run/xtables.lock: Permission denied`) before saying it requires
root, so the mount failed instead of going on without a rule.

* feat(mixins/live-mount): serve any block device, only to its host

- serveBlockDevice(): a target for a host, firewall rule included, which
  can take over the identity (id, CHAP, port) of a previous one
- mountBlockDevice()/unmountBlockDevice(): like mountDisk() for any
  BlockDevice, the VDI being read-only when the LUN is
- beforeUnmount: run first whatever triggers the unmount, the mount stays
  as it is when it fails, e.g. to eject a VDI while the target answers
- smConfig: set atomically with SR.introduce
- targets only accept the addresses of their host (management and PIFs),
  unless iscsi.restrictToHost is false, e.g. behind a NAT

* feat(xo-server): stream local ISOs from the browser through live mount

Experimental, administrators only. The browser serves an ISO over a
WebSocket (/api/browser-media, authenticated by the token cookie), and
POST /vms/{id}/actions/insert_browser_iso inserts it in the CD drive of
the VM: it is served by a read-only live mount, attached to the host of
the VM. /browser-media lists the sessions of every administrator, and
actions/eject ejects one.

While inserted, the VM cannot migrate, checkpoint nor be suspended
(blocked_operations). The ISO is ejected once the browser disconnects,
once another client ejects it, or once it has not been read for
browserMedia.idleTimeout, and everything changed in the pool is undone.

The CD drive uses blkback (backend-kind: vbd): for a CD, XAPI ignores the
backend-kind of the raw LUN VDI and uses tapdisk, which refuses it.

Every change is tagged in the pool and journaled first. After a crash,
the target is served again under its previous identity while the host
detaches the ISO: otherwise the detach fails on the dead target, XAPI
keeps a datapath on the forgotten SR, and the VM can no longer stop.

Disabled with browserMedia.enabled = false.

* fix(xo-server/browser-media): address the review of the second version

- the journal entry is only deleted once the SR is gone from the pool: a
  partial unmount hands the session over to the recovery, and a VM
  missing from XO is only taken as deleted if its pool is connected
- live mount: concurrent unmounts share the same teardown, e.g. the stop
  hooks of live mount and browser media
- a CD drive changed by a failed insertion is cleaned up, from its tag
- an eject waits for an insertion in progress, reports the actual result,
  and released sessions no longer count toward the limit
- the Origin of the WebSocket must match the port when both tell one, and
  X-Forwarded-Host is used behind a trusted reverse proxy
- REST: browserMediaId, task params, Location header, userId
- the ISO size is journaled, for the standby target
- IPv6 addresses of the hosts are canonicalized
- iscsi.restrictToHost is documented, and named in the error of a host
  which cannot reach the target

* feat(mixins/live-mount): name the address a host behind a NAT connects from

Follows the rename to allowedInitiatorAddresses in @vates/iscsi: when the
probe fails after the target refused a connection, the error tells the
address the host connected from, and to set iscsi.restrictToHost = false.

* fix(xo-server/browser-media): address the review of Florent

- re-arm the read timer on each reply, so that a slow link which keeps
  answering is not cut, while a read left unanswered still ends the session
- retry a failed release with pRetry, then quietly at each reconciliation
- recover the journal with asyncEach, key by key
- declare the session state (insertion, insertingPromise, releasingPromise)
  and make XoBrowserMediaSession a union on its status
- a failed insertion is `ejecting` while it is undone, never `inserting`
- forget the CD drive of an insertion on every path that ends it
- warn about invalid CD drive tags, once per drive
- report again the journal entries of a pool which reconnects then
  disconnects
- answer an unexpected authentication failure with a 503, not a 401
- use mock timers in the session tests

* fix(xo-server/browser-media): a cancelled insertion is not a server error

The browser disconnecting during the insertion, e.g. when it is
cancelled, threw a plain error: a 500, logged at the error level by the
REST API. It is now an `incorrect state` on the status of the session,
a 409.

* fix(xo-server/browser-media): drop invalid journal entries, report a cancelled insertion on `closed`

- a journal entry without its pool and VM, or which fails to decode, cannot be recovered and was
  retried forever: it is now deleted, with a warning naming the session id its leftovers are tagged
  with. An entry which cannot be read for another reason (e.g. the database) is still kept and retried.
- an insertion cancelled from the browser reported `status: disconnected`, which is not a status: the
  status is still `inserting` then. The error now reports the property which changed, `closed`.

---------

Co-authored-by: Florent BEAUCHAMP <florent.beauchamp@vates.tech>
2026-11-16 14:23:31 +01:00
Elise-F
067b1ac2ef feat(xo6): add a priority when creating a new traffic rule (#10750) 2026-11-16 13:58:05 +01:00
Mathieu
1dd7cb4319 fix(vectura): update rustls-webpki to 0.103.17 (#10803)
cargo deny fails on master since RUSTSEC-2026-0382 was published against
rustls-webpki 0.103.15: certificate paths through the distrusted emSign
intermediates, whose private keys are now public, may be accepted.
0.103.16 and later reject them.

These keys allow forging a certificate for any host (VSA-2026-050). In
vectura they matter when the host certificate is checked against the
system trust store (no --thumbprint) or a --ca-file bundle: a
man-in-the-middle could then read the ESXi password and the disks.
Xen Orchestra always passes --thumbprint, which bypasses path building,
so imports run from Xen Orchestra were not exposed through vectura.

vectura 0.2.1, bumped and rebuilt with scripts/release.sh patch.
2026-11-16 13:57:50 +01:00
Olivier Lambert
8fb6a9d8e5 feat(@vates/syslog): new syslog client, used by the log syslog transport (#10619)
* feat(@vates/syslog): new syslog client, used by the log syslog transport

`@vates/syslog` sends RFC 5424 (or RFC 3164) messages over UDP, TCP or TLS,
with line feed or octet-counting framing. A client uses at most one
connection, with a connection timeout, and rejects messages when too much is
waiting to be sent instead of buffering without limit.

The syslog transport of `@xen-orchestra/log` now uses it instead of
`syslog-client`, which fixes:

- every log sent with the informational severity (the levels were not read)
- a connection attempt left open each time one timed out
- unbounded buffering when the server does not read
- each failure becoming an unhandled rejection, logged again by the logger

and adds TLS, and the facility, application name, format and framing options.
2026-11-16 13:53:59 +01:00
671 changed files with 32970 additions and 1623 deletions

View File

@@ -53,6 +53,12 @@ module.exports = {
],
},
},
{
files: ['@xen-orchestra/web-core/**/*.unit.{test,spec}.ts'],
rules: {
'n/no-unpublished-import': 'off',
},
},
{
files: ['@xen-orchestra/{web-core,lite,web}/**/*.{vue,ts}'],
parser: 'vue-eslint-parser',

View File

@@ -44,3 +44,39 @@ obfuscated.token = 'qux'
merge(obfuscated, original)
// → { username: 'foo', password: 'bar', token: 'qux' }
```
### `redact(value, [isSensitive], [options])`
> Recursively replace sensitive entries with the same special tag as `obfuscate()`, whatever their type.
>
> Unlike `obfuscate()`, it uses a broader list of sensitive keys (`isExportSensitiveParam`) because redacted values are never merged back: it is meant for data leaving XO, such as support dumps or audit records. Keys are kept so that the structure stays usable.
Options:
- `replacement`: the special tag of `obfuscate()` by default
- `urls`: whether to also apply `redactUrls()` to the other strings, `false` by default
```js
import { redact } from '@vates/obfuscate'
redact({ username: 'foo', password: 'bar', cluster_token: { value: 'baz' } })
// → {
// username: 'foo',
// password: 'obfuscated-q3oi6d9X8uenGvdLnHk2',
// cluster_token: 'obfuscated-q3oi6d9X8uenGvdLnHk2',
// }
redact({ error: 'cannot mount nfs://user:pass@host/path' }, undefined, { replacement: '*', urls: true })
// → { error: 'cannot mount nfs://*@host/path' }
```
### `redactUrls(string, [replacement])`
> Replace the credentials and the sensitive query parameters (e.g. `encryptionKey`) of the URLs in a string, wherever they are (e.g. in an error message).
```js
import { redactUrls } from '@vates/obfuscate'
redactUrls('s3://KEY:secret@s3.lan/bucket?encryptionKey=foo', '*')
// → 's3://*@s3.lan/bucket?encryptionKey=*'
```

View File

@@ -61,6 +61,42 @@ merge(obfuscated, original)
// → { username: 'foo', password: 'bar', token: 'qux' }
```
### `redact(value, [isSensitive], [options])`
> Recursively replace sensitive entries with the same special tag as `obfuscate()`, whatever their type.
>
> Unlike `obfuscate()`, it uses a broader list of sensitive keys (`isExportSensitiveParam`) because redacted values are never merged back: it is meant for data leaving XO, such as support dumps or audit records. Keys are kept so that the structure stays usable.
Options:
- `replacement`: the special tag of `obfuscate()` by default
- `urls`: whether to also apply `redactUrls()` to the other strings, `false` by default
```js
import { redact } from '@vates/obfuscate'
redact({ username: 'foo', password: 'bar', cluster_token: { value: 'baz' } })
// → {
// username: 'foo',
// password: 'obfuscated-q3oi6d9X8uenGvdLnHk2',
// cluster_token: 'obfuscated-q3oi6d9X8uenGvdLnHk2',
// }
redact({ error: 'cannot mount nfs://user:pass@host/path' }, undefined, { replacement: '*', urls: true })
// → { error: 'cannot mount nfs://*@host/path' }
```
### `redactUrls(string, [replacement])`
> Replace the credentials and the sensitive query parameters (e.g. `encryptionKey`) of the URLs in a string, wherever they are (e.g. in an error message).
```js
import { redactUrls } from '@vates/obfuscate'
redactUrls('s3://KEY:secret@s3.lan/bucket?encryptionKey=foo', '*')
// → 's3://*@s3.lan/bucket?encryptionKey=*'
```
## Contributions
Contributions are _very_ welcomed, either on the documentation or on

View File

@@ -57,3 +57,74 @@ function replace(value, replacement) {
return helper(value)
}
exports.replace = replace
// broader than SENSITIVE_PARAMS because redacted values are never merged back:
// meant for data leaving XO (e.g. support dumps, audit records), not for display
const EXPORT_SENSITIVE_PARAMS = [
/api[-_]?key/i, // e.g. `apikey` in the XenServer credentials of user preferences
'encryptionKey',
'privateKey',
'pw_hash',
/passphrase/i,
/password/i,
/secret/i,
/token/i,
]
const isExportSensitiveParam = name =>
EXPORT_SENSITIVE_PARAMS.some(pattern => (typeof pattern === 'string' ? pattern === name : pattern.test(name)))
exports.isExportSensitiveParam = isExportSensitiveParam
// SMB URLs (e.g. of backup repositories) contain the raw password, which can
// contain any character (e.g. `smb://user:p@ss/w@domain\\\\host\0path`), so the
// credentials are everything up to the last `@` before the path
const SMB_CREDENTIALS_RE = /^(smb:\/\/)[^\0]*@/i
// other URLs, anywhere in the string (e.g. an error message): credentials are
// URL encoded and end at the first `@`, see https://datatracker.ietf.org/doc/html/rfc3986#section-3.2.1
const URL_CREDENTIALS_RE = /([a-z][a-z\d+.-]*:\/\/)[^\s/?#@]*@/gi
// e.g. `?encryptionKey=` in a backup repository URL, same names as SENSITIVE_PARAMS
const SENSITIVE_QUERY_PARAM_RE = /([?&](?:encryptionKey|passphrase|token|[^=&#\s]*password[^=&#\s]*)=)[^&#\s]*/gi
// replaces the credentials and the sensitive query parameters of the URLs in a string
function redactUrls(string, replacement = OBFUSCATED_VALUE) {
if (!string.includes('://')) {
return string
}
return string
.replace(SMB_CREDENTIALS_RE, (_, scheme) => `${scheme}${replacement}@`)
.replace(URL_CREDENTIALS_RE, (_, scheme) => `${scheme}${replacement}@`)
.replace(SENSITIVE_QUERY_PARAM_RE, (_, param) => `${param}${replacement}`)
}
exports.redactUrls = redactUrls
// unlike replace(), also replaces non-string entries (e.g. a whole object under
// a `secret` key), keys are kept so that the structure stays usable
//
// options:
// - `replacement`: OBFUSCATED_VALUE by default
// - `urls`: whether to apply redactUrls() to the other strings, false by default
function redact(value, isSensitive = isExportSensitiveParam, { replacement = OBFUSCATED_VALUE, urls = false } = {}) {
function helper(value) {
if (typeof value === 'string') {
return urls ? redactUrls(value, replacement) : value
}
if (typeof value !== 'object' || value === null) {
return value
}
if (Array.isArray(value)) {
return value.map(helper)
}
const result = {}
for (const key of Object.keys(value)) {
result[key] = isSensitive(key) ? replacement : helper(value[key])
}
return result
}
return helper(value)
}
exports.redact = redact

View File

@@ -0,0 +1,94 @@
'use strict'
const { describe, it } = require('node:test')
const assert = require('node:assert/strict')
const { obfuscate, OBFUSCATED_VALUE, redact, redactUrls } = require('./')
describe('redact()', () => {
it('replaces sensitive entries at any depth, whatever their type, and keeps the keys', () => {
const remote = {
name: 'nas',
url: 's3://key@host/bucket',
encryptionKey: 'aes-key',
proxy: { authenticationToken: 'proxy-token' },
credentials: [{ username: 'admin', password: 'pass', secret: { value: 'chap' } }],
}
assert.deepEqual(redact(remote), {
name: 'nas',
url: 's3://key@host/bucket',
encryptionKey: OBFUSCATED_VALUE,
proxy: { authenticationToken: OBFUSCATED_VALUE },
credentials: [{ username: 'admin', password: OBFUSCATED_VALUE, secret: OBFUSCATED_VALUE }],
})
})
it('catches keys missed by obfuscate()', () => {
const plugin = { apiKey: 'k', cluster_token: 't', secretAccessKey: 's', pw_hash: 'h' }
assert.deepEqual(redact(plugin), {
apiKey: OBFUSCATED_VALUE,
cluster_token: OBFUSCATED_VALUE,
secretAccessKey: OBFUSCATED_VALUE,
pw_hash: OBFUSCATED_VALUE,
})
assert.equal(obfuscate(plugin).apiKey, 'k')
})
it('accepts a custom predicate and replacement', () => {
assert.deepEqual(
redact({ a: 1, b: { a: 2, c: 3 } }, key => key === 'a', { replacement: '*' }),
{
a: '*',
b: { a: '*', c: 3 },
}
)
})
it('redacts the URLs of the other strings with `urls`', () => {
const data = {
params: { url: 'smb://admin:p@ss@nas\\\\share' },
error: 'mount of nfs://user:pass@host/path failed',
}
assert.deepEqual(redact(data, undefined, { replacement: '*', urls: true }), {
params: { url: 'smb://*@nas\\\\share' },
error: 'mount of nfs://*@host/path failed',
})
assert.deepEqual(redact(data), data)
})
it('returns other values as is', () => {
assert.equal(redact('password'), 'password')
assert.equal(redact(null), null)
})
})
describe('redactUrls()', () => {
it('replaces the credentials of URLs, anywhere in the string', () => {
assert.equal(
redactUrls('failed to connect to https://user:p%40ss@host/ and s3://KEY:secret@s3.lan/bucket'),
`failed to connect to https://${OBFUSCATED_VALUE}@host/ and s3://${OBFUSCATED_VALUE}@s3.lan/bucket`
)
})
it('replaces the credentials of SMB URLs up to the last @ before the path', () => {
assert.equal(redactUrls('smb://user:p@ss/w@domain\\\\host\0path', '*'), 'smb://*@domain\\\\host\0path')
})
it('replaces sensitive query parameters', () => {
assert.equal(
redactUrls('s3://host/bucket?encryptionKey=k&region=eu&adminPassword=p', '*'),
's3://host/bucket?encryptionKey=*&region=eu&adminPassword=*'
)
})
it('handles replacements containing $', () => {
assert.equal(redactUrls('http://u:p@h/', '$1'), 'http://$1@h/')
})
it('returns strings without URLs as is', () => {
assert.equal(redactUrls('user:pass@host'), 'user:pass@host')
})
})

View File

@@ -18,6 +18,7 @@
"node": ">=8.10"
},
"scripts": {
"postversion": "npm publish --access public"
"postversion": "npm publish --access public",
"test": "node --test"
}
}

48
@vates/syslog/.USAGE.md Normal file
View File

@@ -0,0 +1,48 @@
```js
import { createClient } from '@vates/syslog'
const client = createClient('tls://syslog.company.lan', {
appName: 'my-app',
facility: 'authpriv',
})
await client.send('something happened', { msgid: 'event', severity: 'warning' })
// closes the connection once the messages already sent are delivered, the client reconnects if it is used again
client.close()
```
### `createClient(uri, options)`
`uri`: `udp://host[:port]`, `tcp://host[:port]` or `tls://host[:port]`, the default port is `514`, or `6514` for TLS.
Options:
- `appName`: application name of the messages, `node` by default
- `facility`: one of `FACILITIES` (e.g. `user`, `authpriv`, `local0`), `user` by default
- `format`: `rfc5424` (default) or `rfc3164`
- `framing` (TCP and TLS): `lf` (default, each message followed by a line feed, its own line breaks written as `\n` and `\r`) or `octet-counting` (each message prefixed by its length, required by some servers for TLS, see [RFC 5425](https://datatracker.ietf.org/doc/html/rfc5425#section-4.3))
- `hostname`: host name of the messages, `os.hostname()` by default
- `ca` (TLS): contents of PEM certificate authorities to trust, in addition to the system ones
- `allowUnauthorized` (TLS): do not check the certificate of the server, `false` by default
- `closeTimeout`: in milliseconds, how long `close()` waits for the messages already sent, `10e3` by default
- `connectTimeout`: in milliseconds, `10e3` by default
- `maxPendingBytes`: messages are rejected when more than this is waiting to be sent (e.g. the server is unreachable or does not read), `1 MiB` by default
A client uses at most one connection, opened when needed.
### `client.send(message, options)`
Returns a promise which resolves when the message has been handed to the system. Syslog has no acknowledgement: it does not mean that the server received it.
Options:
- `msgid`: message ID (RFC 5424 only)
- `severity`: one of `SEVERITIES` (e.g. `error`, `warning`, `informational`), `informational` by default
- `timestamp`: `Date` of the message, now by default
The promise rejects if the message cannot be sent, with the cause of the failure (e.g. connection refused, invalid certificate, too much data waiting).
### `client.close()`
Closes the connection, including a connection which is being established. The messages already sent are still delivered first (e.g. while the connection is being established or the host name resolved), for at most `closeTimeout`: after that, those not sent fail.

36
@vates/syslog/.npmignore Normal file
View File

@@ -0,0 +1,36 @@
.*
/benchmark/
/benchmarks/
*.bench.{,c,m}js
*.bench.{,c,m}js.map
/coverage/
/examples/
example.{,c,m}js
example.{,c,m}js.map
*.example.{,c,m}js
*.example.{,c,m}js.map
/fixture/
/fixtures/
*.fixture.{,c,m}js
*.fixture.{,c,m}js.map
*.fixtures.{,c,m}js
*.fixtures.{,c,m}js.map
/test/
/tests/
*.integ.{,c,m}js
*.integ.{,c,m}js.map
*.spec.{,c,m}js
*.spec.{,c,m}js.map
*.test.{,c,m}js
*.test.{,c,m}js.map
__snapshots__/
/docs/
/src/
eslint.config.mjs

81
@vates/syslog/README.md Normal file
View File

@@ -0,0 +1,81 @@
<!-- DO NOT EDIT MANUALLY, THIS FILE HAS BEEN GENERATED -->
# @vates/syslog
[![Package Version](https://badgen.net/npm/v/@vates/syslog)](https://npmjs.org/package/@vates/syslog) ![License](https://badgen.net/npm/license/@vates/syslog) [![PackagePhobia](https://badgen.net/bundlephobia/minzip/@vates/syslog)](https://bundlephobia.com/result?p=@vates/syslog) [![Node compatibility](https://badgen.net/npm/node/@vates/syslog)](https://npmjs.org/package/@vates/syslog)
> Syslog client: RFC 5424 messages over UDP, TCP or TLS, with a bounded buffer
## Install
Installation of the [npm package](https://npmjs.org/package/@vates/syslog):
```sh
npm install --save @vates/syslog
```
## Usage
```js
import { createClient } from '@vates/syslog'
const client = createClient('tls://syslog.company.lan', {
appName: 'my-app',
facility: 'authpriv',
})
await client.send('something happened', { msgid: 'event', severity: 'warning' })
// closes the connection once the messages already sent are delivered, the client reconnects if it is used again
client.close()
```
### `createClient(uri, options)`
`uri`: `udp://host[:port]`, `tcp://host[:port]` or `tls://host[:port]`, the default port is `514`, or `6514` for TLS.
Options:
- `appName`: application name of the messages, `node` by default
- `facility`: one of `FACILITIES` (e.g. `user`, `authpriv`, `local0`), `user` by default
- `format`: `rfc5424` (default) or `rfc3164`
- `framing` (TCP and TLS): `lf` (default, each message followed by a line feed, its own line breaks written as `\n` and `\r`) or `octet-counting` (each message prefixed by its length, required by some servers for TLS, see [RFC 5425](https://datatracker.ietf.org/doc/html/rfc5425#section-4.3))
- `hostname`: host name of the messages, `os.hostname()` by default
- `ca` (TLS): contents of PEM certificate authorities to trust, in addition to the system ones
- `allowUnauthorized` (TLS): do not check the certificate of the server, `false` by default
- `closeTimeout`: in milliseconds, how long `close()` waits for the messages already sent, `10e3` by default
- `connectTimeout`: in milliseconds, `10e3` by default
- `maxPendingBytes`: messages are rejected when more than this is waiting to be sent (e.g. the server is unreachable or does not read), `1 MiB` by default
A client uses at most one connection, opened when needed.
### `client.send(message, options)`
Returns a promise which resolves when the message has been handed to the system. Syslog has no acknowledgement: it does not mean that the server received it.
Options:
- `msgid`: message ID (RFC 5424 only)
- `severity`: one of `SEVERITIES` (e.g. `error`, `warning`, `informational`), `informational` by default
- `timestamp`: `Date` of the message, now by default
The promise rejects if the message cannot be sent, with the cause of the failure (e.g. connection refused, invalid certificate, too much data waiting).
### `client.close()`
Closes the connection, including a connection which is being established. The messages already sent are still delivered first (e.g. while the connection is being established or the host name resolved), for at most `closeTimeout`: after that, those not sent fail.
## Contributions
Contributions are _very_ welcomed, either on the documentation or on
the code.
You may:
- report any [issue](https://github.com/vatesfr/xen-orchestra/issues)
you've encountered;
- fork and create a pull request.
## License
[ISC](https://spdx.org/licenses/ISC) © [Vates SAS](https://vates.fr)

311
@vates/syslog/index.js Normal file
View File

@@ -0,0 +1,311 @@
'use strict'
const dgram = require('dgram')
const net = require('net')
const os = require('os')
const splitHost = require('split-host')
const tls = require('tls')
// https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1
const FACILITIES = {
__proto__: null,
kern: 0,
user: 1,
mail: 2,
daemon: 3,
auth: 4,
syslog: 5,
lpr: 6,
news: 7,
uucp: 8,
cron: 9,
authpriv: 10,
ftp: 11,
ntp: 12,
audit: 13,
alert: 14,
clock: 15,
local0: 16,
local1: 17,
local2: 18,
local3: 19,
local4: 20,
local5: 21,
local6: 22,
local7: 23,
}
exports.FACILITIES = Object.keys(FACILITIES)
const SEVERITIES = {
__proto__: null,
emergency: 0,
alert: 1,
critical: 2,
error: 3,
warning: 4,
notice: 5,
informational: 6,
debug: 7,
}
exports.SEVERITIES = Object.keys(SEVERITIES)
const DEFAULT_PORTS = {
tcp: 514,
// https://datatracker.ietf.org/doc/html/rfc5425#section-4.1
tls: 6514,
udp: 514,
}
// header fields must be printable ASCII characters without spaces
const toHeaderField = (value, maxLength) =>
String(value)
.replace(/[^\x21-\x7e]/g, '_')
.slice(0, maxLength) || '-'
const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
const pad2 = n => String(n).padStart(2, '0')
const FORMATTERS = {
// https://datatracker.ietf.org/doc/html/rfc5424#section-6
rfc5424: ({ appName, hostname, message, msgid, pri, timestamp }) =>
`<${pri}>1 ${timestamp.toISOString()} ${hostname} ${appName} ${process.pid} ${msgid} - ${message}`,
// https://datatracker.ietf.org/doc/html/rfc3164#section-4.1, local time without year
rfc3164: ({ appName, hostname, message, pri, timestamp }) =>
`<${pri}>${MONTHS[timestamp.getMonth()]} ${String(timestamp.getDate()).padStart(2, ' ')} ${pad2(timestamp.getHours())}:${pad2(timestamp.getMinutes())}:${pad2(timestamp.getSeconds())} ${hostname} ${appName}[${process.pid}]: ${message}`,
}
const FRAMERS = {
// https://datatracker.ietf.org/doc/html/rfc6587#section-3.4.2
//
// a line feed ends the message: the line breaks it contains are written as
// `\n` (and `\r`) so that it is received as one message, use octet-counting
// to keep them
lf: message => message.replace(/\r/g, '\\r').replace(/\n/g, '\\n') + '\n',
// https://datatracker.ietf.org/doc/html/rfc6587#section-3.4.1, required by RFC 5425 (TLS)
'octet-counting': message => `${Buffer.byteLength(message)} ${message}`,
}
const noop = Function.prototype
// connecting to a host name with several addresses (e.g. IPv4 and IPv6) fails
// with an AggregateError without message, use the messages of its errors
function withMessage(error) {
if (error.message === '' && Array.isArray(error.errors) && error.errors.length !== 0) {
error.message = error.errors.map(error => error.message).join(', ')
// the first line of the stack has been computed with the empty message
if (typeof error.stack === 'string') {
const i = error.stack.indexOf('\n')
error.stack = `${error.name}: ${error.message}${i === -1 ? '' : error.stack.slice(i)}`
}
}
return error
}
// UDP sockets: callbacks of the datagrams not yet sent (e.g. host name being
// resolved), the socket is closed once they are all called
const pendingDatagrams = new WeakMap()
function closeUdpSocket(socket, timeout) {
const pending = pendingDatagrams.get(socket)
if (pending.size === 0) {
socket.close()
return
}
pending.closing = true
// the datagrams which are still not sent then fail, so that no send() stays pending
setTimeout(() => {
if (pending.size !== 0) {
const callbacks = Array.from(pending)
pending.clear()
socket.close()
const error = new Error('the syslog client was closed before the message could be sent')
callbacks.forEach(cb => cb(error))
}
}, timeout).unref()
}
class SyslogClient {
constructor(
uri,
{
appName = 'node',
ca,
closeTimeout = 10e3,
connectTimeout = 10e3,
facility = 'user',
format = 'rfc5424',
framing = 'lf',
allowUnauthorized = false,
hostname = os.hostname(),
maxPendingBytes = 1024 * 1024,
} = {}
) {
const matches = /^(tcp|tls|udp):\/\/(.+)$/.exec(String(uri).trim())
const protocol = matches?.[1]
const { host, port = DEFAULT_PORTS[protocol] } = (matches !== null && splitHost(matches[2])) || {}
if (!host) {
throw new Error(
`invalid syslog URI: ${uri}, it should be like udp://host[:port], tcp://host[:port] or tls://host[:port]`
)
}
if (!(facility in FACILITIES)) {
throw new Error(`invalid syslog facility: ${facility}`)
}
if (!(format in FORMATTERS)) {
throw new Error(`invalid syslog format: ${format}`)
}
if (!(framing in FRAMERS)) {
throw new Error(`invalid syslog framing: ${framing}`)
}
this._appName = toHeaderField(appName, 48)
this._closeTimeout = closeTimeout
this._connectTimeout = connectTimeout
this._facility = FACILITIES[facility]
this._format = FORMATTERS[format]
this._frame = FRAMERS[framing]
this._host = host
this._hostname = toHeaderField(hostname, 255)
this._maxPendingBytes = maxPendingBytes
this._port = port
this._send = protocol === 'udp' ? this._sendUdp : this._sendStream
this._tlsOptions =
protocol === 'tls'
? {
// the `ca` option replaces the system certificate authorities
ca: ca === undefined ? undefined : [...tls.rootCertificates, ...ca],
rejectUnauthorized: !allowUnauthorized,
}
: undefined
// at most one socket at a time, created when needed
this._socket = undefined
}
// the messages already sent are still delivered (e.g. a connection which is
// being established, or a host name which is being resolved), then the socket
// is closed, at most closeTimeout later
//
// the client can still be used afterwards, it will reconnect
close() {
const socket = this._socket
if (socket === undefined) {
return
}
this._socket = undefined
if (socket instanceof net.Socket) {
// the pending writes are flushed before the connection is ended
socket.end()
const timeout = setTimeout(() => socket.destroy(), this._closeTimeout)
timeout.unref()
socket.once('close', () => clearTimeout(timeout))
} else {
closeUdpSocket(socket, this._closeTimeout)
}
}
// resolves when the message has been handed to the system, which does not
// mean that the server received it (syslog has no acknowledgement)
send(message, { msgid = '-', severity = 'informational', timestamp = new Date() } = {}) {
if (!(severity in SEVERITIES)) {
return Promise.reject(new Error(`invalid syslog severity: ${severity}`))
}
const formatted = this._format({
appName: this._appName,
hostname: this._hostname,
message: String(message),
msgid: toHeaderField(msgid, 32),
pri: this._facility * 8 + SEVERITIES[severity],
timestamp,
})
return new Promise((resolve, reject) => {
this._send(formatted, error => (error == null ? resolve() : reject(error)))
})
}
// TCP and TLS
_sendStream(message, cb) {
let socket = this._socket
if (socket === undefined) {
const tlsOptions = this._tlsOptions
const options = { host: this._host, port: this._port }
socket = this._socket =
tlsOptions === undefined ? net.connect(options) : tls.connect({ ...tlsOptions, ...options })
// a connection attempt that never completes (e.g. packets dropped by a
// firewall, or a TLS handshake without answer) must not stay around
//
// not socket.setTimeout() which is an inactivity timeout, postponed by
// each write during a TLS handshake
const connectTimeout = setTimeout(() => socket.destroy(new Error('connection timed out')), this._connectTimeout)
connectTimeout.unref()
socket.on(tlsOptions === undefined ? 'connect' : 'secureConnect', () => {
clearTimeout(connectTimeout)
// detect a server which disappeared without closing the connection
socket.setKeepAlive(true, 60e3)
})
// errors are passed to the callbacks of the pending writes
socket.on('error', noop)
socket.on('close', () => {
clearTimeout(connectTimeout)
if (this._socket === socket) {
this._socket = undefined
}
})
// do not prevent the process from stopping
socket.unref()
}
// messages are dropped when too much is waiting to be sent (e.g. the server
// is unreachable or no longer reads), instead of filling the memory, this
// also covers the messages written while the connection is being established
if (socket.writableLength > this._maxPendingBytes) {
cb(new Error('too much data waiting to be sent to the syslog server'))
return
}
// pending writes fail with a generic error when the connection fails, report its cause instead
socket.write(this._frame(message), error => cb(error == null ? error : withMessage(socket.errored ?? error)))
}
// one message per datagram, see https://datatracker.ietf.org/doc/html/rfc5426
_sendUdp(message, cb) {
let socket = this._socket
if (socket === undefined) {
socket = this._socket = dgram.createSocket(net.isIPv6(this._host) ? 'udp6' : 'udp4')
pendingDatagrams.set(socket, new Set())
// errors are passed to the callbacks of send(), a failed socket is replaced
socket.on('error', () => {
if (this._socket === socket) {
this.close()
}
})
socket.unref()
}
const pending = pendingDatagrams.get(socket)
pending.add(cb)
socket.send(message, this._port, this._host, error => {
// otherwise, already failed by closeUdpSocket()
if (pending.delete(cb)) {
if (pending.size === 0 && pending.closing) {
socket.close()
}
cb(error)
}
})
}
}
exports.createClient = (uri, opts) => new SyslogClient(uri, opts)

View File

@@ -0,0 +1,286 @@
import assert from 'node:assert/strict'
import dgram from 'node:dgram'
import fs from 'node:fs'
import net from 'node:net'
import tls from 'node:tls'
import { after, describe, it } from 'node:test'
import { setTimeout as wait } from 'node:timers/promises'
import { createClient, FACILITIES, SEVERITIES } from './index.js'
const fixture = name => fs.readFileSync(new URL(`./tests/${name}`, import.meta.url), 'utf8')
const CA = fixture('ca.pem')
const servers = []
after(() => servers.forEach(server => server.close()))
const listen = server =>
new Promise(resolve => {
servers.push(server)
server.listen(0, '127.0.0.1', () => resolve(server.address().port))
})
// stream server collecting the received data
async function createStreamServer(createServer = net.createServer) {
const server = { data: '', sockets: new Set() }
server.port = await listen(
createServer(socket => {
server.sockets.add(socket)
socket.on('close', () => server.sockets.delete(socket))
socket.on('data', data => (server.data += data))
})
)
return server
}
async function createUdpServer() {
const messages = []
const socket = dgram.createSocket('udp4').on('message', message => messages.push(message.toString()))
servers.push(socket)
await new Promise(resolve => socket.bind(0, '127.0.0.1', resolve))
return { messages, port: socket.address().port }
}
describe('createClient()', () => {
it('rejects invalid URIs and options', () => {
for (const uri of ['syslog.lan', 'http://syslog.lan', 'udp://', 'udp://:514', undefined]) {
assert.throws(() => createClient(uri), /invalid syslog URI/, String(uri))
}
assert.throws(() => createClient('udp://h', { facility: 'foo' }), /invalid syslog facility/)
assert.throws(() => createClient('udp://h', { format: 'foo' }), /invalid syslog format/)
assert.throws(() => createClient('udp://h', { framing: 'foo' }), /invalid syslog framing/)
})
it('exposes the facility and severity names', () => {
assert(FACILITIES.includes('authpriv'))
assert.equal(SEVERITIES[4], 'warning')
})
})
describe('send()', () => {
it('formats RFC 5424 messages', async () => {
const server = await createUdpServer()
const client = createClient(` udp://127.0.0.1:${server.port} `, {
appName: 'my app',
facility: 'authpriv',
hostname: 'host',
})
await client.send('{"foo":"bar"}', {
msgid: 'some event',
severity: 'warning',
timestamp: new Date('2026-01-02T03:04:05.678Z'),
})
await wait(50)
client.close()
// header fields are sanitized: no spaces
assert.deepEqual(server.messages, [
`<84>1 2026-01-02T03:04:05.678Z host my_app ${process.pid} some_event - {"foo":"bar"}`,
])
})
it('formats RFC 3164 messages', async () => {
const server = await createUdpServer()
const client = createClient(`udp://127.0.0.1:${server.port}`, {
appName: 'app',
format: 'rfc3164',
hostname: 'host',
})
await client.send('message', { timestamp: new Date(2026, 0, 2, 3, 4, 5) })
await wait(50)
client.close()
assert.deepEqual(server.messages, [`<14>Jan 2 03:04:05 host app[${process.pid}]: message`])
})
it('rejects an invalid severity', async () => {
await assert.rejects(
createClient('udp://127.0.0.1').send('message', { severity: 'foo' }),
/invalid syslog severity/
)
})
it('frames TCP messages with a line feed by default', async () => {
const server = await createStreamServer()
const client = createClient(`tcp://127.0.0.1:${server.port}`)
await client.send('foo')
await client.send('bar')
await wait(50)
client.close()
assert.match(server.data, /^<14>1 [^\n]+ - foo\n<14>1 [^\n]+ - bar\n$/)
})
it('escapes the line breaks of a message framed with a line feed', async () => {
const server = await createStreamServer()
const client = createClient(`tcp://127.0.0.1:${server.port}`)
await client.send('foo\r\nbar\nbaz')
await wait(50)
client.close()
assert.match(server.data, /^<14>1 [^\n]+ - foo\\r\\nbar\\nbaz\n$/)
})
it('frames TCP messages with octet counting', async () => {
const server = await createStreamServer()
const client = createClient(`tcp://127.0.0.1:${server.port}`, { framing: 'octet-counting' })
await client.send('foo')
await client.send('b\när')
await wait(50)
client.close()
// each message is prefixed by its length in bytes
const buffer = Buffer.from(server.data)
const messages = []
for (let offset = 0; offset < buffer.length; ) {
const space = buffer.indexOf(' ', offset)
const length = Number(buffer.toString('utf8', offset, space))
messages.push(buffer.toString('utf8', space + 1, space + 1 + length))
offset = space + 1 + length
}
assert.equal(messages.length, 2)
assert.match(messages[0], /^<14>1 .+ - foo$/)
assert.match(messages[1], /^<14>1 .+ - b\när$/s)
})
it('reconnects when the server closes the connection', async () => {
const server = await createStreamServer()
const client = createClient(`tcp://127.0.0.1:${server.port}`)
await client.send('first')
await wait(50)
server.sockets.forEach(socket => socket.destroy())
await wait(50)
await client.send('second')
await wait(50)
client.close()
assert.match(server.data, /first\n.*second\n$/s)
})
it('reports why the connection failed', async () => {
await assert.rejects(createClient('tcp://127.0.0.1:1').send('message'), { code: 'ECONNREFUSED' })
// several addresses (::1 and 127.0.0.1) fail with an AggregateError, which has no message by itself
await assert.rejects(createClient('tcp://localhost:1').send('message'), error => {
assert.match(error.message, /ECONNREFUSED/)
assert(error.stack.startsWith(`${error.name}: ${error.message}\n`))
return true
})
})
it('stops connecting after connectTimeout, with a single socket', async () => {
// accepts the TCP connection but never answers the TLS handshake
const port = await listen(net.createServer(socket => socket.resume()))
const client = createClient(`tls://127.0.0.1:${port}`, { connectTimeout: 200 })
const sockets = new Set()
const start = Date.now()
const result = client.send('message').catch(error => error)
sockets.add(client._socket)
client.send('message').catch(Function.prototype)
sockets.add(client._socket)
assert.equal((await result).message, 'connection timed out')
assert(Date.now() - start < 1e3)
assert.equal(sockets.size, 1)
})
it('drops messages when too much is waiting to be sent', async () => {
// never reads
const port = await listen(net.createServer(socket => socket.pause()))
const client = createClient(`tcp://127.0.0.1:${port}`, { closeTimeout: 200, maxPendingBytes: 64 * 1024 })
const message = 'x'.repeat(1024)
const results = []
for (let i = 0; i < 10e3; ++i) {
results.push(
client.send(message).then(
() => 'sent',
() => 'dropped'
)
)
}
await wait(500)
client.close()
assert(client._socket === undefined)
assert((await Promise.all(results)).includes('dropped'))
})
it('delivers the messages of a connection which is being established, then closes it', async () => {
const server = await createStreamServer()
const client = createClient(`tcp://127.0.0.1:${server.port}`)
const sent = client.send('message')
const socket = client._socket
client.close()
await sent
await new Promise(resolve => (socket.closed ? resolve() : socket.once('close', resolve)))
assert.match(server.data, /message\n$/)
assert(socket.destroyed)
assert.equal(client._socket, undefined)
})
it('delivers the datagrams whose host name is being resolved, then closes the socket', async () => {
const server = await createUdpServer()
const client = createClient(`udp://localhost:${server.port}`)
const sent = client.send('message')
client.close()
await sent
await wait(100)
assert.equal(server.messages.length, 1)
assert.match(server.messages[0], /message$/)
})
it('stops waiting for the pending writes after closeTimeout', async () => {
// never reads
const port = await listen(net.createServer(socket => socket.pause()))
const client = createClient(`tcp://127.0.0.1:${port}`, { closeTimeout: 200, maxPendingBytes: Infinity })
const results = []
for (let i = 0; i < 1e3; ++i) {
results.push(client.send('x'.repeat(64 * 1024)).then(Function.prototype, error => error))
}
const socket = client._socket
client.close()
const start = Date.now()
await Promise.all(results)
assert(Date.now() - start < 2e3)
assert(socket.destroyed)
})
})
describe('TLS', () => {
const createTlsServer = () =>
createStreamServer(listener =>
tls.createServer({ cert: fixture('server.pem'), key: fixture('server.key') }, listener)
)
it('trusts additional certificate authorities', async () => {
const server = await createTlsServer()
const client = createClient(`tls://localhost:${server.port}`, { ca: [CA] })
await client.send('message')
await wait(50)
client.close()
assert.match(server.data, / - message\n$/)
})
it('rejects an unknown certificate authority, unless allowUnauthorized', async () => {
const server = await createTlsServer()
await assert.rejects(createClient(`tls://localhost:${server.port}`).send('message'), {
code: 'UNABLE_TO_VERIFY_LEAF_SIGNATURE',
})
const client = createClient(`tls://localhost:${server.port}`, { allowUnauthorized: true })
await client.send('message')
client.close()
})
it('defaults to port 6514', () => {
assert.equal(createClient('tls://localhost')._port, 6514)
assert.equal(createClient('tcp://[::1]')._port, 514)
assert.equal(createClient('tcp://[::1]')._host, '::1')
})
})

View File

@@ -0,0 +1,33 @@
{
"private": false,
"name": "@vates/syslog",
"description": "Syslog client: RFC 5424 messages over UDP, TCP or TLS, with a bounded buffer",
"keywords": [
"rfc5424",
"syslog",
"tls"
],
"homepage": "https://github.com/vatesfr/xen-orchestra/tree/master/@vates/syslog",
"bugs": "https://github.com/vatesfr/xen-orchestra/issues",
"repository": {
"directory": "@vates/syslog",
"type": "git",
"url": "https://github.com/vatesfr/xen-orchestra.git"
},
"author": {
"name": "Vates SAS",
"url": "https://vates.fr"
},
"license": "ISC",
"version": "0.1.0",
"engines": {
"node": ">=18"
},
"dependencies": {
"split-host": "^2.0.0"
},
"scripts": {
"postversion": "npm publish --access public",
"test": "node --test"
}
}

View File

@@ -0,0 +1,19 @@
-----BEGIN CERTIFICATE-----
MIIDITCCAgmgAwIBAgIUGikUHbKIfotmlkV7oGy7YubSDn8wDQYJKoZIhvcNAQEL
BQAwHzEdMBsGA1UEAwwUdmF0ZXMtc3lzbG9nIHRlc3QgQ0EwIBcNMjYxMDE4MTAx
MjI1WhgPMjEyNjA5MjQxMDEyMjVaMB8xHTAbBgNVBAMMFHZhdGVzLXN5c2xvZyB0
ZXN0IENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAn/lGtdLEE8tf
gb+hSPe8xLOlGh7ZzRiGcKjkcCbCNFNnjjOa29Lki8ksFD7Su2BWIHpxAzPhEnlQ
9xq7+M9dayM2CslQPuOfKEEyQIBWG9OggXT3kyTn0BVHNFfiGzJlyRz6fIfLf/sU
e2d9AWZhP9I53HpKaNMHyxwuzEBWFxmpv1t7LRVwhrcQjsnoZqxlukpsGyKkT4gs
TNH5/hFhZzmnvfFPhTzQvOGSvFQqgUgd5uxidDmImoRoGA9Ip3bqwMkT99euNrgc
jsxnXeV8pdtHmz4kjQRp+/YIIoh7pA73389OeBx7LC9wpZo1z+3AVKlCAGZ8V9Il
Izk3e7FXTQIDAQABo1MwUTAdBgNVHQ4EFgQUTx7dqoC2XIwpwW0MYcZsoXHqztww
HwYDVR0jBBgwFoAUTx7dqoC2XIwpwW0MYcZsoXHqztwwDwYDVR0TAQH/BAUwAwEB
/zANBgkqhkiG9w0BAQsFAAOCAQEARYUd0q9VwgmZGdhhqks1xCipBuW1eWwBa0jk
Y0jZjhxeq9F0KBMVoazRjjKoL6cwpjvUKytarnN8+kj/7U4dMPLX+/bcpEjwo1gW
DI7MtBI+e1+IohWujDtCqyAiPYpWlwlTTC4kMdfjDH4fbYNY6UHUnedPdSwN3HAp
ZtMb1RoT+gtMedpbnQJKTwxAwH5cBMjTgKeuxeHo6WWjB6evyaLjQINNGLDgLxUC
i4+o0rNYCPtJV3uqw9egDkgoAtMI9mY6snMUxaHGz2JhGzT1wu/UXPrkbFYxCYpm
BGxY36taw81Mr+6n0V1ScWhnGEgPOe3BJCYtoB964YDYfvcFLA==
-----END CERTIFICATE-----

View File

@@ -0,0 +1,28 @@
-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCL0wuMNV3AkIhP
gt4eQ9IPbOkbZiyNOgQWanaRr1P5XeEz4wbWH03MNf9gUDbR2ToGJLfxU68upFYo
uQRCRHRySdbzvhc5+OYbQ2/QvucGKaMnYuerxvENgnh2eLg5QG+Z50M8+IK+jK4t
YJjECe5nefjdtGKQf1h4xgVJp2CQW2zKyfOBqjgcB6bOISDni9+1ssWDkcgVnqyB
8o/zA11CFfO1AL0OBbpD6Fk9HZ29hODCQLOq01vIrfpV2H8S/hsik4tUtMgM10y5
7LNckDzd8LbZQiBUJ/Q63pWDN19SqAW9lsonE3aKJANvew2s/NRtU7EKIeKLvf3a
HPJH83QBAgMBAAECggEABrXXOphrTlj1XL0A5kqOkchSF9s3gUPW80Ey3Wcg2GFo
s9f18ZfdIMM45T02Q0wJtoajuAKCUFKJUsEd1uUQglVgOjB9zn2/I9DwxF+sCEn+
Yy8SQ5Z7pjCEMdnVbAR3UqdUTRBXXHgVihaWIEbifM9wCcpM1mbRJvMoaO5uIkFZ
ztlYElhFC+ITpm8Pjs/fQPNlA8DPZO3xHRSx+M0+tNw3ba7SaFvYTA2o/sMOx1Yq
pyWf7yq6kPDE3vO6NfO8uYrfkw/eNioQ3jZh9tlH/87hm1ucXFOHKxdCpabv2COJ
YIOqIcXlRbXlzVugDY6IOdBcCvUM6DdB+iyOx2m6UQKBgQDEyHoCCJZhLf7ynsmu
onmonWGojX6EwDgpvoey2Lhbr9j7gkCkx7TF+CNRN4AM4o+K9x+m8rF2aJEXKgof
GNwYPpBaUwuV2y+A9wiYtM+o9D4pTy2JPzlfyj7zWIQtOzrIkgSz9BH7QYRA51it
L0d9O6myUs2IILcXdb7gTePA0QKBgQC15qgJ4DeDq+VygQi1VW6Xn2DhiAy1frDY
etG3We+PIKYOc9XN79hI7cSXAy9DYwX7KTQJ13YDYDKNuEEGlijatxMruJv2Zvdm
5CfgNzw+QjFfOM0AXsp9/F4xiiSiUAvLJeZzN7BVPQ/7KUz6kMxtr8RorP66NSFt
zplrq6XMMQKBgQCP+EyraDT9bHV2dI4B4oU3w81LUBocbbWpdOg7BSv8iK8rc6Rv
6lxr6puMNBrPUoLKnPrfXfhQNTjRxcQZ9EoywrNCIjf7r50Vsabscnzrk6ZW+sLK
AyOq3YEo8L3jic38KDigoBT3yntEMP5D1q9rBFenS8VrruPFmjPIT7QtwQKBgQCd
To/bmo/nyuxujbBeQTeW4DoEUIfNHXcKf4yFp71IZc+1h+9KXTUKPLVac2KYQDaX
8hYSvMZOPQ77CHETpSBHpTNrCAe4m2sxC/aALMRogw33b0O6Ij+znGBJL1JnHBpW
4LvewDY6QMhlSF5OApMH+I0+iPzxQ6lZMOX0+0gywQKBgEGcCeJBvqpnSOyMdOFu
MIcLhGa2SIttij1jz7eS9zD+VeONHjmn3Atn7MRagddrYeIGy6ZHUFFsSWBbVqwB
cfT6o0GOeNx0gQn185SUBxB3Oxfg4xWBA0q0GVNFqaScKiXk1IvTj/GTuXM7rehi
HjK6iamDr8lIJE/JFdn2K8ge
-----END PRIVATE KEY-----

View File

@@ -0,0 +1,20 @@
-----BEGIN CERTIFICATE-----
MIIDMzCCAhugAwIBAgIUSGpRtJFiD61hQZBOp49sq7GLkIswDQYJKoZIhvcNAQEL
BQAwHzEdMBsGA1UEAwwUdmF0ZXMtc3lzbG9nIHRlc3QgQ0EwIBcNMjYxMDE4MTAx
MjI1WhgPMjEyNjA5MjQxMDEyMjVaMBQxEjAQBgNVBAMMCWxvY2FsaG9zdDCCASIw
DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBAIvTC4w1XcCQiE+C3h5D0g9s6Rtm
LI06BBZqdpGvU/ld4TPjBtYfTcw1/2BQNtHZOgYkt/FTry6kVii5BEJEdHJJ1vO+
Fzn45htDb9C+5wYpoydi56vG8Q2CeHZ4uDlAb5nnQzz4gr6Mri1gmMQJ7md5+N20
YpB/WHjGBUmnYJBbbMrJ84GqOBwHps4hIOeL37WyxYORyBWerIHyj/MDXUIV87UA
vQ4FukPoWT0dnb2E4MJAs6rTW8it+lXYfxL+GyKTi1S0yAzXTLnss1yQPN3wttlC
IFQn9DrelYM3X1KoBb2WyicTdookA297Daz81G1TsQoh4ou9/doc8kfzdAECAwEA
AaNwMG4wLAYDVR0RBCUwI4IJbG9jYWxob3N0hwR/AAABhxAAAAAAAAAAAAAAAAAA
AAABMB0GA1UdDgQWBBTCMy+a1aPNwrF3QYPIAIR4iDazWTAfBgNVHSMEGDAWgBRP
Ht2qgLZcjCnBbQxhxmyhcerO3DANBgkqhkiG9w0BAQsFAAOCAQEAPWBHmtiuPwFb
z0DIdTOA7VvFziMyJzW0EvI2AmB2wSViPGg5OFqVOLq5+H3OJsi5yTYJaUjNpr4A
UjpMweJJlMkqwsTt/kBKpPiUQbiN7Ja2+b3mmmMhEfyMUSebcfegLNvglABhJlmv
FOwniX8J1LJ8fzxAHfF32HwqxG6vxcZOsP661WqSnkyDSuoHo/jwB4MeCZiljc8h
F4MkcaIGouTtAGMvb8V6bGNz1iWgkQVpfYP9uqKGq8eBXzd+/033RmrnqorHjYiz
38C1Gf3lhbXBQqmMY3+aEhvjSCJrLCfjMV/twDTwRp8khrkG7C9yuEqmXtbTcF1e
/+rsiTEv9A==
-----END CERTIFICATE-----

View File

@@ -7,6 +7,7 @@ import type {
XapiXoRecord,
XoAuthenticationToken,
XoBackupRepository,
XoBrowserMediaSession,
XoConfigBackupArchive,
XoGroup,
XoHost,
@@ -22,6 +23,7 @@ import type {
XoSr,
XoTask,
XoUser,
XoVdi,
XoVif,
XoVm,
XoVmBackupArchive,
@@ -435,6 +437,23 @@ export type XoApp = EventEmitter & {
>
>
getAllSchedules(): Promise<XoSchedule[]>
/** Every browser media session, whoever owns it; empty when the feature is disabled */
getAllBrowserMediaSessions(): XoBrowserMediaSession[]
getBrowserMediaSession(id: XoBrowserMediaSession['id']): XoBrowserMediaSession
/**
* Insert the ISO of a browser media session in the CD drive of a VM. Undone by `ejectBrowserMedia`,
* or when the browser disconnects.
*
* `assertBrowserMediaInsertable` reports the predictable failures synchronously, e.g. before
* starting a task.
*/
insertBrowserMedia(params: {
id: XoBrowserMediaSession['id']
vmId: XoVm['id']
}): Promise<{ vdiId: XoVdi['id'] }>
assertBrowserMediaInsertable(params: { id: XoBrowserMediaSession['id']; vmId: XoVm['id'] }): void
/** Eject the ISO of a browser media session, release its storage, and disconnect the browser */
ejectBrowserMedia(id: XoBrowserMediaSession['id']): Promise<void>
getAllUsers(opts?: { obfuscatePassword?: boolean }): Promise<XoUser[]>
getAllXenServers(): Promise<XoServer[]>
getAuthenticationTokensForUser(userId: XoUser['id']): Promise<XoAuthenticationToken[]>

View File

@@ -52,6 +52,12 @@ type BaseXapiXo = {
*/
$poolId: XoPool['id']
/**
* Only present while the pool is disconnected: the object is kept but may be
* outdated, this is the last time (in milliseconds) the pool was reached
*/
$lastSeen?: number
_xapiRef: string
uuid: string
@@ -515,6 +521,68 @@ export type XoPlugin =
| XoUsageReportPlugin
| XoWebHooksPlugin
/**
* An ISO selected in a browser and streamed from it, which can be inserted in the CD drive of a VM
* while the browser stays connected
*/
export type XoBrowserMediaSession = {
id: Branded<'browser-media'>
/** File name of the ISO, as selected in the browser */
name: string
/** Size of the ISO, in bytes */
size: number
/** User whose browser serves the ISO */
userId: XoUser['id']
/** Timestamp of the browser connection */
createdAt: number
/** Total of the bytes read from the browser */
bytesRead: number
/** Timestamp of the last read from the browser */
lastReadAt?: number
} & (
| {
/** Not inserted in any VM */
status: 'connected'
vmId?: undefined
vdiId?: undefined
insertedAt?: undefined
/** Why the last insertion failed */
error?: string
}
| {
/** Being inserted in a VM */
status: 'inserting'
/** VM the ISO is being inserted in */
vmId: XoVm['id']
vdiId?: undefined
insertedAt?: undefined
error?: undefined
}
| {
/** Inserted in the CD drive of a VM */
status: 'inserted'
/** VM the ISO is inserted in */
vmId: XoVm['id']
/** VDI inserted in the CD drive of the VM */
vdiId: XoVdi['id']
/** Timestamp of the end of the insertion */
insertedAt: number
error?: undefined
}
| {
/** Being ejected, or a failed insertion being undone */
status: 'ejecting'
/** VM the ISO is ejected from */
vmId: XoVm['id']
/** VDI inserted in the CD drive of the VM, unless the insertion failed before */
vdiId?: XoVdi['id']
/** Timestamp of the end of the insertion, unless it failed */
insertedAt?: number
/** Why the insertion failed */
error?: string
}
)
export type XoProxy = {
id: Branded<'proxy'>
url: string
@@ -763,6 +831,7 @@ export type XoTask = {
| 'backup-job'
| 'backup-log'
| 'backup-repository'
| 'browser-media'
| 'group'
| 'plugin'
| 'proxy'
@@ -979,6 +1048,7 @@ export type NonXapiXoRecord =
| AnyXoJob
| AnyXoLog
| XoAuthenticationToken
| XoBrowserMediaSession
| XoGroup
| XoPlugin
| XoProxy

View File

@@ -1,6 +1,11 @@
export default {
read: true,
update: {
dns: true,
gateway: true,
ip: true,
management: true,
mode: true,
netmask: true,
},
}

View File

@@ -2,6 +2,7 @@
## **next**
- [VM/Host] Main actions (shutdown, reboot, start, resume, migrate, snapshot) are shown as buttons in the VM and host headers and move one by one into "More actions" when space runs out; "More actions" groups them under "Change state" and "Actions" sections, and VMs without guest tools get force shutdown and force reboot instead (PR [#10815](https://github.com/vatesfr/xen-orchestra/pull/10815))
- [Web-Core/UiButtonIcon] Update icon buttons design, with a counter replacing the notification dot (PR [#10799](https://github.com/vatesfr/xen-orchestra/pull/10799))
- [Mobile/Side panels] Full-page menus on mobile with "Change state" in "More actions", side panel actions shown as buttons when there is room, and fixes for long names in headers and menu placement (PR [#10745](https://github.com/vatesfr/xen-orchestra/pull/10745))
- [Side panels] Side panels can be resized like the treeview, whose default width now adapts to the screen size (PR [#10725](https://github.com/vatesfr/xen-orchestra/pull/10725))
@@ -9,6 +10,7 @@
- [Treeview] Fix translations of the tooltip for VM and host statuses in treeview (PR [#10643](https://github.com/vatesfr/xen-orchestra/pull/10643))
- [Web-Core/UiDropdownButton] Update dropdown buttons design (PR [#9850](https://github.com/vatesfr/xen-orchestra/pull/9850))
- [Tables] Tables are filtered as you type, half a second after the last keystroke, or right away with Enter; the "Search" button is removed (PR [#10797](https://github.com/vatesfr/xen-orchestra/pull/10797))
- [Side panels] Fix the double scrollbar when the side panel content is taller than the screen: the page header now stays in place, and the list and the side panel each scroll on their own. All scrollbars are now thin, like the side panel one (PR [#10807](https://github.com/vatesfr/xen-orchestra/pull/10807))
## **0.27.0** (2026-10-29)

View File

@@ -94,6 +94,8 @@ useUnreachableHosts()
.main {
flex: 1;
overflow: auto;
display: flex;
flex-direction: column;
background-color: var(--color-neutral-background-secondary);
}
</style>

View File

@@ -14,29 +14,20 @@
<VtsIcon v-tooltip="t('master')" name="status:primary-circle" size="medium" />
</template>
<template #actions>
<VtsChangeStateMenu v-if="!uiStore.isSmall">
<HostPowerStateActions :host />
</VtsChangeStateMenu>
<VtsActionsMenu :label="t('more-actions')" size="medium">
<HostMoreActions :host :show-change-state="uiStore.isSmall" />
</VtsActionsMenu>
<HostHeaderActions :host />
</template>
</UiHeadBar>
</template>
<script lang="ts" setup>
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import HostPowerStateActions from '@/modules/host/components/actions/HostPowerStateActions.vue'
import HostMoreActions from '@/modules/host/components/HostMoreActions.vue'
import HostHeaderActions from '@/modules/host/components/actions/HostHeaderActions.vue'
import { useHostUtils } from '@/modules/host/composables/host-utils.composable.ts'
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
import VtsIcon from '@core/components/icon/VtsIcon.vue'
import VtsActionsMenu from '@core/components/menu/VtsActionsMenu.vue'
import VtsChangeStateMenu from '@core/components/menu/VtsChangeStateMenu.vue'
import VtsObjectIcon from '@core/components/object-icon/VtsObjectIcon.vue'
import UiHeadBar from '@core/components/ui/head-bar/UiHeadBar.vue'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import { useUiStore } from '@core/stores/ui.store.ts'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
@@ -46,8 +37,6 @@ const { host } = defineProps<{
const { t } = useI18n()
const uiStore = useUiStore()
const { isMasterHost } = usePoolStore().subscribe()
const isMaster = computed(() => isMasterHost(host.$ref))

View File

@@ -1,18 +1,15 @@
<template>
<MenuItem
v-tooltip="
selectedRefs.length > 0 &&
!isMigratable &&
t(isSingleAction ? 'this-vm-cant-be-migrated' : 'no-selected-vm-can-be-migrated')
"
accent="neutral"
<VtsActionButton
variant="tertiary"
accent="brand"
:busy="isMigrating"
:disabled="isDisabled"
icon="fa:route"
:hint="disabledReason"
@click="openMigrateModal()"
>
{{ t('action:migrate') }}
</MenuItem>
</VtsActionButton>
</template>
<script lang="ts" setup>
@@ -21,16 +18,15 @@ import { areSomeVmOperationAllowed, isVmOperationPending } from '@/libs/vm.ts'
import { VM_OPERATION } from '@/libs/xen-api/xen-api.enums.ts'
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
import MenuItem from '@core/components/menu/MenuItem.vue'
import VtsActionButton from '@core/components/action-button/VtsActionButton.vue'
import { useDisabled } from '@core/composables/disabled.composable.ts'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import { KEEP_OVERLAY_OPEN } from '@core/packages/overlay/symbols.ts'
import { useOverlay } from '@core/packages/overlay/use-overlay.ts'
import { reactiveComputed } from '@vueuse/core'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { selectedRefs } = defineProps<{
const { selectedRefs, isSingleAction } = defineProps<{
selectedRefs: XenApiVm['$ref'][]
isSingleAction?: boolean
}>()
@@ -53,6 +49,12 @@ const isMigrating = computed(() =>
const isDisabled = useDisabled(() => !isMigratable.value)
const disabledReason = computed(() =>
selectedRefs.length > 0 && !isMigratable.value
? t(isSingleAction ? 'this-vm-cant-be-migrated' : 'no-selected-vm-can-be-migrated')
: undefined
)
const { selectedHost, availableHosts, isValid, migrate } = useVmMigration(() => selectedRefs)
const { open: openModal } = useOverlay({

View File

@@ -1,14 +1,6 @@
<template>
<MenuItem
accent="neutral"
:busy="areVmsBusyToStart"
:disabled="!areVmsHalted"
icon="fa:play"
@click="xenApi.vm.start(vmRefs)"
>
{{ t('action:start') }}
</MenuItem>
<MenuItem accent="neutral" :busy="areVmsBusyToStartOnHost" :disabled="!areVmsHalted" icon="object:host">
<VmPowerStateActionButton v-if="!exclude.start" :action="actions.start" />
<MenuItem accent="neutral" :busy="isStartingOnHost" :disabled="!areVmsHalted" icon="object:host">
{{ t('action:start-on-host') }}
<template #submenu>
<MenuItem
@@ -28,120 +20,52 @@
</MenuItem>
</template>
</MenuItem>
<MenuItem
accent="neutral"
:busy="areVmsBusyToPause"
:disabled="!areVmsRunning"
icon="fa:pause"
@click="xenApi.vm.pause(vmRefs)"
>
{{ t('pause') }}
</MenuItem>
<MenuItem
accent="neutral"
:busy="areVmsBusyToSuspend"
:disabled="!areVmsRunning"
icon="fa:moon"
@click="xenApi.vm.suspend(vmRefs)"
>
{{ t('action:suspend') }}
</MenuItem>
<MenuItem
accent="neutral"
:busy="areVmsBusyToResume"
:disabled="!areVmsSuspended && !areVmsPaused"
icon="fa:play"
@click="xenApi.vm.resume(vmRefsWithPowerState)"
>
{{ t('action:resume') }}
</MenuItem>
<MenuItem
accent="neutral"
:busy="areVmsBusyToReboot"
:disabled="!areVmsRunning"
icon="action:reboot"
@click="xenApi.vm.reboot(vmRefs)"
>
{{ t('action:reboot') }}
</MenuItem>
<MenuItem
accent="neutral"
:busy="areVmsBusyToForceReboot"
:disabled="!areVmsRunning && !areVmsPaused"
icon="action:force-reboot"
@click="xenApi.vm.reboot(vmRefs, true)"
>
{{ t('action:force-reboot') }}
</MenuItem>
<MenuItem
accent="neutral"
:busy="areVmsBusyToShutdown"
:disabled="!areVmsRunning"
icon="action:shutdown"
@click="xenApi.vm.shutdown(vmRefs)"
>
{{ t('action:shutdown') }}
</MenuItem>
<MenuItem
accent="neutral"
:busy="areVmsBusyToForceShutdown"
:disabled="!areVmsRunning && !areVmsSuspended && !areVmsPaused"
icon="action:force-shutdown"
@click="xenApi.vm.shutdown(vmRefs, true)"
>
{{ t('action:force-shutdown') }}
</MenuItem>
<VmPowerStateActionButton v-for="action in menuActions" :key="action" :action="actions[action]" />
</template>
<script lang="ts" setup>
import PowerStateIcon from '@/components/PowerStateIcon.vue'
import { isVmOperationPending } from '@/libs/vm.ts'
import { VM_OPERATION, VM_POWER_STATE } from '@/libs/xen-api/xen-api.enums.ts'
import { VM_POWER_STATE } from '@/libs/xen-api/xen-api.enums.ts'
import type { XenApiHost, XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import VmPowerStateActionButton from '@/modules/vm/components/actions/VmPowerStateActionButton.vue'
import { useVmPowerStateActions } from '@/modules/vm/composables/vm-power-state-actions.composable.ts'
import type { VmPowerStateAction } from '@/modules/vm/utils/vm.util.ts'
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
import { useHostStore } from '@/stores/xen-api/host.store.ts'
import { usePoolStore } from '@/stores/xen-api/pool.store.ts'
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
import { useXenApiStore } from '@/stores/xen-api.store.ts'
import VtsIcon from '@core/components/icon/VtsIcon.vue'
import MenuItem from '@core/components/menu/MenuItem.vue'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const props = defineProps<{
const { vmRefs, exclude = {} } = defineProps<{
vmRefs: XenApiVm['$ref'][]
exclude?: Partial<Record<VmPowerStateAction, boolean>>
}>()
const { t } = useI18n()
const { getByOpaqueRef: getVm } = useVmStore().subscribe()
const { records: hosts } = useHostStore().subscribe()
const { pool } = usePoolStore().subscribe()
const { isHostRunning } = useHostMetricsStore().subscribe()
const vms = computed(() => props.vmRefs.map(getVm).filter((vm): vm is XenApiVm => vm !== undefined))
const vmRefsWithPowerState = computed(() => vms.value.reduce((acc, vm) => ({ ...acc, [vm.$ref]: vm.power_state }), {}))
const xenApi = useXenApiStore().getXapi()
const areVmsRunning = computed(() => vms.value.every(vm => vm.power_state === VM_POWER_STATE.RUNNING))
const areVmsHalted = computed(() => vms.value.every(vm => vm.power_state === VM_POWER_STATE.HALTED))
const areVmsSuspended = computed(() => vms.value.every(vm => vm.power_state === VM_POWER_STATE.SUSPENDED))
const areVmsPaused = computed(() => vms.value.every(vm => vm.power_state === VM_POWER_STATE.PAUSED))
const MENU_ACTIONS: VmPowerStateAction[] = [
'pause',
'suspend',
'resume',
'reboot',
'force-reboot',
'shutdown',
'force-shutdown',
]
const areOperationsPending = (operation: VM_OPERATION | VM_OPERATION[]) =>
vms.value.some(vm => isVmOperationPending(vm, operation))
const { actions, areVmsHalted, isStartingOnHost } = useVmPowerStateActions(() => vmRefs)
const menuActions = computed(() => MENU_ACTIONS.filter(action => !exclude[action]))
const areVmsBusyToStart = computed(() => areOperationsPending(VM_OPERATION.START))
const areVmsBusyToStartOnHost = computed(() => areOperationsPending(VM_OPERATION.START_ON))
const areVmsBusyToPause = computed(() => areOperationsPending(VM_OPERATION.PAUSE))
const areVmsBusyToSuspend = computed(() => areOperationsPending(VM_OPERATION.SUSPEND))
const areVmsBusyToResume = computed(() => areOperationsPending([VM_OPERATION.UNPAUSE, VM_OPERATION.RESUME]))
const areVmsBusyToReboot = computed(() => areOperationsPending(VM_OPERATION.CLEAN_REBOOT))
const areVmsBusyToForceReboot = computed(() => areOperationsPending(VM_OPERATION.HARD_REBOOT))
const areVmsBusyToShutdown = computed(() => areOperationsPending(VM_OPERATION.CLEAN_SHUTDOWN))
const areVmsBusyToForceShutdown = computed(() => areOperationsPending(VM_OPERATION.HARD_SHUTDOWN))
const getHostState = (host: XenApiHost) => (isHostRunning(host) ? VM_POWER_STATE.RUNNING : VM_POWER_STATE.HALTED)
</script>

View File

@@ -1,13 +1,14 @@
<template>
<MenuItem
accent="neutral"
<VtsActionButton
variant="tertiary"
accent="brand"
:busy="areSomeVmsSnapshotting"
:disabled="isDisabled"
icon="fa:camera"
@click="handleSnapshot"
@click="handleSnapshot()"
>
{{ t('snapshot') }}
</MenuItem>
</VtsActionButton>
</template>
<script lang="ts" setup>
@@ -16,7 +17,7 @@ import { VM_OPERATION } from '@/libs/xen-api/xen-api.enums.ts'
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
import { useXenApiStore } from '@/stores/xen-api.store.ts'
import MenuItem from '@core/components/menu/MenuItem.vue'
import VtsActionButton from '@core/components/action-button/VtsActionButton.vue'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'

View File

@@ -11,46 +11,22 @@
/>
</template>
<template #actions>
<VtsChangeStateMenu v-if="vm !== undefined && !uiStore.isSmall" placement="bottom-start">
<VmActionPowerStateItems :vm-refs="[vm.$ref]" />
</VtsChangeStateMenu>
<VtsActionsMenu v-if="vm !== undefined" :label="t('more-actions')" size="medium">
<VtsChangeStateMenuItem v-if="uiStore.isSmall">
<VmActionPowerStateItems :vm-refs="[vm.$ref]" />
</VtsChangeStateMenuItem>
<VmActionCopyItem :selected-refs="[vm.$ref]" is-single-action />
<VmActionExportItem :vm-refs="[vm.$ref]" is-single-action />
<VmActionSnapshotItem :vm-refs="[vm.$ref]" />
<VmActionMigrateItem :selected-refs="[vm.$ref]" is-single-action />
</VtsActionsMenu>
<VmHeaderActions v-if="vm !== undefined" :vm />
</template>
</UiHeadBar>
</template>
<script lang="ts" setup>
import VmActionCopyItem from '@/components/vm/VmActionItems/VmActionCopyItem.vue'
import VmActionExportItem from '@/components/vm/VmActionItems/VmActionExportItem.vue'
import VmActionMigrateItem from '@/components/vm/VmActionItems/VmActionMigrateItem.vue'
import VmActionPowerStateItems from '@/components/vm/VmActionItems/VmActionPowerStateItems.vue'
import VmActionSnapshotItem from '@/components/vm/VmActionItems/VmActionSnapshotItem.vue'
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import VmHeaderActions from '@/modules/vm/components/actions/VmHeaderActions.vue'
import { useVmOperation } from '@/modules/vm/composables/vm-operation.composable.ts'
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
import VtsActionsMenu from '@core/components/menu/VtsActionsMenu.vue'
import VtsChangeStateMenu from '@core/components/menu/VtsChangeStateMenu.vue'
import VtsChangeStateMenuItem from '@core/components/menu/VtsChangeStateMenuItem.vue'
import VtsObjectIcon from '@core/components/object-icon/VtsObjectIcon.vue'
import UiHeadBar from '@core/components/ui/head-bar/UiHeadBar.vue'
import { useUiStore } from '@core/stores/ui.store.ts'
import { toLower } from 'lodash-es'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
import { useRoute } from 'vue-router'
const { t } = useI18n()
const uiStore = useUiStore()
const { getByUuid: getVmByUuid } = useVmStore().subscribe()
const route = useRoute<'/vm/[uuid]'>()

View File

@@ -1,5 +1,13 @@
<template>
<VtsChangeStateMenuItem v-if="showChangeState">
<template v-if="layout === 'sections'">
<HostPowerStateActions :host :exclude>
<template #title>
<VtsMenuTitle>{{ t('action:change-state') }}</VtsMenuTitle>
</template>
</HostPowerStateActions>
<VtsMenuTitle>{{ t('actions') }}</VtsMenuTitle>
</template>
<VtsChangeStateMenuItem v-else-if="layout === 'change-state-submenu'">
<HostPowerStateActions :host />
</VtsChangeStateMenuItem>
<HostRestartToolstackButton :host />
@@ -7,7 +15,7 @@
<HostEnableButton v-else :host />
<HostDetachButton :host />
<HostForgetButton :host />
<VtsDivider type="stretch" />
<VtsDivider v-if="layout !== 'sections'" type="stretch" />
<HostDownloadButton :host-opaque-ref="host.$ref" />
</template>
@@ -20,17 +28,27 @@ import HostEnableButton from '@/modules/host/components/actions/enable/HostEnabl
import HostForgetButton from '@/modules/host/components/actions/forget/HostForgetButton.vue'
import HostPowerStateActions from '@/modules/host/components/actions/HostPowerStateActions.vue'
import HostRestartToolstackButton from '@/modules/host/components/actions/restart-toolstack/HostRestartToolstackButton.vue'
import type { HostQuickAction } from '@/modules/host/composables/host-quick-actions.composable.ts'
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
import VtsDivider from '@core/components/divider/VtsDivider.vue'
import VtsChangeStateMenuItem from '@core/components/menu/VtsChangeStateMenuItem.vue'
import VtsMenuTitle from '@core/components/menu/VtsMenuTitle.vue'
import { HOST_POWER_STATE } from '@vates/types'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { host } = defineProps<{
const {
host,
layout = 'actions-only',
exclude = {},
} = defineProps<{
host: XenApiHost
showChangeState?: boolean
layout?: 'actions-only' | 'change-state-submenu' | 'sections'
exclude?: Partial<Record<HostQuickAction, boolean>>
}>()
const { t } = useI18n()
const { getHostPowerState } = useHostMetricsStore().subscribe()
const isHostHalted = computed(() => getHostPowerState(host) === HOST_POWER_STATE.HALTED)

View File

@@ -0,0 +1,30 @@
<template>
<VtsHeadBarActions v-slot="{ isInline }" :actions="quickActions">
<HostStartButton v-if="isInline.start" :host />
<HostShutdownButton v-if="isInline.shutdown" :host />
<HostRebootButton v-if="isInline.reboot" :host />
<VtsActionsMenu :label="t('more-actions')" size="medium" no-section-title>
<HostMoreActions :host layout="sections" :exclude="isInline" />
</VtsActionsMenu>
</VtsHeadBarActions>
</template>
<script lang="ts" setup>
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import HostRebootButton from '@/modules/host/components/actions/reboot/HostRebootButton.vue'
import HostShutdownButton from '@/modules/host/components/actions/shutdown/HostShutdownButton.vue'
import HostStartButton from '@/modules/host/components/actions/start/HostStartButton.vue'
import HostMoreActions from '@/modules/host/components/HostMoreActions.vue'
import { useHostQuickActions } from '@/modules/host/composables/host-quick-actions.composable.ts'
import VtsHeadBarActions from '@core/components/head-bar/VtsHeadBarActions.vue'
import VtsActionsMenu from '@core/components/menu/VtsActionsMenu.vue'
import { useI18n } from 'vue-i18n'
const { host } = defineProps<{
host: XenApiHost
}>()
const { t } = useI18n()
const quickActions = useHostQuickActions(() => host)
</script>

View File

@@ -1,10 +1,13 @@
<template>
<template v-if="isHostRunning">
<HostRebootButton :host />
<HostForceRebootButton :host />
<HostShutdownButton :host />
<template v-if="hasActions">
<slot name="title" />
<template v-if="isHostRunning">
<HostRebootButton v-if="!exclude.reboot" :host />
<HostForceRebootButton :host />
<HostShutdownButton v-if="!exclude.shutdown" :host />
</template>
<HostStartButton v-else :host />
</template>
<HostStartButton v-else :host />
</template>
<script lang="ts" setup>
@@ -13,12 +16,22 @@ import HostForceRebootButton from '@/modules/host/components/actions/reboot/Host
import HostRebootButton from '@/modules/host/components/actions/reboot/HostRebootButton.vue'
import HostShutdownButton from '@/modules/host/components/actions/shutdown/HostShutdownButton.vue'
import HostStartButton from '@/modules/host/components/actions/start/HostStartButton.vue'
import type { HostQuickAction } from '@/modules/host/composables/host-quick-actions.composable.ts'
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
import { computed } from 'vue'
const { host } = defineProps<{ host: XenApiHost }>()
const { host, exclude = {} } = defineProps<{
host: XenApiHost
exclude?: Partial<Record<HostQuickAction, boolean>>
}>()
defineSlots<{
title?(): any
}>()
const { isHostRunning: isHostRunningStore } = useHostMetricsStore().subscribe()
const isHostRunning = computed(() => isHostRunningStore(host))
const hasActions = computed(() => isHostRunning.value || !exclude.start)
</script>

View File

@@ -1,22 +1,22 @@
<template>
<MenuItem
v-tooltip="!canRebootHost && rebootHostErrorMessage"
accent="neutral"
<VtsActionButton
variant="tertiary"
accent="brand"
:busy="isRebootingHost"
:disabled="!canRebootHost"
icon="action:reboot"
:hint="rebootHostErrorMessage"
@click="rebootHost()"
>
{{ t('action:reboot') }}
</MenuItem>
</VtsActionButton>
</template>
<script lang="ts" setup>
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import { useHostRebootJob } from '@/modules/host/jobs/host-reboot.job.ts'
import MenuItem from '@core/components/menu/MenuItem.vue'
import VtsActionButton from '@core/components/action-button/VtsActionButton.vue'
import { useActionModal } from '@core/composables/modals/use-action-modal.ts'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import { useI18n } from 'vue-i18n'
const { host } = defineProps<{

View File

@@ -1,22 +1,22 @@
<template>
<MenuItem
v-tooltip="!canShutdownHost && shutdownHostErrorMessage"
accent="neutral"
<VtsActionButton
variant="tertiary"
accent="brand"
:busy="isShuttingDownHost"
:disabled="!canShutdownHost"
icon="action:shutdown"
:hint="shutdownHostErrorMessage"
@click="shutdownHost()"
>
{{ t('action:shutdown') }}
</MenuItem>
</VtsActionButton>
</template>
<script lang="ts" setup>
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import { useHostShutdownJob } from '@/modules/host/jobs/host-shutdown.job.ts'
import MenuItem from '@core/components/menu/MenuItem.vue'
import VtsActionButton from '@core/components/action-button/VtsActionButton.vue'
import { useActionModal } from '@core/composables/modals/use-action-modal.ts'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import { useI18n } from 'vue-i18n'
const { host } = defineProps<{

View File

@@ -1,22 +1,22 @@
<template>
<MenuItem
v-tooltip="!canStartHost && startHostErrorMessage"
accent="neutral"
<VtsActionButton
variant="tertiary"
accent="brand"
:busy="isStartingHost"
:disabled="!canStartHost"
icon="fa:play"
:hint="startHostErrorMessage"
@click="startHost()"
>
{{ t('action:start') }}
</MenuItem>
</VtsActionButton>
</template>
<script lang="ts" setup>
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import { useHostStartJob } from '@/modules/host/jobs/host-start.job.ts'
import MenuItem from '@core/components/menu/MenuItem.vue'
import VtsActionButton from '@core/components/action-button/VtsActionButton.vue'
import { useActionModal } from '@core/composables/modals/use-action-modal.ts'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import { useI18n } from 'vue-i18n'
const { host } = defineProps<{

View File

@@ -96,7 +96,7 @@ function getMasterIcon(host: XenApiHost) {
}
const { HeadCells, BodyCells } = useHostColumns({
exclude: ['checkbox', 'srStatus'],
exclude: ['checkbox', 'srStatus', 'actions'],
body: (host: XenApiHost) => {
const ipAddresses = computed(() => getHostIpAddresses(host.address, pifsByHost.value.get(host.$ref)))
const hostIcon = computed(() => getHostIcon(host, getHostPowerState(host)))

View File

@@ -0,0 +1,11 @@
import type { XenApiHost } from '@/libs/xen-api/xen-api.types.ts'
import { useHostMetricsStore } from '@/stores/xen-api/host-metrics.store.ts'
import { computed, type MaybeRefOrGetter, toValue } from 'vue'
export type HostQuickAction = 'start' | 'shutdown' | 'reboot'
export function useHostQuickActions(host: MaybeRefOrGetter<XenApiHost>) {
const { isHostRunning } = useHostMetricsStore().subscribe()
return computed((): HostQuickAction[] => (isHostRunning(toValue(host)) ? ['shutdown', 'reboot'] : ['start']))
}

View File

@@ -7,7 +7,7 @@
<div class="row">
<div class="column">
<NetworkFormTextInput v-bind="nameInputBindings" />
<NetworkFormNumberInput v-bind="mtuInputBindings" />
<VtsNumberInput v-bind="mtuInputBindings" />
</div>
<NewNetworkDescriptionTextarea v-bind="descriptionInputBindings" />
</div>
@@ -18,7 +18,6 @@
</template>
<script lang="ts" setup>
import NetworkFormNumberInput from '@/modules/network/components/form/new/inputs/NetworkFormNumberInput.vue'
import NetworkFormSelect from '@/modules/network/components/form/new/inputs/NetworkFormSelect.vue'
import NetworkFormTextInput from '@/modules/network/components/form/new/inputs/NetworkFormTextInput.vue'
import NewNetworkDescriptionTextarea from '@/modules/network/components/form/new/inputs/NewNetworkDescriptionTextarea.vue'
@@ -27,6 +26,7 @@ import NewNetworkButtonsSection from '@/modules/network/components/form/new/NewN
import { useNewBondedNetworkForm } from '@/modules/network/form/new-bonded/use-new-bonded-network-form.ts'
import type { NewBondedNetworkPayload } from '@/modules/network/jobs/bonded-network-create.job.ts'
import VtsForm from '@core/components/form/VtsForm.vue'
import VtsNumberInput from '@core/components/number-input/VtsNumberInput.vue'
import { useI18n } from 'vue-i18n'
import type { RouteLocationRaw } from 'vue-router'

View File

@@ -4,7 +4,7 @@
<div class="row">
<div class="column">
<NetworkFormTextInput v-bind="nameInputBindings" />
<NetworkFormNumberInput v-bind="mtuInputBindings" />
<VtsNumberInput v-bind="mtuInputBindings" />
</div>
<NewNetworkDescriptionTextarea v-bind="descriptionInputBindings" />
</div>
@@ -16,13 +16,13 @@
</template>
<script setup lang="ts">
import NetworkFormNumberInput from '@/modules/network/components/form/new/inputs/NetworkFormNumberInput.vue'
import NetworkFormTextInput from '@/modules/network/components/form/new/inputs/NetworkFormTextInput.vue'
import NewNetworkDescriptionTextarea from '@/modules/network/components/form/new/inputs/NewNetworkDescriptionTextarea.vue'
import NewNetworkNbdRadio from '@/modules/network/components/form/new/inputs/NewNetworkNbdRadio.vue'
import NewNetworkButtonsSection from '@/modules/network/components/form/new/NewNetworkButtonsSection.vue'
import { useNewInternalNetworkForm } from '@/modules/network/form/new-internal/use-new-internal-network-form.ts'
import type { NewInternalNetworkPayload } from '@/modules/network/jobs/internal-network-create.job.ts'
import VtsNumberInput from '@core/components/number-input/VtsNumberInput.vue'
import { useI18n } from 'vue-i18n'
import type { RouteLocationRaw } from 'vue-router'

View File

@@ -7,18 +7,17 @@
<div class="row">
<div class="column">
<NetworkFormTextInput v-bind="nameInputBindings" />
<NetworkFormNumberInput v-bind="mtuInputBindings" />
<VtsNumberInput v-bind="mtuInputBindings" />
</div>
<NewNetworkDescriptionTextarea v-bind="descriptionInputBindings" />
</div>
<NetworkFormNumberInput v-bind="vlanInputBindings" class="vlan" />
<VtsNumberInput v-bind="vlanInputBindings" class="vlan" />
<NewNetworkNbdRadio class="nbd" v-bind="nbdRadioBindings" />
<NewNetworkButtonsSection :cancel-to :submit-label="t('action:create-network')" />
</VtsForm>
</template>
<script lang="ts" setup>
import NetworkFormNumberInput from '@/modules/network/components/form/new/inputs/NetworkFormNumberInput.vue'
import NetworkFormSelect from '@/modules/network/components/form/new/inputs/NetworkFormSelect.vue'
import NetworkFormTextInput from '@/modules/network/components/form/new/inputs/NetworkFormTextInput.vue'
import NewNetworkDescriptionTextarea from '@/modules/network/components/form/new/inputs/NewNetworkDescriptionTextarea.vue'
@@ -27,6 +26,7 @@ import NewNetworkButtonsSection from '@/modules/network/components/form/new/NewN
import { useNewNetworkForm } from '@/modules/network/form/new/use-new-network-form.ts'
import type { NewNetworkPayload } from '@/modules/network/jobs/network-create.job.ts'
import VtsForm from '@core/components/form/VtsForm.vue'
import VtsNumberInput from '@core/components/number-input/VtsNumberInput.vue'
import { useI18n } from 'vue-i18n'
import type { RouteLocationRaw } from 'vue-router'

View File

@@ -1,27 +0,0 @@
<template>
<VtsInputWrapper :label :message="messages">
<UiInput v-model.number="model" accent="brand" type="number" :required @blur="emit('blur')" />
</VtsInputWrapper>
</template>
<script lang="ts" setup>
import type { InputWrapperMessage } from '@core/components/input-wrapper/VtsInputWrapper.vue'
import VtsInputWrapper from '@core/components/input-wrapper/VtsInputWrapper.vue'
import UiInput from '@core/components/ui/input/UiInput.vue'
import { computed } from 'vue'
const { info, warning, error } = defineProps<{
label: string
error?: InputWrapperMessage
warning?: InputWrapperMessage
info?: string
required?: boolean
}>()
const emit = defineEmits<{ blur: [] }>()
const model = defineModel<number | undefined>()
const messages = computed<InputWrapperMessage>(
() => [info, warning, error].filter(message => message !== undefined) as InputWrapperMessage
)
</script>

View File

@@ -20,7 +20,7 @@
variant="secondary"
/>
<VtsActionsMenu placement="bottom-start">
<HostMoreActions :host="branch.data" show-change-state />
<HostMoreActions :host="branch.data" layout="change-state-submenu" />
</VtsActionsMenu>
</template>
</UiTreeItemLabel>

View File

@@ -7,6 +7,7 @@
<script lang="ts" setup>
import VtsInputWrapper, { type InputWrapperMessage } from '@core/components/input-wrapper/VtsInputWrapper.vue'
import UiInput from '@core/components/ui/input/UiInput.vue'
import { mergeInputWrapperMessages } from '@core/utils/input-wrapper-message.util.ts'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
@@ -20,7 +21,5 @@ const model = defineModel<string>({ required: true })
const { t } = useI18n()
const messages = computed<InputWrapperMessage>(
() => [info, error].filter(message => message !== undefined) as InputWrapperMessage
)
const messages = computed(() => mergeInputWrapperMessages(info, error))
</script>

View File

@@ -0,0 +1,55 @@
<template>
<VtsHeadBarActions v-slot="{ isInline }" :actions="quickActions">
<VmPowerStateActionButton v-if="isInline.start" :action="powerStateActions.start" />
<VmPowerStateActionButton v-if="isInline.resume" :action="powerStateActions.resume" />
<VmPowerStateActionButton v-if="isInline.shutdown" :action="powerStateActions.shutdown" />
<VmPowerStateActionButton v-if="isInline['force-shutdown']" :action="powerStateActions['force-shutdown']" />
<VmPowerStateActionButton v-if="isInline.reboot" :action="powerStateActions.reboot" />
<VmPowerStateActionButton v-if="isInline['force-reboot']" :action="powerStateActions['force-reboot']" />
<VmActionMigrateItem v-if="isInline.migrate" :selected-refs="vmRefs" is-single-action />
<VmActionSnapshotItem v-if="isInline.snapshot" :vm-refs />
<VtsActionsMenu :label="t('more-actions')" size="medium" no-section-title>
<VtsMenuTitle>{{ t('action:change-state') }}</VtsMenuTitle>
<VmActionPowerStateItems :vm-refs :exclude="isInline" />
<VtsMenuTitle>{{ t('actions') }}</VtsMenuTitle>
<VmActionMigrateItem v-if="!isInline.migrate" :selected-refs="vmRefs" is-single-action />
<VmActionSnapshotItem v-if="!isInline.snapshot" :vm-refs />
<VmActionCopyItem :selected-refs="vmRefs" is-single-action />
<VmActionExportItem :vm-refs is-single-action />
</VtsActionsMenu>
</VtsHeadBarActions>
</template>
<script lang="ts" setup>
import VmActionCopyItem from '@/components/vm/VmActionItems/VmActionCopyItem.vue'
import VmActionExportItem from '@/components/vm/VmActionItems/VmActionExportItem.vue'
import VmActionMigrateItem from '@/components/vm/VmActionItems/VmActionMigrateItem.vue'
import VmActionPowerStateItems from '@/components/vm/VmActionItems/VmActionPowerStateItems.vue'
import VmActionSnapshotItem from '@/components/vm/VmActionItems/VmActionSnapshotItem.vue'
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import VmPowerStateActionButton from '@/modules/vm/components/actions/VmPowerStateActionButton.vue'
import { useVmPowerStateActions } from '@/modules/vm/composables/vm-power-state-actions.composable.ts'
import { areVmToolsDetected, getVmQuickActions } from '@/modules/vm/utils/vm.util.ts'
import { useVmGuestMetricsStore } from '@/stores/xen-api/vm-guest-metrics.store.ts'
import VtsHeadBarActions from '@core/components/head-bar/VtsHeadBarActions.vue'
import VtsActionsMenu from '@core/components/menu/VtsActionsMenu.vue'
import VtsMenuTitle from '@core/components/menu/VtsMenuTitle.vue'
import { computed } from 'vue'
import { useI18n } from 'vue-i18n'
const { vm } = defineProps<{
vm: XenApiVm
}>()
const { t } = useI18n()
const vmRefs = computed(() => [vm.$ref])
const { getByOpaqueRef: getGuestMetrics } = useVmGuestMetricsStore().subscribe()
const areToolsDetected = computed(() => areVmToolsDetected(getGuestMetrics(vm.guest_metrics)))
const quickActions = computed(() => getVmQuickActions(vm, areToolsDetected.value))
const { actions: powerStateActions } = useVmPowerStateActions(vmRefs)
</script>

View File

@@ -0,0 +1,21 @@
<template>
<VtsActionButton
variant="tertiary"
accent="brand"
:icon="action.icon"
:busy="action.busy"
:disabled="action.disabled"
@click="action.run()"
>
{{ action.label }}
</VtsActionButton>
</template>
<script lang="ts" setup>
import type { VmPowerStateActionDefinition } from '@/modules/vm/composables/vm-power-state-actions.composable.ts'
import VtsActionButton from '@core/components/action-button/VtsActionButton.vue'
defineProps<{
action: VmPowerStateActionDefinition
}>()
</script>

View File

@@ -0,0 +1,108 @@
import { isVmOperationPending } from '@/libs/vm.ts'
import { VM_OPERATION, VM_POWER_STATE } from '@/libs/xen-api/xen-api.enums.ts'
import type { XenApiVm } from '@/libs/xen-api/xen-api.types.ts'
import type { VmPowerStateAction } from '@/modules/vm/utils/vm.util.ts'
import { useVmStore } from '@/stores/xen-api/vm.store.ts'
import { useXenApiStore } from '@/stores/xen-api.store.ts'
import type { IconName } from '@core/icons'
import { computed, type MaybeRefOrGetter, toValue } from 'vue'
import { useI18n } from 'vue-i18n'
export type VmPowerStateActionDefinition = {
label: string
icon: IconName
busy: boolean
disabled: boolean
run: () => unknown
}
export function useVmPowerStateActions(rawVmRefs: MaybeRefOrGetter<XenApiVm['$ref'][]>) {
const { t } = useI18n()
const { getByOpaqueRef: getVm } = useVmStore().subscribe()
const xenApi = useXenApiStore().getXapi()
const vmRefs = computed(() => toValue(rawVmRefs))
const vms = computed(() => vmRefs.value.map(getVm).filter((vm): vm is XenApiVm => vm !== undefined))
const vmRefsWithPowerState = computed(() =>
vms.value.reduce((acc, vm) => ({ ...acc, [vm.$ref]: vm.power_state }), {})
)
const areVmsInState = (powerState: VM_POWER_STATE) => vms.value.every(vm => vm.power_state === powerState)
const areOperationsPending = (operation: VM_OPERATION | VM_OPERATION[]) =>
vms.value.some(vm => isVmOperationPending(vm, operation))
const areVmsRunning = computed(() => areVmsInState(VM_POWER_STATE.RUNNING))
const areVmsHalted = computed(() => areVmsInState(VM_POWER_STATE.HALTED))
const areVmsSuspended = computed(() => areVmsInState(VM_POWER_STATE.SUSPENDED))
const areVmsPaused = computed(() => areVmsInState(VM_POWER_STATE.PAUSED))
const isStartingOnHost = computed(() => areOperationsPending(VM_OPERATION.START_ON))
const actions = computed(
(): Record<VmPowerStateAction, VmPowerStateActionDefinition> => ({
start: {
label: t('action:start'),
icon: 'fa:play',
busy: areOperationsPending(VM_OPERATION.START),
disabled: !areVmsHalted.value,
run: () => xenApi.vm.start(vmRefs.value),
},
pause: {
label: t('pause'),
icon: 'fa:pause',
busy: areOperationsPending(VM_OPERATION.PAUSE),
disabled: !areVmsRunning.value,
run: () => xenApi.vm.pause(vmRefs.value),
},
suspend: {
label: t('action:suspend'),
icon: 'fa:moon',
busy: areOperationsPending(VM_OPERATION.SUSPEND),
disabled: !areVmsRunning.value,
run: () => xenApi.vm.suspend(vmRefs.value),
},
resume: {
label: t('action:resume'),
icon: 'fa:play',
busy: areOperationsPending([VM_OPERATION.UNPAUSE, VM_OPERATION.RESUME]),
disabled: !areVmsSuspended.value && !areVmsPaused.value,
run: () => xenApi.vm.resume(vmRefsWithPowerState.value),
},
reboot: {
label: t('action:reboot'),
icon: 'action:reboot',
busy: areOperationsPending(VM_OPERATION.CLEAN_REBOOT),
disabled: !areVmsRunning.value,
run: () => xenApi.vm.reboot(vmRefs.value),
},
'force-reboot': {
label: t('action:force-reboot'),
icon: 'action:force-reboot',
busy: areOperationsPending(VM_OPERATION.HARD_REBOOT),
disabled: !areVmsRunning.value && !areVmsPaused.value,
run: () => xenApi.vm.reboot(vmRefs.value, true),
},
shutdown: {
label: t('action:shutdown'),
icon: 'action:shutdown',
busy: areOperationsPending(VM_OPERATION.CLEAN_SHUTDOWN),
disabled: !areVmsRunning.value,
run: () => xenApi.vm.shutdown(vmRefs.value),
},
'force-shutdown': {
label: t('action:force-shutdown'),
icon: 'action:force-shutdown',
busy: areOperationsPending(VM_OPERATION.HARD_SHUTDOWN),
disabled: !areVmsRunning.value && !areVmsSuspended.value && !areVmsPaused.value,
run: () => xenApi.vm.shutdown(vmRefs.value, true),
},
})
)
return { actions, areVmsHalted, isStartingOnHost }
}

View File

@@ -1,5 +1,5 @@
import { VM_OPERATION } from '@/libs/xen-api/xen-api.enums.ts'
import type { XenApiVmGuestMetrics } from '@/libs/xen-api/xen-api.types.ts'
import { VM_OPERATION, VM_POWER_STATE } from '@/libs/xen-api/xen-api.enums.ts'
import type { XenApiVm, XenApiVmGuestMetrics } from '@/libs/xen-api/xen-api.types.ts'
export const CHANGING_STATE_OPERATIONS: VM_OPERATION[] = [
VM_OPERATION.START,
@@ -42,3 +42,33 @@ export function areVmToolsDetected(guestMetrics: XenApiVmGuestMetrics | undefine
return managementAgentDetected && pvDriversDetected
}
export type VmPowerStateAction =
| 'start'
| 'pause'
| 'suspend'
| 'resume'
| 'reboot'
| 'force-reboot'
| 'shutdown'
| 'force-shutdown'
type VmPowerStateQuickAction = Exclude<VmPowerStateAction, 'pause' | 'suspend'>
export type VmQuickAction = VmPowerStateQuickAction | 'migrate' | 'snapshot'
function getVmPowerStateQuickActions(vm: XenApiVm, areToolsDetected: boolean): VmPowerStateQuickAction[] {
switch (vm.power_state) {
case VM_POWER_STATE.RUNNING:
return areToolsDetected ? ['shutdown', 'reboot'] : ['force-shutdown', 'force-reboot']
case VM_POWER_STATE.HALTED:
return ['start']
case VM_POWER_STATE.PAUSED:
case VM_POWER_STATE.SUSPENDED:
return ['resume']
}
}
export function getVmQuickActions(vm: XenApiVm, areToolsDetected: boolean): VmQuickAction[] {
return [...getVmPowerStateQuickActions(vm, areToolsDetected), 'migrate', 'snapshot']
}

View File

@@ -7,7 +7,9 @@
</template>
</HostPifsTable>
</UiCard>
<HostPifSidePanel :pif="selectedPif" @close="selectedPif = undefined" />
<template #panel>
<HostPifSidePanel :pif="selectedPif" @close="selectedPif = undefined" />
</template>
</VtsContentSidePanel>
</template>

View File

@@ -3,13 +3,15 @@
<UiCard class="container">
<StorageRepositoriesTable v-if="pool && host && scope" :srs :pool :scope :busy="!isReady" :error="hasError" />
</UiCard>
<StorageRepositorySidePanel
v-if="pool && host && scope"
:sr="selectedSr"
:pool
:scope
@close="selectedSr = undefined"
/>
<template #panel>
<StorageRepositorySidePanel
v-if="pool && host && scope"
:sr="selectedSr"
:pool
:scope
@close="selectedSr = undefined"
/>
</template>
</VtsContentSidePanel>
</template>

View File

@@ -1,10 +1,7 @@
<template>
<div class="pool-root-view">
<PoolHeader />
<PoolTabBar />
<RouterView />
</div>
<PoolHeader />
<PoolTabBar />
<RouterView />
</template>
<script lang="ts" setup>

View File

@@ -3,7 +3,9 @@
<UiCard class="container">
<HostsTable :hosts :busy="!isReady" :error="hasError" />
</UiCard>
<HostSidePanel :host="selectedHost" @close="selectedHost = undefined" />
<template #panel>
<HostSidePanel :host="selectedHost" @close="selectedHost = undefined" />
</template>
</VtsContentSidePanel>
</template>

View File

@@ -28,7 +28,9 @@
</template>
</PoolHostInternalNetworksTable>
</UiCard>
<PoolNetworkSidePanel :network="selectedNetwork" @close="selectedNetwork = undefined" />
<template #panel>
<PoolNetworkSidePanel :network="selectedNetwork" @close="selectedNetwork = undefined" />
</template>
</VtsContentSidePanel>
</template>

View File

@@ -3,7 +3,9 @@
<UiCard class="container">
<StorageRepositoriesTable v-if="pool" :srs="sortedSrs" :pool :scope :busy="!isReady" :error="hasError" />
</UiCard>
<StorageRepositorySidePanel v-if="pool" :sr="selectedSr" :pool :scope @close="selectedSr = undefined" />
<template #panel>
<StorageRepositorySidePanel v-if="pool" :sr="selectedSr" :pool :scope @close="selectedSr = undefined" />
</template>
</VtsContentSidePanel>
</template>

View File

@@ -9,7 +9,9 @@
</template>
</VifsTable>
</UiCard>
<VifSidePanel :vif="selectedVif" @close="selectedVif = undefined" />
<template #panel>
<VifSidePanel :vif="selectedVif" @close="selectedVif = undefined" />
</template>
</VtsContentSidePanel>
</template>

View File

@@ -3,7 +3,9 @@
<UiCard class="container">
<VdisTable v-if="vm" :vdis :vbds />
</UiCard>
<VdiSidePanel :vdi="selectedVdi" :vbd="selectedVbd" @close="selectedVdi = undefined" />
<template #panel>
<VdiSidePanel :vdi="selectedVdi" :vbd="selectedVbd" @close="selectedVdi = undefined" />
</template>
</VtsContentSidePanel>
</template>

View File

@@ -394,6 +394,20 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/head-bar/vts-head-bar-actions': RouteRecordInfo<
'/story/web-core/head-bar/vts-head-bar-actions',
'/story/web-core/head-bar/vts-head-bar-actions',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/inline-parts/vts-inline-parts': RouteRecordInfo<
'/story/web-core/inline-parts/vts-inline-parts',
'/story/web-core/inline-parts/vts-inline-parts',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/input-wrapper/vts-input-wrapper': RouteRecordInfo<
'/story/web-core/input-wrapper/vts-input-wrapper',
'/story/web-core/input-wrapper/vts-input-wrapper',
@@ -457,6 +471,13 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/menu/vts-menu-title': RouteRecordInfo<
'/story/web-core/menu/vts-menu-title',
'/story/web-core/menu/vts-menu-title',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/menu/vts-mobile-menu': RouteRecordInfo<
'/story/web-core/menu/vts-mobile-menu',
'/story/web-core/menu/vts-mobile-menu',
@@ -471,6 +492,13 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/number-input/vts-number-input': RouteRecordInfo<
'/story/web-core/number-input/vts-number-input',
'/story/web-core/number-input/vts-number-input',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/object-icon/vts-object-icon': RouteRecordInfo<
'/story/web-core/object-icon/vts-object-icon',
'/story/web-core/object-icon/vts-object-icon',
@@ -506,6 +534,13 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/panel/vts-side-panel': RouteRecordInfo<
'/story/web-core/panel/vts-side-panel',
'/story/web-core/panel/vts-side-panel',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/resources/vts-resource': RouteRecordInfo<
'/story/web-core/resources/vts-resource',
'/story/web-core/resources/vts-resource',
@@ -548,6 +583,13 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/success-state-hero/vts-success-state-hero': RouteRecordInfo<
'/story/web-core/success-state-hero/vts-success-state-hero',
'/story/web-core/success-state-hero/vts-success-state-hero',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/tab/router-tab': RouteRecordInfo<
'/story/web-core/tab/router-tab',
'/story/web-core/tab/router-tab',
@@ -576,6 +618,13 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/tags-input/vts-tags-input': RouteRecordInfo<
'/story/web-core/tags-input/vts-tags-input',
'/story/web-core/tags-input/vts-tags-input',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/tree/vts-tree-item': RouteRecordInfo<
'/story/web-core/tree/vts-tree-item',
'/story/web-core/tree/vts-tree-item',
@@ -898,6 +947,13 @@ declare module 'vue-router/auto-routes' {
Record<never, never>,
| never
>,
'/story/web-core/ui/numbered-stepper/ui-numbered-stepper': RouteRecordInfo<
'/story/web-core/ui/numbered-stepper/ui-numbered-stepper',
'/story/web-core/ui/numbered-stepper/ui-numbered-stepper',
Record<never, never>,
Record<never, never>,
| never
>,
'/story/web-core/ui/object-link/ui-object-link': RouteRecordInfo<
'/story/web-core/ui/object-link/ui-object-link',
'/story/web-core/ui/object-link/ui-object-link',
@@ -1521,6 +1577,18 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/stories/web-core/head-bar/vts-head-bar-actions.story.vue': {
routes:
| '/story/web-core/head-bar/vts-head-bar-actions'
views:
| never
}
'src/stories/web-core/inline-parts/vts-inline-parts.story.vue': {
routes:
| '/story/web-core/inline-parts/vts-inline-parts'
views:
| never
}
'src/stories/web-core/input-wrapper/vts-input-wrapper.story.vue': {
routes:
| '/story/web-core/input-wrapper/vts-input-wrapper'
@@ -1575,6 +1643,12 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/stories/web-core/menu/vts-menu-title.story.vue': {
routes:
| '/story/web-core/menu/vts-menu-title'
views:
| never
}
'src/stories/web-core/menu/vts-mobile-menu.story.vue': {
routes:
| '/story/web-core/menu/vts-mobile-menu'
@@ -1587,6 +1661,12 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/stories/web-core/number-input/vts-number-input.story.vue': {
routes:
| '/story/web-core/number-input/vts-number-input'
views:
| never
}
'src/stories/web-core/object-icon/vts-object-icon.story.vue': {
routes:
| '/story/web-core/object-icon/vts-object-icon'
@@ -1617,6 +1697,12 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/stories/web-core/panel/vts-side-panel.story.vue': {
routes:
| '/story/web-core/panel/vts-side-panel'
views:
| never
}
'src/stories/web-core/resources/vts-resource.story.vue': {
routes:
| '/story/web-core/resources/vts-resource'
@@ -1653,6 +1739,12 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/stories/web-core/success-state-hero/vts-success-state-hero.story.vue': {
routes:
| '/story/web-core/success-state-hero/vts-success-state-hero'
views:
| never
}
'src/stories/web-core/tab/router-tab.story.vue': {
routes:
| '/story/web-core/tab/router-tab'
@@ -1677,6 +1769,12 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/stories/web-core/tags-input/vts-tags-input.story.vue': {
routes:
| '/story/web-core/tags-input/vts-tags-input'
views:
| never
}
'src/stories/web-core/tree/vts-tree-item.story.vue': {
routes:
| '/story/web-core/tree/vts-tree-item'
@@ -1953,6 +2051,12 @@ declare module 'vue-router/auto-routes' {
views:
| never
}
'src/stories/web-core/ui/numbered-stepper/ui-numbered-stepper.story.vue': {
routes:
| '/story/web-core/ui/numbered-stepper/ui-numbered-stepper'
views:
| never
}
'src/stories/web-core/ui/object-link/ui-object-link.story.vue': {
routes:
| '/story/web-core/ui/object-link/ui-object-link'

View File

@@ -11,7 +11,7 @@
prop('accent').type('ButtonAccent').enum('brand', 'warning', 'danger').preset('brand').required().widget(),
iconProp().preset('action:connect'),
prop('disabled').bool().widget(),
prop('busy').bool().widget(),
prop('busy').bool().widget().help('In a VtsHeadBarActions, the button is disabled without showing a loader'),
prop('hint').str().preset('Already connected').widget().help('Shown when disabled'),
event('click'),
slot(),

View File

@@ -0,0 +1,52 @@
<template>
<ComponentStory
v-slot="{ properties }"
:params="[
prop('actions').arr('string').required().widget().preset(actions).help('Actions shown in the head bar, in order'),
slot()
.prop('isInline', 'Partial<Record<TAction, boolean>>')
.help(
'Receives which actions fit in the head bar, the others are meant to go in a menu. VtsActionButton components rendered as buttons hide their loader and stay disabled while busy'
),
]"
>
<UiHeadBar>
VM name with a long label
<template #actions>
<VtsHeadBarActions v-slot="{ isInline }" v-bind="properties">
<template v-for="action in properties.actions" :key="action">
<VtsActionButton v-if="isInline[action]" variant="tertiary" accent="brand" :icon="ICONS[action]">
{{ action }}
</VtsActionButton>
</template>
<VtsActionsMenu label="More actions" size="medium" no-section-title>
<template v-for="action in properties.actions" :key="action">
<VtsActionButton v-if="!isInline[action]" variant="tertiary" accent="brand" :icon="ICONS[action]">
{{ action }}
</VtsActionButton>
</template>
</VtsActionsMenu>
</VtsHeadBarActions>
</template>
</UiHeadBar>
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { prop, slot } from '@/libs/story/story-param.ts'
import type { IconName } from '@core/icons'
import VtsActionButton from '@core/components/action-button/VtsActionButton.vue'
import VtsHeadBarActions from '@core/components/head-bar/VtsHeadBarActions.vue'
import VtsActionsMenu from '@core/components/menu/VtsActionsMenu.vue'
import UiHeadBar from '@core/components/ui/head-bar/UiHeadBar.vue'
const actions = ['Shutdown', 'Reboot', 'Migrate', 'Snapshot']
const ICONS: Record<string, IconName> = {
Shutdown: 'action:shutdown',
Reboot: 'action:reboot',
Migrate: 'action:migrate',
Snapshot: 'action:snapshot',
}
</script>

View File

@@ -0,0 +1,26 @@
<template>
<ComponentStory
v-slot="{ properties }"
:params="[
prop('separator')
.required()
.enum('bullet', 'chevron')
.preset('bullet')
.widget()
.help('Bullets join facts, chevrons a location from the widest place to the narrowest'),
slot().help('The parts, separated by the separator; a part hidden by v-if leaves no stray separator'),
]"
>
<VtsInlineParts v-bind="properties">
<span>vcenter.lab</span>
<span>DC-Paris</span>
<span>esx01</span>
</VtsInlineParts>
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { prop, slot } from '@/libs/story/story-param.ts'
import VtsInlineParts from '@core/components/inline-parts/VtsInlineParts.vue'
</script>

View File

@@ -0,0 +1,21 @@
<template>
<ComponentStory
v-slot="{ settings }"
:params="[slot().help('Title of the section'), setting('title').preset('Change state').widget(text())]"
>
<MenuList>
<VtsMenuTitle>{{ settings.title }}</VtsMenuTitle>
<MenuItem accent="neutral" icon="fa:play">Start</MenuItem>
<MenuItem accent="neutral" icon="action:reboot">Reboot</MenuItem>
</MenuList>
</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 MenuItem from '@core/components/menu/MenuItem.vue'
import MenuList from '@core/components/menu/MenuList.vue'
import VtsMenuTitle from '@core/components/menu/VtsMenuTitle.vue'
</script>

View File

@@ -0,0 +1,8 @@
# Usage
A number field with its label and its info, warning and error messages, ready for the field bindings of a validated
form. A cleared input gives an empty value, not `0`.
```vue-template
<VtsNumberInput v-model="quantity" label="Quantity" info="Between 1 and 8" />
```

View File

@@ -0,0 +1,23 @@
<template>
<ComponentStory
v-slot="{ properties }"
:params="[
model().type('number | undefined').preset(2),
prop('label').str().required().preset('Quantity').widget(),
prop('info').str().widget(),
prop('warning').type('InputWrapperMessage').widget(object()),
prop('error').type('InputWrapperMessage').widget(object()),
prop('required').bool().widget(),
event('blur'),
]"
>
<VtsNumberInput v-bind="properties" />
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { event, model, prop } from '@/libs/story/story-param.ts'
import { object } from '@/libs/story/story-widget.ts'
import VtsNumberInput from '@core/components/number-input/VtsNumberInput.vue'
</script>

View File

@@ -0,0 +1,62 @@
<template>
<ComponentStory
v-slot="{ properties }"
full-width-component
:params="[
prop('hasSelection')
.bool()
.widget()
.preset(true)
.help('Opens / closes the panel with the selection where it is not pinned (and on small screens)'),
prop('persistent')
.bool()
.widget()
.preset(false)
.help(
'For a panel that always has something to show: renders its content even without a selection, and shows the close button only where closing collapses it (small screen, or not pinned)'
),
event('close').args({}).help('Emitted when the user clicks the close button'),
slot().help('The panel content, replaced by the no-selection state hero without a selection unless persistent'),
slot('actions').help('For the main action buttons'),
slot('more-actions').help('For other action buttons, shown in a dropdown menu'),
slot('corner-actions').help('For action icon buttons, next to the pin button'),
]"
>
<div class="layout">
<UiButton
v-if="!panelStore.isExpanded"
accent="brand"
variant="secondary"
size="medium"
@click="panelStore.expand()"
>
Expand panel
</UiButton>
<VtsSidePanel v-bind="properties">
<UiPanelCard>
<div>Card Content</div>
</UiPanelCard>
</VtsSidePanel>
</div>
</ComponentStory>
</template>
<script setup lang="ts">
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { event, prop, slot } from '@/libs/story/story-param.ts'
import VtsSidePanel from '@core/components/panel/VtsSidePanel.vue'
import UiButton from '@core/components/ui/button/UiButton.vue'
import UiPanelCard from '@core/components/ui/panel-card/UiPanelCard.vue'
import { usePanelStore } from '@core/stores/panel.store.ts'
const panelStore = usePanelStore()
</script>
<style scoped lang="postcss">
.layout {
display: flex;
justify-content: space-between;
align-items: start;
gap: 1.6rem;
}
</style>

View File

@@ -0,0 +1,13 @@
# Usage
The card telling an action succeeded: an optional title, the success alert, then the actions that follow, centred.
```vue-template
<VtsSuccessStateHero>
<template #title>Connected to 192.168.1.1</template>
The pool is connected.
<template #actions>
<UiLink :to="poolRoute" size="medium">Visit the pool dashboard</UiLink>
</template>
</VtsSuccessStateHero>
```

View File

@@ -0,0 +1,27 @@
<template>
<ComponentStory
v-slot="{ settings }"
:params="[
slot('title').help('Optional, shown above the alert'),
slot().help('The text of the success alert'),
slot('actions').help('The links and buttons that follow the success, centred'),
setting('titleSlot').preset('Connected to 192.168.1.1').widget(),
setting('defaultSlot').preset('The pool is connected.').widget(),
]"
>
<VtsSuccessStateHero>
<template v-if="settings.titleSlot" #title>{{ settings.titleSlot }}</template>
{{ settings.defaultSlot }}
<template #actions>
<UiButton accent="brand" variant="secondary" size="medium">Continue</UiButton>
</template>
</VtsSuccessStateHero>
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { setting, slot } from '@/libs/story/story-param.ts'
import VtsSuccessStateHero from '@core/components/success-state-hero/VtsSuccessStateHero.vue'
import UiButton from '@core/components/ui/button/UiButton.vue'
</script>

View File

@@ -0,0 +1,14 @@
# Usage
Enter or comma adds the typed value: it is trimmed, and an empty value or a value already in the list is ignored. A
pasted comma-separated draft adds each of its values. Enter while an IME composition is in progress adds nothing.
Removing a chip updates the model with the new array.
The label comes from the surrounding `VtsInputWrapper`.
```vue-template
<VtsInputWrapper label="Values">
<VtsTagsInput v-model="values" accent="brand" placeholder="Add a value" />
</VtsInputWrapper>
```

View File

@@ -0,0 +1,21 @@
<template>
<ComponentStory
v-slot="{ properties }"
:params="[
model().type('string[]').preset(['alpha', 'beta']).help('Enter or comma adds the typed value'),
prop('accent').enum('brand', 'warning', 'danger').required().preset('brand').widget(),
prop('placeholder').str().preset('Add a value').widget(),
]"
>
<VtsInputWrapper label="Values">
<VtsTagsInput v-bind="properties" />
</VtsInputWrapper>
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { model, prop } from '@/libs/story/story-param.ts'
import VtsInputWrapper from '@core/components/input-wrapper/VtsInputWrapper.vue'
import VtsTagsInput from '@core/components/tags-input/VtsTagsInput.vue'
</script>

View File

@@ -0,0 +1,33 @@
<template>
<ComponentStory
v-slot="{ properties }"
:params="[
prop('steps').arr('NumberedStepDefinition').required().preset(steps),
prop('currentStep').num().required().preset(0).help('Index of the current step, earlier steps are done'),
]"
:presets
>
<UiNumberedStepper v-bind="properties" />
</ComponentStory>
</template>
<script lang="ts" setup>
import ComponentStory from '@/components/component-story/ComponentStory.vue'
import { prop } from '@/libs/story/story-param.ts'
import UiNumberedStepper, {
type NumberedStepDefinition,
} from '@core/components/ui/numbered-stepper/UiNumberedStepper.vue'
const steps: NumberedStepDefinition[] = [
{ label: 'General information' },
{ label: 'Settings' },
{ label: 'Options' },
{ label: 'Review' },
]
const presets = {
'First step': { props: { steps, currentStep: 0 } },
'Intermediate step': { props: { steps, currentStep: 2 } },
'Last step': { props: { steps, currentStep: 3 } },
}
</script>

View File

@@ -1,7 +1,7 @@
{
"extends": "@vue/tsconfig/tsconfig.dom.json",
"include": ["env.d.ts", "./src/**/*", "./src/**/*.vue", "../web-core/lib/**/*", "../web-core/lib/**/*.vue"],
"exclude": ["./src/**/__tests__/*"],
"exclude": ["./src/**/__tests__/*", "../web-core/lib/**/*.unit.test.ts", "../web-core/lib/**/*.unit.spec.ts"],
"compilerOptions": {
"composite": true,
"noEmit": true,

View File

@@ -1,4 +1,4 @@
{
"extends": "./tsconfig.app.json",
"exclude": ["src/stories"]
"exclude": ["src/stories", "../web-core/lib/**/*.unit.test.ts", "../web-core/lib/**/*.unit.spec.ts"]
}

View File

@@ -137,7 +137,7 @@ configure(
Optional dependency:
```
> yarn add split-host syslog-client
> yarn add @vates/syslog
```
Configuration:
@@ -148,10 +148,25 @@ import transportSyslog from '@xen-orchestra/log/transports/syslog'
// By default, log to udp://localhost:514
configure(transportSyslog())
// But TCP, a different host, or a different port can be used
// But TCP, TLS, a different host, or a different port can be used
configure(transportSyslog({ target: 'tcp://syslog.company.lan' }))
configure(
transportSyslog({
target: 'tls://syslog.company.lan',
// paths to PEM files of certificate authorities to trust, in addition to the system ones
certificateAuthorities: ['/etc/ssl/certs/company-ca.pem'],
// other options of `@vates/syslog`'s `createClient()`
appName: 'my-app',
facility: 'local0',
})
)
```
The namespace of each log is used as message ID. Failures to send logs are reported on the console, not with the logger.
### Helpers
#### Dedupe

View File

@@ -155,7 +155,7 @@ configure(
Optional dependency:
```
> yarn add split-host syslog-client
> yarn add @vates/syslog
```
Configuration:
@@ -166,10 +166,25 @@ import transportSyslog from '@xen-orchestra/log/transports/syslog'
// By default, log to udp://localhost:514
configure(transportSyslog())
// But TCP, a different host, or a different port can be used
// But TCP, TLS, a different host, or a different port can be used
configure(transportSyslog({ target: 'tcp://syslog.company.lan' }))
configure(
transportSyslog({
target: 'tls://syslog.company.lan',
// paths to PEM files of certificate authorities to trust, in addition to the system ones
certificateAuthorities: ['/etc/ssl/certs/company-ca.pem'],
// other options of `@vates/syslog`'s `createClient()`
appName: 'my-app',
facility: 'local0',
})
)
```
The namespace of each log is used as message ID. Failures to send logs are reported on the console, not with the logger.
### Helpers
#### Dedupe

View File

@@ -39,7 +39,15 @@ function compileFilter(filter) {
throw new TypeError('unsupported `filter`')
}
module.exports = function createTransport(config) {
// a transport can have a `close()` method to release its resources (e.g.
// connections) when it is replaced, wrapping transports must forward it
const closeTransport = transport => {
if (typeof transport.close === 'function') {
transport.close()
}
}
module.exports = exports = function createTransport(config) {
if (typeof config === 'function') {
return config
}
@@ -47,11 +55,13 @@ module.exports = function createTransport(config) {
if (Array.isArray(config)) {
const transports = config.map(createTransport)
const { length } = transports
return function () {
const transport = function () {
for (let i = 0; i < length; ++i) {
transports[i].apply(this, arguments)
}
}
transport.close = () => transports.forEach(closeTransport)
return transport
}
const { type } = config
@@ -80,7 +90,10 @@ module.exports = function createTransport(config) {
return orig.apply(this, arguments)
}
}
transport.close = () => closeTransport(orig)
}
return transport
}
exports.closeTransport = closeTransport

View File

@@ -0,0 +1,62 @@
'use strict'
const assert = require('node:assert/strict')
const { describe, it } = require('node:test')
const createTransport = require('./_createTransport.js')
const { createCaptureTransport } = require('./capture.js')
const { configure } = require('./configure.js')
const { dedupe } = require('./dedupe.js')
function createClosable(logs = []) {
const transport = log => {
logs.push(log)
}
transport.nCloses = 0
transport.close = () => {
++transport.nCloses
}
return transport
}
describe('closing transports', () => {
it('closes the transports of a list, through filters, capture and dedupe', () => {
const a = createClosable()
const b = createClosable()
const transport = createCaptureTransport({
level: 'info',
transport: dedupe({ transport: [a, { filter: 'foo', transport: b }, () => {}] }),
})
transport.close()
assert.equal(a.nCloses, 1)
assert.equal(b.nCloses, 1)
})
it('flushes the hidden duplicates before closing', () => {
const logs = []
const transport = dedupe({ transport: createClosable(logs) })
const log = { level: 30, message: 'foo', namespace: 'ns', data: {} }
transport(log)
transport({ ...log })
transport({ ...log })
assert.equal(logs.length, 1)
transport.close()
assert.equal(logs.length, 2)
assert.equal(logs[1].data.nDuplicates, 2)
})
it('configure() closes the replaced transport', () => {
const first = createClosable()
configure({ transport: first })
assert.equal(first.nCloses, 0)
configure({ transport: createClosable() })
assert.equal(first.nCloses, 1)
})
it('supports transports without close()', () => {
createTransport([() => {}, { transport: () => {} }]).close()
})
})

View File

@@ -7,6 +7,7 @@
const { AsyncLocalStorage } = require('node:async_hooks')
const createTransport = require('./_createTransport.js')
const { closeTransport } = createTransport
// stored in the global context so that various versions of the library can interact.
const symbol = Symbol.for('@xen-orchestra/log/capture')
@@ -33,7 +34,7 @@ exports.captureLogs = function captureLogs(onLog, fn) {
exports.createCaptureTransport = function createCaptureTransport(fallback) {
fallback = fallback === undefined ? Function.prototype : createTransport(fallback)
return function captureTransport(log) {
function captureTransport(log) {
const onLog = asyncStorage.getStore()
if (onLog !== undefined) {
onLog(log, fallback)
@@ -41,4 +42,6 @@ exports.createCaptureTransport = function createCaptureTransport(fallback) {
fallback(log)
}
}
captureTransport.close = () => closeTransport(fallback)
return captureTransport
}

View File

@@ -2,6 +2,7 @@
const createConsoleTransport = require('./transports/console')
const createTransport = require('./_createTransport')
const { closeTransport } = createTransport
const { LEVELS, resolve } = require('./levels')
// ===================================================================
@@ -18,8 +19,11 @@ global[symbol] = createTransport({
transport: createConsoleTransport(),
})
// the previous transport is closed (e.g. its connections), once replaced
const configure = config => {
const previous = global[symbol]
global[symbol] = createTransport(config)
closeTransport(previous)
}
exports.configure = configure

View File

@@ -4,6 +4,7 @@ const isEqual = require('lodash/isEqual')
const Log = require('./_Log')
const createTransport = require('./_createTransport')
const { closeTransport } = createTransport
exports.dedupe = function createDedupe({ timeout = 600e3, transport }) {
transport = createTransport(transport)
@@ -22,7 +23,7 @@ exports.dedupe = function createDedupe({ timeout = 600e3, transport }) {
n = 0
}
return function dedupeLog(log) {
function dedupeLog(log) {
if (
log.level === prev.level &&
log.message === prev.message &&
@@ -42,4 +43,11 @@ exports.dedupe = function createDedupe({ timeout = 600e3, transport }) {
prev = log
return transport(log)
}
dedupeLog.close = () => {
if (n !== 0) {
flush()
}
closeTransport(transport)
}
return dedupeLog
}

View File

@@ -1,51 +1,81 @@
'use strict'
const fromCallback = require('promise-toolbox/fromCallback')
const { basename } = require('path')
const { readFileSync } = require('fs')
// eslint-disable-next-line n/no-extraneous-require
const splitHost = require('split-host')
// eslint-disable-next-line n/no-extraneous-require
const { createClient, Facility, Severity, Transport } = require('syslog-client')
const { createClient } = require('@vates/syslog')
const LEVELS = require('../levels')
const { LEVELS } = require('../levels')
// https://github.com/paulgrove/node-syslog-client#syslogseverity
const LEVEL_TO_SEVERITY = {
[LEVELS.FATAL]: Severity.Critical,
[LEVELS.ERROR]: Severity.Error,
[LEVELS.WARN]: Severity.Warning,
[LEVELS.INFO]: Severity.Informational,
[LEVELS.DEBUG]: Severity.Debug,
[LEVELS.FATAL]: 'critical',
[LEVELS.ERROR]: 'error',
[LEVELS.WARN]: 'warning',
[LEVELS.INFO]: 'informational',
[LEVELS.DEBUG]: 'debug',
}
const facility = Facility.User
function createTransport(target) {
if (typeof target === 'object') {
target = target.target
// `config` is either the target or an object with:
// - `target`: `udp://host[:port]`, `tcp://host[:port]` or `tls://host[:port]`, UDP if there is no protocol
// - `certificateAuthorities`: paths to PEM files of certificate authorities to trust (TLS only)
// - the other options of `@vates/syslog`'s `createClient()`
function createTransport(config) {
if (typeof config !== 'object' || config === null) {
config = { target: config }
}
const opts = {}
if (target !== undefined) {
if (target.startsWith('tcp://')) {
target = target.slice(6)
opts.transport = Transport.Tcp
} else if (target.startsWith('udp://')) {
target = target.slice(6)
opts.transport = Transport.Udp
}
// eslint-disable-next-line no-unused-vars
const { certificateAuthorities, target = 'localhost', type, ...opts } = config
;({ host: target, port: opts.port } = splitHost(target))
}
const client = createClient(target, opts)
return log =>
fromCallback(cb =>
client.log(log.message, {
facility,
severity: LEVEL_TO_SEVERITY[log.level],
})
// a single path instead of a list is an easy mistake in a TOML configuration
if (
certificateAuthorities !== undefined &&
!(Array.isArray(certificateAuthorities) && certificateAuthorities.every(path => typeof path === 'string'))
) {
throw new TypeError(
`syslog transport: certificateAuthorities must be a list of paths, e.g. certificateAuthorities = ['/etc/ssl/certs/company-ca.pem'], got ${JSON.stringify(certificateAuthorities)}`
)
}
const client = createClient(/^[a-z]+:\/\//.test(target) ? target : `udp://${target}`, {
// like the previous implementation
appName: basename(process.title),
ca:
certificateAuthorities === undefined ? undefined : certificateAuthorities.map(path => readFileSync(path, 'utf8')),
...opts,
})
// failures must not be logged with the logger, which would send them to this
// transport again, report the first one and the recovery on the console
let nFailures = 0
const onSent = () => {
if (nFailures !== 0) {
console.error('syslog transport: recovered after %d failure(s)', nFailures)
nFailures = 0
}
}
const onError = error => {
if (nFailures++ === 0) {
console.error(
'syslog transport: failed to send logs, next failures will not be reported until it recovers',
error
)
}
}
const transport = log =>
client
.send(log.message, {
msgid: log.namespace,
severity: LEVEL_TO_SEVERITY[log.level],
timestamp: log.time,
})
.then(onSent, onError)
// called by `configure()` when this transport is replaced
transport.close = () => client.close()
return transport
}
module.exports = exports = createTransport

View File

@@ -0,0 +1,82 @@
'use strict'
const assert = require('node:assert/strict')
const dgram = require('node:dgram')
const { describe, it } = require('node:test')
const net = require('node:net')
const createTransport = require('./syslog.js')
const Log = require('../_Log.js')
const { dedupe } = require('../dedupe.js')
describe('syslog transport', () => {
it('rejects certificateAuthorities which is not a list of paths', () => {
for (const certificateAuthorities of ['/etc/ssl/certs/ca.pem', { ca: '/etc/ssl/certs/ca.pem' }, [42]]) {
assert.throws(
() => createTransport({ target: 'tls://localhost', certificateAuthorities }),
/certificateAuthorities must be a list of paths, e\.g\. certificateAuthorities = \['/
)
}
})
it('closes its client', async () => {
const server = dgram.createSocket('udp4')
await new Promise(resolve => server.bind(0, '127.0.0.1', resolve))
const received = new Promise(resolve => server.once('message', resolve))
try {
const transport = createTransport(`udp://127.0.0.1:${server.address().port}`)
await transport({ level: 30, message: 'foo', namespace: 'ns', time: new Date() })
assert.match(String(await received), / ns - foo$/)
transport.close()
} finally {
server.close()
}
})
// the summary of the duplicates is sent when the transport is replaced, e.g.
// on a configuration change, and must not be lost by the closing client
describe('delivers the summary flushed by dedupe when closed', () => {
const logTwice = transport => {
const log = new Log(undefined, 30, 'ns', 'foo')
transport(log)
transport(log)
transport(log)
transport.close()
}
it('over UDP, while the host name is being resolved', async () => {
const server = dgram.createSocket('udp4')
await new Promise(resolve => server.bind(0, '127.0.0.1', resolve))
const messages = []
server.on('message', message => messages.push(String(message)))
try {
logTwice(dedupe({ transport: createTransport(`udp://localhost:${server.address().port}`) }))
await new Promise(resolve => setTimeout(resolve, 300))
// UDP doesn't guarantee message order
assert.equal(messages.length, 2)
assert.ok(messages.some(message => message.endsWith(' ns - foo')))
assert.ok(messages.some(message => message.endsWith(' ns - duplicates of the previous log were hidden')))
} finally {
server.close()
}
})
it('over TCP, while the connection is being established', async () => {
let data = ''
const server = net.createServer(socket => socket.on('data', chunk => (data += chunk)))
await new Promise(resolve => server.listen(0, '127.0.0.1', resolve))
try {
logTwice(dedupe({ transport: createTransport(`tcp://127.0.0.1:${server.address().port}`) }))
await new Promise(resolve => setTimeout(resolve, 300))
const lines = data.split('\n').filter(Boolean)
assert.equal(lines.length, 2)
assert.match(lines[1], /duplicates of the previous log were hidden$/)
} finally {
server.close()
}
})
})
})

View File

@@ -26,3 +26,28 @@ export function detectLocalAddress(host, port = 1) {
})
})
}
/**
* Every address `hostRef` may connect from: its management address, and the ones of its PIFs, a
* storage network included.
*
* @param {object} xapi
* @param {string} hostRef
* @param {string} [hostAddress] - its management address, if already known
* @returns {Promise<string[]>}
*/
export async function getHostAddresses(xapi, hostRef, hostAddress) {
const addresses = new Set([hostAddress ?? (await xapi.getField('host', hostRef, 'address'))])
for (const pifRef of await xapi.getField('host', hostRef, 'PIFs')) {
const { IP, IPv6 } = await xapi.getRecord('PIF', pifRef)
if (IP !== '') {
addresses.add(IP)
}
// with their prefix length, e.g. `fd00::1/64`, and canonicalized like the remote address of a
// socket, e.g. `fd00:0:0::1` becomes `fd00::1`
for (const address of IPv6) {
addresses.add(new URL(`http://[${address.split('/')[0]}]`).hostname.slice(1, -1))
}
}
return [...addresses]
}

View File

@@ -20,7 +20,8 @@ const defaultExec = (command, args) => execFileAsync(command, args, { timeout: E
// enabled by default, so it must stay out of the way of the installs it cannot apply to: rather
// than failing the mounts, no rule is opened, and whatever firewall there is decides
const NOT_ROOT_RE = /you must be root/i
// iptables-legacy fails on the xtables lock before telling so
const NOT_ROOT_RE = /you must be root|can't open lock file .*: Permission denied/i
// ufw not installed, or not enabled: it deletes its chains when stopped
const MISSING_CHAIN_RE = /No chain\/target\/match by that name|does not exist/i
// a rule already gone, dropped by any change made to ufw meanwhile

View File

@@ -99,6 +99,13 @@ describe('createUfwFirewall', () => {
'iptables v1.8.9 (nf_tables): Could not fetch rule set generation id: Permission denied (you must be root)\n',
}),
],
[
'iptables-legacy runs without root',
Object.assign(new Error('Command failed'), {
code: 4,
stderr: "Fatal: can't open lock file /run/xtables.lock: Permission denied\n",
}),
],
]) {
it(`opens nothing, without failing, when ${what}`, async () => {
const exec = async () => {

View File

@@ -2,7 +2,7 @@ import { randomUUID } from 'node:crypto'
import { asyncEach } from '@vates/async-each'
import { createLogger } from '@xen-orchestra/log'
import { cacheLabel, OC_MOUNT } from './_utils.mjs'
import { OC_MOUNT } from './_utils.mjs'
const { debug, info, warn } = createLogger('xo:mixins:LiveMount')
@@ -24,17 +24,20 @@ const IMAGE_FORMAT_RAW = 'raw'
* `SR.introduce`, not `SR.create`: create would scan, and a scan introduces the
* VDI itself with an sm_config we could no longer amend.
*/
export async function introduceSr($defer, { xapi, hostRef, deviceConfig, id, nameLabel, diskPath }) {
export async function introduceSr(
$defer,
{ xapi, hostRef, deviceConfig, id, nameLabel, nameDescription, smConfig = {} }
) {
const srUuid = randomUUID()
const srRef = await xapi.call(
'SR.introduce',
srUuid,
nameLabel ?? `[XO live mount] ${id.slice(0, 8)}`,
`mount of ${diskPath}`,
nameDescription,
SR_TYPE,
'user',
false, // not shared: this mount serves a single host
{}
smConfig // set with the SR itself, so that the SR cannot exist without it
)
$defer.onFailure(() => xapi.call('SR.forget', srRef))
@@ -83,16 +86,16 @@ export async function forgetSr(xapi, srRef) {
* `readOnly` states the intent, but this driver ignores it either way —
* `RAWVDI.introduce()` ends in `_db_introduce()`, which builds the record from
* the driver's own VDI object, the same reason the resulting uuid is not the
* one asked for. The LUN itself is what actually enforces it: a read-only one
* advertises it to the guest, and refuses writes.
* one asked for. The LUN itself is what actually enforces it: a read-only
* `BlockDevice` is reported write-protected, and writes are refused.
*/
export async function introduceVdi({ xapi, srRef, SCSIid, size, diskPath, id, nameLabel, nameDescription, readOnly }) {
export async function introduceVdi({ xapi, srRef, SCSIid, size, id, nameLabel, nameDescription, readOnly }) {
const uuid = randomUUID()
await xapi.call(
'VDI.introduce',
uuid,
nameLabel ?? `${cacheLabel(diskPath)}.raw`,
nameDescription ?? `mount of ${diskPath}`,
nameLabel,
nameDescription,
srRef,
'user',
false, // sharable
@@ -126,6 +129,6 @@ export async function introduceVdi({ xapi, srRef, SCSIid, size, diskPath, id, na
await xapi.setFieldEntry('VDI', vdiRef, 'other_config', OC_MOUNT, id)
return vdi.uuid
}
warn('no VDI found for the introduced LUN', { SCSIid, srRef, diskPath })
throw new Error(`no VDI found for the introduced LUN when tryng to mount ${diskPath}`)
warn('no VDI found for the introduced LUN', { SCSIid, srRef, nameLabel })
throw new Error(`no VDI found for the introduced LUN when trying to mount ${nameLabel}`)
}

View File

@@ -49,7 +49,7 @@ export async function probeScsiId({ xapi, hostRef, deviceConfig, address }) {
} catch (error) {
if (error.code === PROBE_NO_TARGET_ERROR) {
const wrapped = new Error(
`the host cannot reach the iSCSI target at ${address}:${deviceConfig.port}, check iscsi.advertisedAddress and the firewalls between them`
`the host cannot reach the iSCSI target at ${address}:${deviceConfig.port}, check iscsi.advertisedAddress and the firewalls between them, and set iscsi.restrictToHost = false if the host reaches this appliance through a NAT`
)
wrapped.cause = error
throw wrapped

View File

@@ -7,17 +7,30 @@ import { openDiskChain } from '@xen-orchestra/backup-archive/disks'
import { noSuchObject } from 'xo-common/api-errors.js'
import { randomBytes } from 'node:crypto'
import { cacheLabel } from './_utils.mjs'
import { createCache } from './_cache.mjs'
import { detectLocalAddress } from './_address.mjs'
import { detectLocalAddress, getHostAddresses } from './_address.mjs'
import { createUfwFirewall } from './_firewall.mjs'
import { createChapCredentials, probeScsiId } from './_target.mjs'
import { forgetSr, introduceSr, introduceVdi } from './_sr.mjs'
import { cacheLabel } from './_utils.mjs'
const { info, warn } = createLogger('xo:mixins:LiveMount')
/** @typedef {import('@vates/types').Xapi} Xapi */
/**
* A block device served through an iSCSI target, as returned by {@link LiveMount#serveBlockDevice}.
*
* @typedef {object} ServedBlockDevice
* @property {string} id
* @property {string} address - address of the target, as handed to the host
* @property {number} port
* @property {string} iqn
* @property {Record<string, string>} deviceConfig - of an `iscsi` SR on this target, without `SCSIid`
* @property {Set<string>} refusedAddresses - connections refused by `iscsi.restrictToHost` came from these
* @property {() => Promise<void>} close - stops serving, and closes the firewall rule if any
*/
/**
* The XAPI names of what a mount creates, as the user sees them. Each one falls back to a name
* derived from the disk path.
@@ -29,25 +42,28 @@ const { info, warn } = createLogger('xo:mixins:LiveMount')
*/
/**
* A mount, as built by `#createDiskMount`.
* A mount, as built by `#createMount`.
*
* @typedef {object} DiskMount
* @property {string} id
* @property {string} address
* @property {number} port
* @property {string} iqn
* @property {string} diskPath
* @property {string} [diskPath] - unset for a block device mounted by {@link LiveMount#mountBlockDevice}
* @property {string} srRef
* @property {string} srUuid
* @property {string} vdiUuid
* @property {import('@vates/iscsi').IscsiTarget} target
* @property {ServedBlockDevice} served
* @property {Xapi} xapi - replaced by any newer connection to the same pool, see {@link LiveMount#watchConnection}
* @property {string} [poolUuid] - pool of `xapi`, unknown if it was not connected
* @property {{ device: object, lun: object, poolUuid?: string, vbdRef: string, vdiRef: string, xapi: Xapi }} [cache] - local VDI the disk is materialized into, in the pool running this appliance; its `xapi` is replaced like the mount's one
* @property {{ source: string, port: number, id: string }} [firewallRule] - opened by `iscsi.manageFirewall`
* @property {() => Promise<void>} [release]
* @property {() => Promise<void>} [beforeUnmount]
*/
// names the IQN and the LUN serial of the targets serving a backup disk
const DEFAULT_KIND = 'live-mount'
// the firewalls `iscsi.manageFirewall` can drive
const FIREWALLS = {
ufw: createUfwFirewall,
@@ -209,21 +225,7 @@ export default class LiveMount extends EventEmitter {
* holds the cache SR; defaults to `xapi`, when this appliance runs in the pool of the target host
* @returns {Promise<{ id: string, srUuid: string, vdiUuid: string, iqn: string, address: string, port: number }>}
*/
async mountDisk(params) {
const mount = await this.#createDiskMount(params)
this.#mounts.set(mount.id, mount)
this.#watchVdi(mount)
return {
id: mount.id,
srUuid: mount.srUuid,
vdiUuid: mount.vdiUuid,
iqn: mount.iqn,
address: mount.address,
port: mount.port,
}
}
#createDiskMount = defer(async ($defer, params) => {
mountDisk = defer(async ($defer, params) => {
const { cacheSrUuid, diskPath, handler, hostRef, release, vmUuid, xapi, xapiLabels = {} } = params
const { cacheXapi = xapi } = params
if (this.#firewallError !== undefined) {
@@ -232,23 +234,8 @@ export default class LiveMount extends EventEmitter {
if (cacheSrUuid !== undefined && vmUuid === undefined) {
throw new Error('vmUuid is required to create a live mount cache')
}
const config = this.#app.config
// `iscsi.advertisedAddress` overrides auto-detection; unset, the address
// reachable *from* the target host is guessed by asking the OS which
// local address it would route through to reach it — usually right, but
// not guaranteed to be reachable *back* from the host (NAT, asymmetric
// routing), which is what the override is for.
const firewall = this.#firewall
let address = config.getOptional('iscsi.advertisedAddress')
const hostAddress =
address === undefined || firewall !== undefined ? await xapi.getField('host', hostRef, 'address') : undefined
if (address === undefined) {
address = await this.#detectAddress(hostAddress)
}
// the cache is named after the mount, before its target exists
const id = randomBytes(16).toString('hex')
const iqn = `iqn.2026-07.tech.vates.xo:live-mount-${id}`
const chap = createChapCredentials(id)
// the chain must keep its block allocation tables: they tell which blocks
// are allocated, and reading an unallocated one throws
@@ -275,85 +262,258 @@ export default class LiveMount extends EventEmitter {
cache = { device, lun, poolUuid: cacheXapi.pool?.uuid, vbdRef, vdiRef, xapi: cacheXapi }
}
const target = this.#createTarget({
chap,
host: config.getOptional('iscsi.bindAddress'),
identity: { serial: `xo-live-mount-${id}` },
iqn,
return this.#mount({
cache,
diskPath,
hostRef,
id,
lun,
port: 0, // ephemeral: one target per mount
// a cached disk is writable: `lun.readOnly` makes its VDI read/write
nameDescription: xapiLabels.vdiNameDescription ?? `mount of ${diskPath}`,
nameLabel: xapiLabels.srNameLabel,
release,
vdiNameLabel: xapiLabels.vdiNameLabel ?? `${cacheLabel(diskPath)}.raw`,
xapi,
})
// opens the LUN, so its capacity is readable afterwards
await target.listen()
$defer.onFailure(() => target.close())
const { port } = target.address()
})
// scoped to the host's management address: the one the advertised address is detected from,
// so the one it connects from — unless `iscsi.advertisedAddress` points at another network
let firewallRule
if (firewall !== undefined) {
await this.#purgeFirewall()
const rule = { source: hostAddress, port, id }
// none opened when there is no firewall to drive on this install: nothing to close then
if (await firewall.open(rule)) {
firewallRule = rule
$defer.onFailure(() => firewall.close(rule))
/**
* Like {@link LiveMount#mountDisk}, for any block device: serve it and attach it to a host as an
* SR holding a single VDI. Undone by {@link LiveMount#unmountBlockDevice}.
*
* The LUN is closed with the target. Its `readOnly` flag decides whether the VDI is read-only.
*
* @param {object} params
* @param {import('@vates/iscsi').BlockDevice} params.lun
* @param {object} params.xapi - XAPI connection of the pool owning `hostRef`
* @param {string} params.hostRef - opaque ref of the host the device is attached to as an SR
* @param {string} params.kind - names the IQN and the serial of the LUN, e.g. `browser-media`
* @param {string} params.nameLabel - name of the created SR and VDI
* @param {string} params.nameDescription - description of the created SR and VDI
* @param {Record<string, string>} [params.smConfig] - `sm_config` of the SR, set when it is introduced
* @param {Partial<import('@vates/iscsi').IscsiTargetOptions>} [params.targetOptions] - e.g. `maxTransferLength`
* @param {() => Promise<void>} [params.beforeUnmount] - called first on unmount, whatever triggers it,
* e.g. to eject the VDI while the target can still answer the host: if it fails, the device stays
* mounted, and the unmount can be retried
* @param {() => Promise<void>} [params.release] - called on unmount, once the target is closed
* @returns {Promise<{ id: string, srUuid: string, vdiUuid: string, iqn: string, address: string, port: number }>}
*/
async mountBlockDevice({ nameLabel, ...params }) {
if (this.#firewallError !== undefined) {
throw this.#firewallError
}
return this.#mount({ ...params, nameLabel, vdiNameLabel: nameLabel })
}
async #mount(params) {
const mount = await this.#createMount(params)
this.#mounts.set(mount.id, mount)
this.#watchVdi(mount)
return {
id: mount.id,
srUuid: mount.srUuid,
vdiUuid: mount.vdiUuid,
iqn: mount.iqn,
address: mount.address,
port: mount.port,
}
}
/**
* Serve `lun` through a new iSCSI target, for `hostRef` to attach it: the target listens on an
* ephemeral port, requires CHAP, and only accepts connections from the addresses of the host,
* unless `iscsi.restrictToHost` is `false`. With `iscsi.manageFirewall`, its port is opened to
* the host until it is closed.
*
* `id`, `chap` and `port` serve a target again under the identity of a previous one, e.g. so that
* a host still logged in to a target that went away can complete its I/O and detach cleanly.
*
* @param {object} params
* @param {import('@vates/iscsi').BlockDevice} params.lun - closed with the target
* @param {object} params.xapi - XAPI connection of the pool owning `hostRef`
* @param {string} params.hostRef - opaque ref of the host the target is meant for
* @param {string} [params.kind] - names the IQN and the serial of the LUN, defaults to `live-mount`
* @param {string} [params.id] - random by default
* @param {{ user: string, secret: string }} [params.chap] - random by default
* @param {number} [params.port] - ephemeral by default
* @param {Partial<import('@vates/iscsi').IscsiTargetOptions>} [params.targetOptions]
* @returns {Promise<ServedBlockDevice>}
*/
serveBlockDevice = defer(
async (
$defer,
{
lun,
xapi,
hostRef,
kind = DEFAULT_KIND,
id = randomBytes(16).toString('hex'),
chap = createChapCredentials(id),
port: requestedPort = 0,
targetOptions,
}
) => {
if (this.#firewallError !== undefined) {
throw this.#firewallError
}
const config = this.#app.config
// `iscsi.advertisedAddress` overrides auto-detection; unset, the address
// reachable *from* the target host is guessed by asking the OS which
// local address it would route through to reach it — usually right, but
// not guaranteed to be reachable *back* from the host (NAT, asymmetric
// routing), which is what the override is for.
const hostAddress = await xapi.getField('host', hostRef, 'address')
const address = config.getOptional('iscsi.advertisedAddress') ?? (await this.#detectAddress(hostAddress))
// the host is the only expected initiator: nothing else may take the connection slots of the
// target, which only CHAP would keep from logging in otherwise. Behind a NAT, the host connects
// from another address, which is what `iscsi.restrictToHost = false` is for
const allowedInitiatorAddresses =
config.getOptional('iscsi.restrictToHost') === false
? undefined
: await getHostAddresses(xapi, hostRef, hostAddress)
// what the host connected from instead, to tell why it cannot reach the target
const refusedAddresses = new Set()
const iqn = `iqn.2026-07.tech.vates.xo:${kind}-${id}`
const target = this.#createTarget({
...targetOptions,
allowedInitiatorAddresses,
onConnectionRefused: address => refusedAddresses.add(address),
chap,
host: config.getOptional('iscsi.bindAddress'),
identity: { serial: `xo-${kind}-${id}` },
iqn,
lun,
port: requestedPort,
})
// opens the LUN, so its capacity is readable afterwards
await target.listen()
$defer.onFailure(() => target.close())
const { port } = target.address()
// scoped to the host's management address: the one the advertised address is detected from,
// so the one it connects from — unless `iscsi.advertisedAddress` points at another network
const firewall = this.#firewall
let firewallRule
if (firewall !== undefined) {
await this.#purgeFirewall()
const rule = { source: hostAddress, port, id }
// none opened when there is no firewall to drive on this install: nothing to close then
if (await firewall.open(rule)) {
firewallRule = rule
$defer.onFailure(() => firewall.close(rule))
}
}
return {
address,
deviceConfig: {
chapuser: chap.user,
chappassword: chap.secret,
port: String(port),
target: address,
targetIQN: iqn,
},
id,
iqn,
port,
refusedAddresses,
close: async () => {
// stop serving first, so no I/O is left in flight
try {
await target.close()
} finally {
if (firewallRule !== undefined) {
await firewall.close(firewallRule)
}
}
},
}
}
)
const deviceConfig = {
chapuser: chap.user,
chappassword: chap.secret,
port: String(port),
target: address,
targetIQN: iqn,
#createMount = defer(
async (
$defer,
{
lun,
xapi,
hostRef,
kind,
id: requestedId,
cache,
nameLabel,
nameDescription,
vdiNameLabel,
smConfig,
targetOptions,
diskPath,
beforeUnmount,
release,
}
) => {
const served = await this.serveBlockDevice({ lun, xapi, hostRef, kind, id: requestedId, targetOptions })
$defer.onFailure(() => served.close())
const { address, deviceConfig, id, iqn, port } = served
let SCSIid
try {
SCSIid = await probeScsiId({ xapi, hostRef, deviceConfig, address })
} catch (error) {
const [refused] = served.refusedAddresses
if (refused === undefined) {
throw error
}
throw new Error(
`the host connected to the iSCSI target from ${refused}, which is not one of its addresses, e.g. through a NAT: set iscsi.restrictToHost = false`,
{ cause: error }
)
}
const fullDeviceConfig = { ...deviceConfig, SCSIid }
const { srRef, srUuid } = await introduceSr($defer, {
xapi,
hostRef,
deviceConfig: fullDeviceConfig,
id,
nameLabel,
nameDescription,
smConfig,
})
const vdiUuid = await introduceVdi({
xapi,
srRef,
SCSIid,
size: lun.getSize(),
id,
nameLabel: vdiNameLabel,
nameDescription,
readOnly: lun.readOnly === true,
})
info('mounted', { id, address, port, srUuid, vdiUuid, diskPath, cached: cache !== undefined })
const poolUuid = xapi.pool?.uuid
return {
address,
beforeUnmount,
cache,
diskPath,
id,
iqn,
poolUuid,
port,
release,
served,
srRef,
srUuid,
vdiUuid,
xapi,
}
}
const SCSIid = await probeScsiId({ xapi, hostRef, deviceConfig, address })
const fullDeviceConfig = { ...deviceConfig, SCSIid }
const { srRef, srUuid } = await introduceSr($defer, {
xapi,
hostRef,
deviceConfig: fullDeviceConfig,
id,
nameLabel: xapiLabels.srNameLabel,
diskPath,
})
const vdiUuid = await introduceVdi({
xapi,
srRef,
SCSIid,
size: lun.getSize(),
diskPath,
id,
nameLabel: xapiLabels.vdiNameLabel,
nameDescription: xapiLabels.vdiNameDescription,
readOnly: cache === undefined,
})
info('mounted', { id, address, port, srUuid, vdiUuid, diskPath, cached: cache !== undefined })
const poolUuid = xapi.pool?.uuid
return {
address,
cache,
disk,
diskPath,
firewallRule,
id,
iqn,
poolUuid,
port,
release,
srRef,
srUuid,
target,
vdiUuid,
xapi,
}
})
)
/**
* Tear a mount down as soon as its VDI disappears from the pool.
@@ -442,8 +602,7 @@ export default class LiveMount extends EventEmitter {
return
}
// a VDI is removed once and for all, and a mount introduces exactly one: nothing else will ever
// come for this uuid
this.#mountIdsByVdiUuid.delete(uuid)
// come for this uuid. Still watched until the unmount goes through, which stops watching it
info('the live mounted VDI was removed, unmounting', { id: mountId, vdiUuid: uuid })
this.unmountDisk(mountId).catch(error => {
warn('failed to unmount after the VDI was removed', { error, id: mountId })
@@ -468,6 +627,19 @@ export default class LiveMount extends EventEmitter {
// a coded error, so a remote caller (XO driving a proxy) can tell it apart from a failed call
noSuchObject(id, 'live-mount')
}
// the stop hook, a removed VDI and the owner of the mount may all unmount it at once: they share
// the same unmount
mount.unmounting ??= this.#unmount(id, mount).finally(() => {
mount.unmounting = undefined
})
return mount.unmounting
}
async #unmount(id, mount) {
if (mount.beforeUnmount !== undefined) {
// nothing is released yet: on failure, the mount stays as it is, so the unmount can be retried
await mount.beforeUnmount()
}
// drop it first, so a failing teardown cannot be retried against a
// half-released mount
this.#mounts.delete(id)
@@ -475,7 +647,7 @@ export default class LiveMount extends EventEmitter {
// not the deletion this mixin reacts to
this.#unwatchVdi(mount)
const { cache, firewallRule, xapi, srRef, target, release } = mount
const { cache, xapi, srRef, served, release } = mount
const errors = []
const step = async (what, fn) => {
@@ -488,11 +660,7 @@ export default class LiveMount extends EventEmitter {
}
await step('forget the SR', () => forgetSr(xapi, srRef))
// stop serving first, so no I/O is left in flight
await step('close the target', () => target.close())
if (firewallRule !== undefined) {
await step('close the firewall rule', () => this.#firewall.close(firewallRule))
}
await step('stop serving', () => served.close())
if (cache !== undefined) {
// already closed by the target, which owns the LUN — unless closing the target failed before
// getting there, and an open descriptor would then block the unplug and leak the VDI
@@ -519,17 +687,28 @@ export default class LiveMount extends EventEmitter {
info('unmounted', { id, srUuid: mount.srUuid })
}
/** Live disk mounts, in creation order; a cached one also reports how much of the disk is local. */
/**
* Detach a block device mounted by {@link LiveMount#mountBlockDevice} and stop serving it.
*
* @param {string} id
*/
unmountBlockDevice(id) {
return this.unmountDisk(id)
}
/** Live disk mounts, in creation order, without the other block devices; a cached one also reports how much of the disk is local. */
listMountedDisks() {
return [...this.#mounts.values()].map(({ id, srUuid, vdiUuid, diskPath, iqn, address, port, cache }) => ({
id,
srUuid,
vdiUuid,
diskPath,
iqn,
address,
port,
cache: cache?.lun.getMaterialized(),
}))
return [...this.#mounts.values()]
.filter(mount => mount.diskPath !== undefined)
.map(({ id, srUuid, vdiUuid, diskPath, iqn, address, port, cache }) => ({
id,
srUuid,
vdiUuid,
diskPath,
iqn,
address,
port,
cache: cache?.lun.getMaterialized(),
}))
}
}

View File

@@ -138,6 +138,9 @@ const makeXapi = ({
if (type === 'host' && field === 'address') {
return '10.20.30.40' // the host's own management address, as XAPI reports it
}
if (type === 'host' && field === 'PIFs') {
return ['OpaqueRef:pif-management', 'OpaqueRef:pif-storage']
}
return 'sr-uuid'
},
// `@xen-orchestra/xapi` exposes these as methods, not as `call()`s, so they need their own
@@ -174,6 +177,11 @@ const makeXapi = ({
},
async getRecord(type, ref) {
calls.push(['getRecord', type, ref])
if (type === 'PIF') {
return ref === 'OpaqueRef:pif-management'
? { IP: '10.20.30.40', IPv6: ['fd00::40/64'] }
: { IP: '10.99.0.40', IPv6: [] }
}
// the driver derives the VDI uuid from the LUN serial, so it differs from
// the one we asked for
return { uuid: nVdis > 1 ? `vdi-uuid-${nVdis}` : 'vdi-uuid', sm_config: vdiSmConfig ?? { SCSIid: SCSI_ID } }
@@ -210,6 +218,7 @@ const makeMixin = ({
listenError,
advertisedAddress = '192.168.1.8',
manageFirewall,
restrictToHost,
firewall = makeFirewall(),
// thrown by the successive opens of the cache device, in order
cacheDeviceOpenErrors = [],
@@ -229,6 +238,9 @@ const makeMixin = ({
if (path === 'iscsi.manageFirewall') {
return manageFirewall
}
if (path === 'iscsi.restrictToHost') {
return restrictToHost
}
assert.equal(path, 'iscsi.bindAddress', `unexpected config key ${path}`)
return config[path]
},
@@ -481,6 +493,218 @@ describe('mountDisk', () => {
})
})
describe('serveBlockDevice', () => {
const lun = { open: async () => {}, getSize: () => 1024 * 1024, getBlockSize: () => 512 }
it('only accepts the addresses of the host, storage networks included', async () => {
const { mixin, target } = makeMixin()
await mixin.serveBlockDevice({ lun, xapi: makeXapi(), hostRef: HOST_REF })
assert.deepEqual(target.options.allowedInitiatorAddresses, ['10.20.30.40', 'fd00::40', '10.99.0.40'])
})
it('names the address the host connected from when the probe fails because of it', async () => {
const { mixin, target } = makeMixin()
const xapi = makeXapi({ probeError: new XapiError('SR_BACKEND_FAILURE_141', []) })
const listen = target.listen
target.listen = async () => {
await listen()
// the host connects through a NAT
target.options.onConnectionRefused('192.168.1.254')
}
await assert.rejects(
mixin.mountBlockDevice({ lun, xapi, hostRef: HOST_REF, kind: 'test', nameLabel: 'x', nameDescription: '' }),
/from 192\.168\.1\.254, which is not one of its addresses.*restrictToHost = false/
)
})
it('accepts any address when iscsi.restrictToHost is false, e.g. behind a NAT', async () => {
const { mixin, target } = makeMixin({ restrictToHost: false })
await mixin.serveBlockDevice({ lun, xapi: makeXapi(), hostRef: HOST_REF })
assert.equal(target.options.allowedInitiatorAddresses, undefined)
})
it('serves again under the identity of a previous target', async () => {
const { mixin, target } = makeMixin()
const chap = { user: 'xo-cafebabe', secret: '0123456789abcdef' }
const served = await mixin.serveBlockDevice({
lun,
xapi: makeXapi(),
hostRef: HOST_REF,
kind: 'browser-media',
id: 'cafebabe',
chap,
port: 45678,
})
assert.equal(target.options.port, 45678)
assert.equal(target.options.chap, chap)
assert.equal(target.options.iqn, 'iqn.2026-07.tech.vates.xo:browser-media-cafebabe')
assert.equal(served.iqn, target.options.iqn)
assert.deepEqual(served.deviceConfig, {
chapuser: chap.user,
chappassword: chap.secret,
port: '34567', // as the target reports it
target: '192.168.1.8',
targetIQN: served.iqn,
})
await served.close()
assert.equal(target.closed, true)
})
it('closes the firewall rule with the target', async () => {
const firewall = makeFirewall()
const { mixin } = makeMixin({ manageFirewall: 'ufw', firewall })
const served = await mixin.serveBlockDevice({ lun, xapi: makeXapi(), hostRef: HOST_REF, id: 'cafebabe' })
await served.close()
const rule = { source: '10.20.30.40', port: 34567, id: 'cafebabe' }
assert.deepEqual(
firewall.calls.filter(([method]) => method !== 'purge'),
[
['open', rule],
['close', rule],
]
)
})
})
describe('mountBlockDevice', () => {
const makeLun = ({ readOnly } = {}) => ({
closed: false,
readOnly,
open: async () => {},
getSize: () => 790626304,
getBlockSize: () => 512,
})
it('names the target, the SR and the VDI after the caller, and follows the read-only flag of the LUN', async () => {
const { mixin, target } = makeMixin()
const xapi = makeXapi()
let released = false
const result = await mixin.mountBlockDevice({
lun: makeLun({ readOnly: true }),
xapi,
hostRef: HOST_REF,
kind: 'browser-media',
nameLabel: 'debian-13.5.0-amd64-netinst.iso',
nameDescription: 'streamed from a browser',
smConfig: { 'xo:browser-media': 'session-id' },
targetOptions: { maxTransferLength: 1024 * 1024 },
release: async () => {
released = true
},
})
assert.match(result.iqn, /^iqn\.2026-07\.tech\.vates\.xo:browser-media-[0-9a-f]{32}$/)
assert.equal(target.options.identity.serial, `xo-browser-media-${result.id}`)
assert.equal(target.options.maxTransferLength, 1024 * 1024)
const srIntroduce = xapi.calls.find(([method]) => method === 'SR.introduce')
assert.equal(srIntroduce[2], 'debian-13.5.0-amd64-netinst.iso')
assert.equal(srIntroduce[3], 'streamed from a browser')
const vdiIntroduce = xapi.calls.find(([method]) => method === 'VDI.introduce')
assert.equal(vdiIntroduce[2], 'debian-13.5.0-amd64-netinst.iso')
assert.equal(vdiIntroduce[3], 'streamed from a browser')
assert.equal(vdiIntroduce[7], true) // read_only
assert.equal(vdiIntroduce[13], 790626304)
assert.deepEqual(srIntroduce[7], { 'xo:browser-media': 'session-id' }) // sm_config, set atomically
await mixin.unmountBlockDevice(result.id)
assert.equal(target.closed, true)
assert.equal(released, true)
assert.ok(xapi.calls.some(([method]) => method === 'SR.forget'))
})
it('calls beforeUnmount before forgetting the SR, and keeps the mount when it fails', async () => {
const { mixin, target } = makeMixin()
const xapi = makeXapi()
let failing = true
const order = []
const { id } = await mixin.mountBlockDevice({
lun: makeLun({ readOnly: true }),
xapi,
hostRef: HOST_REF,
kind: 'browser-media',
nameLabel: 'iso',
nameDescription: '',
beforeUnmount: async () => {
order.push(['beforeUnmount', xapi.calls.some(([method]) => method === 'SR.forget')])
if (failing) {
throw new Error('VBD.eject failed')
}
},
})
await assert.rejects(mixin.unmountBlockDevice(id), /VBD\.eject failed/)
// nothing released: forgetting the SR now could leave the host with a datapath on it
assert.ok(!xapi.calls.some(([method]) => method === 'SR.forget'))
assert.equal(target.closed, false)
// a block device is not a disk
assert.deepEqual(mixin.listMountedDisks(), [])
failing = false
await mixin.unmountBlockDevice(id)
assert.deepEqual(order, [
['beforeUnmount', false],
['beforeUnmount', false],
])
assert.ok(xapi.calls.some(([method]) => method === 'SR.forget'))
assert.equal(target.closed, true)
assert.deepEqual(mixin.listMountedDisks(), [])
})
it('shares a single unmount between concurrent callers, e.g. the stop hook and the owner', async () => {
const { mixin } = makeMixin()
const xapi = makeXapi()
let nBeforeUnmount = 0
const { id } = await mixin.mountBlockDevice({
lun: makeLun({ readOnly: true }),
xapi,
hostRef: HOST_REF,
kind: 'browser-media',
nameLabel: 'iso',
nameDescription: '',
beforeUnmount: async () => {
++nBeforeUnmount
await new Promise(resolve => setTimeout(resolve, 10))
},
})
let nUnmounted = 0
mixin.on('unmounted', () => ++nUnmounted)
await Promise.all([mixin.unmountBlockDevice(id), mixin.unmountBlockDevice(id)])
assert.equal(nBeforeUnmount, 1)
assert.equal(nUnmounted, 1)
assert.equal(xapi.calls.filter(([method]) => method === 'SR.forget').length, 1)
})
it('introduces a writable VDI for a writable LUN', async () => {
const { mixin } = makeMixin()
const xapi = makeXapi()
await mixin.mountBlockDevice({
lun: makeLun(),
xapi,
hostRef: HOST_REF,
kind: 'test',
nameLabel: 'disk',
nameDescription: '',
})
assert.equal(xapi.calls.find(([method]) => method === 'VDI.introduce')[7], false)
})
})
describe('unmountDisk', () => {
it('unplugs, forgets, closes the target and releases the caller resources', async () => {
const { mixin, target } = makeMixin()

View File

@@ -73,6 +73,12 @@ port = 443
# in. Set to `false` to leave the firewall of this proxy alone.
manageFirewall = 'ufw'
# The iSCSI target of each mount only accepts connections from the addresses of
# the host it is attached to (its management address and the ones of its PIFs),
# so that nothing else can occupy its connection slots. Set to `false` when the
# hosts reach this proxy through a NAT, which hides their own addresses.
#restrictToHost = true
[logs]
# Display all logs matching this filter, regardless of their level
#filter = 'xo:backups:*'

View File

@@ -0,0 +1,123 @@
import {
Example,
Extension,
Get,
Path,
Post,
Query,
Request,
Response,
Route,
Security,
SuccessResponse,
Tags,
} from 'tsoa'
import { inject } from 'inversify'
import { provide } from 'inversify-binding-decorators'
import type { Request as ExRequest } from 'express'
import type { XoBrowserMediaSession } from '@vates/types'
import {
asynchronousActionResp,
badRequestResp,
noContentResp,
notFoundResp,
unauthorizedResp,
type Unbrand,
} from '../open-api/common/response.common.mjs'
import {
browserMedia,
browserMediaIds,
partialBrowserMedia,
} from '../open-api/oa-examples/browser-media.oa-example.mjs'
import { taskLocation } from '../open-api/oa-examples/task.oa-example.mjs'
import type { SendObjects } from '../helpers/helper.type.mjs'
import { XoController } from '../abstract-classes/xo-controller.mjs'
import type { CreateActionReturnType } from '../abstract-classes/base-controller.mjs'
import { RestApi } from '../rest-api/rest-api.mjs'
/**
* An ISO selected in a browser, which serves it over a WebSocket: see `POST /vms/{id}/actions/insert_browser_iso`.
*
* Experimental, restricted to administrators.
*/
@Route('browser-media')
@Security('*')
@Response(badRequestResp.status, badRequestResp.description)
@Response(unauthorizedResp.status, unauthorizedResp.description)
@Tags('browser-media')
@provide(BrowserMediaController)
export class BrowserMediaController extends XoController<XoBrowserMediaSession> {
constructor(@inject(RestApi) restApi: RestApi) {
super('browser-media', restApi)
}
// --- abstract methods
async getAllCollectionObjects(): Promise<XoBrowserMediaSession[]> {
return this.restApi.xoApp.getAllBrowserMediaSessions()
}
async getCollectionObject(id: XoBrowserMediaSession['id']): Promise<XoBrowserMediaSession> {
return this.restApi.xoApp.getBrowserMediaSession(id)
}
/**
* Restricted to administrators.
*
* Every browser media session, whoever owns it.
*
* @example fields "name,status,vmId"
* @example filter "status:inserted"
* @example limit 42
*/
@Example(browserMediaIds)
@Example(partialBrowserMedia)
@Extension('x-mcp-exposure', 'allow')
@Get('')
async getBrowserMediaSessions(
@Request() req: ExRequest,
@Query() fields?: string,
@Query() ndjson?: boolean,
@Query() markdown?: boolean,
@Query() filter?: string,
@Query() limit?: number
): Promise<SendObjects<Partial<Unbrand<XoBrowserMediaSession>>>> {
return this.sendObjects(Object.values(await this.getObjects({ filter })), req, { limit })
}
/**
* Restricted to administrators.
*
* @example id "3f1d0c9e8b7a6f5e4d3c2b1a09f8e7d6"
*/
@Example(browserMedia)
@Extension('x-mcp-exposure', 'allow')
@Get('{id}')
@Response(notFoundResp.status, notFoundResp.description)
getBrowserMediaSession(@Path() id: string): Promise<Unbrand<XoBrowserMediaSession>> {
return this.getObject(id as XoBrowserMediaSession['id'])
}
/**
* Restricted to administrators.
*
* Eject the ISO if it is inserted, release its storage, and disconnect the browser serving it.
*
* @example id "3f1d0c9e8b7a6f5e4d3c2b1a09f8e7d6"
*/
@Example(taskLocation)
@Extension('x-mcp-exposure', 'confirm')
@Post('{id}/actions/eject')
@SuccessResponse(asynchronousActionResp.status, asynchronousActionResp.description)
@Response(noContentResp.status, noContentResp.description)
@Response(notFoundResp.status, notFoundResp.description)
ejectBrowserMedia(@Path() id: string, @Query() sync?: boolean): CreateActionReturnType<void> {
const sessionId = id as XoBrowserMediaSession['id']
const { vmId } = this.restApi.xoApp.getBrowserMediaSession(sessionId)
return this.createAction<void>(() => this.restApi.xoApp.ejectBrowserMedia(sessionId), {
sync,
statusCode: noContentResp.status,
taskProperties: { name: 'eject browser media', objectId: sessionId, params: { vmId } },
})
}
}

View File

@@ -457,6 +457,76 @@ export class HostController extends XapiXoController<XoHost> {
})
}
/**
* Required privilege:
* - resource: pif, actions: update:dns, update:gateway, update:ip, update:management,
* update:mode, update:netmask (on the target PIF and on the previous management PIF)
*
* Move the management IP configuration (IP, netmask, gateway, DNS) of the host
* to the given PIF, then remove it from the previous management PIF.
*
* The target PIF must be attached and must not have an IP address configured.
* The current management PIF must use a static IP configuration.
*
* @example id "b61a5c92-700e-4966-a13b-00633f03eea8"
* @example body { "pifId": "d9e42451-3794-089f-de81-4ee0e6137bee" }
*/
@Example(taskLocation)
@Extension('x-mcp-exposure', 'deny')
@Post('{id}/actions/move_management_ip')
@Middlewares([
json(),
acl({
resource: 'pif',
actions: ['update:dns', 'update:gateway', 'update:ip', 'update:management', 'update:mode', 'update:netmask'],
objectIds: ({ req, restApi }) => {
const host = restApi.getObject<XoHost>(req.params.id as XoHost['id'], 'host')
const managementPif = host.$PIFs
.map(id => restApi.getObject<XoPif>(id as XoPif['id'], 'PIF'))
.find(hostPif => hostPif.management)
if (managementPif) {
return [req.body.pifId as XoPif['id'], managementPif.id]
} else {
return [req.body.pifId as XoPif['id']]
}
},
}),
])
@SuccessResponse(asynchronousActionResp.status, asynchronousActionResp.description)
@Response(noContentResp.status, noContentResp.description)
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
@Response(notFoundResp.status, notFoundResp.description)
@Response(badRequestResp.status, badRequestResp.description)
@Response(invalidParametersResp.status, invalidParametersResp.description)
@Response(internalServerErrorResp.status, internalServerErrorResp.description)
@Response(incorrectStateResp.status, incorrectStateResp.description)
moveManagementIp(
@Path() id: string,
@Body() body: { pifId: string },
@Query() sync?: boolean
): CreateActionReturnType<void> {
const hostId = id as XoHost['id']
const pif = this.restApi.getObject<XoPif>(body.pifId as XoPif['id'], 'PIF')
if (pif.$host !== hostId) {
throw invalidParameters(`the PIF ${pif.id} does not belong to host ${hostId}`)
}
const action = async () => {
await this.#hostService.moveManagementIp(hostId, body.pifId as XoPif['id'])
}
return this.createAction<void>(action, {
sync,
statusCode: noContentResp.status,
taskProperties: {
name: 'move management IP configuration',
objectId: hostId,
params: body,
},
})
}
/**
* Required privileges:
* - resource: host, action: disable

View File

@@ -1,6 +1,17 @@
import { asyncEach } from '@vates/async-each'
import { createLogger } from '@xen-orchestra/log'
import { HOST_POWER_STATE, Xapi, XcpPatches, XenApiHostWrapped, XoPool, XsPatches, type XoHost } from '@vates/types'
import {
HOST_POWER_STATE,
Xapi,
XcpPatches,
XenApiHostWrapped,
XoPool,
XsPatches,
type XoHost,
type XoPif,
type XenApiPif,
IP_CONFIGURATION_MODE,
} from '@vates/types'
import { incorrectState } from 'xo-common/api-errors.js'
import { parseXml, ensureArray } from '../helpers/utils.helper.mjs'
import type {
@@ -12,6 +23,7 @@ import type {
} from './host.type.mjs'
import type { RestApi } from '../rest-api/rest-api.mjs'
import semver from 'semver'
import { Task } from '@vates/task'
const log = createLogger('xo:rest-api:host-service')
@@ -75,9 +87,14 @@ export class HostService {
let nHostsFailed = 0
await asyncEach(hosts, async (host: XoHost) => {
const xapi = this.#restApi.xoApp.getXapi(host)
// its pool is disconnected: what it misses is unknown until it is back
if (host.$lastSeen !== undefined) {
nHostsFailed++
return
}
try {
const xapi = this.#restApi.xoApp.getXapi(host)
const patches = await xapi.listMissingPatches(host.id)
if (patches.length > 0) {
@@ -158,6 +175,127 @@ export class HostService {
await this.#restApi.getXapiObject<XoHost>(hostId, 'host').$restartAgent()
}
/**
* Move the management IP configuration of the host to the given PIF.
*/
async moveManagementIp(hostId: XoHost['id'], pifId: XoPif['id']): Promise<void> {
const host = this.#restApi.getObject<XoHost>(hostId)
if (host.power_state !== HOST_POWER_STATE.RUNNING) {
throw incorrectState({
actual: host.power_state,
expected: HOST_POWER_STATE.RUNNING,
object: host.id,
property: 'power_state',
})
}
const pif = this.#restApi.getObject<XoPif>(pifId, 'PIF')
if (!pif.attached) {
throw incorrectState({
actual: pif.attached,
expected: true,
object: pif.id,
property: 'attached',
})
}
if (pif.management) {
throw incorrectState({
actual: pif.management,
expected: false,
object: pif.id,
property: 'management',
})
}
if (pif.mode !== IP_CONFIGURATION_MODE.NONE) {
throw incorrectState({
actual: pif.mode,
expected: IP_CONFIGURATION_MODE.NONE,
object: pif.id,
property: 'mode',
})
}
const managementPif = host.$PIFs
.map(id => this.#restApi.getObject<XoPif>(id, 'PIF'))
.find(hostPif => hostPif.management)
if (managementPif === undefined) {
throw incorrectState({
actual: managementPif,
expected: 'a management PIF',
object: hostId,
property: '$PIFs',
})
}
if (managementPif.mode !== IP_CONFIGURATION_MODE.STATIC) {
throw incorrectState({
actual: managementPif.mode,
expected: IP_CONFIGURATION_MODE.STATIC,
object: managementPif.id,
property: 'mode',
})
}
const xapiHost = this.#restApi.getXapiObject<XoHost>(hostId, 'host')
const xapi = xapiHost.$xapi
await xapi.callAsync(
'PIF.reconfigure_ip',
pif._xapiRef,
managementPif.mode,
managementPif.ip,
managementPif.netmask,
managementPif.gateway,
managementPif.dns
)
try {
await xapi.callAsync('host.management_reconfigure', pif._xapiRef)
} catch (error) {
let isManagement: boolean
try {
isManagement = await xapi.getField<XenApiPif, 'management'>(
'PIF',
pif._xapiRef as XenApiPif['$ref'],
'management'
)
} catch (readError) {
Task.warning(
'Could not check whether the management interface moved: please check the host, and remove the IP from the target PIF if it is not the management PIF',
{ pifId: pif.id, readError }
)
throw error
}
if (!isManagement) {
try {
await this.#removePifIp(xapi, pif)
} catch (rollbackError) {
Task.warning('The target PIF still has the copied IP: please remove it manually', {
pifId: pif.id,
rollbackError,
})
}
throw error
}
log.warn('management_reconfigure failed, but the management interface moved', { pifId: pif.id, error })
}
try {
await this.#removePifIp(xapi, managementPif)
} catch (error) {
Task.warning(
'Management interface moved, but the IP could not be removed from the previous management PIF: please remove it manually',
{ pifId: managementPif.id, error }
)
}
}
async #removePifIp(xapi: Xapi, pif: XoPif): Promise<void> {
await xapi.callAsync('PIF.reconfigure_ip', pif._xapiRef, IP_CONFIGURATION_MODE.NONE, '', '', '', '')
}
async #rebootChecks(
hostId: XoHost['id'],
opts: {

View File

@@ -0,0 +1,197 @@
import assert from 'node:assert/strict'
import { describe, it } from 'node:test'
import type { XoHost, XoPif } from '@vates/types'
import { HOST_POWER_STATE, IP_CONFIGURATION_MODE } from '@vates/types'
import type { RestApi } from '../rest-api/rest-api.mjs'
import { HostService } from './host.service.mjs'
const HOST_ID = 'b61a5c92-700e-4966-a13b-00633f03eea8' as XoHost['id']
const TARGET_PIF_ID = 'd9e42451-3794-089f-de81-4ee0e6137bee' as XoPif['id']
const MANAGEMENT_PIF_ID = '355ee47d-ff4c-4924-3db2-fd86ae629676' as XoPif['id']
const objects = {
[HOST_ID]: {
id: HOST_ID,
power_state: HOST_POWER_STATE.RUNNING,
$PIFs: [TARGET_PIF_ID, MANAGEMENT_PIF_ID],
},
[TARGET_PIF_ID]: {
id: TARGET_PIF_ID,
$host: HOST_ID,
attached: true,
management: false,
mode: IP_CONFIGURATION_MODE.NONE,
_xapiRef: 'OpaqueRef:target-pif',
},
[MANAGEMENT_PIF_ID]: {
id: MANAGEMENT_PIF_ID,
management: true,
mode: IP_CONFIGURATION_MODE.STATIC,
ip: '192.168.1.1',
netmask: '255.255.255.0',
gateway: '192.168.1.254',
dns: '192.168.1.1',
_xapiRef: 'OpaqueRef:management-pif',
},
}
const RECONFIGURE_ERROR = new Error('management_reconfigure failed')
const ROLLBACK_ERROR = new Error('management_reconfigure rollback failed')
function createRestApi({ failRollback = false, managementMoved = false, failRead = false } = {}) {
const calls: unknown[][] = []
const xapi = {
async callAsync(...args: unknown[]) {
calls.push(args)
if (args[0] === 'host.management_reconfigure') {
throw RECONFIGURE_ERROR
}
if (failRollback && args[0] === 'PIF.reconfigure_ip' && args[2] === 'None') {
throw ROLLBACK_ERROR
}
},
async getField() {
if (failRead) {
throw new Error('Failed to read field')
}
return managementMoved
},
}
const restApi = {
getObject: id => objects[id],
getXapiObject: () => ({ $xapi: xapi }),
} as unknown as RestApi
return { calls, restApi }
}
describe('HostService.moveManagementIp', () => {
it('should remove the copied IP from the target PIF and rethrow the original error', async () => {
const { calls, restApi } = createRestApi()
const hostService = new HostService(restApi)
await assert.rejects(hostService.moveManagementIp(HOST_ID, TARGET_PIF_ID), RECONFIGURE_ERROR)
assert.deepEqual(calls, [
[
'PIF.reconfigure_ip',
'OpaqueRef:target-pif',
'Static',
'192.168.1.1',
'255.255.255.0',
'192.168.1.254',
'192.168.1.1',
],
['host.management_reconfigure', 'OpaqueRef:target-pif'],
['PIF.reconfigure_ip', 'OpaqueRef:target-pif', 'None', '', '', '', ''],
])
})
it('should still rethrow the original error when the rollback fails too', async () => {
const { calls, restApi } = createRestApi({ failRollback: true })
const hostService = new HostService(restApi)
await assert.rejects(hostService.moveManagementIp(HOST_ID, TARGET_PIF_ID), RECONFIGURE_ERROR)
assert.deepEqual(calls, [
[
'PIF.reconfigure_ip',
'OpaqueRef:target-pif',
'Static',
'192.168.1.1',
'255.255.255.0',
'192.168.1.254',
'192.168.1.1',
],
['host.management_reconfigure', 'OpaqueRef:target-pif'],
['PIF.reconfigure_ip', 'OpaqueRef:target-pif', 'None', '', '', '', ''],
])
})
it('should complete the move when the management interface moved despite the error', async () => {
const { calls, restApi } = createRestApi({ managementMoved: true })
const hostService = new HostService(restApi)
await hostService.moveManagementIp(HOST_ID, TARGET_PIF_ID)
assert.deepEqual(calls, [
[
'PIF.reconfigure_ip',
'OpaqueRef:target-pif',
'Static',
'192.168.1.1',
'255.255.255.0',
'192.168.1.254',
'192.168.1.1',
],
['host.management_reconfigure', 'OpaqueRef:target-pif'],
['PIF.reconfigure_ip', 'OpaqueRef:management-pif', 'None', '', '', '', ''],
])
})
it('should not roll back and rethrow the original error when the management flag cannot be read', async () => {
const { calls, restApi } = createRestApi({ failRead: true })
const hostService = new HostService(restApi)
await assert.rejects(hostService.moveManagementIp(HOST_ID, TARGET_PIF_ID), RECONFIGURE_ERROR)
assert.deepEqual(calls, [
[
'PIF.reconfigure_ip',
'OpaqueRef:target-pif',
'Static',
'192.168.1.1',
'255.255.255.0',
'192.168.1.254',
'192.168.1.1',
],
['host.management_reconfigure', 'OpaqueRef:target-pif'],
])
})
})
describe('HostService.getMissingPatchesInfo', () => {
it('counts the hosts of a disconnected pool as failed, and still reports the others', async () => {
const hosts = {
live: { id: 'live', $pool: 'pool-live' },
stale: { id: 'stale', $pool: 'pool-stale', $lastSeen: Date.now() },
}
const queried: string[] = []
const xapi = {
listMissingPatches: async (hostId: string) => {
queried.push(hostId)
return [{ name: 'patch-1' }]
},
}
const restApi = {
getObjectsByType: () => hosts,
xoApp: {
checkFeatureAuthorization: async () => {},
getXapi: (host: { $lastSeen?: number }) => {
if (host.$lastSeen !== undefined) {
throw new Error('the pool of this object is disconnected')
}
return xapi
},
},
} as unknown as RestApi
const info = await new HostService(restApi).getMissingPatchesInfo()
assert.deepEqual(queried, ['live'])
assert.equal(info.nHostsFailed, 1)
assert.equal(info.nHostsWithMissingPatches, 1)
assert.equal(info.nPoolsWithMissingPatches, 1)
assert.deepEqual(info.missingPatches, [{ name: 'patch-1' }])
})
it('counts a host whose XAPI cannot be found as failed, instead of failing every pool', async () => {
const restApi = {
getObjectsByType: () => ({ gone: { id: 'gone', $pool: 'pool-gone' } }),
xoApp: {
checkFeatureAuthorization: async () => {},
getXapi: () => {
throw new Error('no connection found for this object')
},
},
} as unknown as RestApi
const info = await new HostService(restApi).getMissingPatchesInfo()
assert.equal(info.nHostsFailed, 1)
assert.deepEqual(info.missingPatches, [])
})
})

View File

@@ -0,0 +1,23 @@
export const browserMediaIds = ['/rest/v0/browser-media/3f1d0c9e8b7a6f5e4d3c2b1a09f8e7d6']
export const partialBrowserMedia = [
{
name: 'debian-13.5.0-amd64-netinst.iso',
status: 'inserted',
href: '/rest/v0/browser-media/3f1d0c9e8b7a6f5e4d3c2b1a09f8e7d6',
},
]
export const browserMedia = {
id: '3f1d0c9e8b7a6f5e4d3c2b1a09f8e7d6',
name: 'debian-13.5.0-amd64-netinst.iso',
size: 790626304,
userId: '722d17b9-699b-49d2-8193-be1ac573d3de',
status: 'inserted',
createdAt: 1791699889013,
bytesRead: 24150016,
lastReadAt: 1791699920635,
vmId: '613f541c-4bed-fc77-7ca8-2db6b68f079c',
vdiId: '49d1f713-059d-4aa0-02ec-6c92eaff0a5c',
insertedAt: 1791699912916,
}

View File

@@ -26,6 +26,7 @@ import type {
XapiVmStats,
XenApiVm,
XoAlarm,
XoBrowserMediaSession,
XoVmBackupJob,
XoHost,
XoTask,
@@ -747,6 +748,67 @@ export class VmController extends XapiXoController<XoVm> {
})
}
/**
* Experimental, restricted to administrators.
*
* Insert an ISO streamed from a browser in the CD drive of the VM: nothing is uploaded, and nothing is installed on
* the hosts. The ISO stays inserted for as long as the browser serving it stays connected, and is read: then it is
* ejected, see `POST /browser-media/{id}/actions/eject`. Meanwhile, the VM cannot migrate nor be suspended.
*
* The VM must be halted, or running with an empty CD drive. A halted VM without CD drive gets a bootable one, which
* is removed with the ISO if the VM is halted by then, and is otherwise left empty. A VM protected by HA is refused,
* since the ISO is attached to a single host.
*
* The browser serves the ISO over a WebSocket to `/api/browser-media`, authenticated by the `token` cookie of an
* administrator:
* 1. it sends `{"name": string, "size": number}`, the size being a multiple of 512 bytes between 32 KiB and 128 GiB;
* 2. it receives `{"session": string}`, the id of the browser media session, to pass as `browserMediaId`;
* 3. then it receives read requests `{"id": number, "offset": number, "length": number}` (at most 1 MiB), each
* answered by a binary message: `id` as a big-endian uint32, followed by exactly `length` bytes of the ISO.
*
* Closing the WebSocket ejects the ISO. The server closes it with code `4400` on a protocol error, `4408` once the
* ISO is not read anymore, `4410` once it is ejected, and `4503` when the feature is unavailable.
*
* @example id "f07ab729-c0e8-721c-45ec-f11276377030"
* @example body { "browserMediaId": "3f1d0c9e8b7a6f5e4d3c2b1a09f8e7d6" }
*/
@Example(taskLocation)
@Extension('x-mcp-exposure', 'confirm')
@Post('{id}/actions/insert_browser_iso')
@Middlewares(json())
@SuccessResponse(asynchronousActionResp.status, asynchronousActionResp.description)
@Response(createdResp.status, 'ISO inserted')
@Response(forbiddenOperationResp.status, forbiddenOperationResp.description)
@Response(notFoundResp.status, notFoundResp.description)
@Response(
incorrectStateResp.status,
'The session or the VM is in the wrong state, or the VM already has an ISO streamed from a browser'
)
insertBrowserIso(
@Path() id: string,
@Body() body: { browserMediaId: string },
@Query() sync?: boolean
): CreateActionReturnType<{ vdiId: XoVdi['id'] }> {
const vmId = id as XoVm['id']
const params = { id: body.browserMediaId as XoBrowserMediaSession['id'], vmId }
// reported as such rather than as a failed task
this.restApi.xoApp.assertBrowserMediaInsertable(params)
const action = async () => {
const result = await this.restApi.xoApp.insertBrowserMedia(params)
if (sync) {
this.setHeader('Location', `${BASE_URL}/vdis/${result.vdiId}`)
}
return result
}
return this.createAction<{ vdiId: XoVdi['id'] }>(action, {
sync,
statusCode: createdResp.status,
taskProperties: { name: 'insert browser ISO', objectId: vmId, params: body },
})
}
/**
* Required privilege:
* - resource: vm, action: clone

View File

@@ -777,8 +777,10 @@ export default class Esxi extends EventEmitter {
}
// the cards are read from the devices and not from the vmx: they carry the key the inventory names
// them by, the vmx only has the address of a generated MAC, and lists the cards which are not present
const networks = parseDevices(config.hardware?.device).nics.map(
// them by, the vmx only has the address of a generated MAC, and lists the cards which are not present.
// In the whole `config` they are the `device` elements themselves, not wrapped in a `VirtualDevice`
// as the value of `config.hardware.device` is
const networks = parseDevices({ VirtualDevice: config.hardware?.device }).nics.map(
({ key, label, macAddress, addressType, network }) => ({
key,
label,

View File

@@ -1334,37 +1334,34 @@ createType="vmfs"
RW 67108864 VMFS "vm-000001-flat.vmdk"
`
const config = vmPathName => ({
const VMXNET3 = {
attributes: { 'xsi:type': 'VirtualVmxnet3' },
key: '4000',
deviceInfo: { label: 'Network adapter 1' },
macAddress: '00:0c:29:00:00:01',
addressType: 'generated',
backing: { network: moRef('Network', 'network-13') },
}
const E1000E = {
attributes: { 'xsi:type': 'VirtualE1000e' },
key: '4001',
deviceInfo: { label: 'Network adapter 2' },
macAddress: '00:50:56:00:00:02',
addressType: 'manual',
}
// in the whole `config`, the devices are the repeated `device` elements of the hardware: the
// `ArrayOfVirtualDevice` holding `VirtualDevice` elements is only the value of
// `config.hardware.device` read on its own
const config = (vmPathName, device) => ({
attributes: { 'xsi:type': 'VirtualMachineConfigInfo' },
name: 'a vm',
guestId: 'ubuntu64Guest',
guestFullName: 'Ubuntu Linux (64-bit)',
firmware: 'efi',
files: { vmPathName },
hardware: {
memoryMB: '2048',
numCPU: '2',
device: {
attributes: { 'xsi:type': 'ArrayOfVirtualDevice' },
VirtualDevice: [
{
attributes: { 'xsi:type': 'VirtualVmxnet3' },
key: '4000',
deviceInfo: { label: 'Network adapter 1' },
macAddress: '00:0c:29:00:00:01',
addressType: 'generated',
backing: { network: moRef('Network', 'network-13') },
},
{
attributes: { 'xsi:type': 'VirtualE1000e' },
key: '4001',
deviceInfo: { label: 'Network adapter 2' },
macAddress: '00:50:56:00:00:02',
addressType: 'manual',
},
],
},
},
hardware: { memoryMB: '2048', numCPU: '2', device },
})
const RUNTIME = { attributes: { 'xsi:type': 'VirtualMachineRuntimeInfo' }, powerState: 'poweredOn' }
@@ -1380,8 +1377,13 @@ RW 67108864 VMFS "vm-000001-flat.vmdk"
* @param {object} [options]
* @param {string} [options.vmPathName] - `files.vmPathName` reported for the VM
* @param {number} [options.vmsdStatus] - status of the response to the vmsd request
* @param {object | object[]} [options.device] - `hardware.device` of the config of the VM
*/
const transferableEsxi = async ({ vmPathName = '[ds main] a.vm/a.vm.vmx', vmsdStatus = 404 } = {}) => {
const transferableEsxi = async ({
vmPathName = '[ds main] a.vm/a.vm.vmx',
vmsdStatus = 404,
device = [VMXNET3, E1000E],
} = {}) => {
const requested = []
const { esxi } = await connectedEsxi({
responses: {
@@ -1396,7 +1398,7 @@ RW 67108864 VMFS "vm-000001-flat.vmdk"
}
return pathSet[0] === 'runtime'
? propertyOf('VirtualMachine', 'vm-1', 'runtime', RUNTIME)
: propertyOf('VirtualMachine', 'vm-1', 'config', config(vmPathName))
: propertyOf('VirtualMachine', 'vm-1', 'config', config(vmPathName, device))
},
},
fetch: async (url, options) => {
@@ -1459,6 +1461,18 @@ RW 67108864 VMFS "vm-000001-flat.vmdk"
])
})
it('reads the card of a VM with a single device', async function () {
// the SOAP library returns a lone element as the element itself
const { esxi } = await transferableEsxi({ device: VMXNET3 })
const { networks } = await esxi.getTransferableVmMetadata('vm-1')
assert.deepEqual(
networks.map(({ key, macAddress }) => ({ key, macAddress })),
[{ key: '4000', macAddress: '00:0c:29:00:00:01' }]
)
})
it('treats a missing vmsd as a VM without snapshot', async function () {
const { esxi } = await transferableEsxi()

View File

@@ -585,9 +585,9 @@ dependencies = [
[[package]]
name = "rustls-webpki"
version = "0.103.15"
version = "0.103.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "f3c3cf1d8b1e7d4927e2d154c3fcb02979afb9939629c62cd9048d4f07b60ac2"
checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5"
dependencies = [
"aws-lc-rs",
"ring",
@@ -803,7 +803,7 @@ checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
[[package]]
name = "vectura"
version = "0.2.0"
version = "0.2.1"
dependencies = [
"aws-lc-rs",
"clap",

View File

@@ -1,6 +1,6 @@
[package]
name = "vectura"
version = "0.2.0"
version = "0.2.1"
edition = "2024"
description = "Standalone client for VMware's NFC disk-read protocol"
# The license of the Xen Orchestra application components, see LICENSE.md at

View File

@@ -211,3 +211,14 @@ So, a small utility can be used to add this style on the element that needs it:
```
Then, you can tweak the `inset` property to get the desired result.
## `•` separator utility
To separate inline parts with an interpunct (`•`), wrap them in `VtsInlineParts` (`@core/components/inline-parts/VtsInlineParts.vue`) with `separator="bullet"`: each rendered child after the first gets the separator, so a child hidden by `v-if` leaves no stray one. It renders a `<span>` with the global `interpunct-list` class, which a container that must stay another element can carry itself.
```html
<VtsInlineParts separator="bullet">
<span>{{ t('n-hosts', { n: hostCount }) }}</span>
<span v-if="srCount !== undefined">{{ t('n-srs', { n: srCount }) }}</span>
</VtsInlineParts>
```

View File

@@ -7,6 +7,7 @@
- [Stores](./stores.md)
- [Subscribable stores](./subscribable-stores.md)
- [Overlays (modals & drawers)](./overlays.md)
- [Tests](./tests.md)
# Composables

View File

@@ -0,0 +1,34 @@
# 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).
| Path | Role |
| ---------------------- | ------------------------------------------------------------------------- |
| `vitest.config.ts` | Runner config: `vue` + `vue-i18n` plugins, `@core` alias, `globals: true` |
| `test/setup.ts` | Global setup: auto-unmounts every mounted wrapper after each test |
| `tsconfig.vitest.json` | Type-checks test files with the Vitest globals |
| `tsconfig.app.json` | Type-checks the library, test files excluded |
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.
`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.
## Running tests
```sh
cd @xen-orchestra/web-core
# Type-check, then run the whole suite once
yarn test
# Watch mode
yarn vitest
# Browse and re-run tests from the Vitest UI
yarn test:ui
# Type-check the library and the tests
yarn type-check
```

View File

@@ -17,14 +17,13 @@
color-scheme: dark;
}
--scrollbar-width: 1.4rem;
--scrollbar-border: 0.4rem;
--scrollbar-width: 0.7rem;
--scrollbar-border: 0.2rem;
--scrollbar-thumb-color: var(--color-brand-item-active);
--scrollbar-track-color: var(--color-brand-background-selected);
/* Firefox/Gecko and Chrome versions >= 121 */
scrollbar-color: var(--scrollbar-thumb-color) var(--scrollbar-track-color);
scrollbar-width: auto;
/* Chrome/Webkit */
@@ -44,6 +43,10 @@
}
}
* {
scrollbar-width: thin;
}
a {
color: var(--color-brand-txt-base);
}
@@ -79,19 +82,13 @@ pre {
text-decoration: underline;
}
.scrollbar-small {
scrollbar-width: thin;
&::-webkit-scrollbar {
--scrollbar-width: 0.7rem;
}
&::-webkit-scrollbar-thumb {
--scrollbar-border: 0.2rem;
}
}
.em-dash-prefix::before {
content: '\2014'; /* em dash — */
margin-inline-end: 0.8rem;
}
/* Between rendered children only: a child hidden by `v-if` leaves no stray separator. Empty alt text: not read out */
.interpunct-list > * + *::before {
content: '•' / '';
margin-inline: 0.8rem;
}

View File

@@ -12,8 +12,8 @@
:variant
:accent
:left-icon="icon"
:disabled
:busy
:disabled="disabled || (busy && isBusyHidden)"
:busy="busy && !isBusyHidden"
@click="onClick?.()"
>
<slot />
@@ -26,11 +26,11 @@ import MenuItem from '@core/components/menu/MenuItem.vue'
import UiButton, { type ButtonAccent, type ButtonVariant } from '@core/components/ui/button/UiButton.vue'
import { vTooltip } from '@core/directives/tooltip.directive.ts'
import type { IconName } from '@core/icons'
import { IK_IN_MENU, IK_PANEL_ACTIONS } from '@core/utils/injection-keys.util.ts'
import { IK_HIDE_ACTION_BUTTON_BUSY, IK_IN_MENU, IK_PANEL_ACTIONS } from '@core/utils/injection-keys.util.ts'
import { useCurrentElement } from '@vueuse/core'
import { computed, inject, toValue } from 'vue'
const { accent, onClick } = defineProps<{
const { accent, busy, onClick } = defineProps<{
variant: ButtonVariant
accent: ButtonAccent
icon?: IconName
@@ -46,6 +46,8 @@ defineSlots<{
const isInMenu = inject(IK_IN_MENU, false)
const isBusyHidden = inject(IK_HIDE_ACTION_BUTTON_BUSY, false)
const panelActions = isInMenu ? undefined : inject(IK_PANEL_ACTIONS, undefined)
const isCollapsed = panelActions?.register(useCurrentElement()) ?? false

View File

@@ -0,0 +1,63 @@
<template>
<div ref="content" class="vts-head-bar-actions">
<slot :is-inline />
</div>
</template>
<script lang="ts" setup generic="TAction extends string">
import { useCollapseOnOverflow } from '@core/composables/collapse-on-overflow.composable.ts'
import { useUiStore } from '@core/stores/ui.store.ts'
import { IK_HIDE_ACTION_BUTTON_BUSY } from '@core/utils/injection-keys.util.ts'
import { objectFromEntries } from '@core/utils/object.util.ts'
import { computed, provide, useTemplateRef, watch } from 'vue'
const { actions } = defineProps<{
actions: TAction[]
}>()
defineSlots<{
default(props: { isInline: Partial<Record<TAction, boolean>> }): any
}>()
const uiStore = useUiStore()
const content = useTemplateRef('content')
const container = computed(() => content.value?.parentElement)
const { collapsedCount, reset } = useCollapseOnOverflow(container, content, () => actions.length)
const inlineCount = computed(() => (uiStore.isSmall ? 0 : actions.length - collapsedCount.value))
const isInline = computed(
(): Partial<Record<TAction, boolean>> =>
objectFromEntries(actions.slice(0, inlineCount.value).map(action => [action, true] as const))
)
watch(
() => actions.join(),
() => reset()
)
provide(IK_HIDE_ACTION_BUTTON_BUSY, true)
</script>
<style lang="postcss" scoped>
.vts-head-bar-actions {
margin-inline-start: auto;
display: flex;
align-items: center;
gap: 0.8rem;
white-space: nowrap;
}
:global(.ui-head-bar:has(> .actions > .vts-head-bar-actions)) {
flex-wrap: nowrap;
}
@media (--medium-or-large) {
:global(.ui-head-bar > .actions:has(> .vts-head-bar-actions)) {
flex: 0 1 50%;
}
}
</style>

Some files were not shown because too many files have changed in this diff Show More