20 Commits
Author SHA1 Message Date
christianmanivong 8339e7b548 Merge pull request 'feat: get_web_login_auth on the vCenter (0.6.0)' (#14) from feature/web-login-auth-662 into main
driver / test (3.13) (push) Successful in 53s
driver / standard (push) Successful in 16s
driver / lint (push) Successful in 13s
driver / lowest (push) Successful in 29s
driver / types (push) Successful in 1m9s
driver / test (3.12) (push) Successful in 1m11s
driver / build (push) Successful in 27s
driver / security (push) Successful in 59s
driver / publish (push) Successful in 25s
CI / driver (push) Successful in 5m51s
2026-11-29 22:41:24 +00:00
Christian Manivong 3275f06615 refactor: split web_login_sources so it stays within the complexity ratchet (NetOrk/netork#662)
driver / lint (pull_request) Successful in 13s
driver / standard (pull_request) Successful in 14s
driver / lowest (pull_request) Successful in 51s
driver / types (pull_request) Successful in 1m24s
driver / test (3.13) (pull_request) Successful in 1m12s
driver / test (3.12) (pull_request) Successful in 1m26s
driver / build (pull_request) Successful in 32s
driver / security (pull_request) Successful in 1m10s
CI / driver (pull_request) Successful in 2m15s
driver / publish (pull_request) Skipped
2026-11-29 23:30:19 +01:00
Christian Manivong 6a66c05f5e feat: read the identity providers best effort; a refused list is federation not read (NetOrk/netork#662)
driver / lint (pull_request) Successful in 15s
driver / standard (pull_request) Failing after 17s
driver / lowest (pull_request) Successful in 34s
driver / test (3.12) (pull_request) Successful in 1m3s
driver / types (pull_request) Successful in 1m5s
driver / test (3.13) (pull_request) Successful in 1m2s
driver / build (pull_request) Successful in 24s
driver / security (pull_request) Successful in 1m8s
CI / driver (pull_request) Failing after 1m59s
driver / publish (pull_request) Skipped
Listing the providers needs VcIdentityProviders.Manage besides .Read,
which allows changing the identity provider configuration. The verdict is
not assessed either way, so the driver no longer needs it: a 401/403 on
GET /api/vcenter/identity/providers yields the SSO domains plus one
source, "identity federation (not read)" (federation, unknown), instead
of an error. PermissionError stays for a refused domainList; any other
error of the REST read is raised as before. Part of 0.6.0, not yet tagged.
2026-11-29 22:41:02 +01:00
Christian Manivong cf4d115475 chore(release): 0.6.0
driver / lint (pull_request) Successful in 14s
driver / standard (pull_request) Successful in 15s
driver / lowest (pull_request) Successful in 34s
driver / types (pull_request) Successful in 1m3s
driver / test (3.12) (pull_request) Successful in 1m6s
driver / test (3.13) (pull_request) Successful in 57s
driver / build (pull_request) Successful in 24s
driver / security (pull_request) Successful in 59s
CI / driver (pull_request) Successful in 1m48s
driver / publish (pull_request) Skipped
2026-11-29 20:10:03 +01:00
Christian Manivong ab18ca87ca feat: get_web_login_auth on the vCenter, a source per provider and SSO domain (NetOrk/netork#662)
The vCenter driver reads how people log in to the vSphere Client, in
napalm-device-types' WebLoginAuthDict: each identity provider of identity
federation (GET /api/vcenter/identity/providers) is a source that decides
itself (external), the default first; each SSO domain the vSphere API names
(UserDirectory.domainList) is a source whose second factor cannot be read
(unknown), since smart card and RSA SecurID live in SSO's authentication
policy, which neither API exposes.

Listing the providers needs VcIdentityProviders.Read and .Manage; without
them the vCenter answers 403 and the driver raises PermissionError naming
them. The REST read logs in to /api/session with the same account and logs
out after. The ESXi driver has no reader.
2026-11-29 20:09:55 +01:00
christianmanivong e1677bebb2 Merge pull request 'chore(release): 0.5.0' (#13) from feature/pve93-2728 into main
driver / types (push) Successful in 1m8s
driver / standard (push) Successful in 17s
driver / lint (push) Successful in 16s
driver / test (3.12) (push) Successful in 1m7s
driver / test (3.13) (push) Successful in 1m1s
driver / lowest (push) Successful in 36s
driver / build (push) Successful in 30s
driver / security (push) Successful in 1m12s
driver / publish (push) Successful in 34s
CI / driver (push) Successful in 6m46s
2026-11-26 17:12:08 +00:00
Christian Manivong ebf437dac6 chore(release): 0.5.0
driver / standard (pull_request) Successful in 18s
driver / lint (pull_request) Successful in 14s
driver / types (pull_request) Successful in 1m7s
driver / test (3.12) (pull_request) Successful in 1m9s
driver / test (3.13) (pull_request) Successful in 1m2s
driver / lowest (pull_request) Successful in 32s
driver / build (pull_request) Successful in 30s
driver / security (pull_request) Successful in 1m8s
CI / driver (pull_request) Successful in 2m49s
driver / publish (pull_request) Skipped
2026-11-26 18:05:27 +01:00
Christian Manivong 005575d18e feat: get_vms reports the instance UUID as the guest uid (NetOrk/netork#2728) 2026-11-26 17:26:57 +01:00
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
29 changed files with 1472 additions and 50 deletions

No files matched your search

+2
View File
@@ -11,5 +11,7 @@ jobs:
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 }}
+57
View File
@@ -7,6 +7,63 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased]
## [0.6.0] - 2026-11-29
### Added
- `get_web_login_auth()` on the vCenter driver (napalm-device-types 4.50.0's
`WebLoginAuthDict`, NetOrk/netork#662): how people log in to the vSphere Client.
Each identity provider of identity federation (`GET /api/vcenter/identity/providers`)
is a source that decides itself (`external`), the default one first; each SSO domain
the vSphere API names (`UserDirectory.domainList`: the system domain, `localos`, each
AD or LDAP identity source) is a source whose second factor cannot be read
(`unknown`): smart card and RSA SecurID live in SSO's authentication policy, which
neither API exposes. Reading the providers is best effort: the vCenter lists them only
to an account with `VcIdentityProviders.Read` **and** `VcIdentityProviders.Manage`.
*Manage* allows changing the identity provider configuration, and the verdict is "not
assessed" either way, so it is not required, and granting it is not advised. When the
list is refused (401/403), the reading is the SSO domains plus one source, `identity
federation (not read)` (`federation`, `unknown`). With both privileges the providers
are named instead. `PermissionError` is raised only when `domainList` itself is
refused; any other error of the REST read is raised as it is. The ESXi driver has no
reader.
### Changed
- Requires napalm-device-types 4.50.0 or later (`WebLoginAuthDict`).
## [0.5.0] - 2026-11-26
### Added
- `get_vms()` reports each VM's `uid` (napalm-device-types 4.44.0's `VMDict.uid`,
NetOrk/netork#2728): its instance UUID, which already survives a migration and a
restore. netOrk knows a guest by `uid` on every hypervisor that has one.
## [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.
+43 -3
View File
@@ -25,15 +25,17 @@ 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_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 |
| `get_web_login_auth` | — | ✅ | identity providers (REST) and SSO domains, see [Web interface logins](#web-interface-logins) |
| VIBs, updates | — | — | not yet |
Unverified assumptions, to be checked against real hardware:
@@ -41,6 +43,8 @@ Unverified assumptions, to be checked against real hardware:
- the HTTP fingerprints (`vmware esxi` on the Host Client page, `vcenter` on
the vSphere Client page)
- the free vSphere Hypervisor license reporting `editionKey` `esxBasic`
- a vCenter's `UserDirectory.domainList` naming its SSO domains (vcsim leaves it
empty)
## Requirements
@@ -48,6 +52,14 @@ Unverified assumptions, to be checked against real hardware:
- An account that may read the inventory. For power and snapshot actions it
also needs *Virtual machine → Interaction → Power on/off/Reset/Suspend* and
*Virtual machine → Snapshot management*.
- For `get_web_login_auth`: nothing beyond reading the inventory
(`System.View`, for the SSO domains). The identity providers are read best
effort (vCenter 7.0 U2 or later, for the `/api` REST endpoints): the vCenter
lists them only to an account with `VcIdentityProviders.Read` **and**
`VcIdentityProviders.Manage`. **Granting *Manage* is not advised:** it allows
changing the identity provider configuration, and the verdict is "not
assessed" either way. Without it the reading names the SSO domains and
`identity federation (not read)`; with both privileges it names the providers.
- For provisioning: `qemu-img` (package `qemu-utils`) where the driver runs,
and HTTPS from there to every ESXi host that may receive a VM -- through a
vCenter the disk upload goes straight to the host, not via the vCenter.
@@ -57,7 +69,7 @@ Unverified assumptions, to be checked against real hardware:
## Install
Python 3.10 or later.
Python 3.12 or later.
```bash
pip install napalm-vmware
@@ -119,7 +131,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
@@ -137,6 +150,33 @@ Linux guests are provisioned; `guest_os` other than `"linux"` is refused
Unverified until #305: that each distribution's cloud kernel carries the
PVSCSI and VMXNET3 drivers.
## Web interface logins
`get_web_login_auth()` (vCenter only, NetOrk/netork#662) returns
napalm-device-types' `WebLoginAuthDict`: the sources a vSphere Client login can go
to, each with what it asks for.
| Source | `kind` | `factors` | Read from |
|---|---|---|---|
| an identity provider of identity federation (ADFS, Entra ID, Okta, PingFederate), the default first | its `config_tag`, lowercased (`oauth2`, `oidc`) | `external`: the provider decides | `GET /api/vcenter/identity/providers` |
| `identity federation (not read)`, in the providers' place when the vCenter refused to list them (401/403) | `federation` | `unknown` | — |
| `localos` | `localos` | `unknown` | `UserDirectory.domainList` |
| every other SSO domain: the system domain, each AD or LDAP identity source | `sso` | `unknown` | `UserDirectory.domainList` |
- An SSO domain a provider serves (its `domain_names`) is listed once, as the
provider. Federation does not switch the local domain off, so the SSO domains
stay sources beside it.
- **Why `unknown`:** whether vCenter Single Sign-On asks for a smart card (with
password login switched off) or an RSA SecurID code is its authentication
policy (`sso-config.sh`), which neither the vSphere API nor the vCenter REST API
exposes. The driver does not guess `password` or `password_otp`. No reading
therefore proves a second factor.
- **Errors:** a refused provider list is not one (see the table). A refused
`domainList` raises `PermissionError`; any other error of the REST read
(e.g. 404 before vCenter 7.0 U2) is raised as it is.
- The vSphere API session cannot be reused for the REST API, so the driver logs
in to `/api/session` with the same account, reads, and logs out again.
## Design notes
**One seam.** Every read goes through `Inventory.collect(type, paths)`, a
+13
View File
@@ -72,6 +72,19 @@ class Inventory:
return []
return self.properties(manager, ["licenses"]).get("licenses", [])
def sso_domains(self) -> list[str]:
"""The SSO domains a login can name (``UserDirectory.domainList``, vCenter)."""
directory = getattr(self._content, "userDirectory", None)
if directory is None:
return []
try:
props = self.properties(directory, ["domainList"])
except vim.fault.NoPermission as exc:
raise PermissionError(
f"reading the SSO domains (domainList) was refused: {exc.privilegeId}"
) from exc
return list(props.get("domainList") or [])
def _retrieve(
self, obj_spec: Any, vim_type: Any, paths: Sequence[str], *, raw: bool = False
) -> list[dict[str, Any]]:
+46 -3
View File
@@ -1,7 +1,7 @@
"""Opening and closing a vSphere API session.
"""Opening and closing a vSphere API session, and one read of the vCenter REST API.
Kept apart from everything else because it is the only code that opens a
socket; the tests replace it wholesale.
Kept apart from everything else because it is the only code that opens an API
session; the tests replace it wholesale.
"""
from __future__ import annotations
@@ -9,8 +9,12 @@ from __future__ import annotations
import ssl
from typing import Any
import requests
from pyVim.connect import Disconnect, SmartConnect
#: The vCenter REST API's session resource (vCenter 7.0 U2 or later).
_REST_SESSION = "/api/session"
def _ssl_context(verify: bool) -> ssl.SSLContext:
context = ssl.create_default_context()
@@ -45,3 +49,42 @@ def alive(si: Any) -> bool: # pragma: no cover - talks to a live session
except Exception:
return False
return True
def rest_get(
host: str, port: int, user: str, password: str, path: str, *, verify_ssl: bool, timeout: int
) -> Any:
"""``GET path`` on the vCenter REST API, in a session of its own that is closed after.
The vSphere API session cannot be handed to the REST API, so this logs in
again with the same account.
:raises PermissionError: when the login or the read is refused (401, 403).
:raises requests.HTTPError: for any other error, e.g. 404 before vCenter 7.0 U2.
"""
base = f"https://{f'[{host}]' if ':' in host else host}:{port}"
with requests.Session() as http:
http.verify = verify_ssl
login = http.post(f"{base}{_REST_SESSION}", auth=(user, password), timeout=timeout)
_raise_for(login, f"POST {_REST_SESSION}")
http.headers["vmware-api-session-id"] = login.json()
try:
response = http.get(f"{base}{path}", timeout=timeout)
_raise_for(response, f"GET {path}")
return response.json()
finally:
_logout(http, f"{base}{_REST_SESSION}", timeout)
def _logout(http: Any, url: str, timeout: int) -> None:
"""End the REST session; a failure here must not hide the read's own result."""
try:
http.delete(url, timeout=timeout)
except requests.RequestException:
pass
def _raise_for(response: Any, what: str) -> None:
if response.status_code in (401, 403):
raise PermissionError(f"{what} was refused ({response.status_code})")
response.raise_for_status()
+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(
+20 -1
View File
@@ -6,7 +6,7 @@ from pathlib import Path
from typing import Any, ClassVar
from napalm.base.exceptions import ConnectionException
from napalm_device_types import HypervisorDriver, LicenseMixin
from napalm_device_types import ClusterDict, HypervisorDriver, LicenseMixin
from napalm_device_types.models import (
HypervisorHostDict,
LicenseDict,
@@ -18,6 +18,7 @@ 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
@@ -160,5 +161,23 @@ class VmwareBaseDriver(LicenseMixin, HypervisorDriver):
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
+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"))
+2
View File
@@ -87,6 +87,8 @@ def _vm(
return {
"name": vm.get("name", ""),
"vmid": vm["config.instanceUuid"],
# VMDict.uid: the instance UUID already survives a migration and a restore.
"uid": vm["config.instanceUuid"],
"moref": vm["_moref"],
"type": "vm",
"status": _STATUS.get(vm.get("runtime.powerState", ""), "unknown"),
+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,
}
+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(
+21 -4
View File
@@ -35,7 +35,7 @@ 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.placement import NodeRefused, Placement, choose_placement
from napalm_vmware.provision.seed import meta_data, nocloud_iso, user_data
logger = logging.getLogger(__name__)
@@ -153,6 +153,7 @@ class VmwareProvisioningMixin:
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:
@@ -163,13 +164,11 @@ class VmwareProvisioningMixin:
# 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(
@@ -196,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)
+6 -2
View File
@@ -15,10 +15,14 @@ from napalm_vmware.actions import VmwareActionsMixin
from napalm_vmware.base import VmwareBaseDriver
from napalm_vmware.parse.facts import vcenter_facts
from napalm_vmware.provisioning import VmwareProvisioningMixin
from napalm_vmware.web_login import VcenterWebLoginMixin
class VmwareVcenterDriver(VmwareProvisioningMixin, VmwareActionsMixin, VmwareBaseDriver):
"""A vCenter and every VM, datastore and port group it manages."""
class VmwareVcenterDriver(
VcenterWebLoginMixin, VmwareProvisioningMixin, VmwareActionsMixin, VmwareBaseDriver
):
"""A vCenter and every VM, datastore and port group it manages, and how people
log in to its web interface (``web_login``)."""
DRIVER_NAME = "vmware_vcenter"
API_TYPE = "VirtualCenter"
+145
View File
@@ -0,0 +1,145 @@
"""How people log in to vCenter's web interface (NetOrk/netork#662).
napalm-device-types' ``WebLoginAuthDict``: the sources a login is checked against,
each with what it asks for. Read only. vCenter only: the ESXi host client's
logins are not read, so the ESXi driver has no ``get_web_login_auth``.
**What a source is.** The vSphere Client hands every login to vCenter Single
Sign-On, so the sources are SSO's:
- **each SSO domain** the vSphere API names (``UserDirectory.domainList``): the
system domain (``vsphere.local`` unless renamed at install), ``localos`` (the
appliance's own accounts) and each Active Directory or LDAP identity source.
``{"name": "vsphere.local", "kind": "sso", "factors": "unknown"}``; ``localos``
has the kind ``localos``. The API names a domain, not its type, so an AD and an
OpenLDAP source are both ``sso``;
- **each identity provider of identity federation** (``GET
/api/vcenter/identity/providers``, vCenter 7.0 U2 or later): ADFS, Entra ID,
Okta, PingFederate. ``{"name": "Microsoft ADFS", "kind": "oauth2", "factors":
"external"}``, the kind its ``config_tag``. The default provider comes first. An
SSO domain that a provider serves (its ``domain_names``) is the provider's and is
not listed again. Federation does not switch the local domain off:
``administrator@vsphere.local`` still logs in, so the SSO domains stay sources.
**What a source asks for.**
- A federated provider is ``external``: the provider decides whether it asks for
a second factor, and vCenter cannot say.
- An SSO domain is ``unknown``. Whether SSO asks for a smart card (with password
login switched off) or an RSA SecurID code is in SSO's authentication policy
(``sso-config.sh``), which neither the vSphere API nor the vCenter REST API
exposes. Saying ``password`` would be a guess, and so would ``password_otp``.
So no reading of a vCenter proves a second factor: its web interface is judged
*not assessed*, with the sources named, until an API shows the policy.
**The privileges, and why federation is best effort.** ``domainList`` is read
with ``System.View``, which every role has; if even that is refused, the driver
raises ``PermissionError``. ``GET /api/vcenter/identity/providers`` needs
``VcIdentityProviders.Read`` **and** ``VcIdentityProviders.Manage`` (vSphere
Automation API reference). *Manage* lets an account change the identity provider
configuration, a lot to grant for a reading whose verdict is *not assessed*
either way, so the driver does not need it: when the vCenter refuses the list
(401 or 403), the reading is the SSO domains plus :data:`FEDERATION_NOT_READ`, a
source that stands for the providers that could not be read (``unknown``, never
a pass). With both privileges the providers are named instead. Any other error
of that read is raised as it is.
"""
from __future__ import annotations
from collections.abc import Iterable, Mapping
from typing import Any
from napalm_device_types import LoginSourceDict, WebLoginAuthDict
from napalm_vmware import _session
#: The vCenter REST endpoint listing identity federation's providers.
PROVIDERS_PATH = "/api/vcenter/identity/providers"
#: The source that stands for identity federation when the vCenter refused to list
#: its providers: there may be some, and what they ask for cannot be read.
FEDERATION_NOT_READ: LoginSourceDict = {
"name": "identity federation (not read)",
"kind": "federation",
"factors": "unknown",
}
#: The SSO identity source of the appliance's own operating system accounts.
LOCAL_OS = "localos"
def _provider_source(provider: Mapping[str, Any]) -> LoginSourceDict:
name = str(provider.get("name") or provider.get("provider") or "")
kind = str(provider.get("config_tag") or "provider").lower()
return {"name": name, "kind": kind, "factors": "external"}
def _domain_source(domain: str) -> LoginSourceDict:
kind = LOCAL_OS if domain.lower() == LOCAL_OS else "sso"
return {"name": domain, "kind": kind, "factors": "unknown"}
def web_login_sources(
*, domains: Iterable[str], providers: Iterable[Mapping[str, Any]] | None
) -> list[LoginSourceDict]:
"""The providers (the default first), then the SSO domains in the API's order.
*domains* is ``UserDirectory.domainList``, *providers* the answer of
:data:`PROVIDERS_PATH`, or None when it was refused: then
:data:`FEDERATION_NOT_READ` takes the providers' place.
"""
if providers is None:
return [FEDERATION_NOT_READ, *_domain_sources(domains, served=set())]
federated = sorted(providers, key=lambda p: not p.get("is_default"))
sources = [_provider_source(p) for p in federated]
return sources + _domain_sources(domains, served=_served_domains(federated))
def _served_domains(providers: Iterable[Mapping[str, Any]]) -> set[str]:
"""The SSO domains the providers serve (``domain_names``), lowercased."""
return {str(d).lower() for p in providers for d in p.get("domain_names") or ()}
def _domain_sources(domains: Iterable[str], *, served: set[str]) -> list[LoginSourceDict]:
"""A source per named SSO domain that no provider serves, in the API's order."""
return [_domain_source(d) for d in domains if d and d.lower() not in served]
class VcenterWebLoginMixin:
"""``get_web_login_auth`` for the vCenter driver."""
hostname: str
username: str
password: str
timeout: int
_port: int
_verify_ssl: bool
_inventory: Any
def get_web_login_auth(self) -> WebLoginAuthDict:
"""The sources a vSphere Client login can go to, each with what it asks for.
Example::
{"sources": [{"name": "vsphere.local", "kind": "sso", "factors": "unknown"}]}
:raises PermissionError: when the API login may not read the SSO domains.
A refused list of identity providers is not an error (see the module
docstring).
"""
domains = self._inventory.sso_domains()
try:
providers = _session.rest_get(
self.hostname,
self._port,
self.username,
self.password,
PROVIDERS_PATH,
verify_ssl=self._verify_ssl,
timeout=self.timeout,
)
except PermissionError:
providers = None
else:
providers = providers or []
return {"sources": web_login_sources(domains=domains, providers=providers)}
+7 -9
View File
@@ -4,10 +4,10 @@ build-backend = "setuptools.build_meta"
[project]
name = "napalm-vmware"
version = "0.3.0"
version = "0.6.0"
description = "NAPALM drivers for VMware ESXi hosts and vCenter Server (vSphere API via pyVmomi)"
readme = "README.md"
requires-python = ">=3.10"
requires-python = ">=3.12"
license = "Apache-2.0"
authors = [
{ name = "Christian Manivong", email = "christian@manivong.de" },
@@ -19,8 +19,6 @@ classifiers = [
"Intended Audience :: System Administrators",
"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",
@@ -28,13 +26,13 @@ classifiers = [
"Typing :: Typed",
]
dependencies = [
"napalm>=5.0.0",
"napalm-device-types>=4.21.1",
"napalm>=5.1", # older releases import pkg_resources, which a 3.12 venv lacks
"napalm-device-types>=4.50.0",
"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]
@@ -69,7 +67,7 @@ markers = [
[tool.ruff]
line-length = 100
target-version = "py310"
target-version = "py312"
[tool.ruff.lint]
select = ["E", "F", "I", "UP", "B"]
@@ -79,7 +77,7 @@ select = ["E", "F", "I", "UP", "B"]
"tests/**" = ["E501"]
[tool.mypy]
python_version = "3.10"
python_version = "3.12"
strict = true
# napalm itself is untyped, so every driver subclasses Any.
disallow_subclassing_any = false
+3
View File
@@ -42,6 +42,9 @@ class FakeInventory:
def licenses(self) -> list[dict[str, Any]]:
return self.data.get("licenses", [])
def sso_domains(self) -> list[str]:
return self.data.get("sso_domains", [])
def collect(self, type_name: str, paths: Sequence[str]) -> list[dict[str, Any]]:
self.calls.append((type_name, tuple(paths)))
rows = self.data["objects"].get(type_name, [])
+2 -3
View File
@@ -5,13 +5,12 @@
"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
"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": 57
"napalm_vmware/provisioning.py::VmwareProvisioningMixin.create_vm_from_cloud_init": 56
},
"mypy_relaxed": [
"napalm_vmware._inventory",
+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
+74
View File
@@ -74,6 +74,7 @@ class TestIdentity:
"get_virtual_networks",
"get_hypervisor_hosts",
"get_licenses",
"get_clusters",
],
)
@pytest.mark.parametrize("cls", DRIVERS)
@@ -248,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]
+26
View File
@@ -131,3 +131,29 @@ def test_raw_properties_keep_the_pyvmomi_objects(content):
vim.VirtualMachine("vm-1", None), ["config.hardware.device"], raw=True
)
assert props["config.hardware.device"][0] is disk
def test_sso_domains_are_read_from_the_user_directory(content):
"""The SSO domains a vCenter login can name (NetOrk/netork#662)."""
content.userDirectory = vim.UserDirectory("UserDirectory", None)
content.propertyCollector.RetrievePropertiesEx.return_value = SimpleNamespace(
objects=[
_content(vim.UserDirectory("UserDirectory", None), {"domainList": ["vsphere.local"]})
],
token=None,
)
assert Inventory(content).sso_domains() == ["vsphere.local"]
def test_sso_domains_empty_without_a_user_directory(content):
content.userDirectory = None
assert Inventory(content).sso_domains() == []
def test_sso_domains_refused_is_a_permission_error(content):
content.userDirectory = vim.UserDirectory("UserDirectory", None)
content.propertyCollector.RetrievePropertiesEx.side_effect = vim.fault.NoPermission(
privilegeId="System.View"
)
with pytest.raises(PermissionError, match="System.View"):
Inventory(content).sso_domains()
+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([], [], [], []))
+5
View File
@@ -33,6 +33,11 @@ class TestVmListFromVcsim:
assert vm["node"] == "localhost.localdomain"
assert vm["type"] == "vm"
def test_the_uid_is_the_instance_uuid(self, esxi_data, vm0):
# VMDict.uid: an identity that survives a migration and a restore; vSphere's
# instance UUID is one (NetOrk/netork#2728).
assert _vms(esxi_data)[0]["uid"] == vm0["config.instanceUuid"]
def test_vcenter_node_is_the_esxi_host(self, vcenter_data):
nodes = {vm["name"]: vm["node"] for vm in _vms(vcenter_data)}
assert nodes["DC0_H0_VM0"] == "DC0_H0"
+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)
+26 -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(
@@ -170,6 +170,31 @@ class TestCreate:
_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"
+41
View File
@@ -150,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"])
+298
View File
@@ -0,0 +1,298 @@
"""get_web_login_auth: how people log in to vCenter's web interface (NetOrk/netork#662).
A vCenter login goes to vCenter Single Sign-On. Every SSO domain the vSphere API
names (``UserDirectory.domainList``: the system domain, ``localos``, each AD or
LDAP identity source) is a source, and so is every identity provider of identity
federation (``GET /api/vcenter/identity/providers``). Whether SSO asks a domain's
users for a smart card or an RSA SecurID code is in its authentication policy,
which neither API exposes: those sources are ``unknown``, never guessed. A
federated provider decides itself: ``external``.
The provider shapes follow the vSphere Automation API reference
(``Providers.Summary``: ``provider``, ``name``, ``config_tag``, ``is_default``,
``domain_names``).
"""
from __future__ import annotations
from typing import Any
from unittest.mock import MagicMock, patch
import pytest
import requests
from napalm_vmware import VmwareEsxiDriver, VmwareVcenterDriver, _session
from napalm_vmware.web_login import FEDERATION_NOT_READ, PROVIDERS_PATH, web_login_sources
from tests.conftest import FakeInventory, load
def _source(name: str, kind: str, factors: str) -> dict[str, str]:
return {"name": name, "kind": kind, "factors": factors}
def _provider(name: str, *, tag: str = "Oidc", default: bool = False, domains=()) -> dict:
return {
"provider": f"id-{name}",
"name": name,
"config_tag": tag,
"is_default": default,
"domain_names": list(domains),
}
class TestSources:
def test_every_sso_domain_is_a_source_whose_second_factor_cannot_be_read(self):
assert web_login_sources(domains=["vsphere.local", "CORP"], providers=[]) == [
_source("vsphere.local", "sso", "unknown"),
_source("CORP", "sso", "unknown"),
]
def test_the_local_os_source_is_named_as_such(self):
assert web_login_sources(domains=["localos"], providers=[]) == [
_source("localos", "localos", "unknown")
]
def test_a_federated_identity_provider_decides_itself(self):
sources = web_login_sources(
domains=["vsphere.local"], providers=[_provider("Microsoft ADFS", tag="Oauth2")]
)
assert sources == [
_source("Microsoft ADFS", "oauth2", "external"),
_source("vsphere.local", "sso", "unknown"),
]
def test_federation_does_not_switch_the_local_domain_off(self):
"""administrator@vsphere.local still logs in beside the provider: both are ways in."""
sources = web_login_sources(
domains=["vsphere.local"], providers=[_provider("Okta", default=True)]
)
assert [s["name"] for s in sources] == ["Okta", "vsphere.local"]
def test_the_default_provider_comes_first(self):
providers = [_provider("ADFS"), _provider("Entra ID", default=True)]
assert [s["name"] for s in web_login_sources(domains=[], providers=providers)] == [
"Entra ID",
"ADFS",
]
def test_a_domain_a_provider_serves_is_not_listed_twice(self):
providers = [_provider("ADFS", domains=["corp.example.com"])]
sources = web_login_sources(
domains=["vsphere.local", "CORP.example.com"], providers=providers
)
assert [s["name"] for s in sources] == ["ADFS", "vsphere.local"]
def test_a_provider_without_a_name_or_tag_is_named_by_its_id(self):
provider = {"provider": "b7d3", "is_default": False}
assert web_login_sources(domains=[], providers=[provider]) == [
_source("b7d3", "provider", "external")
]
def test_no_reading_ever_passes(self):
"""Nothing either API says proves a second factor; the verdict can only be
not met (never produced here) or not assessed."""
sources = web_login_sources(
domains=["vsphere.local", "localos", "CORP"], providers=[_provider("Okta")]
)
assert {s["factors"] for s in sources} <= {"unknown", "external"}
def test_nothing_named_is_no_source(self):
assert web_login_sources(domains=[], providers=[]) == []
def _vcenter(domains=("vsphere.local",)) -> VmwareVcenterDriver:
data = load("vcsim-vcenter")
data["sso_domains"] = list(domains)
driver = VmwareVcenterDriver("vc01.example.lan", "netork@vsphere.local", "secret")
driver._si = MagicMock()
driver._inventory = FakeInventory(data)
return driver
class TestDriver:
def test_the_vcenter_reads_both_apis(self):
driver = _vcenter(domains=["vsphere.local", "localos"])
with patch.object(
_session, "rest_get", return_value=[_provider("ADFS", tag="Oauth2")]
) as get:
reading = driver.get_web_login_auth()
assert reading == {
"sources": [
_source("ADFS", "oauth2", "external"),
_source("vsphere.local", "sso", "unknown"),
_source("localos", "localos", "unknown"),
]
}
args, kwargs = get.call_args
assert args == (
"vc01.example.lan",
443,
"netork@vsphere.local",
"secret",
PROVIDERS_PATH,
)
assert kwargs == {"verify_ssl": True, "timeout": 60}
@pytest.mark.parametrize("status", [401, 403])
def test_providers_refused_still_names_the_sso_domains_and_federation_not_read(self, status):
"""Listing the providers needs VcIdentityProviders.Manage, which netOrk does not
ask for: refused, the reading is the SSO domains plus federation as not read."""
driver = _vcenter(domains=["vsphere.local"])
refused = PermissionError(f"GET {PROVIDERS_PATH} was refused ({status})")
with patch.object(_session, "rest_get", side_effect=refused):
reading = driver.get_web_login_auth()
assert reading == {
"sources": [
FEDERATION_NOT_READ,
_source("vsphere.local", "sso", "unknown"),
]
}
def test_federation_not_read_is_never_a_pass(self):
assert FEDERATION_NOT_READ["factors"] == "unknown"
def test_any_other_api_error_still_raises(self):
driver = _vcenter()
with (
patch.object(_session, "rest_get", side_effect=requests.HTTPError("500 Error")),
pytest.raises(requests.HTTPError),
):
driver.get_web_login_auth()
def test_sso_domains_refused_is_a_permission_error(self):
"""Without domainList there is nothing to name: not judged by the providers alone."""
driver = _vcenter()
driver._inventory = MagicMock()
driver._inventory.sso_domains.side_effect = PermissionError("domainList: NoPermission")
with (
patch.object(_session, "rest_get", return_value=[_provider("ADFS")]),
pytest.raises(PermissionError, match="domainList"),
):
driver.get_web_login_auth()
def test_esxi_has_no_reader(self):
"""The host client's logins are not read; hasattr stays a truthful answer."""
assert not hasattr(VmwareEsxiDriver, "get_web_login_auth")
class _Response:
def __init__(self, status: int, body: Any = None) -> None:
self.status_code = status
self._body = body
def json(self) -> Any:
return self._body
def raise_for_status(self) -> None:
if self.status_code >= 400:
raise requests.HTTPError(f"{self.status_code} Error", response=self) # type: ignore[arg-type]
class _Http:
"""A ``requests.Session`` stand-in that records the calls."""
def __init__(self, *, login: _Response, get: _Response) -> None:
self.headers: dict[str, str] = {}
self.verify: bool | str = True
self.calls: list[tuple[str, str, dict]] = []
self._login, self._get = login, get
def __enter__(self) -> _Http:
return self
def __exit__(self, *exc: object) -> None:
return None
def post(self, url: str, **kwargs: Any) -> _Response:
self.calls.append(("POST", url, kwargs))
return self._login
def get(self, url: str, **kwargs: Any) -> _Response:
self.calls.append(
("GET", url, dict(kwargs, session=self.headers.get("vmware-api-session-id")))
)
return self._get
def delete(self, url: str, **kwargs: Any) -> _Response:
self.calls.append(("DELETE", url, kwargs))
return _Response(204)
def _rest_get(http: _Http, path: str = PROVIDERS_PATH) -> Any:
with patch.object(_session.requests, "Session", return_value=http):
return _session.rest_get(
"vc01.example.lan",
443,
"netork@vsphere.local",
"secret",
path,
verify_ssl=False,
timeout=7,
)
class TestRestSession:
def test_it_logs_in_reads_and_logs_out(self):
http = _Http(login=_Response(201, "token-1"), get=_Response(200, [{"provider": "p"}]))
assert _rest_get(http) == [{"provider": "p"}]
assert http.verify is False
assert [(m, u) for m, u, _ in http.calls] == [
("POST", "https://vc01.example.lan:443/api/session"),
("GET", f"https://vc01.example.lan:443{PROVIDERS_PATH}"),
("DELETE", "https://vc01.example.lan:443/api/session"),
]
assert http.calls[0][2]["auth"] == ("netork@vsphere.local", "secret")
assert http.calls[1][2] == {"timeout": 7, "session": "token-1"}
@pytest.mark.parametrize("status", [401, 403])
def test_a_refused_read_is_a_permission_error(self, status):
http = _Http(
login=_Response(201, "token-1"), get=_Response(status, {"error_type": "UNAUTHORIZED"})
)
with pytest.raises(PermissionError, match=f"refused \\({status}\\)"):
_rest_get(http)
assert http.calls[-1][0] == "DELETE"
def test_a_refused_login_is_a_permission_error(self):
http = _Http(
login=_Response(401, {"error_type": "UNAUTHENTICATED"}), get=_Response(200, [])
)
with pytest.raises(PermissionError, match="POST /api/session"):
_rest_get(http)
assert [m for m, _, _ in http.calls] == ["POST"]
def test_a_vcenter_without_the_api_raises(self):
"""Before vCenter 7.0 U2 there is no /api: not a permission matter, still an error."""
http = _Http(login=_Response(404), get=_Response(200, []))
with pytest.raises(requests.HTTPError):
_rest_get(http)
def test_an_ipv6_address_is_bracketed(self):
http = _Http(login=_Response(201, "t"), get=_Response(200, []))
with patch.object(_session.requests, "Session", return_value=http):
_session.rest_get("fd00::5", 443, "u", "p", PROVIDERS_PATH, verify_ssl=True, timeout=1)
assert http.calls[0][1] == "https://[fd00::5]:443/api/session"
def test_a_failed_logout_does_not_hide_the_reading():
class _Flaky(_Http):
def delete(self, url: str, **kwargs: Any) -> _Response:
raise requests.ConnectionError("gone")
http = _Flaky(login=_Response(201, "t"), get=_Response(200, [{"provider": "p"}]))
assert _rest_get(http) == [{"provider": "p"}]