napalm-vmware 0.3.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,6 @@
1
+ """NAPALM drivers for VMware ESXi (``vmware_esxi``) and vCenter (``vmware_vcenter``)."""
2
+
3
+ from napalm_vmware.esxi import VmwareEsxiDriver
4
+ from napalm_vmware.vcenter import VmwareVcenterDriver
5
+
6
+ __all__ = ["VmwareEsxiDriver", "VmwareVcenterDriver"]
@@ -0,0 +1,96 @@
1
+ """Bulk reads through the vSphere PropertyCollector.
2
+
3
+ Every read in this package asks for an explicit list of property paths
4
+ (``napalm_vmware.paths``) instead of touching attributes on managed objects.
5
+ One round trip per object type rather than one per attribute, and it keeps
6
+ working where lazy attribute access does not: pyVmomi fails to deserialize
7
+ whole ``summary`` objects from some servers while the individual paths are
8
+ fine.
9
+
10
+ This class is the one seam the tests replace. Its output is already plain
11
+ (see :mod:`napalm_vmware._plain`), so a fake only has to return dicts.
12
+ """
13
+
14
+ from __future__ import annotations
15
+
16
+ from collections.abc import Sequence
17
+ from typing import Any
18
+
19
+ from pyVmomi import vim, vmodl
20
+
21
+ from napalm_vmware._plain import to_plain
22
+
23
+ _PC = vmodl.query.PropertyCollector
24
+ _PAGE_SIZE = 500
25
+
26
+
27
+ def _vim_type(type_name: str) -> Any:
28
+ vim_type = getattr(vim, type_name, None) or getattr(vim.dvs, type_name, None)
29
+ if vim_type is None:
30
+ raise ValueError(f"Unknown vSphere managed object type {type_name!r}")
31
+ return vim_type
32
+
33
+
34
+ class Inventory:
35
+ """Read-only access to a connected ServiceInstance's content."""
36
+
37
+ def __init__(self, content: Any) -> None:
38
+ self._content = content
39
+
40
+ def about(self) -> dict[str, Any]:
41
+ """``ServiceContent.about``: product, version and API type of the endpoint."""
42
+ return to_plain(self._content.about)
43
+
44
+ def collect(self, type_name: str, paths: Sequence[str]) -> list[dict[str, Any]]:
45
+ """Every object of ``type_name`` in the inventory, with the given properties."""
46
+ vim_type = _vim_type(type_name)
47
+ view = self._content.viewManager.CreateContainerView(
48
+ self._content.rootFolder, [vim_type], True
49
+ )
50
+ try:
51
+ traversal = _PC.TraversalSpec(
52
+ name="view", path="view", skip=False, type=vim.view.ContainerView
53
+ )
54
+ obj_spec = _PC.ObjectSpec(obj=view, skip=True, selectSet=[traversal])
55
+ return self._retrieve(obj_spec, vim_type, paths)
56
+ finally:
57
+ view.Destroy()
58
+
59
+ def properties(self, obj: Any, paths: Sequence[str], *, raw: bool = False) -> dict[str, Any]:
60
+ """The given properties of one managed object; ``{}`` if it is gone.
61
+
62
+ ``raw=True`` keeps the pyVmomi objects -- for a caller that has to hand
63
+ a device back to vSphere whole, backing and all, in a reconfigure.
64
+ """
65
+ rows = self._retrieve(_PC.ObjectSpec(obj=obj), type(obj), paths, raw=raw)
66
+ return rows[0] if rows else {}
67
+
68
+ def licenses(self) -> list[dict[str, Any]]:
69
+ """Licenses assigned on this endpoint (edition key, name, used/total)."""
70
+ manager = getattr(self._content, "licenseManager", None)
71
+ if manager is None:
72
+ return []
73
+ return self.properties(manager, ["licenses"]).get("licenses", [])
74
+
75
+ def _retrieve(
76
+ self, obj_spec: Any, vim_type: Any, paths: Sequence[str], *, raw: bool = False
77
+ ) -> list[dict[str, Any]]:
78
+ spec = _PC.FilterSpec(
79
+ objectSet=[obj_spec], propSet=[_PC.PropertySpec(type=vim_type, pathSet=list(paths))]
80
+ )
81
+ pc = self._content.propertyCollector
82
+ result = pc.RetrievePropertiesEx([spec], _PC.RetrieveOptions(maxObjects=_PAGE_SIZE))
83
+ rows: list[dict[str, Any]] = []
84
+ while result is not None:
85
+ rows.extend(_row(obj, raw) for obj in result.objects)
86
+ if not result.token:
87
+ break
88
+ result = pc.ContinueRetrievePropertiesEx(token=result.token)
89
+ return rows
90
+
91
+
92
+ def _row(obj_content: Any, raw: bool = False) -> dict[str, Any]:
93
+ row: dict[str, Any] = {"_moref": obj_content.obj._moId}
94
+ for prop in obj_content.propSet or []:
95
+ row[prop.name] = prop.val if raw else to_plain(prop.val)
96
+ return row
@@ -0,0 +1,57 @@
1
+ """Convert pyVmomi objects into plain, JSON-safe Python values.
2
+
3
+ The drivers never parse pyVmomi objects directly. Everything fetched from the
4
+ vSphere API goes through :func:`to_plain` first, so a parser sees the same
5
+ shape whether its input came from a live host or from a JSON fixture that
6
+ ``tools/harvest.py`` captured.
7
+
8
+ Conventions:
9
+
10
+ * a managed object (``HostSystem``, ``VirtualMachine`` ...) becomes its MoRef
11
+ id string, e.g. ``"host-21"``
12
+ * a data object becomes a dict of its set properties plus ``"_type"``, the
13
+ WSDL type name (``"VirtualDisk"``) -- device lists are told apart by it
14
+ * enums become ``str``, datetimes become epoch seconds, binary data ``None``
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import datetime
20
+ from typing import Any
21
+
22
+ from pyVmomi import VmomiSupport
23
+
24
+ _NOISE = frozenset({"dynamicType", "dynamicProperty"})
25
+
26
+
27
+ def to_plain(value: Any) -> Any:
28
+ """Recursively convert ``value`` into dicts, lists and scalars."""
29
+ if value is None or isinstance(value, bool):
30
+ return value
31
+ if isinstance(value, VmomiSupport.ManagedObject):
32
+ return value._moId
33
+ if isinstance(value, VmomiSupport.DataObject):
34
+ return _data_object(value)
35
+ if isinstance(value, str):
36
+ return str(value)
37
+ if isinstance(value, (int, float)):
38
+ return value
39
+ if isinstance(value, datetime.datetime):
40
+ return value.timestamp()
41
+ if isinstance(value, (bytes, bytearray)):
42
+ return None
43
+ if isinstance(value, (list, tuple)):
44
+ return [to_plain(v) for v in value]
45
+ return str(value)
46
+
47
+
48
+ def _data_object(obj: Any) -> dict[str, Any]:
49
+ out: dict[str, Any] = {"_type": obj._wsdlName}
50
+ for prop in obj._GetPropertyList():
51
+ if prop.name in _NOISE:
52
+ continue
53
+ val = getattr(obj, prop.name, None)
54
+ if val is None or (isinstance(val, list) and not val):
55
+ continue
56
+ out[prop.name] = to_plain(val)
57
+ return out
@@ -0,0 +1,47 @@
1
+ """Opening and closing a vSphere API session.
2
+
3
+ Kept apart from everything else because it is the only code that opens a
4
+ socket; the tests replace it wholesale.
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import ssl
10
+ from typing import Any
11
+
12
+ from pyVim.connect import Disconnect, SmartConnect
13
+
14
+
15
+ def _ssl_context(verify: bool) -> ssl.SSLContext:
16
+ context = ssl.create_default_context()
17
+ if not verify:
18
+ # ESXi hosts ship a self-signed certificate; most homelab and many
19
+ # production hosts keep it.
20
+ context.check_hostname = False
21
+ context.verify_mode = ssl.CERT_NONE
22
+ return context
23
+
24
+
25
+ def connect( # pragma: no cover - opens a live session
26
+ host: str, port: int, user: str, password: str, *, verify_ssl: bool, timeout: int
27
+ ) -> Any:
28
+ return SmartConnect(
29
+ host=host,
30
+ port=port,
31
+ user=user,
32
+ pwd=password,
33
+ sslContext=_ssl_context(verify_ssl),
34
+ httpConnectionTimeout=timeout,
35
+ )
36
+
37
+
38
+ def disconnect(si: Any) -> None: # pragma: no cover - talks to a live session
39
+ Disconnect(si)
40
+
41
+
42
+ def alive(si: Any) -> bool: # pragma: no cover - talks to a live session
43
+ try:
44
+ si.CurrentTime()
45
+ except Exception:
46
+ return False
47
+ return True
@@ -0,0 +1,83 @@
1
+ """vSphere tasks and faults, in the terms of the HypervisorDriver contract.
2
+
3
+ Contract methods raise ``RuntimeError`` when the platform refuses an
4
+ operation. vSphere reports refusals two ways: a ``MethodFault`` raised by the
5
+ call itself, or a task that ends in state ``error``. Both end up here.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import time
11
+ from collections.abc import Callable
12
+ from typing import Any, TypeVar
13
+
14
+ from pyVmomi import vmodl
15
+
16
+ from napalm_vmware._plain import to_plain
17
+
18
+ T = TypeVar("T")
19
+
20
+ _POLL_SECONDS = 0.5
21
+ _FREE_LICENSE = (
22
+ "the host runs the free vSphere Hypervisor license, which makes the "
23
+ "vSphere API read-only; assign a paid license to change VMs from netOrk"
24
+ )
25
+
26
+
27
+ def fault_message(fault: dict[str, Any]) -> str:
28
+ """A readable sentence for a (plain) vSphere fault."""
29
+ if fault.get("_type") == "RestrictedVersion":
30
+ return _FREE_LICENSE
31
+ return fault.get("localizedMessage") or fault.get("msg") or fault.get("_type", "unknown fault")
32
+
33
+
34
+ def invoke(call: Callable[..., T], *args: Any, **kwargs: Any) -> T:
35
+ """Run a vSphere call, re-raising any ``MethodFault`` as ``RuntimeError``."""
36
+ try:
37
+ return call(*args, **kwargs)
38
+ except vmodl.MethodFault as fault:
39
+ raise RuntimeError(fault_message(to_plain(fault))) from fault
40
+
41
+
42
+ def wait_for_task(
43
+ inventory: Any,
44
+ task: Any,
45
+ timeout: float,
46
+ *,
47
+ clock: Callable[[], float] = time.monotonic,
48
+ sleep: Callable[[float], None] = time.sleep,
49
+ ) -> None:
50
+ """Block until ``task`` succeeds; raise ``RuntimeError`` otherwise."""
51
+ deadline = clock() + timeout
52
+ while True:
53
+ info = inventory.properties(task, ["info.state", "info.error"])
54
+ if not info:
55
+ raise RuntimeError("the vSphere task disappeared before it finished")
56
+ state = info.get("info.state")
57
+ if state == "success":
58
+ return
59
+ if state == "error":
60
+ raise RuntimeError(fault_message(info.get("info.error") or {}))
61
+ if clock() >= deadline:
62
+ raise RuntimeError(f"the vSphere task did not finish within {timeout:g}s")
63
+ sleep(_POLL_SECONDS)
64
+
65
+
66
+ def wait_until(
67
+ check: Callable[[], bool],
68
+ timeout: float,
69
+ what: str,
70
+ *,
71
+ clock: Callable[[], float] = time.monotonic,
72
+ sleep: Callable[[float], None] = time.sleep,
73
+ ) -> None:
74
+ """Poll ``check`` until it is true; for operations vSphere runs without a task.
75
+
76
+ ``ShutdownGuest`` only *asks* VMware Tools to shut the guest down and
77
+ returns at once, so completion has to be observed from the power state.
78
+ """
79
+ deadline = clock() + timeout
80
+ while not check():
81
+ if clock() >= deadline:
82
+ raise RuntimeError(f"{what} did not finish within {timeout:g}s")
83
+ sleep(_POLL_SECONDS)
@@ -0,0 +1,109 @@
1
+ """Power and snapshot operations (the write half of the HypervisorDriver contract)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from pyVmomi import vim
8
+
9
+ from napalm_vmware._tasks import invoke, wait_for_task, wait_until
10
+ from napalm_vmware.parse.snapshots import find_snapshot, snapshot_list
11
+
12
+ _TASK_TIMEOUT = 300
13
+ _GUEST_SHUTDOWN_TIMEOUT = 300
14
+ _RUNNING = "poweredOn"
15
+ _TOOLS_RUNNING = "guestToolsRunning"
16
+
17
+
18
+ class VmwareActionsMixin:
19
+ """Mixed into both drivers ahead of :class:`VmwareBaseDriver`."""
20
+
21
+ _inventory: Any
22
+ _find_vm: Any
23
+ _mo: Any
24
+
25
+ def _vm_mo(self, vm: dict[str, Any]) -> Any:
26
+ return self._mo(vim.VirtualMachine, vm["_moref"])
27
+
28
+ def _run(self, call: Any, *args: Any, **kwargs: Any) -> None:
29
+ wait_for_task(self._inventory, invoke(call, *args, **kwargs), _TASK_TIMEOUT)
30
+
31
+ @staticmethod
32
+ def _require_running(vm: dict[str, Any], action: str) -> None:
33
+ if vm.get("runtime.powerState") != _RUNNING:
34
+ raise RuntimeError(f"Cannot {action} VM {vm.get('name')!r}: it is not running")
35
+
36
+ @staticmethod
37
+ def _require_tools(vm: dict[str, Any], action: str) -> None:
38
+ if vm.get("guest.toolsRunningStatus") != _TOOLS_RUNNING:
39
+ raise RuntimeError(
40
+ f"A graceful {action} of {vm.get('name')!r} needs VMware Tools running "
41
+ "in the guest; use force to cut power instead"
42
+ )
43
+
44
+ # -- power ---------------------------------------------------------------
45
+
46
+ def start_vm(self, name: str) -> None:
47
+ self._run(self._vm_mo(self._find_vm(name)).PowerOnVM_Task)
48
+
49
+ def stop_vm(self, name: str, force: bool = False) -> None:
50
+ vm = self._find_vm(name)
51
+ self._require_running(vm, "stop")
52
+ mo = self._vm_mo(vm)
53
+ if force:
54
+ self._run(mo.PowerOffVM_Task)
55
+ return
56
+ self._require_tools(vm, "shutdown")
57
+ invoke(mo.ShutdownGuest)
58
+ wait_until(
59
+ lambda: (
60
+ self._inventory.properties(mo, ["runtime.powerState"]).get("runtime.powerState")
61
+ == "poweredOff"
62
+ ),
63
+ _GUEST_SHUTDOWN_TIMEOUT,
64
+ f"guest shutdown of {vm.get('name')!r}",
65
+ )
66
+
67
+ def reboot_vm(self, name: str, force: bool = False) -> None:
68
+ vm = self._find_vm(name)
69
+ self._require_running(vm, "reboot")
70
+ mo = self._vm_mo(vm)
71
+ if force:
72
+ self._run(mo.ResetVM_Task)
73
+ return
74
+ # RebootGuest returns once Tools accepted the request; the guest gives
75
+ # no signal when it is back, so there is nothing further to wait for.
76
+ self._require_tools(vm, "reboot")
77
+ invoke(mo.RebootGuest)
78
+
79
+ def suspend_vm(self, name: str) -> None:
80
+ vm = self._find_vm(name)
81
+ self._require_running(vm, "suspend")
82
+ self._run(self._vm_mo(vm).SuspendVM_Task)
83
+
84
+ # -- snapshots -------------------------------------------------------------
85
+
86
+ def create_vm_snapshot(
87
+ self, name: str, snapshot: str, description: str = "", include_memory: bool = False
88
+ ) -> None:
89
+ vm = self._find_vm(name)
90
+ if any(s["name"] == snapshot for s in snapshot_list(vm)):
91
+ raise ValueError(f"VM {vm.get('name')!r} already has a snapshot named {snapshot!r}")
92
+ self._run(
93
+ self._vm_mo(vm).CreateSnapshot_Task,
94
+ name=snapshot,
95
+ description=description,
96
+ memory=include_memory and vm.get("runtime.powerState") == _RUNNING,
97
+ quiesce=False,
98
+ )
99
+
100
+ def _snapshot_mo(self, name: str, snapshot: str) -> Any:
101
+ return self._mo(vim.vm.Snapshot, find_snapshot(self._find_vm(name), snapshot))
102
+
103
+ def delete_vm_snapshot(self, name: str, snapshot: str) -> None:
104
+ # removeChildren=False consolidates the snapshot into its children
105
+ # instead of discarding them.
106
+ self._run(self._snapshot_mo(name, snapshot).RemoveSnapshot_Task, removeChildren=False)
107
+
108
+ def rollback_vm_snapshot(self, name: str, snapshot: str) -> None:
109
+ self._run(self._snapshot_mo(name, snapshot).RevertToSnapshot_Task)
napalm_vmware/base.py ADDED
@@ -0,0 +1,164 @@
1
+ """What the ESXi and vCenter drivers share: session, VM lookup, common getters."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from pathlib import Path
6
+ from typing import Any, ClassVar
7
+
8
+ from napalm.base.exceptions import ConnectionException
9
+ from napalm_device_types import HypervisorDriver, LicenseMixin
10
+ from napalm_device_types.models import (
11
+ HypervisorHostDict,
12
+ LicenseDict,
13
+ SnapshotDict,
14
+ StorageVolumeDict,
15
+ VirtualNetworkDict,
16
+ VMConfigDict,
17
+ )
18
+
19
+ from napalm_vmware import _session, paths
20
+ from napalm_vmware._inventory import Inventory
21
+ from napalm_vmware.parse.environment import environment
22
+ from napalm_vmware.parse.hosts import hypervisor_hosts
23
+ from napalm_vmware.parse.licenses import license_list
24
+ from napalm_vmware.parse.networks import NetworkIndex, network_index, virtual_networks
25
+ from napalm_vmware.parse.snapshots import snapshot_list
26
+ from napalm_vmware.parse.storage import storage_pools
27
+ from napalm_vmware.parse.vm_config import vm_config
28
+ from napalm_vmware.parse.vms import vm_list
29
+ from napalm_vmware.provision.image import DEFAULT_CACHE_DIR
30
+
31
+ _DEFAULT_PORT = 443
32
+ #: ``about.apiType`` -> the driver that handles it, for a helpful refusal.
33
+ _DRIVER_FOR_API = {"HostAgent": "vmware_esxi", "VirtualCenter": "vmware_vcenter"}
34
+
35
+
36
+ class VmwareBaseDriver(LicenseMixin, HypervisorDriver):
37
+ """Shared implementation. Concrete drivers set ``API_TYPE`` and ``STANDALONE``."""
38
+
39
+ VENDOR = "VMware"
40
+ USES_SSH = False
41
+ platform = "vmware"
42
+
43
+ #: ``about.apiType`` this driver accepts.
44
+ API_TYPE: ClassVar[str] = ""
45
+ #: True when the driver talks to one host directly (ESXi), False for vCenter.
46
+ STANDALONE: ClassVar[bool] = True
47
+
48
+ def __init__(
49
+ self,
50
+ hostname: str,
51
+ username: str,
52
+ password: str,
53
+ timeout: int = 60,
54
+ optional_args: dict[str, Any] | None = None,
55
+ ) -> None:
56
+ self.hostname = hostname
57
+ self.username = username
58
+ self.password = password
59
+ self.timeout = timeout
60
+ args = optional_args or {}
61
+ self._port = int(args.get("port") or _DEFAULT_PORT)
62
+ self._verify_ssl = bool(args.get("verify_ssl", args.get("ssl_verify", True)))
63
+ # Where converted cloud images are kept between provisioning jobs.
64
+ self._image_cache_dir = Path(args.get("image_cache_dir") or DEFAULT_CACHE_DIR)
65
+ self._si: Any = None
66
+ self._inventory: Any = None
67
+
68
+ # -- session -------------------------------------------------------------
69
+
70
+ def open(self) -> None:
71
+ try:
72
+ si = _session.connect(
73
+ self.hostname,
74
+ self._port,
75
+ self.username,
76
+ self.password,
77
+ verify_ssl=self._verify_ssl,
78
+ timeout=self.timeout,
79
+ )
80
+ except Exception as exc:
81
+ raise ConnectionException(f"Cannot connect to {self.hostname}: {exc}") from exc
82
+ inventory = Inventory(si.RetrieveContent())
83
+ about = inventory.about()
84
+ if about.get("apiType") != self.API_TYPE:
85
+ _session.disconnect(si)
86
+ other = _DRIVER_FOR_API.get(about.get("apiType", ""), "another driver")
87
+ raise ConnectionException(
88
+ f"{self.hostname} is {about.get('fullName', 'not a supported VMware endpoint')}"
89
+ f"; use the {other} driver for it"
90
+ )
91
+ self._si, self._inventory = si, inventory
92
+
93
+ def close(self) -> None:
94
+ if self._si is not None:
95
+ _session.disconnect(self._si)
96
+ self._si = self._inventory = None
97
+
98
+ def is_alive(self) -> dict[str, bool]:
99
+ return {"is_alive": self._si is not None and _session.alive(self._si)}
100
+
101
+ def _mo(self, vim_type: Any, moref: str) -> Any:
102
+ """A live managed-object reference for a MoRef id from a plain row."""
103
+ return vim_type(moref, self._si._stub)
104
+
105
+ # -- inventory reads -------------------------------------------------------
106
+
107
+ def _hosts(self) -> list[dict[str, Any]]:
108
+ return self._inventory.collect("HostSystem", paths.HOST)
109
+
110
+ def _vm_rows(self) -> list[dict[str, Any]]:
111
+ return self._inventory.collect("VirtualMachine", paths.VM)
112
+
113
+ def _index(self, hosts: list[dict[str, Any]]) -> NetworkIndex:
114
+ dv_portgroups = self._inventory.collect("DistributedVirtualPortgroup", paths.DV_PORTGROUP)
115
+ return network_index(hosts, dv_portgroups)
116
+
117
+ def _find_vm(self, name: str) -> dict[str, Any]:
118
+ """The VM whose instance UUID, MoRef or name is ``name``."""
119
+ vms = [
120
+ vm
121
+ for vm in self._vm_rows()
122
+ if vm.get("config.instanceUuid") and not vm.get("config.template")
123
+ ]
124
+ for key in ("config.instanceUuid", "_moref"):
125
+ match = [vm for vm in vms if vm.get(key) == name]
126
+ if match:
127
+ return match[0]
128
+ match = [vm for vm in vms if vm.get("name") == name]
129
+ if len(match) > 1:
130
+ raise ValueError(f"{len(match)} VMs are named {name!r}; address one by its vmid")
131
+ if not match:
132
+ raise ValueError(f"There is no VM named or identified by {name!r}")
133
+ return match[0]
134
+
135
+ # -- HypervisorDriver ------------------------------------------------------
136
+
137
+ def get_vms(self) -> list[dict[str, Any]]:
138
+ hosts = self._hosts()
139
+ return vm_list(self._vm_rows(), hosts, self._index(hosts))
140
+
141
+ def get_vm_config(self, name: str) -> VMConfigDict:
142
+ return vm_config(self._find_vm(name), self._index(self._hosts()))
143
+
144
+ def get_vm_snapshots(self, name: str) -> list[SnapshotDict]:
145
+ return snapshot_list(self._find_vm(name))
146
+
147
+ def get_vm_storage_pools(self) -> dict[str, StorageVolumeDict]:
148
+ return storage_pools(self._inventory.collect("Datastore", paths.DATASTORE))
149
+
150
+ def get_virtual_networks(self) -> dict[str, VirtualNetworkDict]:
151
+ return virtual_networks( # type: ignore[return-value]
152
+ self._hosts(),
153
+ self._inventory.collect("DistributedVirtualPortgroup", paths.DV_PORTGROUP),
154
+ self._inventory.collect("DistributedVirtualSwitch", paths.DV_SWITCH),
155
+ )
156
+
157
+ def get_environment(self) -> dict[str, Any]:
158
+ return environment(self._hosts())
159
+
160
+ def get_hypervisor_hosts(self) -> list[HypervisorHostDict]:
161
+ return hypervisor_hosts(self._hosts(), standalone=self.STANDALONE)
162
+
163
+ def get_licenses(self) -> list[LicenseDict]:
164
+ return license_list(self._inventory.licenses())
napalm_vmware/esxi.py ADDED
@@ -0,0 +1,75 @@
1
+ """NAPALM driver for a VMware ESXi host, addressed directly."""
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing import Any
6
+
7
+ from napalm_device_types import FingerprintRule
8
+ from pyVmomi import vim
9
+
10
+ from napalm_vmware._plain import to_plain
11
+ from napalm_vmware._tasks import invoke
12
+ from napalm_vmware.actions import VmwareActionsMixin
13
+ from napalm_vmware.base import VmwareBaseDriver
14
+ from napalm_vmware.parse.facts import esxi_facts
15
+ from napalm_vmware.parse.interfaces import host_interfaces, host_interfaces_ip
16
+ from napalm_vmware.parse.lldp import lldp_neighbors
17
+ from napalm_vmware.provisioning import VmwareProvisioningMixin
18
+
19
+
20
+ class VmwareEsxiDriver(VmwareProvisioningMixin, VmwareActionsMixin, VmwareBaseDriver):
21
+ """One ESXi host. Its VMs, vmnics, vmkernel NICs, datastores and port groups."""
22
+
23
+ DRIVER_NAME = "vmware_esxi"
24
+ API_TYPE = "HostAgent"
25
+ STANDALONE = True
26
+ # A host reboot runs through hardware POST before ESXi starts its services.
27
+ REBOOT_SETTLE_SECONDS = 300
28
+ # Unverified against real hardware: the Host Client landing page says
29
+ # "VMware ESXi"; a vCenter's does not, and it says "vCenter".
30
+ HTTP_FINGERPRINT = [
31
+ FingerprintRule("vmware esxi", weight=9.0, mandatory=True),
32
+ FingerprintRule("vcenter", weight=9.0, negative=True),
33
+ ]
34
+
35
+ def _host(self) -> dict[str, Any]:
36
+ hosts = self._hosts()
37
+ if not hosts:
38
+ raise RuntimeError(f"{self.hostname} shows no host in its inventory")
39
+ return hosts[0]
40
+
41
+ def get_facts(self) -> dict[str, Any]:
42
+ return esxi_facts(self._inventory.about(), self._host())
43
+
44
+ def get_interfaces(self) -> dict[str, dict[str, Any]]:
45
+ return host_interfaces(self._host())
46
+
47
+ def get_interfaces_ip(self) -> dict[str, dict[str, Any]]:
48
+ return host_interfaces_ip(self._host())
49
+
50
+ def reboot_host(self) -> None:
51
+ """Restart the host, which has to be in maintenance mode.
52
+
53
+ ``force=True`` would restart a host with running VMs by cutting their
54
+ power. Evacuating them -- or deciding not to -- is the operator's call,
55
+ made by entering maintenance mode in vSphere first.
56
+ """
57
+ host = self._host()
58
+ if not host.get("runtime.inMaintenanceMode"):
59
+ raise RuntimeError(
60
+ f"{host.get('name', self.hostname)} is not in maintenance mode; "
61
+ "enter it in vSphere first so running VMs are not powered off"
62
+ )
63
+ # The task finishes as the host goes down; there is nothing to wait for.
64
+ invoke(self._mo(vim.HostSystem, host["_moref"]).RebootHost_Task, force=False)
65
+
66
+ def get_lldp_neighbors(self) -> dict[str, list[dict[str, str]]]:
67
+ network_system = self._host().get("configManager.networkSystem")
68
+ if not network_system:
69
+ return {}
70
+ mo = self._mo(vim.host.NetworkSystem, network_system)
71
+ try:
72
+ hints = invoke(mo.QueryNetworkHint)
73
+ except RuntimeError:
74
+ return {}
75
+ return lldp_neighbors(to_plain(hints) or [])
File without changes