# Licensed under the Apache License, Version 2.0 """NAPALM driver for OpenMediaVault NAS systems. Extends LinuxDriver with OMV-specific storage management: * Physical disk inventory via lsblk and smartctl * md RAID array status via /proc/mdstat and mdadm * Mounted filesystem info via df * SMB, NFS, and FTP share enumeration via omv-confdbadm Connects via SSH. Sudo access is required for smartctl and mdadm. All optional_args from LinuxDriver are accepted (pkg_manager, sudo_password, …). Tested against OpenMediaVault 6.x and 7.x (Debian Bullseye / Bookworm base). """ from __future__ import annotations import json as _json import logging import re from shlex import quote as _shlex_quote from typing import Any from napalm_device_types import FingerprintRule, StorageDriver from napalm_device_types.models import ( DiskPoolDict, LogicalVolumeDict, NASShareDict, PhysicalDiskDict, ReplicationJobDict, StorageQuotaDict, StorageServiceDict, VolumeSnapshotDict, ) from napalm_linux.linux import LinuxDriver from napalm_openmediavault._local_accounts import OmvLocalAccountsMixin logger = logging.getLogger(__name__) #: One label of a hostname (RFC 1123); OMV's own schema asks the same. _HOSTNAME_LABEL_RE = re.compile(r"^(?!-)[A-Za-z0-9-]{1,63}(?/dev/null" #: The overall verdict of an ATA or NVMe disk: ``PASSED`` or ``FAILED!``. _SMART_VERDICT_RE = re.compile(r"^SMART overall-health self-assessment test result:\s*(\S+)", re.M) #: A SCSI/SAS disk's: ``OK``, or the failure it predicts. _SMART_SCSI_STATUS_RE = re.compile(r"^SMART Health Status:\s*(.+?)\s*$", re.M) _SMART_VERDICTS = {"PASSED": "healthy", "FAILED": "failed"} #: An ATA disk's temperature attribute, an NVMe disk's ``Temperature:`` line. _SMART_TEMP_RE = re.compile( r"(?:Temperature_Celsius|Current Temperature|Temperature:)[^\n]*?(\d+)\s*(?:Celsius|\(|$)" ) #: A SCSI/SAS disk's; a QEMU disk without a sensor prints ``0 C``. _SMART_SCSI_TEMP_RE = re.compile(r"^Current Drive Temperature:\s+(\d+) C\s*$", re.M) #: An md array's line in /proc/mdstat, and its members: ``sda1[0]``, ``sdc1[1](F)``. _MDSTAT_ARRAY_RE = re.compile(r"^(md\d+)\s*:(.*)$", re.M) _MDSTAT_MEMBER_RE = re.compile(r"(\S+?)\[\d+\]") def smart_health(output: str) -> str: """The overall SMART verdict in ``smartctl -H`` output. ``"healthy"`` or ``"failed"``; ``"unknown"`` when smartctl printed none (no SMART support, a USB bridge without pass-through). """ verdict = _SMART_VERDICT_RE.search(output) if verdict: return _SMART_VERDICTS.get(verdict.group(1).rstrip("!"), "unknown") status = _SMART_SCSI_STATUS_RE.search(output) if status: return "healthy" if status.group(1) == "OK" else "failed" return "unknown" def smart_temperature(output: str) -> int: """A disk's temperature in Celsius from ``smartctl -A`` output; ``-1`` if none.""" found = _SMART_TEMP_RE.search(output) if found: return int(found.group(1)) scsi = _SMART_SCSI_TEMP_RE.search(output) if scsi and int(scsi.group(1)) > 0: return int(scsi.group(1)) return -1 def md_members(mdstat: str) -> dict[str, str]: """Each member device in ``/proc/mdstat``, mapped to its array: ``{"sda1": "md1"}``.""" return { member: array for array, rest in _MDSTAT_ARRAY_RE.findall(mdstat) for member in _MDSTAT_MEMBER_RE.findall(rest) } def _pool_of(disk: str, members: dict[str, str]) -> str: """The array *disk* or one of its partitions is a member of, or ``""``. Linux names a partition by appending its number, after a ``p`` when the disk's name ends in a digit: ``sda`` owns ``sda1``, ``nvme0n1`` owns ``nvme0n1p1``; ``sdaa1`` is not ``sda``'s, nor ``nvme0n11`` (another namespace) ``nvme0n1``'s. """ partition = r"p\d+" if disk[-1:].isdigit() else r"\d+" own = re.compile(rf"{re.escape(disk)}(?:{partition})?") return next((array for member, array in members.items() if own.fullmatch(member)), "") class OpenMediaVaultDriver(OmvLocalAccountsMixin, StorageDriver, LinuxDriver): """NAPALM driver for OpenMediaVault NAS systems. Declares both roles it fills: a NAS built on Debian. Storage comes first, so netOrk shows it as storage rather than as a Linux host. Inherits all Linux OS functionality from LinuxDriver (packages, services, users, processes, cron, Docker) -- OMV really is Debian, so apt applies -- and adds OMV-specific storage management on top. NAS services are ``get_storage_services()``; the systemd service list stays ``get_services()``. Two names for two different things. """ TYPE_LABEL = "Storage" DRIVER_NAME = "openmediavault" #: "Upgrade everything" must be a full upgrade: OMV's own packages and the #: kernel are held back by a plain ``apt-get upgrade`` (``omv-upgrade`` is a #: dist-upgrade). netOrk reads this when it upgrades the host. FULL_UPGRADE = True driver_name = "openmediavault" SSH_FINGERPRINT = [ FingerprintRule("debian", weight=4.0), ] HTTP_FINGERPRINT = [ FingerprintRule("openmediavault", weight=9.0, mandatory=True), ] #: OMV generates sshd_config from its own database; a drop-in netOrk wrote #: would be dropped on the next apply of the SSH settings. Inherited from #: napalm-linux, so opted out here (NetOrk/netork#1027). harden_ssh_server = None # type: ignore[assignment] # ── Facts override ───────────────────────────────────────────────────────── def get_facts(self) -> dict[str, Any]: """Return device facts, overriding OMV version from dpkg.""" facts = super().get_facts() try: ver = self._send("dpkg-query -W -f='${Version}' openmediavault 2>/dev/null").strip() if ver: facts["os_version"] = f"OMV {ver}" except Exception: logger.debug("%s: OMV version not read: ignored", self.hostname, exc_info=True) return facts # ── Hostname ─────────────────────────────────────────────────────────────── def set_hostname(self, new_hostname: str) -> None: """Rename the NAS the way OMV's web UI does, through its own database. LinuxDriver's rename writes ``/etc/hostname`` and ``/etc/hosts``, which OMV regenerates from ``conf.system.network.dns`` on its next apply. So the name goes to ``Network.setGeneralSettings`` -- an FQDN sets the domain as well, a bare name keeps it -- and ``Config.applyChanges`` deploys the modules the rename made dirty, plus the hostname modules that already were. Other changes pending in the web UI stay pending. :raises ValueError: for a name that is not a valid hostname, before anything runs on the NAS. :raises RuntimeError: when OMV refuses a step. """ labels = new_hostname.split(".") if len(new_hostname) > 253 or not all(_HOSTNAME_LABEL_RE.match(x) for x in labels): raise ValueError(f"not a valid hostname: {new_hostname!r}") current = self._omv_rpc("Network", "getGeneralSettings") domain = ".".join(labels[1:]) if len(labels) > 1 else current.get("domainname", "") before = set(self._omv_dirty_modules()) self._omv_rpc( "Network", "setGeneralSettings", {"hostname": labels[0], "domainname": domain} ) after = set(self._omv_dirty_modules()) modules = sorted((after - before) | (after & _HOSTNAME_MODULES)) if modules: # Salt restarts what it deploys (Samba, Postfix, networkd): give it time. self._omv_rpc("Config", "applyChanges", {"modules": modules, "force": False}, 600) def _omv_rpc( self, service: str, method: str, params: dict[str, Any] | None = None, timeout: float = 60 ) -> Any: """Call ``omv-rpc`` as root and return its decoded answer. :raises RuntimeError: when the call fails, with OMV's answer. """ command = f"omv-rpc -u admin {service} {method}" if params is not None: command += f" {_shlex_quote(_json.dumps(params))}" output, status = self._sudo_status(command, timeout) if status != 0: raise RuntimeError(f"omv-rpc {service}.{method} failed: {output[-300:]}") lines = output.splitlines() return _json.loads(lines[-1]) if lines else None def _omv_dirty_modules(self) -> list[str]: """The modules with configuration changes not yet deployed.""" output, _status = self._sudo_status(f"cat {_DIRTY_MODULES} 2>/dev/null || echo '[]'", 30) try: dirty = _json.loads(output or "[]") except ValueError: return [] return [m for m in dirty if isinstance(m, str)] if isinstance(dirty, list) else [] # ── Physical disks ───────────────────────────────────────────────────────── def get_disks(self) -> list[PhysicalDiskDict]: """Return physical disk inventory. Uses ``lsblk -J`` for device enumeration, ``smartctl -iHA`` (via sudo) for health, temperature, and RPM data, and ``/proc/mdstat``, read once, for array membership. Each entry contains: * slot (string) - device path, e.g. ``"/dev/sda"`` * model (string) - drive model string * serial (string) - drive serial number * vendor (string) - drive manufacturer * type (string) - ``"hdd"``, ``"ssd"``, or ``"nvme"`` * size (int) - raw capacity in bytes * rpm (int) - rotational speed; ``0`` for SSD/NVMe * temperature (int) - temperature in Celsius; ``-1`` if unavailable * health (string) - ``"healthy"``, ``"failed"``, or ``"unknown"`` * pool (string) - md array name if member; empty string otherwise Example:: [ { "slot": "/dev/sda", "model": "HGST HUS726T6TALE6L4", "serial": "K3GXXXXX", "vendor": "HGST", "type": "hdd", "size": 6001175126016, "rpm": 7200, "temperature": 34, "health": "healthy", "pool": "md1", }, ] """ result: list[PhysicalDiskDict] = [] try: raw = self._send( "lsblk -J -b -o NAME,SIZE,TYPE,ROTA,VENDOR,MODEL,SERIAL,TRAN 2>/dev/null" ) lsblk = _json.loads(raw) except Exception: return result members = self._md_members() for dev in lsblk.get("blockdevices", []): if dev.get("type") != "disk": continue name = dev.get("name", "") if not name: continue size = int(dev.get("size") or 0) rota = str(dev.get("rota", "1")) vendor = (dev.get("vendor") or "").strip() model = (dev.get("model") or "").strip() serial = (dev.get("serial") or "").strip() tran = (dev.get("tran") or "").strip().lower() if tran == "nvme": disk_type = "nvme" elif rota == "0": disk_type = "ssd" else: disk_type = "hdd" health, temperature, rpm = self._smart(name, disk_type) result.append( PhysicalDiskDict( slot=f"/dev/{name}", model=model, serial=serial, vendor=vendor, type=disk_type, size=size, rpm=rpm, temperature=temperature, health=health, pool=_pool_of(name, members), ) ) return result def _smart(self, name: str, disk_type: str) -> tuple[str, int, int]: """A disk's SMART health, temperature (``-1`` if unknown) and rpm (``0``).""" health, temperature, rpm = "unknown", -1, 0 try: smart = self._sudo(_SMARTCTL.format(name=name), read_timeout=15) health = smart_health(smart) temperature = smart_temperature(smart) if disk_type == "hdd": rpm_m = re.search(r"Rotation Rate:\s+(\d+)\s+rpm", smart) if rpm_m: rpm = int(rpm_m.group(1)) except Exception: logger.debug("%s: smartctl for %s: ignored", self.hostname, name, exc_info=True) return health, temperature, rpm def _md_members(self) -> dict[str, str]: """The md array of each member device, from one read of ``/proc/mdstat``.""" try: return md_members(self._send("cat /proc/mdstat 2>/dev/null")) except Exception: logger.debug("%s: /proc/mdstat not read: ignored", self.hostname, exc_info=True) return {} # ── md RAID pools ────────────────────────────────────────────────────────── def get_disk_pools(self) -> dict[str, DiskPoolDict]: """Return md RAID array status from ``/proc/mdstat`` and ``mdadm --detail``. Keys are array names (e.g. ``"md1"``). Each value contains: * name (string) - array name * type (string) - always ``"md"`` * level (string) - RAID level, e.g. ``"raid1"``, ``"raid5"`` * status (string) - ``"online"``, ``"degraded"``, ``"faulted"``, or ``"offline"`` * total (int) - usable array size in bytes (``0`` if mdadm unavailable) * used (int) - always ``0`` (use ``get_volumes()`` for per-filesystem usage) * available (int) - always ``0`` * disks (list of strings) - member device names (e.g. ``["sda1", "sdb1"]``) * auto_expand (bool) - always ``False`` (not applicable for md) * dedup (bool) - always ``False`` * compression (string) - always ``"off"`` Example:: { "md1": { "name": "md1", "type": "md", "level": "raid1", "status": "online", "total": 2000398925824, "used": 0, "available": 0, "disks": ["sda1", "sdb1"], "auto_expand": False, "dedup": False, "compression": "off", }, } """ result: dict[str, DiskPoolDict] = {} try: mdstat = self._send("cat /proc/mdstat 2>/dev/null") except Exception: return result for line in mdstat.splitlines(): m = re.match(r"^(md\d+)\s*:\s+(\S+)\s+(\S+)\s+(.*)", line) if not m: continue md_name, state_word, level_raw, members_raw = m.groups() member_disks = re.findall(r"(\w+)\[\d+\]", members_raw) status = "online" if state_word == "active" else "offline" total = 0 try: detail = self._sudo(f"mdadm --detail /dev/{md_name} 2>/dev/null", read_timeout=10) size_m = re.search(r"Array Size\s*:\s*(\d+)\s*\(", detail) if size_m: total = int(size_m.group(1)) * 1024 # kB → bytes if "degraded" in detail.lower(): status = "degraded" elif re.search(r"State\s*:.*(?:faulty|failed)", detail, re.IGNORECASE): status = "faulted" except Exception: logger.debug( "%s: mdadm --detail for %s: ignored", self.hostname, md_name, exc_info=True ) result[md_name] = DiskPoolDict( name=md_name, type="md", level=level_raw.lower(), status=status, total=total, used=0, available=0, disks=member_disks, auto_expand=False, dedup=False, compression="off", ) return result # ── Logical volumes / filesystems ────────────────────────────────────────── def get_volumes(self) -> dict[str, LogicalVolumeDict]: """Return mounted filesystem info from ``df``. Only real block devices (``/dev/…``) are included; tmpfs, devtmpfs, overlays, and similar pseudo-filesystems are skipped. Keys are derived from the mountpoint (e.g. ``"srv-dev-disk-by-label-data"`` for ``/srv/dev/disk/by-label/data``; ``"root"`` for ``/``). Each value contains: * name (string) - key repeated for convenience * pool (string) - device name without ``/dev/`` prefix * type (string) - always ``"filesystem"`` * total (int) - total size in bytes * used (int) - used space in bytes * available (int) - available space in bytes * mountpoint (string) - absolute mount path * compression (string) - always ``"off"`` * dedup (bool) - always ``False`` * readonly (bool) - ``True`` if mounted ``ro`` * snapshots (int) - always ``0`` Example:: { "srv-data": { "name": "srv-data", "pool": "md1", "type": "filesystem", "total": 2000398925824, "used": 945000000000, "available": 1055398925824, "mountpoint": "/srv/data", "compression": "off", "dedup": False, "readonly": False, "snapshots": 0, }, } """ result: dict[str, LogicalVolumeDict] = {} try: df_out = self._send("df -Pk 2>/dev/null") except Exception: return result try: mounts = self._send("cat /proc/mounts 2>/dev/null") except Exception: mounts = "" for line in df_out.splitlines()[1:]: parts = line.split() if len(parts) < 6: continue device = parts[0] total_k, used_k, avail_k = int(parts[1]), int(parts[2]), int(parts[3]) mountpoint = parts[5] if not device.startswith("/dev/"): continue key = mountpoint.lstrip("/").replace("/", "-") or "root" pool = device.removeprefix("/dev/") readonly = bool( re.search( rf"^{re.escape(device)}\s+\S+\s+\S+\s+(?:[^,\s]*,)*ro(?:,|\s|$)", mounts, re.MULTILINE, ) ) result[key] = LogicalVolumeDict( name=key, pool=pool, type="filesystem", total=total_k * 1024, used=used_k * 1024, available=avail_k * 1024, mountpoint=mountpoint, compression="off", dedup=False, readonly=readonly, snapshots=0, ) return result # ── NAS shares ──────────────────────────────────────────────────────────── def get_shares(self) -> dict[str, NASShareDict]: """Return all configured NAS shares from the OMV config database. Covers SMB/CIFS, NFS, and FTP shares. Keys are prefixed with the protocol (e.g. ``"smb:media"``, ``"nfs:backups"``, ``"ftp:upload"``). Each value contains: * name (string) - share name without protocol prefix * protocol (string) - ``"smb"``, ``"nfs"``, or ``"ftp"`` * path (string) - absolute filesystem path * volume (string) - last path component (leaf directory) * enabled (bool) - whether the share is currently exported * readonly (bool) - whether the share is exported read-only * description (string) - human-readable comment (SMB only) * clients (list of strings) - allowed client addresses (NFS only) Example:: { "smb:media": { "name": "media", "protocol": "smb", "path": "/srv/dev/disk/by-label/data/media", "volume": "media", "enabled": True, "readonly": False, "description": "Media library", "clients": [], }, "nfs:backups": { "name": "backups", "protocol": "nfs", "path": "/srv/dev/disk/by-label/data/backups", "volume": "backups", "enabled": True, "readonly": False, "description": "", "clients": ["192.168.1.0/24"], }, } """ shares: dict[str, NASShareDict] = {} shares.update(self._smb_shares()) shares.update(self._nfs_shares()) shares.update(self._ftp_shares()) return shares # ── Storage services ────────────────────────────────────────────────────── def get_storage_services(self) -> dict[str, StorageServiceDict]: """Return status of key NAS services (SMB, NFS, FTP, SSH, rsync). This method is separate from ``get_services()`` (inherited from LinuxDriver) which returns the full systemd service list. Keys are service names. Each value contains: * name (string) - service name * enabled (bool) - configured to start on boot * running (bool) - currently active * port (int) - primary listening port * version (string) - protocol version; empty if unknown Example:: { "smb": {"name": "smb", "enabled": True, "running": True, "port": 445, "version": ""}, "nfs": {"name": "nfs", "enabled": True, "running": True, "port": 2049, "version": ""}, "ftp": {"name": "ftp", "enabled": False, "running": False, "port": 21, "version": ""}, "ssh": {"name": "ssh", "enabled": True, "running": True, "port": 22, "version": ""}, "rsync": {"name": "rsync", "enabled": False, "running": False, "port": 873, "version": ""}, } """ _SVC_MAP = [ # (key, systemd unit, default port) ("smb", "smbd", 445), ("nfs", "nfs-server", 2049), ("ftp", "proftpd", 21), ("ssh", "ssh", 22), ("rsync", "rsync", 873), ] result: dict[str, StorageServiceDict] = {} for key, unit, port in _SVC_MAP: try: running = ( self._send(f"systemctl is-active {unit} 2>/dev/null || true").strip() == "active" ) enabled = ( self._send(f"systemctl is-enabled {unit} 2>/dev/null || true").strip() == "enabled" ) except Exception: running = enabled = False result[key] = StorageServiceDict( name=key, enabled=enabled, running=running, port=port, version="", ) return result # ── Not implemented ──────────────────────────────────────────────────────── def get_volume_snapshots(self, volume: str = "") -> list[VolumeSnapshotDict]: """Return volume snapshots (not supported on OpenMediaVault).""" raise NotImplementedError("OpenMediaVault does not expose volume snapshots via this driver") def get_replication_jobs(self) -> list[ReplicationJobDict]: """Return replication jobs (not supported on OpenMediaVault).""" raise NotImplementedError def get_quotas(self) -> list[StorageQuotaDict]: """Return storage quotas (not supported on OpenMediaVault).""" raise NotImplementedError # ── Internal helpers ─────────────────────────────────────────────────────── def _omv_read(self, key: str) -> list[dict[str, Any]]: """Query the OMV config database and return a list of objects. Handles both OMV 6+ (returns a JSON array directly) and older versions that wrap the array in a dict under a common key. """ try: raw = self._send(f"omv-confdbadm read {key!r} 2>/dev/null").strip() if not raw: return [] data = _json.loads(raw) if isinstance(data, list): return data # Older OMV wraps the list: {"share": [...]} for wrapper in ("share", "rule", "entry", "mntent", "sharedfolder"): if wrapper in data and isinstance(data[wrapper], list): wrapped: list[dict[str, Any]] = data[wrapper] return wrapped return [] except Exception: return [] def _resolve_shared_folder(self, uuid: str) -> str: """Resolve an OMV shared folder UUID to its absolute filesystem path.""" if not uuid: return "" try: for folder in self._omv_read("conf.system.sharedfolder"): if folder.get("uuid") != uuid: continue rel = folder.get("reldirpath", "").strip("/") mnt_uuid = folder.get("mntentref", "") mnt_dir = "" for mntent in self._omv_read("conf.system.filesystem.mountpoint"): if mntent.get("uuid") == mnt_uuid: mnt_dir = mntent.get("dir", "").rstrip("/") break return f"{mnt_dir}/{rel}".rstrip("/") if rel else mnt_dir except Exception: logger.debug("%s: shared folder %s: ignored", self.hostname, uuid, exc_info=True) return "" def _smb_shares(self) -> dict[str, NASShareDict]: out: dict[str, NASShareDict] = {} for s in self._omv_read("conf.service.smb.shares"): name = s.get("name", "") if not name: continue path = self._resolve_shared_folder(s.get("sharedfolderref", "")) out[f"smb:{name}"] = NASShareDict( name=name, protocol="smb", path=path, volume=path.split("/")[-1] if path else "", enabled=bool(s.get("enable", True)), readonly=bool(s.get("readonly", False)), description=s.get("comment", ""), clients=[], ) return out def _nfs_shares(self) -> dict[str, NASShareDict]: out: dict[str, NASShareDict] = {} for s in self._omv_read("conf.service.nfs.shares"): path = self._resolve_shared_folder(s.get("sharedfolderref", "")) name = path.split("/")[-1] or s.get("sharedfolderref", "") clients_raw = s.get("client", "") or "" clients = [c.strip() for c in clients_raw.split(",") if c.strip()] opts = s.get("options", "") or "" out[f"nfs:{name}"] = NASShareDict( name=name, protocol="nfs", path=path, volume=path.split("/")[-1] if path else "", enabled=bool(s.get("enable", True)), readonly="ro" in [o.strip() for o in opts.split(",")], description="", clients=clients, ) return out def _ftp_shares(self) -> dict[str, NASShareDict]: out: dict[str, NASShareDict] = {} for s in self._omv_read("conf.service.ftp.shares"): path = self._resolve_shared_folder(s.get("sharedfolderref", "")) name = path.split("/")[-1] or s.get("sharedfolderref", "") out[f"ftp:{name}"] = NASShareDict( name=name, protocol="ftp", path=path, volume=path.split("/")[-1] if path else "", enabled=bool(s.get("enable", True)), readonly=bool(s.get("readonly", False)), description="", clients=[], ) return out