Files
napalm-openmediavault/napalm_openmediavault/openmediavault.py
T
Christian Manivong 70ad7883bc
driver / standard (pull_request) Successful in 17s
driver / lint (pull_request) Successful in 17s
driver / types (pull_request) Successful in 1m15s
driver / test (3.12) (pull_request) Successful in 1m11s
driver / test (3.13) (pull_request) Successful in 1m0s
driver / lowest (pull_request) Successful in 30s
driver / build (pull_request) Successful in 34s
driver / security (pull_request) Successful in 1m12s
CI / driver (pull_request) Successful in 2m58s
driver / publish (pull_request) Skipped
feat(time-sync): servers and zone through OpenMediaVault's own settings
napalm-linux now brings napalm-device-types' PosixTimeSyncMixin (4.35.0). Its write -- a chrony drop-in with every other source commented out, timedatectl set-timezone -- is the wrong way in on OpenMediaVault: OMV generates chrony.conf and the zone from conf.system.time through Salt and would take the change back on its next deploy, the web UI would keep showing its own servers, and netOrk's automatic alignment would rewrite on every poll (NetOrk/netork#2370).

OmvTimeSyncMixin reads the servers and the zone from System.getTimeSettings (no servers while NTP is off) and keeps the host's reading for whether the clock is synchronised and by which client. Both values are written through System.setTimeSettings, NTP switched on for servers, and only the modules that change made dirty are applied, plus chrony and timezone if already dirty, as set_hostname does. A value OMV already has is not written again, so a second write changes nothing. The floor rises to napalm-device-types 4.35.0.
2026-11-11 15:18:56 +01:00

808 lines
33 KiB
Python

# 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.base.exceptions import CommandErrorException
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
from napalm_openmediavault._scheduled_jobs import OmvScheduledJobsMixin
from napalm_openmediavault._time_sync import OmvTimeSyncMixin
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}(?<!-)$")
#: The modules OMV regenerates from ``conf.system.network.dns``. One already
#: dirty before the rename is applied with it, or the new name would not reach it.
_HOSTNAME_MODULES = frozenset(
{"hostname", "hosts", "postfix", "avahi", "samba", "proftpd", "systemdnetworkd"}
)
_DIRTY_MODULES = "/var/lib/openmediavault/dirtymodules.json"
#: Every block device, as JSON; sizes in bytes.
_LSBLK = "lsblk -J -b -o NAME,SIZE,TYPE,ROTA,VENDOR,MODEL,SERIAL,TRAN 2>/dev/null"
#: Identity, overall health verdict and attributes; ``-H`` alone prints the verdict.
_SMARTCTL = "smartctl -iHA /dev/{name} 2>/dev/null"
_SMARTCTL_TIMEOUT = 15
#: smartctl's exit status bits 0 and 1: the command line did not parse (sudo's own
#: refusal exits 1 as well) or the device could not be opened. Bits 2-7 describe the
#: disk, not the call.
_SMARTCTL_CALL_FAILED = 0b11
#: 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"}
#: ATA attributes counting sectors the disk lost or could not read, and the raw value
#: of each (the column after WHEN_FAILED).
_SMART_ATA_DEGRADED = ("Reallocated_Sector_Ct", "Current_Pending_Sector", "Offline_Uncorrectable")
_SMART_ATA_RAW_RE = re.compile(r"^\s*\d+\s+(\S+)\s+0x[0-9a-fA-F]+\s+(?:\S+\s+){6}(\d+)", re.M)
#: An NVMe disk's own warning flags, and the media errors it counted.
_SMART_NVME_CRITICAL_RE = re.compile(r"^Critical Warning:\s+0x([0-9a-fA-F]+)\s*$", re.M)
_SMART_NVME_MEDIA_ERRORS_RE = re.compile(r"^Media and Data Integrity Errors:\s+([\d,]+)\s*$", re.M)
#: A SCSI/SAS disk's reassigned blocks.
_SMART_SCSI_DEFECTS_RE = re.compile(r"^Elements in grown defect list:\s+(\d+)\s*$", re.M)
#: 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:
"""A disk's health from ``smartctl -iHA`` output.
``"failed"`` when the overall verdict says so; ``"warning"`` when it passed but
the disk counts lost or unreadable sectors (ATA reallocated, pending or offline
uncorrectable sectors, SAS grown defects) or, for NVMe, sets a critical warning
flag or counts media errors; ``"healthy"`` otherwise; ``"unknown"`` when
smartctl printed no verdict (no SMART support, a USB bridge without
pass-through).
"""
verdict = _smart_verdict(output)
if verdict == "healthy" and _smart_degraded(output):
return "warning"
return verdict
def _smart_verdict(output: str) -> str:
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_degraded(output: str) -> bool:
ata = any(
name in _SMART_ATA_DEGRADED and int(raw) > 0
for name, raw in _SMART_ATA_RAW_RE.findall(output)
)
critical = _SMART_NVME_CRITICAL_RE.search(output)
media = _SMART_NVME_MEDIA_ERRORS_RE.search(output)
defects = _SMART_SCSI_DEFECTS_RE.search(output)
return (
ata
or bool(critical and int(critical.group(1), 16))
or bool(media and int(media.group(1).replace(",", "")))
or bool(defects and int(defects.group(1)))
)
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, OmvScheduledJobsMixin, OmvTimeSyncMixin, 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, scheduled jobs, Docker) -- OMV really is Debian, so apt
applies -- and adds OMV-specific storage management on top. The scheduled
jobs of OMV's web UI go through its RPC (``_scheduled_jobs``), and so do its
time servers and zone (``_time_sync``).
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, but its template includes
#: /etc/ssh/sshd_config.d, which salt leaves alone: the SSH hardening from
#: napalm-linux goes into a drop-in there and never into sshd_config itself.
SSHD_CONFIG_GENERATED = True
# ── 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"``, ``"warning"``, ``"failed"``, or
``"unknown"`` (see :func:`smart_health`); a smartctl call that failed is
logged as a warning and leaves the disk ``"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",
},
]
:raises CommandErrorException: when lsblk printed no device list.
"""
result: list[PhysicalDiskDict] = []
devices = self._lsblk()
members = self._md_members()
for dev in devices:
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 _lsblk(self) -> list[dict[str, Any]]:
"""The block devices lsblk lists; a failed or garbled read raises."""
raw = self._send(_LSBLK)
try:
devices = _json.loads(raw)["blockdevices"]
except (ValueError, KeyError, TypeError) as exc:
raise CommandErrorException(
f"lsblk on {self.hostname} printed no device list: {raw[-300:]!r}"
) from exc
if not isinstance(devices, list):
raise CommandErrorException(f"lsblk on {self.hostname}: blockdevices is no list")
return devices
def _smart(self, name: str, disk_type: str) -> tuple[str, int, int]:
"""A disk's SMART health, temperature (``-1`` if unknown) and rpm (``0``).
A smartctl call that failed (timeout, sudo refused, device not opened) is
logged as a warning, so it is told apart from a disk without SMART; the
disk stays in the inventory as ``"unknown"``.
"""
try:
smart, status = self._sudo_status(
_SMARTCTL.format(name=name), read_timeout=_SMARTCTL_TIMEOUT
)
except OSError as exc: # TimeoutError and the socket's own errors
logger.warning("%s: smartctl for %s failed: %s", self.hostname, name, exc)
return "unknown", -1, 0
if status is not None and status & _SMARTCTL_CALL_FAILED:
logger.warning(
"%s: smartctl for %s failed (exit status %s): %s",
self.hostname,
name,
status,
smart[-300:],
)
return "unknown", -1, 0
rpm = 0
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))
return smart_health(smart), smart_temperature(smart), rpm
def _md_members(self) -> dict[str, str]:
"""The md array of each member device, from one read of ``/proc/mdstat``.
A host without the md driver has no ``/proc/mdstat`` and no members; a
failed read raises.
"""
return md_members(self._send("cat /proc/mdstat 2>/dev/null"))
# ── 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