Author SHA1 Message Date
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
19 changed files with 362 additions and 158 deletions

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
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
secrets:
PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }}
+26
View File
@@ -7,6 +7,20 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased] ## [Unreleased]
## [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 ### Added
- VM provisioning (`create_vm_from_cloud_init`, `destroy_vm`, - VM provisioning (`create_vm_from_cloud_init`, `destroy_vm`,
`get_vm_status`, `get_network_targets`, `get_image_storages`) from qcow2/raw `get_vm_status`, `get_network_targets`, `get_image_storages`) from qcow2/raw
@@ -15,6 +29,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- `reboot_host` on ESXi, refused outside maintenance mode. - `reboot_host` on ESXi, refused outside maintenance mode.
- Declares `open-vm-tools` as the guest agent for provisioned VMs. - 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 ## [0.1.0] - 2026-09-24
### Added ### Added
+22 -9
View File
@@ -1,7 +1,7 @@
# napalm-vmware # napalm-vmware
NAPALM drivers for VMware vSphere, speaking the vSphere API through 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 | | Driver | Endpoint | Device in netOrk |
|---|---|---| |---|---|---|
@@ -29,7 +29,8 @@ hardware**: see [Harvesting fixtures](#harvesting-fixtures).
| `get_vm_snapshots`, `create/delete/rollback_vm_snapshot` | ✅ | ✅ | snapshot tree | | `get_vm_snapshots`, `create/delete/rollback_vm_snapshot` | ✅ | ✅ | snapshot tree |
| `get_vm_storage_pools` | ✅ | ✅ | datastores | | `get_vm_storage_pools` | ✅ | ✅ | datastores |
| `get_virtual_networks` | ✅ | ✅ (+ dvPortgroups) | port groups | | `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 |
| `reboot_host` | ✅ (maintenance mode only) | — | `RebootHost_Task` | | `reboot_host` | ✅ (maintenance mode only) | — | `RebootHost_Task` |
| `create_vm_from_cloud_init`, `destroy_vm`, `get_vm_status` | ✅ | ✅ | see [Provisioning](#provisioning) | | `create_vm_from_cloud_init`, `destroy_vm`, `get_vm_status` | ✅ | ✅ | see [Provisioning](#provisioning) |
| `get_network_targets`, `get_image_storages` | ✅ | ✅ | port groups, datastores | | `get_network_targets`, `get_image_storages` | ✅ | ✅ | port groups, datastores |
@@ -56,8 +57,10 @@ Unverified assumptions, to be checked against real hardware:
## Install ## Install
Python 3.10 or later.
```bash ```bash
pip install -e vendor/napalm-device-types/ -e vendor/napalm-vmware/ pip install napalm-vmware
``` ```
## Usage ## Usage
@@ -65,8 +68,9 @@ pip install -e vendor/napalm-device-types/ -e vendor/napalm-vmware/
```python ```python
from napalm_vmware import VmwareEsxiDriver from napalm_vmware import VmwareEsxiDriver
driver = VmwareEsxiDriver("esx01.example.lan", "root", "secret", driver = VmwareEsxiDriver(
optional_args={"verify_ssl": False}) "esx01.example.lan", "root", "secret", optional_args={"verify_ssl": False}
)
driver.open() driver.open()
print(driver.get_facts()) print(driver.get_facts())
for vm in driver.get_vms(): for vm in driver.get_vms():
@@ -84,8 +88,11 @@ by two VMs is refused rather than guessed.
## Tests ## Tests
The rules are in [STANDARDS.md](https://git.netork.io/NAPALM/driver-standard/src/branch/main/STANDARDS.md).
```bash ```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: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 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 VCSIM_VCENTER_PORT=8989 VCSIM_ESXI_PORT=8990 pytest -m vcsim
@@ -123,7 +130,9 @@ offers for Proxmox (qcow2/raw):
A port group fixes its VLAN, so `get_network_targets` reports each one with 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 `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 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 Unverified until #305: that each distribution's cloud kernel carries the
PVSCSI and VMXNET3 drivers. PVSCSI and VMXNET3 drivers.
@@ -146,5 +155,9 @@ The MoRef is reported alongside as `moref`.
hosts. Reporting them on the vCenter would attach their MACs to the wrong hosts. Reporting them on the vCenter would attach their MACs to the wrong
device. Add a host with `vmware_esxi` to see its NICs. device. Add a host with `vmware_esxi` to see its NICs.
**Warnings are raw.** `get_device_warnings()` returns `{code, meta}` only; **Facts, not warnings.** The driver names no warnings. `get_hypervisor_hosts()`
what a code means is decided in netOrk's `WARNING_CATALOG`. 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.
+11 -5
View File
@@ -6,8 +6,10 @@ from pathlib import Path
from typing import Any, ClassVar from typing import Any, ClassVar
from napalm.base.exceptions import ConnectionException from napalm.base.exceptions import ConnectionException
from napalm_device_types import HypervisorDriver from napalm_device_types import HypervisorDriver, LicenseMixin
from napalm_device_types.models import ( from napalm_device_types.models import (
HypervisorHostDict,
LicenseDict,
SnapshotDict, SnapshotDict,
StorageVolumeDict, StorageVolumeDict,
VirtualNetworkDict, VirtualNetworkDict,
@@ -17,12 +19,13 @@ from napalm_device_types.models import (
from napalm_vmware import _session, paths from napalm_vmware import _session, paths
from napalm_vmware._inventory import Inventory from napalm_vmware._inventory import Inventory
from napalm_vmware.parse.environment import environment 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.networks import NetworkIndex, network_index, virtual_networks
from napalm_vmware.parse.snapshots import snapshot_list from napalm_vmware.parse.snapshots import snapshot_list
from napalm_vmware.parse.storage import storage_pools from napalm_vmware.parse.storage import storage_pools
from napalm_vmware.parse.vm_config import vm_config from napalm_vmware.parse.vm_config import vm_config
from napalm_vmware.parse.vms import vm_list 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 from napalm_vmware.provision.image import DEFAULT_CACHE_DIR
_DEFAULT_PORT = 443 _DEFAULT_PORT = 443
@@ -30,7 +33,7 @@ _DEFAULT_PORT = 443
_DRIVER_FOR_API = {"HostAgent": "vmware_esxi", "VirtualCenter": "vmware_vcenter"} _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``.""" """Shared implementation. Concrete drivers set ``API_TYPE`` and ``STANDALONE``."""
VENDOR = "VMware" VENDOR = "VMware"
@@ -154,5 +157,8 @@ class VmwareBaseDriver(HypervisorDriver):
def get_environment(self) -> dict[str, Any]: def get_environment(self) -> dict[str, Any]:
return environment(self._hosts()) return environment(self._hosts())
def get_device_warnings(self) -> list[dict[str, Any]]: def get_hypervisor_hosts(self) -> list[HypervisorHostDict]:
return host_warnings(self._hosts(), self._inventory.licenses(), standalone=self.STANDALONE) return hypervisor_hosts(self._hosts(), standalone=self.STANDALONE)
def get_licenses(self) -> list[LicenseDict]:
return license_list(self._inventory.licenses())
+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 from typing import Any
_DEFAULT_MTU = 1500 _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]: 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
]
-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 -3
View File
@@ -12,7 +12,9 @@ import hashlib
import json import json
import os import os
import shutil import shutil
import subprocess
# qemu-img is run with a fixed argv and no shell (see below).
import subprocess # nosec B404
import tempfile import tempfile
from collections.abc import Callable from collections.abc import Callable
from pathlib import Path 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: 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(), _qemu_img(),
"convert", "convert",
@@ -64,7 +67,8 @@ def convert_to_vmdk(src: Path, dst: Path) -> None:
def virtual_size(path: Path) -> int: def virtual_size(path: Path) -> int:
"""The disk size the image describes, in bytes (not the file size).""" """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)], [_qemu_img(), "info", "--output", "json", str(path)],
check=True, check=True,
capture_output=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 __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 _HW_VERSION = "vmx-13" # ESXi 6.5 and later
_GUEST_OS = "otherLinux64Guest" _GUEST_OS = "otherLinux64Guest"
-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) 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: def nocloud_iso(user: str, meta: str, network: dict[str, Any] | None) -> bytes:
"""An ISO 9660 image (Rock Ridge + Joliet) holding the seed files.""" """An ISO 9660 image (Rock Ridge + Joliet) holding the seed files."""
files = {"user-data": user, "meta-data": meta} files = {"user-data": user, "meta-data": meta}
+25 -10
View File
@@ -22,6 +22,7 @@ from napalm_device_types.models import (
VMProvisionResultDict, VMProvisionResultDict,
VMStatusDict, VMStatusDict,
) )
from napalm_device_types.provisioning import GuestAgents, network_config
from pyVmomi import vim from pyVmomi import vim
from napalm_vmware import paths from napalm_vmware import paths
@@ -35,7 +36,7 @@ from napalm_vmware.provision.image import ImageCache
from napalm_vmware.provision.ovf import ovf_descriptor from napalm_vmware.provision.ovf import ovf_descriptor
from napalm_vmware.provision.placement import Inventory as PlacementInventory from napalm_vmware.provision.placement import Inventory as PlacementInventory
from napalm_vmware.provision.placement import Placement, choose_placement 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.seed import meta_data, nocloud_iso, user_data
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
@@ -48,11 +49,14 @@ _STATUS = {"poweredOn": "running", "poweredOff": "stopped", "suspended": "suspen
class VmwareProvisioningMixin: class VmwareProvisioningMixin:
"""Mixed into both drivers ahead of :class:`VmwareBaseDriver`.""" """Mixed into both drivers ahead of :class:`VmwareBaseDriver`."""
GUEST_AGENT_PACKAGES: tuple[str, ...] = ("open-vm-tools",) # Linux only: BSD guests on VMware are optional (NetOrk/netork#801). The
# The unit is open-vm-tools on Debian/Ubuntu and vmtoolsd on EL/Fedora. # unit is open-vm-tools on Debian/Ubuntu and vmtoolsd on EL/Fedora.
GUEST_AGENT_RUNCMD: tuple[str, ...] = ( GUEST_AGENTS: GuestAgents = {
"systemctl enable --now open-vm-tools || systemctl enable --now vmtoolsd", "linux": (
) ("open-vm-tools",),
("systemctl enable --now open-vm-tools || systemctl enable --now vmtoolsd",),
),
}
hostname: str hostname: str
_port: int _port: int
@@ -147,9 +151,17 @@ class VmwareProvisioningMixin:
ssh_public_keys: list[str] | None = None, ssh_public_keys: list[str] | None = None,
disk_resize_gb: int | None = None, disk_resize_gb: int | None = None,
storage: str | None = None, storage: str | None = None,
cpu_type: str | None = None,
guest_os: str = "linux",
download_timeout: int = 300, download_timeout: int = 300,
timeout: int = 180, timeout: int = 180,
) -> VMProvisionResultDict: ) -> 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) self._check_nics(nics)
try: try:
vmdk, image_size = ImageCache(self._image_cache_dir).vmdk( vmdk, image_size = ImageCache(self._image_cache_dir).vmdk(
@@ -240,7 +252,7 @@ class VmwareProvisioningMixin:
try: try:
lease.HttpNfcLeaseAbort() lease.HttpNfcLeaseAbort()
except Exception: # noqa: BLE001 - the original error is the one to report 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 raise
return info["info"]["entity"] return info["info"]["entity"]
@@ -267,13 +279,16 @@ class VmwareProvisioningMixin:
changes = _mac_changes(adapters, nics) + _disk_growth(devices, disk_gb, image_size) changes = _mac_changes(adapters, nics) + _disk_growth(devices, disk_gb, image_size)
macs = [ macs = [
(nic.get("mac") or adapter.macAddress or "").lower() (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( seed = nocloud_iso(
user, user,
meta_data(name, f"iid-{uuid.uuid4()}"), meta_data(name, f"iid-{uuid.uuid4()}"),
network_config( 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]) vm_dir = posixpath.dirname(str(props["config.files.vmPathName"]).split("] ", 1)[1])
@@ -353,7 +368,7 @@ class VmwareProvisioningMixin:
def _mac_changes(adapters: list[Any], nics: list[NICConfigDict]) -> list[Any]: def _mac_changes(adapters: list[Any], nics: list[NICConfigDict]) -> list[Any]:
"""Device edits pinning the MACs the caller asked for.""" """Device edits pinning the MACs the caller asked for."""
changes = [] changes = []
for adapter, nic in zip(adapters, nics): for adapter, nic in zip(adapters, nics, strict=True):
if not nic.get("mac"): if not nic.get("mac"):
continue continue
adapter.addressType = "manual" adapter.addressType = "manual"
+45 -12
View File
@@ -1,14 +1,14 @@
[build-system] [build-system]
requires = ["setuptools>=68", "wheel"] requires = ["setuptools>=77"]
build-backend = "setuptools.build_meta" build-backend = "setuptools.build_meta"
[project] [project]
name = "napalm-vmware" name = "napalm-vmware"
version = "0.1.0" version = "0.3.0"
description = "NAPALM drivers for VMware ESXi hosts and vCenter Server (vSphere API via pyVmomi)" description = "NAPALM drivers for VMware ESXi hosts and vCenter Server (vSphere API via pyVmomi)"
readme = "README.md" readme = "README.md"
requires-python = ">=3.10" requires-python = ">=3.10"
license = { text = "Apache-2.0" } license = "Apache-2.0"
authors = [ authors = [
{ name = "Christian Manivong", email = "christian@manivong.de" }, { name = "Christian Manivong", email = "christian@manivong.de" },
] ]
@@ -17,19 +17,19 @@ classifiers = [
"Development Status :: 3 - Alpha", "Development Status :: 3 - Alpha",
"Intended Audience :: Developers", "Intended Audience :: Developers",
"Intended Audience :: System Administrators", "Intended Audience :: System Administrators",
"License :: OSI Approved :: Apache Software License",
"Operating System :: OS Independent", "Operating System :: OS Independent",
"Programming Language :: Python :: 3", "Programming Language :: Python :: 3",
"Programming Language :: Python :: 3.10", "Programming Language :: Python :: 3.10",
"Programming Language :: Python :: 3.11", "Programming Language :: Python :: 3.11",
"Programming Language :: Python :: 3.12", "Programming Language :: Python :: 3.12",
"Programming Language :: Python :: 3.13",
"Topic :: System :: Networking", "Topic :: System :: Networking",
"Topic :: System :: Systems Administration", "Topic :: System :: Systems Administration",
"Typing :: Typed", "Typing :: Typed",
] ]
dependencies = [ dependencies = [
"napalm>=5.0.0", "napalm>=5.0.0",
"napalm-device-types>=2.0.0", "napalm-device-types>=4.21.1",
"pyvmomi>=8.0.1", "pyvmomi>=8.0.1",
# Provisioning: download the image, write the NoCloud seed ISO and its YAML. # Provisioning: download the image, write the NoCloud seed ISO and its YAML.
"requests>=2.31", "requests>=2.31",
@@ -39,10 +39,10 @@ dependencies = [
[project.optional-dependencies] [project.optional-dependencies]
dev = [ dev = [
"pytest", "pytest>=8",
"pytest-cov", "pytest-cov>=5",
"ruff", "mypy>=1.11",
"mypy", "ruff>=0.6",
] ]
[project.entry-points."napalm.drivers"] [project.entry-points."napalm.drivers"]
@@ -51,6 +51,8 @@ vmware_vcenter = "napalm_vmware:VmwareVcenterDriver"
[project.urls] [project.urls]
Repository = "https://git.netork.io/NAPALM/napalm-vmware" 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] [tool.setuptools.packages.find]
where = ["."] where = ["."]
@@ -69,11 +71,42 @@ markers = [
line-length = 100 line-length = 100
target-version = "py310" target-version = "py310"
# Same rule set the netOrk repo gates on.
[tool.ruff.lint] [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] [tool.mypy]
python_version = "3.10" python_version = "3.10"
warn_unused_configs = true 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 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
+31
View File
@@ -0,0 +1,31 @@
{
"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,
"napalm_vmware/provision/placement.py::choose_placement": 16
},
"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": 57
},
"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": []
}
+25 -5
View File
@@ -72,7 +72,8 @@ class TestIdentity:
"rollback_vm_snapshot", "rollback_vm_snapshot",
"get_vm_storage_pools", "get_vm_storage_pools",
"get_virtual_networks", "get_virtual_networks",
"get_device_warnings", "get_hypervisor_hosts",
"get_licenses",
], ],
) )
@pytest.mark.parametrize("cls", DRIVERS) @pytest.mark.parametrize("cls", DRIVERS)
@@ -94,8 +95,14 @@ class TestIdentity:
assert callable(getattr(cls, method, None)) assert callable(getattr(cls, method, None))
@pytest.mark.parametrize("cls", DRIVERS) @pytest.mark.parametrize("cls", DRIVERS)
def test_declares_its_guest_agent(self, cls): def test_provisions_linux_guests_with_open_vm_tools(self, cls):
assert cls.GUEST_AGENT_PACKAGES == ("open-vm-tools",) """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: class TestOptionalArgs:
@@ -198,9 +205,22 @@ class TestEsxiGetters:
with pytest.raises(RuntimeError, match="no host"): with pytest.raises(RuntimeError, match="no host"):
esxi.get_facts() esxi.get_facts()
def test_warnings(self, esxi, esxi_host): def test_host_facts(self, esxi, esxi_host):
esxi_host["runtime.inMaintenanceMode"] = True 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): def test_storage_and_networks(self, esxi):
assert list(esxi.get_vm_storage_pools()) assert list(esxi.get_vm_storage_pools())
+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 from __future__ import annotations
import pytest import pytest
from napalm_vmware.parse.environment import environment 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.lldp import lldp_neighbors
from napalm_vmware.parse.storage import storage_pools from napalm_vmware.parse.storage import storage_pools
from napalm_vmware.parse.warnings import host_warnings
class TestStoragePools: class TestStoragePools:
@@ -125,60 +126,76 @@ class TestLldpNeighbors:
assert lldp_neighbors([]) == {} 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): 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): def test_maintenance_mode(self, esxi_host):
esxi_host["runtime.inMaintenanceMode"] = True esxi_host["runtime.inMaintenanceMode"] = True
assert host_warnings([esxi_host], [], standalone=True) == [ assert hypervisor_hosts([esxi_host], standalone=True)[0]["maintenance"] is True
{"code": "vmware_host_maintenance_mode", "meta": {"host": "localhost.localdomain"}}
]
@pytest.mark.parametrize("state", ["disconnected", "notResponding"]) @pytest.mark.parametrize("state", ["disconnected", "notResponding"])
def test_disconnected_host_under_vcenter(self, esxi_host, state): def test_disconnected_host_under_vcenter(self, esxi_host, state):
esxi_host["runtime.connectionState"] = state esxi_host["runtime.connectionState"] = state
assert host_warnings([esxi_host], [], standalone=False) == [ assert hypervisor_hosts([esxi_host], standalone=False)[0]["connected"] is False
{
"code": "vmware_host_disconnected", def test_connected_host_under_vcenter(self, esxi_host):
"meta": {"host": "localhost.localdomain", "state": state}, 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): def test_config_issues(self, esxi_host):
esxi_host["configIssue"] = [ esxi_host["configIssue"] = [
{"fullFormattedMessage": "SSH for the host has been enabled"}, {"fullFormattedMessage": "SSH for the host has been enabled"},
{"fullFormattedMessage": ""}, {"fullFormattedMessage": ""},
] ]
assert host_warnings([esxi_host], [], standalone=True) == [ assert hypervisor_hosts([esxi_host], standalone=True)[0]["config_issues"] == [
{ "SSH for the host has been enabled"
"code": "vmware_host_config_issue",
"meta": {
"host": "localhost.localdomain",
"issues": ["SSH for the host has been enabled"],
},
}
] ]
def test_standalone_driver_on_a_vcenter_managed_host(self, esxi_host): def test_standalone_driver_on_a_vcenter_managed_host(self, esxi_host):
esxi_host["summary.managementServerIp"] = "192.0.2.5" esxi_host["summary.managementServerIp"] = "192.0.2.5"
assert host_warnings([esxi_host], [], standalone=True) == [ assert hypervisor_hosts([esxi_host], standalone=True)[0]["managed_by"] == "192.0.2.5"
{"code": "vmware_host_managed_by_vcenter", "meta": {"vcenter": "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): def test_vcenter_driver_does_not_report_its_own_management(self, esxi_host):
esxi_host["summary.managementServerIp"] = "192.0.2.5" 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"}] class TestLicenseList:
assert host_warnings([esxi_host], licenses, standalone=True) == [ def test_the_edition_key_is_the_edition(self):
licenses = [
{ {
"code": "vmware_api_read_only", "editionKey": "esxBasic",
"meta": {"edition": "VMware vSphere 8 Hypervisor"}, "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): def test_the_key_is_never_reported(self):
licenses = [{"editionKey": "eval", "name": "Evaluation Mode"}] licenses = [{"editionKey": "eval", "name": "Evaluation Mode", "licenseKey": "00000"}]
assert host_warnings([esxi_host], licenses, standalone=True) == [] assert "00000" not in str(license_list(licenses))
def test_none(self):
assert license_list([]) == []
+10 -11
View File
@@ -6,8 +6,11 @@ import io
import pycdlib import pycdlib
import yaml 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: class TestUserData:
@@ -34,17 +37,13 @@ def test_meta_data():
class TestNetworkConfig: class TestNetworkConfig:
def test_dhcp_nics_matched_by_mac(self): """Written by napalm-device-types, which Proxmox uses as well (NetOrk/netork#794)."""
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},
},
}
def test_no_dhcp_nic_means_no_network_config(self): def test_the_seed_is_built_with_the_generic_network_config(self):
assert network_config([("00:50:56:aa:bb:cc", False)]) is None 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: def _read(iso: bytes, name: str) -> str:
+30
View File
@@ -141,6 +141,29 @@ class TestCreate:
_create(driver) _create(driver)
staged.discard.assert_called_once_with("vm-99") 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): def test_placement_refusal_is_a_runtime_error(self, driver, staged):
with patch.object(prov, "choose_placement", side_effect=ValueError("no host")): with patch.object(prov, "choose_placement", side_effect=ValueError("no host")):
with pytest.raises(RuntimeError, match="no host"): with pytest.raises(RuntimeError, match="no host"):
@@ -235,6 +258,13 @@ class TestFinishVm:
_, spec = self._finish(driver, esxi_data, [{"bridge": "VM Network"}], disk_gb=1) _, 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) 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: class TestDestroyAndStatus:
def test_destroy_powers_off_first(self, driver, esxi_data): def test_destroy_powers_off_first(self, driver, esxi_data):
+2 -1
View File
@@ -50,7 +50,8 @@ def test_esxi_reads(esxi):
assert esxi.get_vm_storage_pools() assert esxi.get_vm_storage_pools()
assert esxi.get_virtual_networks() assert esxi.get_virtual_networks()
assert "cpu" in esxi.get_environment() 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) assert isinstance(esxi.get_lldp_neighbors(), dict)