Files
napalm-homeassistant/napalm_homeassistant/driver.py
T
Christian Manivong ed8e58267a
driver / lint (pull_request) Successful in 15s
driver / standard (pull_request) Successful in 19s
driver / lowest (pull_request) Failing after 25s
driver / types (pull_request) Successful in 1m5s
driver / test (3.12) (pull_request) Successful in 1m11s
driver / test (3.13) (pull_request) Successful in 1m3s
driver / build (pull_request) Successful in 30s
driver / security (pull_request) Successful in 1m8s
CI / driver (pull_request) Failing after 1m52s
driver / publish (pull_request) Skipped
feat: Home Assistant OS driver over the WebSocket API (0.1.0)
A driver for Home Assistant OS and Supervised installs. It reaches the
Supervisor through Home Assistant's WebSocket (supervisor/api) with an
administrator's long-lived access token: no add-on, no SSH.

Getters: facts, interfaces and addresses, host status (pending reboot,
data disk), pending updates of Core, OS, Supervisor and add-ons, add-ons
as services, running backups. Actions: apply updates, add-on start/stop/
restart and start at boot, refresh updates, reboot and shutdown.

The fixtures are built from the Supervisor 2026.11.0 API source, not
recorded; they are replaced once the first device is onboarded.
2026-12-03 01:22:18 +01:00

366 lines
14 KiB
Python

"""NAPALM driver for Home Assistant OS over the Home Assistant WebSocket API.
It reads and acts through the Supervisor, which Home Assistant reaches for an
administrator's access token: no add-on and no SSH on the device.
Credentials
-----------
A long-lived access token of a Home Assistant administrator, as ``password`` or as
``optional_args["token_value"]`` (which wins). The username is not used.
Optional args
-------------
port : int
Home Assistant's port (default 8123).
use_ssl : bool
``wss://`` instead of ``ws://``; the default on port 443.
ssl_verify / verify_ssl : bool
Verify the certificate against the system's CAs (default True). Pinned
fingerprints (``tls_fingerprints``) are checked either way.
"""
from __future__ import annotations
import logging
import re
import ssl
import time
from collections.abc import Callable
from typing import Any, Protocol
from napalm.base.exceptions import ConnectionException
from napalm.base.models import FactsDict, InterfaceDict, InterfacesIPDict
from napalm_device_types import FingerprintRule, OSDriver, PortSpec
from napalm_device_types.models import (
ApplyUpdatesResultDict,
HostStatusDict,
ServiceDict,
UpdateDict,
)
from napalm_device_types.running_backups import RunningBackupDict, RunningBackupsMixin
from napalm_device_types.tls_certificates import CertificateCheck
from napalm_homeassistant.parsers import (
parse_facts,
parse_host_status,
parse_interfaces,
parse_interfaces_ip,
parse_running_backups,
parse_services,
parse_updates,
)
from napalm_homeassistant.parsers.system import VENDOR
from napalm_homeassistant.parsers.updates import CORE, OS, SUPERVISOR
from napalm_homeassistant.transport import (
UNKNOWN_COMMAND,
ConnectionLost,
HomeAssistantError,
connect,
start_session,
)
LOG = logging.getLogger(__name__)
DEFAULT_PORT = 8123
TLS_PORT = 443
WEBSOCKET_PATH = "/api/websocket"
#: How long one update may run: an image download on a slow line.
UPDATE_WAIT = 3600.0
#: How long Home Assistant may take to come back after an update of Core.
RESTART_WAIT = 900.0
RECONNECT_INTERVAL = 10.0
#: What apply_updates accepts as a name, as the contract has it.
PACKAGE_NAME = re.compile(r"^[a-zA-Z0-9_\-\+\.]+$")
ADDON_SLUG = re.compile(r"^[a-z0-9_]+$")
ADDON_ACTIONS = frozenset({"start", "stop", "restart"})
BOOT_BY_ACTION = {"enable": "auto", "disable": "manual"}
#: The order updates run in: add-ons, then what restarts more and more of the host.
UPDATE_ORDER = {SUPERVISOR: 1, CORE: 2, OS: 3}
CORE_ONLY_MODEL = "Home Assistant (without Supervisor)"
class SupervisorApi(Protocol):
"""A logged-in connection to Home Assistant (``transport.Session``)."""
ha_version: str | None
def supervisor(
self,
endpoint: str,
method: str = "get",
data: dict[str, Any] | None = None,
*,
wait: float | None = None,
) -> Any: ...
def close(self) -> None: ...
class HomeAssistantDriver(RunningBackupsMixin, OSDriver):
"""Home Assistant OS (or a Supervised install) through Home Assistant's WebSocket."""
VENDOR = VENDOR
DRIVER_NAME = "homeassistant"
USES_SSH = False
#: Home Assistant OS boots and starts Core before the API answers again.
REBOOT_SETTLE_SECONDS = 180
default_port = DEFAULT_PORT
PORT_SPECS = [PortSpec("http", DEFAULT_PORT, ("/",), weight=6.0)]
HTTP_FINGERPRINT = [FingerprintRule("home assistant", weight=8.0, mandatory=True)]
def __init__(
self,
hostname: str,
username: str,
password: str,
timeout: int = 60,
optional_args: dict[str, Any] | None = None,
) -> None:
self.hostname = hostname
self.username = username
self.timeout = timeout
self.optional_args = dict(optional_args or {})
self.token = str(self.optional_args.get("token_value") or password or "")
self.port = int(self.optional_args.get("port") or DEFAULT_PORT)
self.use_ssl = bool(self.optional_args.get("use_ssl", self.port == TLS_PORT))
verify = self.optional_args.get("ssl_verify", self.optional_args.get("verify_ssl", True))
self.ssl_verify = bool(verify)
self.transport: SupervisorApi | None = None
@property
def url(self) -> str:
host = f"[{self.hostname}]" if ":" in self.hostname else self.hostname
scheme = "wss" if self.use_ssl else "ws"
return f"{scheme}://{host}:{self.port}{WEBSOCKET_PATH}"
# --- connection -------------------------------------------------------------------
def open(self) -> None:
if not self.token:
raise ConnectionException(
f"{self.hostname}: no access token; give a long-lived access token "
"as the password or as token_value"
)
self.transport = self._open_transport()
def _open_transport(self) -> SupervisorApi: # pragma: no cover - live I/O
tls: ssl.SSLContext | None = None
check: CertificateCheck | None = None
if self.use_ssl:
tls = ssl.create_default_context()
if not self.ssl_verify:
# The pinned fingerprint (CertificateCheck) stands in for the CA.
tls.check_hostname = False
tls.verify_mode = ssl.CERT_NONE
check = CertificateCheck(self.optional_args, self.hostname, self.port)
socket, certificate = connect(self.url, timeout=float(self.timeout), tls=tls)
return start_session(
socket, self.token, timeout=float(self.timeout), check=check, certificate=certificate
)
def close(self) -> None:
transport, self.transport = self.transport, None
if transport is not None:
try:
transport.close()
except Exception: # a connection Home Assistant dropped closes badly
LOG.debug("%s: closing a dropped connection failed", self.hostname)
def is_alive(self) -> dict[str, bool]:
return {"is_alive": self.transport is not None}
def _session(self) -> SupervisorApi:
if self.transport is None:
raise ConnectionException(f"{self.hostname}: not connected; call open() first")
return self.transport
def _get(self, endpoint: str) -> Any:
return self._session().supervisor(endpoint)
def _post(self, endpoint: str, data: dict[str, Any] | None = None, **kwargs: Any) -> Any:
return self._session().supervisor(endpoint, "post", data, **kwargs)
# --- getters ----------------------------------------------------------------------
def get_facts(self) -> FactsDict:
try:
host = self._get("/host/info")
except HomeAssistantError as exc:
if exc.code != UNKNOWN_COMMAND:
raise
return self._core_facts()
return parse_facts(host, self._get("/os/info"), self._get("/network/info"))
def _core_facts(self) -> FactsDict:
"""Home Assistant without a Supervisor: only Core's version is known."""
return {
"vendor": VENDOR,
"model": CORE_ONLY_MODEL,
"hostname": self.hostname,
"fqdn": self.hostname,
"os_version": f"Home Assistant Core {self._session().ha_version or ''}".strip(),
"serial_number": "",
"uptime": -1.0,
"interface_list": [],
}
def get_interfaces(self) -> dict[str, InterfaceDict]:
return parse_interfaces(self._get("/network/info"))
def get_interfaces_ip(self) -> dict[str, InterfacesIPDict]:
return parse_interfaces_ip(self._get("/network/info"))
def get_available_updates(self) -> list[UpdateDict]:
"""Core, the OS, the Supervisor and every add-on with a newer version."""
return parse_updates(
self._get("/core/info"),
self._get("/os/info"),
self._get("/supervisor/info"),
self._get("/addons"),
)
def get_host_status(self) -> HostStatusDict:
return parse_host_status(
self._get("/host/info"), self._get("/os/info"), self._get("/resolution/info")
)
def get_services(self) -> list[ServiceDict]:
"""Every installed add-on, by its slug."""
addons = self._get("/addons")
boots = {
str(addon["slug"]): str(self._get(f"/addons/{addon['slug']}/info").get("boot"))
for addon in addons.get("addons", [])
}
return parse_services(addons, boots)
def get_running_backups(self) -> list[RunningBackupDict]:
return parse_running_backups(self._get("/jobs/info"))
# --- add-ons ----------------------------------------------------------------------
def manage_service(self, name: str, action: str) -> dict[str, Any]:
"""Start, stop or restart an add-on; enable or disable its start at boot."""
if action not in ADDON_ACTIONS and action not in BOOT_BY_ACTION:
raise ValueError(f"unknown action {action!r}")
installed = {str(a["slug"]) for a in self._get("/addons").get("addons", [])}
if not ADDON_SLUG.fullmatch(name) or name not in installed:
raise ValueError(f"no installed add-on {name!r}")
try:
if action in BOOT_BY_ACTION:
self._post(f"/addons/{name}/options", {"boot": BOOT_BY_ACTION[action]})
else:
self._post(f"/addons/{name}/{action}")
except HomeAssistantError as exc:
return {"success": False, "output": str(exc)}
return {"success": True, "output": f"{action} {name}: done"}
# --- updates ----------------------------------------------------------------------
def refresh_available_updates(self) -> dict[str, Any]:
"""Has the Supervisor look up the newest versions again."""
try:
self._post("/reload_updates")
except HomeAssistantError as exc:
return {"success": False, "output": str(exc)}
return {"success": True, "output": "update information reloaded"}
def apply_updates(
self, packages: list[str], *, log: Callable[[str], None] | None = None
) -> ApplyUpdatesResultDict:
"""Updates the named parts (``core``, ``os``, ``supervisor``, add-on slugs).
An empty list updates everything pending. Add-ons go first, then the
Supervisor, Core and the OS, which restarts the host last. The run stops at
the first refused update.
"""
updates, missing = self._pending_updates(packages)
if missing:
return {
"success": False,
"output": "",
"error": f"no pending update for: {', '.join(missing)}",
}
lines: list[str] = []
def say(line: str) -> None:
lines.append(line)
if log is not None:
log(line)
for update in updates:
try:
self._apply_one(update, say)
except (HomeAssistantError, ConnectionException) as exc:
error = f"{update.get('title') or update['name']}: {exc}"
say(error)
return {"success": False, "output": "\n".join(lines), "error": error}
return {"success": True, "output": "\n".join(lines)}
def _pending_updates(self, packages: list[str]) -> tuple[list[UpdateDict], list[str]]:
"""The pending updates *packages* name (all for none), in the order they run,
and the names that have none pending."""
for name in packages:
if not PACKAGE_NAME.fullmatch(name):
raise ValueError(f"not an update name: {name!r}")
pending = {update["name"]: update for update in self.get_available_updates()}
wanted = list(packages) or list(pending)
missing = [name for name in wanted if name not in pending]
ordered = sorted((n for n in wanted if n in pending), key=lambda n: UPDATE_ORDER.get(n, 0))
return [pending[name] for name in ordered], missing
def _apply_one(self, update: UpdateDict, say: Callable[[str], None]) -> None:
name = update["name"]
title = update.get("title") or name
say(f"Updating {title} {update['current_version']} -> {update['new_version']}")
if name == OS:
self._post_expecting_restart("/os/update", {})
say("Home Assistant OS installed; the host restarts")
elif name == CORE:
if self._post_expecting_restart("/core/update", {"backup": False}):
say("Home Assistant Core is restarting")
self._wait_until_back()
say("Home Assistant Core is back")
elif name == SUPERVISOR:
self._post("/supervisor/update", {}, wait=UPDATE_WAIT)
else:
self._post(f"/store/addons/{name}/update", {"backup": False}, wait=UPDATE_WAIT)
say(f"{title} updated")
def _post_expecting_restart(self, endpoint: str, data: dict[str, Any]) -> bool:
"""Whether the connection dropped: Home Assistant restarting is the update going on."""
try:
self._post(endpoint, data, wait=UPDATE_WAIT)
except ConnectionLost:
return True
return False
def _wait_until_back(self) -> None:
deadline = time.monotonic() + RESTART_WAIT
self.close()
while True:
try:
self.transport = self._open_transport()
return
except ConnectionException as exc:
if time.monotonic() >= deadline:
raise ConnectionException(
f"Home Assistant did not come back within {RESTART_WAIT:g}s"
) from exc
time.sleep(RECONNECT_INTERVAL)
# --- power ------------------------------------------------------------------------
def reboot_host(self) -> None:
self._power("/host/reboot")
def shutdown_host(self) -> None:
self._power("/host/shutdown")
def _power(self, endpoint: str) -> None:
try:
self._post(endpoint, {})
except ConnectionLost:
return # the host is on its way down
except HomeAssistantError as exc:
raise RuntimeError(f"{self.hostname}: the Supervisor refused: {exc}") from exc