Author SHA1 Message Date
christianmanivong 14a1b08db2 Merge pull request 'chore(release): 0.4.0' (#12) from chore/release-0.4.0 into main
driver / types (push) Successful in 1m10s
driver / standard (push) Successful in 17s
driver / lint (push) Successful in 14s
driver / test (3.12) (push) Successful in 1m14s
driver / test (3.13) (push) Successful in 1m4s
driver / lowest (push) Successful in 32s
driver / build (push) Successful in 29s
driver / security (push) Successful in 1m9s
driver / publish (push) Successful in 29s
CI / driver (push) Successful in 3m24s
2026-11-25 21:17:19 +00:00
Christian Manivong d8a9088747 chore(release): 0.4.0
driver / standard (pull_request) Successful in 19s
driver / lint (pull_request) Successful in 17s
driver / types (pull_request) Successful in 1m11s
driver / test (3.12) (pull_request) Successful in 1m13s
driver / test (3.13) (pull_request) Successful in 1m1s
driver / lowest (pull_request) Successful in 36s
driver / build (pull_request) Successful in 33s
driver / security (pull_request) Successful in 1m15s
CI / driver (pull_request) Successful in 3m4s
driver / publish (pull_request) Skipped
2026-11-25 22:09:47 +01:00
Christian Manivong 2367155b73 Merge branch 'fix/vm-resume-2658' 2026-11-25 22:09:31 +01:00
Christian Manivong b781538a87 feat(power): resume_vm powers a suspended VM on (NetOrk/netork#2658)
driver / standard (pull_request) Successful in 16s
driver / lint (pull_request) Successful in 15s
driver / types (pull_request) Successful in 1m13s
driver / test (3.12) (pull_request) Successful in 1m9s
driver / test (3.13) (pull_request) Successful in 57s
driver / lowest (pull_request) Successful in 31s
driver / build (pull_request) Successful in 29s
driver / security (pull_request) Successful in 1m8s
CI / driver (pull_request) Successful in 2m49s
driver / publish (pull_request) Skipped
The hypervisor contract gained resume_vm beside suspend_vm. vSphere has no
call of its own for it: PowerOnVM_Task resumes a suspended VM from its saved
state. A VM that is not suspended is refused, so resume never starts a VM
that was off.
2026-11-25 21:29:22 +01:00
christianmanivong 447b17cbeb Merge pull request 'feat: get_clusters() and create_vm_from_cloud_init(node=)' (#10) from feat/cluster-inventory into main
driver / lint (push) Successful in 15s
driver / standard (push) Successful in 15s
driver / types (push) Successful in 1m15s
driver / test (3.13) (push) Successful in 1m30s
driver / lowest (push) Successful in 34s
driver / test (3.12) (push) Successful in 1m37s
driver / build (push) Successful in 35s
driver / security (push) Successful in 1m8s
CI / driver (push) Successful in 2m53s
driver / publish (push) Skipped
2026-11-01 19:11:34 +00:00
Christian Manivong 881ba7f1db ci: install napalm-device-types from main until the cluster shapes are on PyPI
driver / standard (pull_request) Successful in 14s
driver / lint (pull_request) Successful in 14s
driver / types (pull_request) Successful in 1m5s
driver / test (3.12) (pull_request) Successful in 1m4s
driver / test (3.13) (pull_request) Successful in 1m4s
driver / lowest (pull_request) Successful in 38s
driver / build (pull_request) Successful in 26s
driver / security (pull_request) Successful in 1m6s
CI / driver (pull_request) Successful in 2m34s
driver / publish (pull_request) Skipped
2026-11-01 20:07:02 +01:00
Christian Manivong 68194b6164 refactor: import the cluster shapes from the package root
driver / standard (pull_request) Successful in 19s
driver / lint (pull_request) Successful in 16s
driver / types (pull_request) Failing after 1m12s
driver / test (3.12) (pull_request) Failing after 1m9s
driver / test (3.13) (pull_request) Failing after 58s
driver / lowest (pull_request) Failing after 46s
driver / build (pull_request) Successful in 36s
driver / security (pull_request) Successful in 1m24s
CI / driver (pull_request) Failing after 3m10s
driver / publish (pull_request) Skipped
napalm-device-types keeps them in a module of their own now; the package exports them.

Refs NetOrk/netork#484
2026-11-01 17:08:10 +01:00
Christian Manivong 52c802ed41 feat: get_clusters() and create_vm_from_cloud_init(node=)
driver / standard (pull_request) Successful in 14s
driver / lint (pull_request) Successful in 13s
driver / types (pull_request) Failing after 1m2s
driver / test (3.12) (pull_request) Failing after 57s
driver / test (3.13) (pull_request) Failing after 52s
driver / lowest (pull_request) Failing after 25s
driver / build (pull_request) Successful in 24s
driver / security (pull_request) Successful in 57s
CI / driver (pull_request) Failing after 2m21s
driver / publish (pull_request) Skipped
vCenter reports each cluster compute resource, and each standalone host
it runs as a cluster of one, identified by "<instanceUuid>/<moref>"; an
ESXi host reports itself. Nodes carry state, maintenance, CPU and memory;
datastores and port groups carry the hosts that see them.

create_vm_from_cloud_init(node=) places the VM on that host and refuses
one that does not exist or cannot take it, before anything is created.
Placement now runs before the image download, so a refused host fails at
once instead of after the download.

Refs NetOrk/netork#484, NetOrk/netork#1822
2026-11-01 16:38:38 +01:00
christianmanivong 1bf8de4c23 Merge pull request 'chore: Python 3.12 is the floor (NAPALM/driver-standard#6)' (#9) from chore/python-312-floor into main
driver / standard (push) Successful in 18s
driver / lint (push) Successful in 12s
driver / types (push) Successful in 1m36s
driver / test (3.12) (push) Successful in 1m34s
driver / test (3.13) (push) Successful in 1m13s
driver / lowest (push) Successful in 29s
driver / build (push) Successful in 35s
driver / security (push) Successful in 1m13s
CI / driver (push) Successful in 3m18s
driver / publish (push) Skipped
2026-10-27 11:38:15 +00:00
Christian Manivong fdb43fe882 fix: the floor on PyYAML is 6.0.1 (NAPALM/driver-standard#6)
driver / standard (pull_request) Successful in 14s
driver / lint (pull_request) Successful in 13s
driver / types (pull_request) Successful in 1m1s
driver / test (3.12) (pull_request) Successful in 1m1s
driver / test (3.13) (pull_request) Successful in 49s
driver / lowest (pull_request) Successful in 25s
driver / build (pull_request) Successful in 25s
driver / security (pull_request) Successful in 59s
CI / driver (pull_request) Successful in 2m20s
driver / publish (pull_request) Skipped
PyYAML 6.0 ships no Python 3.12 wheel and fails to build from source
there, so the lowest job could not install it.
2026-10-27 12:22:48 +01:00
Christian Manivong e66c7795bc fix: the floor on napalm is 5.1 (NAPALM/driver-standard#6)
driver / standard (pull_request) Successful in 14s
driver / lint (pull_request) Successful in 13s
driver / types (pull_request) Successful in 1m1s
driver / test (3.12) (pull_request) Successful in 1m2s
driver / test (3.13) (pull_request) Successful in 54s
driver / lowest (pull_request) Failing after 21s
driver / build (pull_request) Successful in 26s
driver / security (pull_request) Successful in 59s
CI / driver (pull_request) Failing after 2m28s
driver / publish (pull_request) Skipped
napalm 5.0 and older import pkg_resources, which a Python 3.12 venv no
longer has, so the lowest job failed on them.
2026-10-27 10:49:32 +01:00
Christian Manivong 3b3f5d9d02 chore: Python 3.12 is the floor (NAPALM/driver-standard#6)
driver / standard (pull_request) Successful in 18s
driver / lint (pull_request) Successful in 14s
driver / test (3.13) (pull_request) Successful in 55s
driver / types (pull_request) Successful in 1m7s
driver / test (3.12) (pull_request) Successful in 1m9s
driver / lowest (pull_request) Failing after 5s
driver / build (pull_request) Successful in 35s
driver / security (pull_request) Successful in 1m12s
CI / driver (pull_request) Failing after 2m51s
driver / publish (pull_request) Skipped
netOrk runs every driver in its own containers on Python 3.12, so 3.10
and 3.11 are no longer supported or tested. requires-python, mypy and
ruff move to 3.12, along with what ruff's pyupgrade rules then rewrite.
2026-10-27 10:19:01 +01:00
christianmanivong e235eb96b4 Merge pull request 'chore: adopt the NAPALM driver standard' (#8) from chore/driver-standard into main
driver / lint (push) Successful in 13s
driver / standard (push) Successful in 14s
driver / types (push) Successful in 1m0s
driver / test (3.11) (push) Successful in 57s
driver / test (3.10) (push) Successful in 59s
driver / lowest (push) Successful in 35s
driver / test (3.12) (push) Successful in 1m3s
driver / test (3.13) (push) Successful in 56s
driver / build (push) Successful in 24s
driver / security (push) Successful in 55s
driver / publish (push) Successful in 26s
CI / driver (push) Successful in 3m8s
2026-10-23 10:43:57 +00:00
Christian Manivong 46b595e8ba chore(release): 0.3.0
driver / standard (pull_request) Successful in 13s
driver / lint (pull_request) Successful in 11s
driver / types (pull_request) Successful in 48s
driver / test (3.10) (pull_request) Successful in 50s
driver / test (3.11) (pull_request) Successful in 49s
driver / test (3.12) (pull_request) Successful in 49s
driver / test (3.13) (pull_request) Successful in 43s
driver / lowest (pull_request) Successful in 24s
driver / security (pull_request) Successful in 47s
driver / build (pull_request) Successful in 23s
CI / driver (pull_request) Successful in 5m57s
driver / publish (pull_request) Skipped
2026-10-23 10:29:09 +02:00
Christian Manivong 24617b7f82 chore: adopt the NAPALM driver standard
driver / standard (pull_request) Successful in 14s
driver / lint (pull_request) Successful in 11s
driver / types (pull_request) Successful in 46s
driver / test (3.10) (pull_request) Successful in 50s
driver / test (3.11) (pull_request) Successful in 48s
driver / test (3.12) (pull_request) Successful in 49s
driver / test (3.13) (pull_request) Successful in 42s
driver / lowest (pull_request) Successful in 24s
driver / security (pull_request) Successful in 46s
driver / build (pull_request) Successful in 22s
CI / driver (pull_request) Successful in 5m52s
driver / publish (pull_request) Skipped
- CI moves to .gitea/workflows/ci.yml and calls the shared driver workflow
  of NAPALM/driver-standard; .github/ is gone.
- setuptools>=77 with the SPDX license string, no License classifier,
  Python 3.13 classifier, napalm-device-types>=4.21.1, a dev extra with
  floors, Issues and Changelog links; README installs from PyPI and links
  pyVmomi on PyPI.
- mypy strict for the package (the blanket ignore_missing_imports is now
  limited to napalm and yaml); exempt for now (35 errors): _inventory,
  _session, _tasks, base, esxi, parse.environment, parse.snapshots,
  parse.vm_devices, provision.seed, provision.transfer, provisioning.
  Recorded in the quality baseline with the long and complex functions.
- Coverage floor 97 % (measured 97.11 %).
2026-10-23 08:40:42 +02:00
Christian Manivong 06b446934f fix: what bandit and the remaining lint rules found
- zip() in provisioning is strict (B905): the OVF asks for one adapter
  per requested NIC, so the two lists match. A VM that came back with
  fewer adapters used to get a seed that left a NIC unconfigured; it now
  fails, and create_vm_from_cloud_init discards it as on any other error
  after the import. A test covers it.
- A failed abort of the import lease is logged at debug level instead of
  passed over (B110); the original error is still the one raised.
- nosec for false positives, each with its reason: the 0.0.0.0 entries in
  the parsers are addresses vSphere reports, not binds (B104); qemu-img
  runs with a fixed argv and no shell (B404, B603); xml.sax.saxutils only
  escapes the OVF descriptor the driver writes, nothing is parsed (B406),
  so defusedxml would not apply.
2026-10-23 08:38:41 +02:00
Christian Manivong 1271218868 style: ruff format and the lint rules of the driver standard
Mechanical: ruff format, and ruff check --fix with the rule set every NAPALM
driver uses (E, F, I, UP, B at line length 100, Python 3.10). What ruff
cannot fix comes in the next commit.
2026-10-23 08:36:49 +02:00
christianmanivong f943fde994 Merge pull request 'feat!: report hosts and licenses as facts, not warnings (0.2.0)' (#6) from feat/facts-not-warnings into main
CI / test (3.10) (push) Successful in 27s
CI / test (3.11) (push) Successful in 25s
CI / test (3.12) (push) Successful in 26s
2026-10-17 08:34:58 +00:00
Christian Manivong 990dfe2f3c feat!: report hosts and licenses as facts, not warnings (0.2.0)
CI / test (3.10) (push) Successful in 27s
CI / test (3.11) (push) Successful in 25s
CI / test (3.12) (push) Successful in 27s
CI / test (3.10) (pull_request) Successful in 27s
CI / test (3.11) (pull_request) Successful in 24s
CI / test (3.12) (pull_request) Successful in 26s
get_device_warnings is gone; netOrk names the warnings from facts
(netOrk #1111). get_hypervisor_hosts() reports each host's connection
state, maintenance mode, configuration issues and managing vCenter;
get_licenses() the assigned licenses with the edition key as edition,
never the key itself.

The reach stays: the ESXi driver reports connected as None (a
disconnected host could not have answered), and managed_by only for a
host it reached directly. parse/warnings.py is replaced by
parse/hosts.py and parse/licenses.py.
2026-10-17 09:41:47 +02:00
christianmanivong 276276bd9f Merge pull request 'feat(vm-provision): declare the guest agent per guest OS, Linux only' (#4) from feat/guest-os into main
CI / test (3.10) (push) Successful in 27s
CI / test (3.11) (push) Successful in 26s
CI / test (3.12) (push) Successful in 28s
2026-10-08 06:05:06 +00:00
Christian Manivong b5c830acfe feat(vm-provision): declare the guest agent per guest OS, Linux only
CI / test (3.10) (push) Successful in 30s
CI / test (3.11) (push) Successful in 26s
CI / test (3.12) (push) Successful in 28s
CI / test (3.10) (pull_request) Successful in 27s
CI / test (3.11) (pull_request) Successful in 26s
CI / test (3.12) (pull_request) Successful in 27s
Follows napalm-device-types 3.0, which replaces GUEST_AGENT_PACKAGES /
GUEST_AGENT_RUNCMD with GUEST_AGENTS = {guest_os: (packages, runcmd)}.
VMware lists Linux with open-vm-tools, as before, and refuses any other
guest_os before anything is created: BSD guests on VMware are optional
for now (NetOrk/netork#801).

The NoCloud network-config moved to napalm-device-types
(`provisioning.network_config`), which Proxmox now uses as well; the seed
module's copy is gone, and the tests check that the generic one is used.
2026-10-08 07:54:13 +02:00
christianmanivong 0430ded280 Merge pull request 'ci: run the tests and build the package on every push and pull request' (#3) from ci/workflow into main
CI / test (3.10) (push) Successful in 27s
CI / test (3.11) (push) Successful in 25s
CI / test (3.12) (push) Successful in 27s
2026-10-07 06:42:10 +00:00
Christian Manivong 3171721b44 ci: run the tests and build the package on every push and pull request
CI / test (3.10) (push) Successful in 29s
CI / test (3.11) (push) Successful in 26s
CI / test (3.12) (push) Successful in 29s
CI / test (3.10) (pull_request) Successful in 27s
CI / test (3.11) (pull_request) Successful in 25s
CI / test (3.12) (pull_request) Successful in 27s
The same job as napalm-fritzbox and napalm-opnsense: Python 3.10, 3.11 and
3.12, pytest, then wheel and sdist. napalm-device-types comes from
git.netork.io first, because PyPI has an unrelated package of that name.
2026-10-07 07:52:44 +02:00
christianmanivong b5bc04ec83 Merge pull request 'feat(provisioning): accept cpu_type, and refuse one that cannot be honoured' (#2) from feat/vm-cpu-type into main 2026-10-04 15:42:16 +00:00
Christian Manivong 4b4410741f feat(provisioning): accept cpu_type, and refuse one that cannot be honoured
napalm_device_types' create_vm_from_cloud_init gained cpu_type, the CPU model
a new VM gets (netork#494). VMware sets CPU compatibility per cluster (EVC),
not per VM, and this driver has no get_vm_cpu_types() to offer a model, so
None is the only value it can honour. Anything else raises ValueError before
the image is fetched rather than being dropped silently.
2026-10-04 12:02:48 +02:00
christianmanivong 25bad821ab Merge pull request 'feat: VM provisioning, and reboot_host on ESXi' (#1) from feature/host-reboot-snapshots-provisioning into main 2026-10-01 18:59:37 +00:00
29 changed files with 1215 additions and 196 deletions

No files matched your search

+17
View File
@@ -0,0 +1,17 @@
name: CI
on:
push:
branches: [main]
tags: ["v*"]
pull_request:
jobs:
driver:
uses: NAPALM/driver-standard/.gitea/workflows/driver.yml@main
with:
standard-ref: main
# Until napalm-device-types with the cluster shapes (ClusterDict) is on PyPI.
pre-install: "git+https://git.netork.io/NAPALM/napalm-device-types.git"
secrets:
PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }}
+53
View File
@@ -7,6 +7,47 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [0.4.0] - 2026-11-25
### Added
- `resume_vm(name)` on both drivers (napalm-device-types' `HypervisorDriver`,
NetOrk/netork#2658): a VM `suspend_vm` suspended is powered on, which vSphere resumes
from its saved state. A VM that is not suspended is refused.
- `get_clusters()` on both drivers. The vCenter reports each cluster and each host
added to a datacenter directly (as a cluster of one with no name), with the id
`<instanceUuid>/<MoRef>`; an ESXi host reports itself, `local`, with its system
UUID as the id. Each cluster lists its hosts (state, maintenance mode, CPU and
memory; a disconnected host keeps only its name and state), the accessible
datastores and the port groups its hosts see, each with the hosts that see it
(NetOrk/netork#484).
- `create_vm_from_cloud_init(node=…)`: the host to create the VM on. A host that does
not exist, is not connected, is in maintenance mode or does not see the datastore
and port groups is refused with ValueError, before the image is downloaded
(NetOrk/netork#1822).
### Changed
- Provisioning chooses the host before it downloads the image, so a request no host
can take fails at once.
- Python 3.12 is the floor (`requires-python = ">=3.12"`): netOrk runs every driver
on 3.12, so 3.10 and 3.11 are no longer tested (NAPALM/driver-standard#6).
- The floor on napalm is 5.1: older releases import `pkg_resources`, which a Python
3.12 venv no longer has.
- The floor on PyYAML is 6.0.1: 6.0 has no Python 3.12 wheel and does not build there.
## [0.3.0] - 2026-10-23
The first release on PyPI.
### Changed
- The driver follows the NAPALM driver standard
(https://git.netork.io/NAPALM/driver-standard): CI on Gitea runs ruff, mypy, the
tests on Python 3.10–3.13 and at the lowest declared versions, bandit, pip-audit and
a build check, and a release tag publishes to PyPI. Python 3.10 remains the floor;
requires napalm-device-types 4.21.1.
- Provisioning fails, and removes the imported VM, when vSphere hands back fewer
network adapters than NICs were asked for, instead of leaving a NIC unconfigured.
A failed abort of the import lease is logged at debug level.
### Added
- VM provisioning (`create_vm_from_cloud_init`, `destroy_vm`,
`get_vm_status`, `get_network_targets`, `get_image_storages`) from qcow2/raw
@@ -15,6 +56,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `reboot_host` on ESXi, refused outside maintenance mode.
- Declares `open-vm-tools` as the guest agent for provisioned VMs.
### Changed
- **Breaking:** `get_device_warnings` is gone; the driver reports facts and the
caller names the warnings (netOrk #1111). `get_hypervisor_hosts()` gives each
host's connection state (`None` on ESXi, which cannot tell), maintenance mode,
configuration issues and managing vCenter (ESXi only); `get_licenses()` gives
the assigned licenses with their edition key as `edition`. Requires
napalm-device-types 4.14.0; version 0.2.0.
- The guest agent is declared per guest OS (`GUEST_AGENTS`, napalm-device-types
3.0); VMware provisions Linux guests only and refuses any other `guest_os`.
- The NoCloud network-config comes from napalm-device-types
(`provisioning.network_config`), which Proxmox uses as well.
## [0.1.0] - 2026-09-24
### Added
+26 -11
View File
@@ -1,7 +1,7 @@
# napalm-vmware
NAPALM drivers for VMware vSphere, speaking the vSphere API through
[pyVmomi](https://github.com/vmware/pyvmomi):
[pyVmomi](https://pypi.org/project/pyvmomi/):
| Driver | Endpoint | Device in netOrk |
|---|---|---|
@@ -25,11 +25,13 @@ hardware**: see [Harvesting fixtures](#harvesting-fixtures).
| `get_environment` | ✅ | ✅ (per host) | quick stats + hardware sensors |
| `get_vms` | ✅ | ✅ | VMs, templates excluded |
| `get_vm_config` | ✅ | ✅ | virtual hardware |
| `start_vm`, `stop_vm`, `reboot_vm`, `suspend_vm` | ✅ | ✅ | power tasks / VMware Tools |
| `start_vm`, `stop_vm`, `reboot_vm`, `suspend_vm`, `resume_vm` | ✅ | ✅ | power tasks / VMware Tools |
| `get_vm_snapshots`, `create/delete/rollback_vm_snapshot` | ✅ | ✅ | snapshot tree |
| `get_vm_storage_pools` | ✅ | ✅ | datastores |
| `get_virtual_networks` | ✅ | ✅ (+ dvPortgroups) | port groups |
| `get_device_warnings` | ✅ | ✅ | raw `{code, meta}` |
| `get_hypervisor_hosts` | ✅ | ✅ | connection state, maintenance mode, config issues, managing vCenter |
| `get_licenses` | ✅ | ✅ | license manager: name and edition key, never the key |
| `get_clusters` | ✅ (the host, a cluster of one) | ✅ (each cluster and standalone host) | compute resources, hosts, datastores, port groups |
| `reboot_host` | ✅ (maintenance mode only) | — | `RebootHost_Task` |
| `create_vm_from_cloud_init`, `destroy_vm`, `get_vm_status` | ✅ | ✅ | see [Provisioning](#provisioning) |
| `get_network_targets`, `get_image_storages` | ✅ | ✅ | port groups, datastores |
@@ -56,8 +58,10 @@ Unverified assumptions, to be checked against real hardware:
## Install
Python 3.12 or later.
```bash
pip install -e vendor/napalm-device-types/ -e vendor/napalm-vmware/
pip install napalm-vmware
```
## Usage
@@ -65,8 +69,9 @@ pip install -e vendor/napalm-device-types/ -e vendor/napalm-vmware/
```python
from napalm_vmware import VmwareEsxiDriver
driver = VmwareEsxiDriver("esx01.example.lan", "root", "secret",
optional_args={"verify_ssl": False})
driver = VmwareEsxiDriver(
"esx01.example.lan", "root", "secret", optional_args={"verify_ssl": False}
)
driver.open()
print(driver.get_facts())
for vm in driver.get_vms():
@@ -84,8 +89,11 @@ by two VMs is refused rather than guessed.
## Tests
The rules are in [STANDARDS.md](https://git.netork.io/NAPALM/driver-standard/src/branch/main/STANDARDS.md).
```bash
pytest # unit tests, no network
python -m venv .venv && .venv/bin/pip install -e ".[dev]"
.venv/bin/pytest --cov # unit tests, no network
docker run -d --rm -p 127.0.0.1:8989:8989 vmware/vcsim -l 0.0.0.0:8989
docker run -d --rm -p 127.0.0.1:8990:8989 vmware/vcsim -esx -l 0.0.0.0:8989
VCSIM_VCENTER_PORT=8989 VCSIM_ESXI_PORT=8990 pytest -m vcsim
@@ -112,7 +120,8 @@ offers for Proxmox (qcow2/raw):
is cached by URL in `image_cache_dir`; the download is not kept.
2. A host is chosen that is connected, not in maintenance mode, and sees the
datastore and every requested port group (the named datastore, or the one
with the most free space).
with the most free space). `node` names the host to use; one that does not
exist or does not qualify is refused with ValueError before the download.
3. The VM is created from a minimal OVF descriptor (PVSCSI disk, VMXNET3
NICs) and the disk streamed in over NFC.
4. Requested MACs are pinned, the disk grown to `disk_resize_gb`, and a
@@ -123,7 +132,9 @@ offers for Proxmox (qcow2/raw):
A port group fixes its VLAN, so `get_network_targets` reports each one with
`kind="portgroup"`, `vlan_aware=False` and its `fixed_vlan_tag`; a NIC asking
for a different `vlan_tag` is refused. The guest agent netOrk installs is
`open-vm-tools` (`GUEST_AGENT_PACKAGES`), which reports the IP address back.
`open-vm-tools` (`GUEST_AGENTS`), which reports the IP address back. Only
Linux guests are provisioned; `guest_os` other than `"linux"` is refused
(BSD guests on VMware: NetOrk/netork#801).
Unverified until #305: that each distribution's cloud kernel carries the
PVSCSI and VMXNET3 drivers.
@@ -146,5 +157,9 @@ The MoRef is reported alongside as `moref`.
hosts. Reporting them on the vCenter would attach their MACs to the wrong
device. Add a host with `vmware_esxi` to see its NICs.
**Warnings are raw.** `get_device_warnings()` returns `{code, meta}` only;
what a code means is decided in netOrk's `WARNING_CATALOG`.
**Facts, not warnings.** The driver names no warnings. `get_hypervisor_hosts()`
and `get_licenses()` report what the endpoint says; whether a host in
maintenance mode or the free `esxBasic` edition is a problem is the caller's
to decide. The ESXi driver reports `connected` as `None` (a disconnected host
could not have answered) and the managing vCenter's address as `managed_by`;
under the vCenter driver `managed_by` is `None`, since every host names it.
+2 -4
View File
@@ -9,14 +9,12 @@ from __future__ import annotations
import time
from collections.abc import Callable
from typing import Any, TypeVar
from typing import Any
from pyVmomi import vmodl
from napalm_vmware._plain import to_plain
T = TypeVar("T")
_POLL_SECONDS = 0.5
_FREE_LICENSE = (
"the host runs the free vSphere Hypervisor license, which makes the "
@@ -31,7 +29,7 @@ def fault_message(fault: dict[str, Any]) -> str:
return fault.get("localizedMessage") or fault.get("msg") or fault.get("_type", "unknown fault")
def invoke(call: Callable[..., T], *args: Any, **kwargs: Any) -> T:
def invoke[T](call: Callable[..., T], *args: Any, **kwargs: Any) -> T:
"""Run a vSphere call, re-raising any ``MethodFault`` as ``RuntimeError``."""
try:
return call(*args, **kwargs)
+8
View File
@@ -12,6 +12,7 @@ from napalm_vmware.parse.snapshots import find_snapshot, snapshot_list
_TASK_TIMEOUT = 300
_GUEST_SHUTDOWN_TIMEOUT = 300
_RUNNING = "poweredOn"
_SUSPENDED = "suspended"
_TOOLS_RUNNING = "guestToolsRunning"
@@ -81,6 +82,13 @@ class VmwareActionsMixin:
self._require_running(vm, "suspend")
self._run(self._vm_mo(vm).SuspendVM_Task)
def resume_vm(self, name: str) -> None:
"""Power a suspended VM on: vSphere resumes it from its saved state."""
vm = self._find_vm(name)
if vm.get("runtime.powerState") != _SUSPENDED:
raise RuntimeError(f"Cannot resume VM {vm.get('name')!r}: it is not suspended")
self._run(self._vm_mo(vm).PowerOnVM_Task)
# -- snapshots -------------------------------------------------------------
def create_vm_snapshot(
+30 -5
View File
@@ -6,8 +6,10 @@ from pathlib import Path
from typing import Any, ClassVar
from napalm.base.exceptions import ConnectionException
from napalm_device_types import HypervisorDriver
from napalm_device_types import ClusterDict, HypervisorDriver, LicenseMixin
from napalm_device_types.models import (
HypervisorHostDict,
LicenseDict,
SnapshotDict,
StorageVolumeDict,
VirtualNetworkDict,
@@ -16,13 +18,15 @@ from napalm_device_types.models import (
from napalm_vmware import _session, paths
from napalm_vmware._inventory import Inventory
from napalm_vmware.parse.clusters import ClusterSources, host_cluster, manager_clusters
from napalm_vmware.parse.environment import environment
from napalm_vmware.parse.hosts import hypervisor_hosts
from napalm_vmware.parse.licenses import license_list
from napalm_vmware.parse.networks import NetworkIndex, network_index, virtual_networks
from napalm_vmware.parse.snapshots import snapshot_list
from napalm_vmware.parse.storage import storage_pools
from napalm_vmware.parse.vm_config import vm_config
from napalm_vmware.parse.vms import vm_list
from napalm_vmware.parse.warnings import host_warnings
from napalm_vmware.provision.image import DEFAULT_CACHE_DIR
_DEFAULT_PORT = 443
@@ -30,7 +34,7 @@ _DEFAULT_PORT = 443
_DRIVER_FOR_API = {"HostAgent": "vmware_esxi", "VirtualCenter": "vmware_vcenter"}
class VmwareBaseDriver(HypervisorDriver):
class VmwareBaseDriver(LicenseMixin, HypervisorDriver):
"""Shared implementation. Concrete drivers set ``API_TYPE`` and ``STANDALONE``."""
VENDOR = "VMware"
@@ -154,5 +158,26 @@ class VmwareBaseDriver(HypervisorDriver):
def get_environment(self) -> dict[str, Any]:
return environment(self._hosts())
def get_device_warnings(self) -> list[dict[str, Any]]:
return host_warnings(self._hosts(), self._inventory.licenses(), standalone=self.STANDALONE)
def get_hypervisor_hosts(self) -> list[HypervisorHostDict]:
return hypervisor_hosts(self._hosts(), standalone=self.STANDALONE)
def get_clusters(self) -> list[ClusterDict]:
collect = self._inventory.collect
src = ClusterSources(
hosts=self._hosts(),
datastores=collect("Datastore", paths.DATASTORE),
networks=collect("Network", paths.NETWORK),
dv_portgroups=collect("DistributedVirtualPortgroup", paths.DV_PORTGROUP),
)
if self.STANDALONE:
return [host_cluster(src)]
clusters = collect("ClusterComputeResource", paths.CLUSTER)
return manager_clusters(
collect("ComputeResource", paths.CLUSTER),
{c["_moref"] for c in clusters},
src,
instance_uuid=self._inventory.about().get("instanceUuid"),
)
def get_licenses(self) -> list[LicenseDict]:
return license_list(self._inventory.licenses())
+225
View File
@@ -0,0 +1,225 @@
"""``get_clusters``: clusters, their hosts, and the datastores and port groups they see.
A vCenter runs two kinds of compute resource: a ``ClusterComputeResource``,
and a plain ``ComputeResource`` for a host added to a datacenter directly.
Each is one cluster here; the plain one has no name, since the contract keeps
names for clusters an operator made. An ESXi host is a cluster of one.
A cluster's datastores and port groups are the ones its hosts list, each with
the hosts that list it. vSphere has no cluster quorum and no cpuinfo flags, so
``quorate`` and ``cpu_flags`` are always None.
"""
from __future__ import annotations
from dataclasses import dataclass
from typing import Any
from napalm_device_types import (
ClusterDict,
ClusterNetworkDict,
ClusterNodeDict,
ClusterStorageDict,
)
from napalm_vmware.parse.networks import dv_vlan, is_uplink
Row = dict[str, Any]
_MB = 1024 * 1024
_STATUS = {"connected": "online", "disconnected": "offline", "notResponding": "offline"}
#: What a datastore can hold for netOrk: VM disks and the cloud-init seed ISO.
_CONTENT = ["images", "iso"]
#: A standard port group's "VLAN" 4095 trunks every VLAN to the guest.
_TRUNK = 4095
@dataclass
class ClusterSources:
"""The inventory rows every cluster draws from."""
hosts: list[Row]
datastores: list[Row]
networks: list[Row] # ``Network`` objects, distributed port groups included
dv_portgroups: list[Row]
def manager_clusters(
compute_resources: list[Row],
cluster_refs: set[str],
src: ClusterSources,
*,
instance_uuid: str | None,
) -> list[ClusterDict]:
"""vCenter: one cluster per compute resource; ``cluster_refs`` are the real clusters.
The id is ``<instanceUuid>/<MoRef>``: a MoRef alone repeats across vCenters.
"""
hosts = {h["_moref"]: h for h in src.hosts}
clusters = []
for cr in compute_resources:
members = [hosts[ref] for ref in cr.get("host") or [] if ref in hosts]
name = cr.get("name") if cr["_moref"] in cluster_refs else None
ident = f"{instance_uuid}/{cr['_moref']}" if instance_uuid else cr["_moref"]
clusters.append(_cluster(ident, name, members, src, local=False))
return sorted(clusters, key=lambda c: (c["name"] is None, c["name"] or _first_node(c)))
def host_cluster(src: ClusterSources) -> ClusterDict:
"""ESXi: the host itself, a cluster of one with no name."""
if not src.hosts:
raise RuntimeError("The inventory shows no host")
host = src.hosts[0]
ident = (host.get("hardware.systemInfo") or {}).get("uuid")
return _cluster(ident, None, [host], src, local=True)
def _first_node(cluster: ClusterDict) -> str:
return cluster["nodes"][0]["name"] if cluster["nodes"] else ""
def _cluster(
ident: str | None, name: str | None, hosts: list[Row], src: ClusterSources, *, local: bool
) -> ClusterDict:
hosts = sorted(hosts, key=_host_name)
return {
"id": ident,
"name": name,
"quorate": None,
"nodes": [_node(h, local) for h in hosts],
"storages": _storages(hosts, src.datastores),
"networks": _networks(hosts, src),
}
def _host_name(host: Row) -> str:
return str(host.get("name") or host["_moref"])
# -- nodes ---------------------------------------------------------------------
def _node(host: Row, local: bool) -> ClusterNodeDict:
status = _STATUS.get(host.get("runtime.connectionState") or "", "unknown")
hardware: Row = {}
stats: Row = {}
# A host vCenter cannot reach reports what it last knew, if anything.
if status != "offline":
hardware = host.get("summary.hardware") or {}
stats = host.get("summary.quickStats") or {}
memory_used = stats.get("overallMemoryUsage")
return {
"name": _host_name(host),
"status": status,
"local": local,
"maintenance": host.get("runtime.inMaintenanceMode"),
"cpu_threads": hardware.get("numCpuThreads"),
"cpu_cores": hardware.get("numCpuCores"),
"cpu_model": hardware.get("cpuModel"),
"cpu_flags": None,
"cpu_usage": _cpu_usage(hardware, stats),
"memory_total": hardware.get("memorySize"),
"memory_used": memory_used * _MB if memory_used is not None else None,
}
def _cpu_usage(hardware: Row, stats: Row) -> float | None:
"""Used MHz over the host's total MHz (``cpuMhz`` per core)."""
used = stats.get("overallCpuUsage")
total = (hardware.get("cpuMhz") or 0) * (hardware.get("numCpuCores") or 0)
if used is None or not total:
return None
return min(1.0, float(used) / total)
# -- storages ------------------------------------------------------------------
def _mounts(hosts: list[Row], key: str) -> dict[str, list[str]]:
"""MoRef -> names of the hosts whose ``key`` list holds it, in host order."""
seen: dict[str, list[str]] = {}
for host in hosts:
for ref in host.get(key) or []:
seen.setdefault(ref, []).append(_host_name(host))
return seen
def _storages(hosts: list[Row], datastores: list[Row]) -> list[ClusterStorageDict]:
mounts = _mounts(hosts, "datastore")
result: list[ClusterStorageDict] = []
for ds in datastores:
summary = ds.get("summary") or {}
if ds["_moref"] not in mounts or not summary.get("accessible"):
continue
total = summary.get("capacity")
free = summary.get("freeSpace")
result.append(
{
"name": ds.get("name") or summary.get("name") or ds["_moref"],
"type": str(summary.get("type", "")).lower(),
"shared": bool(summary.get("multipleHostAccess")),
"content": list(_CONTENT),
"nodes": mounts[ds["_moref"]],
"total": total,
"used": total - free if total is not None and free is not None else None,
}
)
return sorted(result, key=lambda s: s["name"])
# -- networks ------------------------------------------------------------------
def _networks(hosts: list[Row], src: ClusterSources) -> list[ClusterNetworkDict]:
return [
{
"name": name,
"kind": "portgroup",
# The port group fixes the VLAN; a NIC cannot add a tag of its own.
"vlan_aware": False,
"fixed_vlan_tag": _fixed_tag(vlans),
"nodes": nodes,
}
for name, (nodes, vlans) in sorted(_seen_networks(hosts, src).items())
]
def _seen_networks(
hosts: list[Row], src: ClusterSources
) -> dict[str, tuple[list[str], set[int | None]]]:
"""Port group name -> (the hosts that have it, the VLAN it carries on each)."""
names = {n["_moref"]: n.get("name") or n["_moref"] for n in src.networks}
dv = {pg["_moref"]: pg for pg in src.dv_portgroups}
seen: dict[str, tuple[list[str], set[int | None]]] = {}
for host in hosts:
for ref in _vm_networks(host, dv):
name = names.get(ref, ref)
nodes, vlans = seen.setdefault(name, ([], set()))
if _host_name(host) not in nodes:
nodes.append(_host_name(host))
vlans.add(_vlan(ref, name, host, dv))
return seen
def _vm_networks(host: Row, dv: dict[str, Row]) -> list[str]:
"""The host's networks a VM can use: a vDS's uplink port group carries none."""
return [ref for ref in host.get("network") or [] if not (ref in dv and is_uplink(dv[ref]))]
def _vlan(ref: str, name: str, host: Row, dv: dict[str, Row]) -> int | None:
"""The VLAN ``ref`` carries on ``host``; None where it cannot be read."""
if ref in dv:
return dv_vlan(dv[ref].get("config.defaultPortConfig"))
for pg in host.get("config.network.portgroup") or []:
spec = pg.get("spec") or {}
if spec.get("name") == name:
return int(spec.get("vlanId", 0))
return None
def _fixed_tag(vlans: set[int | None]) -> int | None:
"""One VLAN on every host, and a single tag at that; else None."""
if len(vlans) != 1:
return None
(vlan,) = vlans
return vlan if vlan not in (None, 0, _TRUNK) else None
+40
View File
@@ -0,0 +1,40 @@
"""The hosts a driver sees, as facts (``HypervisorDriver.get_hypervisor_hosts``).
Whether a host in maintenance mode or one managed by a vCenter is a problem is
decided by the caller, never here.
"""
from __future__ import annotations
from typing import Any
from napalm_device_types.models import HypervisorHostDict
_CONNECTED = "connected"
# Addresses vSphere reports for "no managing vCenter"; data, not a bind.
_UNMANAGED = {None, "", "0.0.0.0"} # nosec B104
def _host(host: dict[str, Any], standalone: bool) -> HypervisorHostDict:
manager = host.get("summary.managementServerIp")
return {
"name": host.get("name", host.get("_moref", "")),
# A disconnected host could not have answered the ESXi driver.
"connected": None
if standalone
else host.get("runtime.connectionState", _CONNECTED) == _CONNECTED,
"maintenance": bool(host.get("runtime.inMaintenanceMode")),
"config_issues": [
i["fullFormattedMessage"]
for i in host.get("configIssue") or []
if i.get("fullFormattedMessage")
],
# Under a vCenter every host names that vCenter; only a host the ESXi
# driver reached directly can be managed by someone else.
"managed_by": manager if standalone and manager not in _UNMANAGED else None,
}
def hypervisor_hosts(hosts: list[dict[str, Any]], *, standalone: bool) -> list[HypervisorHostDict]:
"""``standalone`` is True for the ESXi driver, False for vCenter."""
return [_host(host, standalone) for host in hosts]
+2 -1
View File
@@ -12,7 +12,8 @@ import ipaddress
from typing import Any
_DEFAULT_MTU = 1500
_UNASSIGNED = {"", "0.0.0.0"}
# Addresses vSphere reports for an interface without one; data, not a bind.
_UNASSIGNED = {"", "0.0.0.0"} # nosec B104
def _uplink_mtus(host: dict[str, Any]) -> dict[str, int]:
+19
View File
@@ -0,0 +1,19 @@
"""Licenses assigned on an endpoint, as facts (``LicenseMixin.get_licenses``).
The edition key says which edition runs -- ``esxBasic`` is the free vSphere
Hypervisor, whose API refuses every write; what follows from that is the
caller's to decide. The license key itself is never reported.
"""
from __future__ import annotations
from typing import Any
from napalm_device_types.models import LicenseDict
def license_list(licenses: list[dict[str, Any]]) -> list[LicenseDict]:
return [
{"name": lic.get("name", ""), "status": "active", "edition": str(lic.get("editionKey", ""))}
for lic in licenses
]
+2 -2
View File
@@ -76,7 +76,7 @@ def _network(name: str, kind: str, bridge: str, vlan: int) -> dict[str, Any]:
}
def _is_uplink(pg: dict[str, Any]) -> bool:
def is_uplink(pg: dict[str, Any]) -> bool:
if "config.uplink" in pg:
return bool(pg["config.uplink"])
return bool(_UPLINK_NAME.search(pg.get("name", "")))
@@ -97,7 +97,7 @@ def virtual_networks(
)
switch_names = {s["_moref"]: s.get("name", s["_moref"]) for s in dv_switches}
for pg in dv_portgroups:
if _is_uplink(pg):
if is_uplink(pg):
continue
dvs = pg.get("config.distributedVirtualSwitch", "")
vlan = dv_vlan(pg.get("config.defaultPortConfig"))
-53
View File
@@ -1,53 +0,0 @@
"""Raw device warnings: ``{"code", "meta"}`` only.
What a code means to a user -- severity, wording, the fix -- is decided in
netOrk's ``WARNING_CATALOG``, never here.
"""
from __future__ import annotations
from typing import Any
_CONNECTED = "connected"
_UNMANAGED = {None, "", "0.0.0.0"}
#: License edition of the free vSphere Hypervisor. The vSphere API refuses
#: every write on it (power, snapshots) with a RestrictedVersion fault.
_FREE_EDITIONS = ("esxBasic",)
def _host_codes(host: dict[str, Any], standalone: bool) -> list[dict[str, Any]]:
name = host.get("name", host.get("_moref", ""))
found: list[dict[str, Any]] = []
state = host.get("runtime.connectionState", _CONNECTED)
if not standalone and state != _CONNECTED:
found.append({"code": "vmware_host_disconnected", "meta": {"host": name, "state": state}})
if host.get("runtime.inMaintenanceMode"):
found.append({"code": "vmware_host_maintenance_mode", "meta": {"host": name}})
issues = [
i["fullFormattedMessage"]
for i in host.get("configIssue") or []
if i.get("fullFormattedMessage")
]
if issues:
found.append({"code": "vmware_host_config_issue", "meta": {"host": name, "issues": issues}})
manager = host.get("summary.managementServerIp")
if standalone and manager not in _UNMANAGED:
found.append({"code": "vmware_host_managed_by_vcenter", "meta": {"vcenter": manager}})
return found
def host_warnings(
hosts: list[dict[str, Any]], licenses: list[dict[str, Any]], *, standalone: bool
) -> list[dict[str, Any]]:
"""Warnings for the hosts this driver sees.
``standalone`` is True for the ESXi driver. It alone reports a host being
managed by a vCenter -- a hint to add the vCenter instead -- and it never
reports disconnection, since a disconnected host could not have answered.
"""
found = [w for host in hosts for w in _host_codes(host, standalone)]
for lic in licenses:
if str(lic.get("editionKey", "")).startswith(_FREE_EDITIONS):
found.append({"code": "vmware_api_read_only", "meta": {"edition": lic.get("name", "")}})
break
return found
+7 -1
View File
@@ -78,6 +78,11 @@ COMPUTE_RESOURCE = ("parent", "resourcePool")
FOLDER = ("parent",)
DATACENTER = ("name", "vmFolder")
# get_clusters: every compute resource and its hosts. Read once as
# ComputeResource (clusters included, a subtype) and once as
# ClusterComputeResource to tell the two apart.
CLUSTER = ("name", "host")
#: Managed object type name -> paths, in the order harvest.py dumps them.
ALL = {
"HostSystem": HOST,
@@ -86,7 +91,8 @@ ALL = {
"DistributedVirtualPortgroup": DV_PORTGROUP,
"DistributedVirtualSwitch": DV_SWITCH,
"Network": NETWORK,
"ComputeResource": COMPUTE_RESOURCE,
"ComputeResource": tuple(dict.fromkeys(COMPUTE_RESOURCE + CLUSTER)),
"ClusterComputeResource": CLUSTER,
"Folder": FOLDER,
"Datacenter": DATACENTER,
}
+7 -3
View File
@@ -12,7 +12,9 @@ import hashlib
import json
import os
import shutil
import subprocess
# qemu-img is run with a fixed argv and no shell (see below).
import subprocess # nosec B404
import tempfile
from collections.abc import Callable
from pathlib import Path
@@ -46,7 +48,8 @@ def fetch(url: str, dest: Path, timeout: float) -> None: # pragma: no cover - n
def convert_to_vmdk(src: Path, dst: Path) -> None:
subprocess.run(
# Fixed argv, no shell: qemu-img from PATH and the cache's own file paths.
subprocess.run( # nosec B603
[
_qemu_img(),
"convert",
@@ -64,7 +67,8 @@ def convert_to_vmdk(src: Path, dst: Path) -> None:
def virtual_size(path: Path) -> int:
"""The disk size the image describes, in bytes (not the file size)."""
out = subprocess.run(
# Fixed argv, no shell: qemu-img from PATH and the cache's own file path.
out = subprocess.run( # nosec B603
[_qemu_img(), "info", "--output", "json", str(path)],
check=True,
capture_output=True,
+2 -1
View File
@@ -11,7 +11,8 @@ VMXNET3. Both drivers are in the mainline kernel; whether every distribution's
from __future__ import annotations
from xml.sax.saxutils import escape, quoteattr
# Escaping for the descriptor this module writes; no XML is parsed here.
from xml.sax.saxutils import escape, quoteattr # nosec B406
_HW_VERSION = "vmx-13" # ESXi 6.5 and later
_GUEST_OS = "otherLinux64Guest"
+55 -15
View File
@@ -2,9 +2,10 @@
A host qualifies when it is connected, not in maintenance mode, and sees both
a usable datastore and every requested network. Among those, the pair with
the most free space wins -- or the named datastore, when one is given. The
resource pool comes from the host's compute resource and the VM folder from
the datacenter above it; a standalone ESXi host has the same shape
the most free space wins -- or the named datastore, when one is given; a
named host narrows the choice to that host and is refused if it does not
qualify. The resource pool comes from the host's compute resource and the VM
folder from the datacenter above it; a standalone ESXi host has the same shape
(``ha-compute-res`` under ``ha-datacenter``), so one path serves both.
"""
@@ -16,6 +17,10 @@ from typing import Any
Row = dict[str, Any]
class NodeRefused(ValueError):
"""The host named for a new VM does not exist or cannot take it."""
@dataclass
class Inventory:
hosts: list[Row]
@@ -71,15 +76,35 @@ def _datacenter(inv: Inventory, compute_resource: str) -> Row:
return datacenters[node]
def choose_placement(inv: Inventory, storage: str | None, networks: list[str]) -> Placement:
usable = _usable_datastores(inv, storage)
names = {n["_moref"]: n.get("name", "") for n in inv.networks}
def _refusal(host: Row) -> str | None:
"""Why ``host`` cannot take a new VM, or None if it can."""
if host.get("runtime.connectionState") != "connected":
return "is not connected"
if host.get("runtime.inMaintenanceMode"):
return "is in maintenance mode"
return None
def _candidates(inv: Inventory, host_name: str | None) -> list[Row]:
"""The hosts placement may choose from: every eligible one, or the named one."""
hosts = sorted(inv.hosts, key=lambda h: h.get("name", ""))
if host_name is None:
return [h for h in hosts if _refusal(h) is None]
named = [h for h in hosts if h.get("name") == host_name]
if not named:
raise NodeRefused(f"There is no host named {host_name!r}")
reason = _refusal(named[0])
if reason:
raise NodeRefused(f"Host {host_name} {reason}")
return named[:1]
def _best(
hosts: list[Row], usable: dict[str, Row], names: dict[str, str], networks: list[str]
) -> tuple[Row, Row, list[str]] | None:
"""The host/datastore pair with the most free space, and the host's networks."""
best: tuple[int, Row, Row, list[str]] | None = None
for host in sorted(inv.hosts, key=lambda h: h.get("name", "")):
if host.get("runtime.connectionState") != "connected" or host.get(
"runtime.inMaintenanceMode"
):
continue
for host in hosts:
host_nets = _host_networks(host, names, networks)
if host_nets is None:
continue
@@ -88,11 +113,26 @@ def choose_placement(inv: Inventory, storage: str | None, networks: list[str]) -
free = int((ds or {}).get("summary", {}).get("freeSpace", 0))
if ds is not None and (best is None or free > best[0]):
best = (free, host, ds, host_nets)
return best[1:] if best else None
def choose_placement(
inv: Inventory, storage: str | None, networks: list[str], *, host_name: str | None = None
) -> Placement:
"""Where a VM on ``storage`` with ``networks`` goes; ``host_name`` pins the host.
Raises NodeRefused (a ValueError) when the named host does not exist or
cannot take the VM, and ValueError when no host can.
"""
usable = _usable_datastores(inv, storage)
names = {n["_moref"]: n.get("name", "") for n in inv.networks}
best = _best(_candidates(inv, host_name), usable, names, networks)
wanted = f"datastore {storage or '(any)'} and networks {networks}"
if best is None and host_name is not None:
raise NodeRefused(f"Host {host_name} does not see {wanted}")
if best is None:
raise ValueError(
f"There is no host that sees datastore {storage or '(any)'} and networks {networks}"
)
_, host, ds, host_nets = best
raise ValueError(f"There is no host that sees {wanted}")
host, ds, host_nets = best
compute = next(c for c in inv.compute_resources if c["_moref"] == host.get("parent"))
dc = _datacenter(inv, compute["_moref"])
return Placement(
-14
View File
@@ -31,20 +31,6 @@ def meta_data(hostname: str, instance_id: str) -> str:
return yaml.safe_dump({"instance-id": instance_id, "local-hostname": hostname}, sort_keys=False)
def network_config(nics: list[tuple[str, bool]]) -> dict[str, Any] | None:
"""Netplan v2 config: DHCP on every ``(mac, dhcp)`` NIC that asks for it.
``None`` when no NIC does -- cloud-init then leaves networking alone
rather than being told to configure nothing.
"""
ethernets = {
f"nic{i}": {"match": {"macaddress": mac}, "dhcp4": True}
for i, (mac, dhcp) in enumerate(nics)
if dhcp
}
return {"version": 2, "ethernets": ethernets} if ethernets else None
def nocloud_iso(user: str, meta: str, network: dict[str, Any] | None) -> bytes:
"""An ISO 9660 image (Rock Ridge + Joliet) holding the seed files."""
files = {"user-data": user, "meta-data": meta}
+46 -14
View File
@@ -22,6 +22,7 @@ from napalm_device_types.models import (
VMProvisionResultDict,
VMStatusDict,
)
from napalm_device_types.provisioning import GuestAgents, network_config
from pyVmomi import vim
from napalm_vmware import paths
@@ -34,8 +35,8 @@ from napalm_vmware.provision import transfer
from napalm_vmware.provision.image import ImageCache
from napalm_vmware.provision.ovf import ovf_descriptor
from napalm_vmware.provision.placement import Inventory as PlacementInventory
from napalm_vmware.provision.placement import Placement, choose_placement
from napalm_vmware.provision.seed import meta_data, network_config, nocloud_iso, user_data
from napalm_vmware.provision.placement import NodeRefused, Placement, choose_placement
from napalm_vmware.provision.seed import meta_data, nocloud_iso, user_data
logger = logging.getLogger(__name__)
@@ -48,11 +49,14 @@ _STATUS = {"poweredOn": "running", "poweredOff": "stopped", "suspended": "suspen
class VmwareProvisioningMixin:
"""Mixed into both drivers ahead of :class:`VmwareBaseDriver`."""
GUEST_AGENT_PACKAGES: tuple[str, ...] = ("open-vm-tools",)
# The unit is open-vm-tools on Debian/Ubuntu and vmtoolsd on EL/Fedora.
GUEST_AGENT_RUNCMD: tuple[str, ...] = (
"systemctl enable --now open-vm-tools || systemctl enable --now vmtoolsd",
)
# Linux only: BSD guests on VMware are optional (NetOrk/netork#801). The
# unit is open-vm-tools on Debian/Ubuntu and vmtoolsd on EL/Fedora.
GUEST_AGENTS: GuestAgents = {
"linux": (
("open-vm-tools",),
("systemctl enable --now open-vm-tools || systemctl enable --now vmtoolsd",),
),
}
hostname: str
_port: int
@@ -147,17 +151,24 @@ class VmwareProvisioningMixin:
ssh_public_keys: list[str] | None = None,
disk_resize_gb: int | None = None,
storage: str | None = None,
cpu_type: str | None = None,
guest_os: str = "linux",
node: str | None = None,
download_timeout: int = 300,
timeout: int = 180,
) -> VMProvisionResultDict:
if guest_os not in self.GUEST_AGENTS:
raise ValueError(f"VMware provisions Linux guests only, not {guest_os!r}")
if cpu_type is not None:
# CPU compatibility is a cluster setting here (EVC), not a per-VM
# one, and there is no get_vm_cpu_types() that could offer a model.
raise ValueError(f"VMware cannot give a single VM a CPU type ({cpu_type!r})")
self._check_nics(nics)
place = self._place(storage, nics, node)
try:
vmdk, image_size = ImageCache(self._image_cache_dir).vmdk(
image_url, image_checksum, download_timeout
)
place = choose_placement(
self._placement_inventory(), storage, [n["bridge"] for n in nics]
)
except ValueError as exc:
raise RuntimeError(str(exc)) from exc
descriptor = ovf_descriptor(
@@ -184,6 +195,24 @@ class VmwareProvisioningMixin:
)
return {"vmid": props["config.instanceUuid"], "name": name, "node": place.host_name}
def _place(self, storage: str | None, nics: list[NICConfigDict], node: str | None) -> Placement:
"""Where the VM goes, decided before the image is fetched.
A ``node`` that does not exist or cannot take the VM stays a
ValueError, as the contract has it; no host at all is a RuntimeError.
"""
try:
return choose_placement(
self._placement_inventory(),
storage,
[n["bridge"] for n in nics],
host_name=node,
)
except NodeRefused:
raise
except ValueError as exc:
raise RuntimeError(str(exc)) from exc
def _run_task(self, call: Any, *args: Any, **kwargs: Any) -> None:
wait_for_task(self._inventory, invoke(call, *args, **kwargs), _TASK_TIMEOUT)
@@ -240,7 +269,7 @@ class VmwareProvisioningMixin:
try:
lease.HttpNfcLeaseAbort()
except Exception: # noqa: BLE001 - the original error is the one to report
pass
logger.debug("Aborting the import lease failed: ignored", exc_info=True)
raise
return info["info"]["entity"]
@@ -267,13 +296,16 @@ class VmwareProvisioningMixin:
changes = _mac_changes(adapters, nics) + _disk_growth(devices, disk_gb, image_size)
macs = [
(nic.get("mac") or adapter.macAddress or "").lower()
for adapter, nic in zip(adapters, nics)
for adapter, nic in zip(adapters, nics, strict=True)
]
seed = nocloud_iso(
user,
meta_data(name, f"iid-{uuid.uuid4()}"),
network_config(
[(mac, nic.get("dhcp", i == 0)) for i, (mac, nic) in enumerate(zip(macs, nics))]
[
(mac, nic.get("dhcp", i == 0))
for i, (mac, nic) in enumerate(zip(macs, nics, strict=True))
]
),
)
vm_dir = posixpath.dirname(str(props["config.files.vmPathName"]).split("] ", 1)[1])
@@ -353,7 +385,7 @@ class VmwareProvisioningMixin:
def _mac_changes(adapters: list[Any], nics: list[NICConfigDict]) -> list[Any]:
"""Device edits pinning the MACs the caller asked for."""
changes = []
for adapter, nic in zip(adapters, nics):
for adapter, nic in zip(adapters, nics, strict=True):
if not nic.get("mac"):
continue
adapter.addressType = "manual"
+50 -19
View File
@@ -1,14 +1,14 @@
[build-system]
requires = ["setuptools>=68", "wheel"]
requires = ["setuptools>=77"]
build-backend = "setuptools.build_meta"
[project]
name = "napalm-vmware"
version = "0.1.0"
version = "0.4.0"
description = "NAPALM drivers for VMware ESXi hosts and vCenter Server (vSphere API via pyVmomi)"
readme = "README.md"
requires-python = ">=3.10"
license = { text = "Apache-2.0" }
requires-python = ">=3.12"
license = "Apache-2.0"
authors = [
{ name = "Christian Manivong", email = "christian@manivong.de" },
]
@@ -17,32 +17,30 @@ classifiers = [
"Development Status :: 3 - Alpha",
"Intended Audience :: Developers",
"Intended Audience :: System Administrators",
"License :: OSI Approved :: Apache Software License",
"Operating System :: OS Independent",
"Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Topic :: System :: Networking",
"Topic :: System :: Systems Administration",
"Typing :: Typed",
]
dependencies = [
"napalm>=5.0.0",
"napalm-device-types>=2.0.0",
"napalm>=5.1", # older releases import pkg_resources, which a 3.12 venv lacks
"napalm-device-types>=4.21.1",
"pyvmomi>=8.0.1",
# Provisioning: download the image, write the NoCloud seed ISO and its YAML.
"requests>=2.31",
"pycdlib>=1.14",
"PyYAML>=6.0",
"PyYAML>=6.0.1", # 6.0 has no Python 3.12 wheel and does not build there
]
[project.optional-dependencies]
dev = [
"pytest",
"pytest-cov",
"ruff",
"mypy",
"pytest>=8",
"pytest-cov>=5",
"mypy>=1.11",
"ruff>=0.6",
]
[project.entry-points."napalm.drivers"]
@@ -51,6 +49,8 @@ vmware_vcenter = "napalm_vmware:VmwareVcenterDriver"
[project.urls]
Repository = "https://git.netork.io/NAPALM/napalm-vmware"
Issues = "https://git.netork.io/NAPALM/napalm-vmware/issues"
Changelog = "https://git.netork.io/NAPALM/napalm-vmware/src/branch/main/CHANGELOG.md"
[tool.setuptools.packages.find]
where = ["."]
@@ -67,13 +67,44 @@ markers = [
[tool.ruff]
line-length = 100
target-version = "py310"
target-version = "py312"
# Same rule set the netOrk repo gates on.
[tool.ruff.lint]
select = ["E", "F", "I", "UP"]
select = ["E", "F", "I", "UP", "B"]
[tool.ruff.lint.per-file-ignores]
# Recorded device output keeps its lines.
"tests/**" = ["E501"]
[tool.mypy]
python_version = "3.10"
warn_unused_configs = true
python_version = "3.12"
strict = true
# napalm itself is untyped, so every driver subclasses Any.
disallow_subclassing_any = false
[[tool.mypy.overrides]]
module = ["napalm.*", "yaml.*"]
ignore_missing_imports = true
[[tool.mypy.overrides]]
# Not yet under strict mypy (quality baseline); may only shrink.
module = [
"napalm_vmware._inventory",
"napalm_vmware._session",
"napalm_vmware._tasks",
"napalm_vmware.base",
"napalm_vmware.esxi",
"napalm_vmware.parse.environment",
"napalm_vmware.parse.snapshots",
"napalm_vmware.parse.vm_devices",
"napalm_vmware.provision.seed",
"napalm_vmware.provision.transfer",
"napalm_vmware.provisioning",
]
ignore_errors = true
[tool.coverage.run]
source = ["napalm_vmware"]
[tool.coverage.report]
fail_under = 97
+30
View File
@@ -0,0 +1,30 @@
{
"coverage_floor": 97.0,
"function_complexity": {
"napalm_vmware/_plain.py::to_plain": 11,
"napalm_vmware/base.py::VmwareBaseDriver._find_vm": 12,
"napalm_vmware/parse/facts.py::host_serial": 11,
"napalm_vmware/parse/interfaces.py::host_interfaces": 11,
"napalm_vmware/parse/vms.py::_vm": 13
},
"function_lines": {
"napalm_vmware/provision/ovf.py::ovf_descriptor": 80,
"napalm_vmware/provisioning.py::VmwareProvisioningMixin._import_ovf": 56,
"napalm_vmware/provisioning.py::VmwareProvisioningMixin.create_vm_from_cloud_init": 56
},
"mypy_relaxed": [
"napalm_vmware._inventory",
"napalm_vmware._session",
"napalm_vmware._tasks",
"napalm_vmware.base",
"napalm_vmware.esxi",
"napalm_vmware.parse.environment",
"napalm_vmware.parse.snapshots",
"napalm_vmware.parse.vm_devices",
"napalm_vmware.provision.seed",
"napalm_vmware.provision.transfer",
"napalm_vmware.provisioning"
],
"python_file_lines": {},
"untyped_public": []
}
+14
View File
@@ -80,6 +80,20 @@ class TestPower:
with pytest.raises(RuntimeError, match="not running"):
driver.suspend_vm(vm0["name"])
def test_resume_powers_a_suspended_vm_on(self, driver, vm0, waited):
"""vSphere resumes a suspended VM by powering it on (NetOrk/netork#2658)."""
vm0["runtime.powerState"] = "suspended"
driver.resume_vm(vm0["name"])
driver.mo.PowerOnVM_Task.assert_called_once_with()
assert waited.call_args.args[1] is driver.mo.PowerOnVM_Task.return_value
@pytest.mark.parametrize("state", ["poweredOn", "poweredOff"])
def test_resume_requires_a_suspended_vm(self, driver, vm0, state):
vm0["runtime.powerState"] = state
with pytest.raises(RuntimeError, match="not suspended"):
driver.resume_vm(vm0["name"])
driver.mo.PowerOnVM_Task.assert_not_called()
def test_free_license_refusal_is_explained(self, driver, vm0):
from pyVmomi import vim
+99 -5
View File
@@ -72,7 +72,9 @@ class TestIdentity:
"rollback_vm_snapshot",
"get_vm_storage_pools",
"get_virtual_networks",
"get_device_warnings",
"get_hypervisor_hosts",
"get_licenses",
"get_clusters",
],
)
@pytest.mark.parametrize("cls", DRIVERS)
@@ -94,8 +96,14 @@ class TestIdentity:
assert callable(getattr(cls, method, None))
@pytest.mark.parametrize("cls", DRIVERS)
def test_declares_its_guest_agent(self, cls):
assert cls.GUEST_AGENT_PACKAGES == ("open-vm-tools",)
def test_provisions_linux_guests_with_open_vm_tools(self, cls):
"""Linux only: BSD guests on VMware are optional (NetOrk/netork#801)."""
assert cls.GUEST_AGENTS == {
"linux": (
("open-vm-tools",),
("systemctl enable --now open-vm-tools || systemctl enable --now vmtoolsd",),
),
}
class TestOptionalArgs:
@@ -198,9 +206,22 @@ class TestEsxiGetters:
with pytest.raises(RuntimeError, match="no host"):
esxi.get_facts()
def test_warnings(self, esxi, esxi_host):
def test_host_facts(self, esxi, esxi_host):
esxi_host["runtime.inMaintenanceMode"] = True
assert [w["code"] for w in esxi.get_device_warnings()] == ["vmware_host_maintenance_mode"]
assert [h["maintenance"] for h in esxi.get_hypervisor_hosts()] == [True]
def test_license_facts(self, esxi):
esxi._inventory.data["licenses"] = [{"editionKey": "esxBasic", "name": "Free"}]
assert esxi.get_licenses() == [{"name": "Free", "status": "active", "edition": "esxBasic"}]
@pytest.mark.parametrize("cls", DRIVERS)
def test_no_warnings_of_their_own(self, cls):
"""Hosts and licenses are facts; the caller names the warnings (netOrk #1111)."""
assert not any(
"get_device_warnings" in vars(c)
for c in cls.__mro__
if c.__module__.startswith("napalm_vmware")
)
def test_storage_and_networks(self, esxi):
assert list(esxi.get_vm_storage_pools())
@@ -228,6 +249,79 @@ class TestVcenterGetters:
assert vcenter.get_virtual_networks()["DC0_DVPG0"]["type"] == "dvportgroup"
def _vcsim_topology(data, compute, clusters, networks):
"""What the harvested fixtures predate: compute resources, Network objects,
and each host's datastores and networks -- as vcsim reports them."""
objects = data["objects"]
objects["ComputeResource"] = compute
objects["ClusterComputeResource"] = [c for c in compute if c["_moref"] in clusters]
objects["Network"] = networks
for host in objects["HostSystem"]:
host["datastore"] = [ds["_moref"] for ds in objects["Datastore"]]
host["network"] = [n["_moref"] for n in networks]
class TestClusters:
@pytest.fixture
def vcenter(self, vcenter_data):
_vcsim_topology(
vcenter_data,
[
{"_moref": "domain-s24", "name": "DC0_H0", "host": ["host-21"]},
{
"_moref": "domain-c28",
"name": "DC0_C0",
"host": ["host-37", "host-47", "host-57"],
},
],
{"domain-c28"},
[
{"_moref": "network-6", "name": "VM Network"},
{"_moref": "dvportgroup-10", "name": "DVS0-DVUplinks-8"},
{"_moref": "dvportgroup-12", "name": "DC0_DVPG0"},
],
)
return _driver(VmwareVcenterDriver, vcenter_data, hostname="vc01.example.lan")
@pytest.fixture
def esxi(self, esxi_data):
_vcsim_topology(
esxi_data,
[{"_moref": "ha-compute-res", "name": "localhost.localdomain", "host": ["ha-host"]}],
set(),
[{"_moref": "HaNetwork-VM Network", "name": "VM Network"}],
)
return _driver(VmwareEsxiDriver, esxi_data)
def test_vcenter_reports_its_cluster_and_its_standalone_host(self, vcenter, vcenter_data):
uuid = vcenter_data["about"]["instanceUuid"]
clusters = vcenter.get_clusters()
assert [(c["name"], c["id"]) for c in clusters] == [
("DC0_C0", f"{uuid}/domain-c28"),
(None, f"{uuid}/domain-s24"),
]
assert [n["name"] for n in clusters[0]["nodes"]] == ["DC0_C0_H0", "DC0_C0_H1", "DC0_C0_H2"]
assert [n["name"] for n in clusters[1]["nodes"]] == ["DC0_H0"]
assert {n["name"] for n in clusters[0]["networks"]} == {"VM Network", "DC0_DVPG0"}
assert clusters[0]["storages"][0]["nodes"] == ["DC0_C0_H0", "DC0_C0_H1", "DC0_C0_H2"]
def test_esxi_is_a_cluster_of_one_with_itself_local(self, esxi, esxi_host):
(cluster,) = esxi.get_clusters()
assert (cluster["id"], cluster["name"]) == (esxi_host["hardware.systemInfo"]["uuid"], None)
assert [(n["name"], n["local"], n["status"]) for n in cluster["nodes"]] == [
(esxi_host["name"], True, "online")
]
assert [s["name"] for s in cluster["storages"]] == ["LocalDS_0"]
assert [n["name"] for n in cluster["networks"]] == ["VM Network"]
@pytest.mark.parametrize("name", ["vcenter", "esxi"])
def test_a_failed_read_raises_instead_of_reporting_nothing(self, request, name):
driver = request.getfixturevalue(name)
driver._inventory.collect = MagicMock(side_effect=RuntimeError("session gone"))
with pytest.raises(RuntimeError, match="session gone"):
driver.get_clusters()
class TestFindVm:
def test_by_name_vmid_or_moref(self, esxi, esxi_data):
vm0 = esxi_data["objects"]["VirtualMachine"][0]
+280
View File
@@ -0,0 +1,280 @@
"""``get_clusters``: clusters, their hosts, datastores and port groups, from plain rows."""
from __future__ import annotations
import pytest
from napalm_vmware.parse.clusters import ClusterSources, host_cluster, manager_clusters
MB = 1024 * 1024
UUID = "35bb7c82-8526-5aa7-a886-cd7f8e6be786"
def _host(moref, name, *, state="connected", maint=False, datastores=(), networks=(), pgs=()):
return {
"_moref": moref,
"name": name,
"runtime.connectionState": state,
"runtime.inMaintenanceMode": maint,
"summary.hardware": {
"cpuMhz": 2000,
"cpuModel": "Xeon",
"memorySize": 64 * 1024 * MB,
"numCpuCores": 8,
"numCpuThreads": 16,
},
"summary.quickStats": {"overallCpuUsage": 4000, "overallMemoryUsage": 1024},
"hardware.systemInfo": {"uuid": f"uuid-{moref}"},
"datastore": list(datastores),
"network": list(networks),
"config.network.portgroup": [
{"spec": {"name": pg, "vlanId": vlan, "vswitchName": "vSwitch0"}} for pg, vlan in pgs
],
}
def _ds(moref, name, *, shared=False, accessible=True, capacity=1000, free=400, kind="VMFS"):
return {
"_moref": moref,
"name": name,
"summary": {
"accessible": accessible,
"capacity": capacity,
"freeSpace": free,
"multipleHostAccess": shared,
"type": kind,
},
}
@pytest.fixture
def src():
return ClusterSources(
hosts=[
_host(
"host-1",
"esx01",
datastores=["ds-san", "ds-local1", "ds-gone"],
networks=["network-1", "network-10", "dvportgroup-12", "dvportgroup-10"],
pgs=[("VM Network", 0), ("Storage", 30)],
),
_host(
"host-2",
"esx02",
state="disconnected",
datastores=["ds-san"],
networks=["network-1", "dvportgroup-12"],
pgs=[("VM Network", 0)],
),
_host(
"host-3",
"esx03",
maint=True,
datastores=["ds-san"],
networks=["network-1", "dvportgroup-12"],
pgs=[("VM Network", 0)],
),
_host("host-9", "lonely", datastores=["ds-local9"], networks=["network-1"]),
],
datastores=[
_ds("ds-san", "san", shared=True, capacity=10_000, free=2_500),
_ds("ds-local1", "local1", kind="vmfs"),
_ds("ds-gone", "gone", accessible=False),
_ds("ds-local9", "local9", kind="NFS"),
],
networks=[
{"_moref": "network-1", "name": "VM Network"},
{"_moref": "network-10", "name": "Storage"},
{"_moref": "dvportgroup-10", "name": "DVS0-DVUplinks-8"},
{"_moref": "dvportgroup-12", "name": "DC0_DVPG0"},
],
dv_portgroups=[
{
"_moref": "dvportgroup-10",
"name": "DVS0-DVUplinks-8",
"config.defaultPortConfig": {"vlan": {"_type": "TrunkVlanSpec"}},
},
{
"_moref": "dvportgroup-12",
"name": "DC0_DVPG0",
"config.defaultPortConfig": {
"vlan": {"_type": "VmwareDistributedVirtualSwitchVlanIdSpec", "vlanId": 42}
},
},
],
)
COMPUTE = [
{"_moref": "domain-c7", "name": "Prod", "host": ["host-1", "host-2", "host-3"]},
{"_moref": "domain-s9", "name": "lonely", "host": ["host-9"]},
]
@pytest.fixture
def clusters(src):
return manager_clusters(COMPUTE, {"domain-c7"}, src, instance_uuid=UUID)
def _standalone(src, index):
"""``src`` as an ESXi host sees it: one host, ``src.hosts[index]``."""
src.hosts = [src.hosts[index]]
return host_cluster(src)
def _by_name(items):
return {i["name"]: i for i in items}
class TestManager:
def test_one_entry_per_cluster_and_per_standalone_host(self, clusters):
assert [(c["name"], c["id"]) for c in clusters] == [
("Prod", f"{UUID}/domain-c7"),
(None, f"{UUID}/domain-s9"),
]
assert all(c["quorate"] is None for c in clusters)
def test_the_moref_alone_without_an_instance_uuid(self, src):
(prod, _) = manager_clusters(COMPUTE, {"domain-c7"}, src, instance_uuid=None)
assert prod["id"] == "domain-c7"
def test_a_cluster_lists_only_its_own_hosts(self, clusters):
prod, lonely = clusters
assert [n["name"] for n in prod["nodes"]] == ["esx01", "esx02", "esx03"]
assert [n["name"] for n in lonely["nodes"]] == ["lonely"]
assert all(n["local"] is False for c in clusters for n in c["nodes"])
def test_an_empty_cluster_is_still_a_cluster(self, src):
(empty,) = manager_clusters(
[{"_moref": "domain-c8", "name": "Empty"}], {"domain-c8"}, src, instance_uuid=UUID
)
assert (empty["name"], empty["nodes"], empty["storages"], empty["networks"]) == (
"Empty",
[],
[],
[],
)
class TestNodes:
def test_a_connected_host(self, clusters):
node = _by_name(clusters[0]["nodes"])["esx01"]
assert node == {
"name": "esx01",
"status": "online",
"local": False,
"maintenance": False,
"cpu_threads": 16,
"cpu_cores": 8,
"cpu_model": "Xeon",
"cpu_flags": None,
"cpu_usage": 0.25,
"memory_total": 64 * 1024 * MB,
"memory_used": 1024 * MB,
}
def test_a_disconnected_host_keeps_its_name_and_state_but_no_capacity(self, clusters):
node = _by_name(clusters[0]["nodes"])["esx02"]
assert (node["status"], node["maintenance"]) == ("offline", False)
capacity = ("cpu_threads", "cpu_cores", "cpu_model", "cpu_usage")
assert all(node[k] is None for k in (*capacity, "memory_total", "memory_used"))
def test_a_host_in_maintenance(self, clusters):
node = _by_name(clusters[0]["nodes"])["esx03"]
assert (node["status"], node["maintenance"], node["cpu_cores"]) == ("online", True, 8)
@pytest.mark.parametrize(
("state", "status"),
[("notResponding", "offline"), ("disconnected", "offline"), (None, "unknown")],
)
def test_status_from_the_connection_state(self, src, state, status):
src.hosts[3]["runtime.connectionState"] = state
node = _standalone(src, 3)["nodes"][0]
assert node["status"] == status
@pytest.mark.parametrize(
"change",
[
lambda h: h["summary.hardware"].update(cpuMhz=0),
lambda h: h["summary.hardware"].pop("numCpuCores"),
lambda h: h.pop("summary.quickStats"),
],
)
def test_cpu_usage_is_none_when_it_cannot_be_computed(self, src, change):
change(src.hosts[0])
node = _standalone(src, 0)["nodes"][0]
assert node["cpu_usage"] is None
def test_cpu_usage_never_exceeds_one(self, src):
src.hosts[0]["summary.quickStats"]["overallCpuUsage"] = 99_999
assert _standalone(src, 0)["nodes"][0]["cpu_usage"] == 1.0
class TestStorages:
def test_shared_and_local_datastores_with_the_hosts_that_mount_them(self, clusters):
storages = _by_name(clusters[0]["storages"])
assert storages["san"] == {
"name": "san",
"type": "vmfs",
"shared": True,
"content": ["images", "iso"],
"nodes": ["esx01", "esx02", "esx03"],
"total": 10_000,
"used": 7_500,
}
assert (storages["local1"]["shared"], storages["local1"]["nodes"]) == (False, ["esx01"])
def test_an_inaccessible_datastore_is_left_out(self, clusters):
assert "gone" not in _by_name(clusters[0]["storages"])
def test_only_the_datastores_of_the_clusters_hosts(self, clusters):
assert sorted(_by_name(clusters[0]["storages"])) == ["local1", "san"]
assert [s["name"] for s in clusters[1]["storages"]] == ["local9"]
assert clusters[1]["storages"][0]["type"] == "nfs"
class TestNetworks:
def test_standard_and_distributed_port_groups(self, clusters):
networks = _by_name(clusters[0]["networks"])
assert networks["VM Network"] == {
"name": "VM Network",
"kind": "portgroup",
"vlan_aware": False,
"fixed_vlan_tag": None,
"nodes": ["esx01", "esx02", "esx03"],
}
assert networks["DC0_DVPG0"]["fixed_vlan_tag"] == 42
def test_a_port_group_on_one_host_only(self, clusters):
storage = _by_name(clusters[0]["networks"])["Storage"]
assert (storage["nodes"], storage["fixed_vlan_tag"]) == (["esx01"], 30)
def test_the_uplink_port_group_is_no_network_for_a_vm(self, clusters):
assert "DVS0-DVUplinks-8" not in _by_name(clusters[0]["networks"])
def test_a_vlan_that_differs_between_hosts_is_not_reported(self, src, clusters):
src.hosts[1]["config.network.portgroup"][0]["spec"]["vlanId"] = 7
prod = manager_clusters(COMPUTE, {"domain-c7"}, src, instance_uuid=UUID)[0]
assert _by_name(prod["networks"])["VM Network"]["fixed_vlan_tag"] is None
def test_a_trunk_port_group_has_no_fixed_tag(self, src):
src.hosts[0]["config.network.portgroup"][1]["spec"]["vlanId"] = 4095
networks = _by_name(_standalone(src, 0)["networks"])
assert networks["Storage"]["fixed_vlan_tag"] is None
class TestStandaloneHost:
def test_the_host_is_a_cluster_of_one(self, src):
cluster = _standalone(src, 3)
assert (cluster["id"], cluster["name"], cluster["quorate"]) == ("uuid-host-9", None, None)
assert [(n["name"], n["local"]) for n in cluster["nodes"]] == [("lonely", True)]
assert [s["name"] for s in cluster["storages"]] == ["local9"]
assert [n["name"] for n in cluster["networks"]] == ["VM Network"]
def test_no_id_without_a_system_uuid(self, src):
del src.hosts[3]["hardware.systemInfo"]
assert _standalone(src, 3)["id"] is None
def test_no_host_is_a_failed_read(self, src):
with pytest.raises(RuntimeError, match="no host"):
host_cluster(ClusterSources([], [], [], []))
+50 -33
View File
@@ -1,13 +1,14 @@
"""Datastores, sensors/utilisation, CDP/LLDP neighbours and raw device warnings."""
"""Datastores, sensors/utilisation, CDP/LLDP neighbours, host and license facts."""
from __future__ import annotations
import pytest
from napalm_vmware.parse.environment import environment
from napalm_vmware.parse.hosts import hypervisor_hosts
from napalm_vmware.parse.licenses import license_list
from napalm_vmware.parse.lldp import lldp_neighbors
from napalm_vmware.parse.storage import storage_pools
from napalm_vmware.parse.warnings import host_warnings
class TestStoragePools:
@@ -125,60 +126,76 @@ class TestLldpNeighbors:
assert lldp_neighbors([]) == {}
class TestHostWarnings:
class TestHypervisorHosts:
"""Facts only (netOrk #1111): which of them is a warning is the caller's call."""
def test_healthy_vcsim_host(self, esxi_host):
assert host_warnings([esxi_host], [], standalone=True) == []
assert hypervisor_hosts([esxi_host], standalone=True) == [
{
"name": "localhost.localdomain",
"connected": None,
"maintenance": False,
"config_issues": [],
"managed_by": None,
}
]
def test_maintenance_mode(self, esxi_host):
esxi_host["runtime.inMaintenanceMode"] = True
assert host_warnings([esxi_host], [], standalone=True) == [
{"code": "vmware_host_maintenance_mode", "meta": {"host": "localhost.localdomain"}}
]
assert hypervisor_hosts([esxi_host], standalone=True)[0]["maintenance"] is True
@pytest.mark.parametrize("state", ["disconnected", "notResponding"])
def test_disconnected_host_under_vcenter(self, esxi_host, state):
esxi_host["runtime.connectionState"] = state
assert host_warnings([esxi_host], [], standalone=False) == [
{
"code": "vmware_host_disconnected",
"meta": {"host": "localhost.localdomain", "state": state},
}
]
assert hypervisor_hosts([esxi_host], standalone=False)[0]["connected"] is False
def test_connected_host_under_vcenter(self, esxi_host):
assert hypervisor_hosts([esxi_host], standalone=False)[0]["connected"] is True
def test_a_standalone_host_cannot_tell(self, esxi_host):
"""A disconnected host could not have answered the ESXi driver."""
esxi_host["runtime.connectionState"] = "disconnected"
assert hypervisor_hosts([esxi_host], standalone=True)[0]["connected"] is None
def test_config_issues(self, esxi_host):
esxi_host["configIssue"] = [
{"fullFormattedMessage": "SSH for the host has been enabled"},
{"fullFormattedMessage": ""},
]
assert host_warnings([esxi_host], [], standalone=True) == [
{
"code": "vmware_host_config_issue",
"meta": {
"host": "localhost.localdomain",
"issues": ["SSH for the host has been enabled"],
},
}
assert hypervisor_hosts([esxi_host], standalone=True)[0]["config_issues"] == [
"SSH for the host has been enabled"
]
def test_standalone_driver_on_a_vcenter_managed_host(self, esxi_host):
esxi_host["summary.managementServerIp"] = "192.0.2.5"
assert host_warnings([esxi_host], [], standalone=True) == [
{"code": "vmware_host_managed_by_vcenter", "meta": {"vcenter": "192.0.2.5"}}
]
assert hypervisor_hosts([esxi_host], standalone=True)[0]["managed_by"] == "192.0.2.5"
@pytest.mark.parametrize("ip", ["", "0.0.0.0", None])
def test_unmanaged(self, esxi_host, ip):
esxi_host["summary.managementServerIp"] = ip
assert hypervisor_hosts([esxi_host], standalone=True)[0]["managed_by"] is None
def test_vcenter_driver_does_not_report_its_own_management(self, esxi_host):
esxi_host["summary.managementServerIp"] = "192.0.2.5"
assert host_warnings([esxi_host], [], standalone=False) == []
assert hypervisor_hosts([esxi_host], standalone=False)[0]["managed_by"] is None
def test_free_license_makes_the_api_read_only(self, esxi_host):
licenses = [{"editionKey": "esxBasic", "name": "VMware vSphere 8 Hypervisor"}]
assert host_warnings([esxi_host], licenses, standalone=True) == [
class TestLicenseList:
def test_the_edition_key_is_the_edition(self):
licenses = [
{
"code": "vmware_api_read_only",
"meta": {"edition": "VMware vSphere 8 Hypervisor"},
"editionKey": "esxBasic",
"name": "VMware vSphere 8 Hypervisor",
"licenseKey": "AAAAA-BBBBB-CCCCC-DDDDD-EEEEE",
}
]
assert license_list(licenses) == [
{"name": "VMware vSphere 8 Hypervisor", "status": "active", "edition": "esxBasic"}
]
def test_evaluation_license_is_not_read_only(self, esxi_host):
licenses = [{"editionKey": "eval", "name": "Evaluation Mode"}]
assert host_warnings([esxi_host], licenses, standalone=True) == []
def test_the_key_is_never_reported(self):
licenses = [{"editionKey": "eval", "name": "Evaluation Mode", "licenseKey": "00000"}]
assert "00000" not in str(license_list(licenses))
def test_none(self):
assert license_list([]) == []
+1 -1
View File
@@ -54,7 +54,7 @@ def test_lists_are_converted_elementwise():
def test_datetime_becomes_epoch_seconds():
when = datetime.datetime(2026, 1, 1, tzinfo=datetime.timezone.utc)
when = datetime.datetime(2026, 1, 1, tzinfo=datetime.UTC)
assert to_plain(when) == 1767225600.0
+41 -1
View File
@@ -5,7 +5,7 @@ from __future__ import annotations
import pytest
from napalm_vmware.provision.placement import Inventory as Inv
from napalm_vmware.provision.placement import choose_placement
from napalm_vmware.provision.placement import NodeRefused, choose_placement
def _host(moref, name, *, datastores, networks, parent="domain-c1", state="connected", maint=False):
@@ -112,3 +112,43 @@ def test_datacenter_is_found_through_nested_folders(inv):
inv.compute_resources[0]["parent"] = "group-h2"
inv.folders.append({"_moref": "group-h2", "parent": "group-h1"})
assert choose_placement(inv, storage=None, networks=["VM Network"]).datacenter_name == "DC0"
class TestNamedHost:
"""``create_vm_from_cloud_init(node=...)``: only that host is considered."""
def test_the_named_host_is_used_even_with_less_free_space_elsewhere(self, inv):
inv.hosts[0]["datastore"] = ["ds-1"]
p = choose_placement(inv, storage=None, networks=["VM Network"], host_name="esx01")
assert (p.host, p.datastore_name, p.networks) == ("host-1", "local1", ["net-1"])
def test_the_best_datastore_of_the_named_host(self, inv):
p = choose_placement(inv, storage=None, networks=["VM Network"], host_name="esx02")
assert (p.host, p.datastore_name) == ("host-2", "san")
def test_an_unknown_host(self, inv):
with pytest.raises(NodeRefused, match="no host named 'esx99'"):
choose_placement(inv, storage=None, networks=["VM Network"], host_name="esx99")
@pytest.mark.parametrize(
("change", "message"),
[
(lambda h: h.update({"runtime.inMaintenanceMode": True}), "maintenance"),
(lambda h: h.update({"runtime.connectionState": "disconnected"}), "not connected"),
],
)
def test_a_host_that_cannot_take_a_vm(self, inv, change, message):
change(inv.hosts[1])
with pytest.raises(NodeRefused, match=f"esx02.*{message}"):
choose_placement(inv, storage=None, networks=["VM Network"], host_name="esx02")
def test_a_host_without_the_networks(self, inv):
with pytest.raises(NodeRefused, match="esx02 does not see"):
choose_placement(inv, storage=None, networks=["DC0_DVPG0"], host_name="esx02")
def test_a_host_without_the_datastore(self, inv):
with pytest.raises(NodeRefused, match="esx02 does not see datastore local1"):
choose_placement(inv, storage="local1", networks=["VM Network"], host_name="esx02")
def test_a_refused_host_is_a_value_error(self):
assert issubclass(NodeRefused, ValueError)
+10 -11
View File
@@ -6,8 +6,11 @@ import io
import pycdlib
import yaml
from napalm_device_types import provisioning as generic
from napalm_vmware.provision.seed import meta_data, network_config, nocloud_iso, user_data
from napalm_vmware import provisioning as prov
from napalm_vmware.provision import seed
from napalm_vmware.provision.seed import meta_data, nocloud_iso, user_data
class TestUserData:
@@ -34,17 +37,13 @@ def test_meta_data():
class TestNetworkConfig:
def test_dhcp_nics_matched_by_mac(self):
cfg = network_config([("00:50:56:aa:bb:cc", True), ("00:50:56:aa:bb:dd", False)])
assert cfg == {
"version": 2,
"ethernets": {
"nic0": {"match": {"macaddress": "00:50:56:aa:bb:cc"}, "dhcp4": True},
},
}
"""Written by napalm-device-types, which Proxmox uses as well (NetOrk/netork#794)."""
def test_no_dhcp_nic_means_no_network_config(self):
assert network_config([("00:50:56:aa:bb:cc", False)]) is None
def test_the_seed_is_built_with_the_generic_network_config(self):
assert prov.network_config is generic.network_config
def test_no_copy_of_it_is_left_here(self):
assert not hasattr(seed, "network_config")
def _read(iso: bytes, name: str) -> str:
+56 -1
View File
@@ -11,7 +11,7 @@ import yaml
from napalm_vmware import VmwareEsxiDriver
from napalm_vmware import provisioning as prov
from napalm_vmware.provision.placement import Placement
from napalm_vmware.provision.placement import NodeRefused, Placement
from tests.conftest import FakeInventory
PLACE = Placement(
@@ -141,12 +141,60 @@ class TestCreate:
_create(driver)
staged.discard.assert_called_once_with("vm-99")
def test_no_cpu_type_is_the_normal_case(self, driver, staged):
assert _create(driver, cpu_type=None)["vmid"] == "uuid-99"
def test_a_cpu_type_is_refused_before_anything_happens(self, driver, staged):
"""VMware sets CPU compatibility per cluster (EVC), not per VM, so a
requested model cannot be honoured -- and is not silently dropped."""
with pytest.raises(ValueError, match="CPU type"):
_create(driver, cpu_type="host")
staged.cache.return_value.vmdk.assert_not_called()
staged.import_ovf.assert_not_called()
@pytest.mark.parametrize("guest_os", ["freebsd", "openbsd"])
def test_a_guest_other_than_linux_is_refused_before_anything_happens(
self, driver, staged, guest_os
):
with pytest.raises(ValueError, match=guest_os):
_create(driver, guest_os=guest_os)
staged.cache.return_value.vmdk.assert_not_called()
staged.import_ovf.assert_not_called()
def test_linux_is_the_default_guest(self, driver, staged):
assert _create(driver, guest_os="linux")["vmid"] == "uuid-99"
def test_placement_refusal_is_a_runtime_error(self, driver, staged):
with patch.object(prov, "choose_placement", side_effect=ValueError("no host")):
with pytest.raises(RuntimeError, match="no host"):
_create(driver)
staged.import_ovf.assert_not_called()
def test_an_image_refusal_is_a_runtime_error(self, driver, staged):
staged.cache.return_value.vmdk.side_effect = ValueError("checksum mismatch")
with pytest.raises(RuntimeError, match="checksum mismatch"):
_create(driver)
staged.import_ovf.assert_not_called()
def test_no_node_leaves_the_host_to_placement(self, driver, staged):
with patch.object(prov, "choose_placement", return_value=PLACE) as choose:
_create(driver)
assert choose.call_args.kwargs["host_name"] is None
def test_the_node_is_the_only_host_placement_considers(self, driver, staged):
with patch.object(prov, "choose_placement", return_value=PLACE) as choose:
assert _create(driver, node="esx01")["node"] == "esx01"
assert choose.call_args.kwargs["host_name"] == "esx01"
def test_a_refused_node_is_a_value_error_before_anything_happens(self, driver, staged):
refusal = NodeRefused("There is no host named 'esx99'")
with patch.object(prov, "choose_placement", side_effect=refusal):
with pytest.raises(ValueError, match="esx99") as raised:
_create(driver, node="esx99")
assert not isinstance(raised.value, RuntimeError)
staged.cache.return_value.vmdk.assert_not_called()
staged.import_ovf.assert_not_called()
MAC = "00:0c:29:39:31:62"
@@ -235,6 +283,13 @@ class TestFinishVm:
_, spec = self._finish(driver, esxi_data, [{"bridge": "VM Network"}], disk_gb=1)
assert not any(type(c.device).__name__.endswith("VirtualDisk") for c in spec.deviceChange)
def test_a_vm_without_an_adapter_per_requested_nic_is_refused(self, driver, esxi_data):
# The OVF asks for one adapter per NIC; a VM that came back with fewer would
# get a seed that leaves a NIC unconfigured. create_vm_from_cloud_init
# discards it on any error from here.
with pytest.raises(ValueError):
self._finish(driver, esxi_data, [{"bridge": "VM Network"}, {"bridge": "VM Network"}])
class TestDestroyAndStatus:
def test_destroy_powers_off_first(self, driver, esxi_data):
+43 -1
View File
@@ -50,7 +50,8 @@ def test_esxi_reads(esxi):
assert esxi.get_vm_storage_pools()
assert esxi.get_virtual_networks()
assert "cpu" in esxi.get_environment()
assert isinstance(esxi.get_device_warnings(), list)
assert isinstance(esxi.get_hypervisor_hosts(), list)
assert isinstance(esxi.get_licenses(), list)
assert isinstance(esxi.get_lldp_neighbors(), dict)
@@ -149,3 +150,44 @@ def test_provision_and_destroy(which, image_url, tmp_path, request):
finally:
driver.destroy_vm(result["vmid"])
assert not any(vm["vmid"] == result["vmid"] for vm in driver.get_vms())
def test_vcenter_clusters(vcenter):
clusters = vcenter.get_clusters()
named = [c for c in clusters if c["name"]]
assert [c["name"] for c in named] == ["DC0_C0"]
assert len(named[0]["nodes"]) == 3
assert any(c["name"] is None and len(c["nodes"]) == 1 for c in clusters)
assert all(c["id"] and "/" in c["id"] for c in clusters)
assert "DC0_DVPG0" in {n["name"] for n in named[0]["networks"]}
assert named[0]["storages"]
def test_esxi_cluster(esxi):
(cluster,) = esxi.get_clusters()
(node,) = cluster["nodes"]
assert (cluster["name"], node["local"], node["status"]) == (None, True, "online")
assert cluster["id"]
assert node["cpu_cores"] and node["memory_total"]
assert [n["name"] for n in cluster["networks"]] == ["VM Network"]
def test_provision_on_a_named_node(vcenter, image_url, tmp_path):
vcenter._image_cache_dir = tmp_path / "cache"
(cluster,) = [c for c in vcenter.get_clusters() if c["name"]]
node = cluster["nodes"][-1]["name"]
kwargs = dict(
image_url=image_url,
cpu=1,
memory=512,
nics=[{"bridge": "VM Network", "dhcp": True}],
cloud_init_config={},
)
with pytest.raises(ValueError, match="no host named"):
vcenter.create_vm_from_cloud_init("netork-nowhere", node="nope", **kwargs)
result = vcenter.create_vm_from_cloud_init("netork-pinned", node=node, **kwargs)
try:
assert result["node"] == node
assert next(vm for vm in vcenter.get_vms() if vm["vmid"] == result["vmid"])["node"] == node
finally:
vcenter.destroy_vm(result["vmid"])