"""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 an API session; the tests replace it wholesale. """ 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() if not verify: # ESXi hosts ship a self-signed certificate; most homelab and many # production hosts keep it. context.check_hostname = False context.verify_mode = ssl.CERT_NONE return context def connect( # pragma: no cover - opens a live session host: str, port: int, user: str, password: str, *, verify_ssl: bool, timeout: int ) -> Any: return SmartConnect( host=host, port=port, user=user, pwd=password, sslContext=_ssl_context(verify_ssl), httpConnectionTimeout=timeout, ) def disconnect(si: Any) -> None: # pragma: no cover - talks to a live session Disconnect(si) def alive(si: Any) -> bool: # pragma: no cover - talks to a live session try: si.CurrentTime() 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()