diff --git a/CHANGELOG.md b/CHANGELOG.md index f7e7ce6..0308a0e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -6,7 +6,26 @@ All notable changes to this driver. The format follows ## [Unreleased] +## [0.4.0] - 2026-12-03 + +### Fixed +- `get_shares()` found no share at all (NetOrk/netork#3104): it asked for data models + OMV does not have (`conf.service.nfs.shares` and its siblings; the models are + `…share`), without root although `config.xml` is root's, without the full path + although `/usr/sbin` is not on a login user's `PATH` -- and every failure read as a NAS + without shares. Samba shares were dropped because OMV gives them no name of their own, + and several NFS clients of one folder overwrote each other. Now every model is read + through sudo in one round trip, a share takes its shared folder's name, NFS is one share + per folder with one access rule per client, and a read that fails raises. + ### Added +- Each share names the service that serves it (`service`: `smbd`, `nfs-server`, `proftpd`, + `rsync`, `tftpd-hpa`), what a client names to reach it (`export`: the Samba share, + `/export/` over NFS, `/` under the FTP root), who may (`access`, with + each NFS client's options and comment) and, for Samba, whether guests may (`guest`). + `volume` is the file system the shared folder is on. +- rsync modules, the TFTP plugin's root and Samba's home directories (`homes`, when + switched on) are shares too. A share is enabled only while OMV has its service on. - Time sync through OpenMediaVault's own settings (NetOrk/netork#2370). napalm-linux brings napalm-device-types' `PosixTimeSyncMixin` (4.35.0), whose write -- a chrony drop-in with the other sources commented out, `timedatectl set-timezone` -- OMV would take back the diff --git a/README.md b/README.md index 1e33c08..514d58b 100644 --- a/README.md +++ b/README.md @@ -38,7 +38,7 @@ with driver("192.0.2.10", "admin", "secret", optional_args={"sudo_password": "se | `get_disks` | `lsblk` for the disks, `smartctl -iHA` for health (`healthy`, `warning`, `failed`, `unknown`), temperature and RPM | | `get_disk_pools` | md arrays from `/proc/mdstat`, size and state from `mdadm --detail` | | `get_volumes` | mounted block-device filesystems from `df`, read-only flag from `/proc/mounts` | -| `get_shares` | SMB, NFS and FTP shares from OMV's configuration database (`omv-confdbadm`) | +| `get_shares` | Samba, NFS, FTP, rsync and TFTP shares from OMV's database (`omv-confdbadm` through sudo, every model in one round trip): a share takes its shared folder's name, NFS is one share per folder with one access rule per client, and each names its service (`smbd`, `nfs-server`, `proftpd`, `rsync`, `tftpd-hpa`) and what a client names (`/export/` over NFS); a read that fails raises | | `get_storage_services` | whether `smbd`, `nfs-server`, `proftpd`, `ssh` and `rsync` are enabled and running | | `get_scheduled_jobs` | napalm-linux's reading of the host, but the web UI's "Scheduled Jobs" and the power-management schedule come from `Cron.getList` (`omv:`, disabled ones too) instead of the lines OMV generates for them; the cron files OMV generates (`/etc/cron.d/openmediavault-*`, `openmediavault-flushmailq`, `-apticron`, `-samba-recycle`) are `platform` and only run | | `manage_scheduled_job` | an OMV job: `Cron.set` with only `enable` changed, or `Cron.execute` followed through `Exec.getOutput` (stopped after 300 s); a power-management job is not run; anything else as napalm-linux, never a generated file | diff --git a/napalm_openmediavault/_shares.py b/napalm_openmediavault/_shares.py new file mode 100644 index 0000000..cc56ab8 --- /dev/null +++ b/napalm_openmediavault/_shares.py @@ -0,0 +1,358 @@ +"""OpenMediaVault's shares, from its own database (NetOrk/netork#3104). + +OMV keeps every share in ``config.xml``. A *shared folder* +(``conf.system.sharedfolder``) is a directory on a mounted file system +(``conf.system.filesystem.mountpoint``); each service makes shares of shared folders: + +* Samba, ``conf.service.smb.share``: the share takes its shared folder's name; the + home directories are one more share, ``homes``, when switched on; +* NFS, ``conf.service.nfs.share``: one entry per client, so one share per shared + folder, with one access rule per entry. OMV binds each folder under ``/export``, + which is what a client mounts; +* FTP, ``conf.service.ftp.share``: a directory under the FTP root; +* rsync, ``conf.service.rsyncd.module``: a module by its own name; +* TFTP (the plugin), ``conf.service.tftp``: one shared folder is the TFTP root. + +Each share names the service that serves it as ``get_services`` names the unit +(``smbd``, ``nfs-server``, ``proftpd``, ``rsync``, ``tftpd-hpa``), and a share is +enabled only while its service is switched on in OMV. + +``config.xml`` is root's (``0660 root:openmediavault-config``), so ``omv-confdbadm`` +runs through sudo, every model in one round trip, with its full path: ``/usr/sbin`` is +not on a login user's ``PATH``. A plugin that is not installed has no data model and +no shares. A model that could not be read raises, and so does a report cut short: +an unread NAS must never look like one without shares. +""" + +from __future__ import annotations + +import json as _json +from typing import TYPE_CHECKING, Any + +from napalm_device_types.models import NASShareDict, ShareAccessDict + +_DATAMODELS = "/usr/share/openmediavault/datamodels" +_END = "@@omv-end" +_ABSENT = "@@absent" + +#: Every model a share is made of, read in one go. +_MODELS = ( + "conf.system.sharedfolder", + "conf.system.filesystem.mountpoint", + "conf.service.smb", + "conf.service.smb.share", + "conf.service.nfs", + "conf.service.nfs.share", + "conf.service.ftp", + "conf.service.ftp.share", + "conf.service.rsyncd", + "conf.service.rsyncd.module", + "conf.service.tftp", +) + +#: The command that reads them: per model a ``@@omv `` line, then its JSON and +#: ``@@rc ``, or ``@@absent`` when OMV has no such model (its plugin is not +#: installed); ``@@omv-end`` last. +CONFDB_READ_COMMAND = ( + f"for m in {' '.join(_MODELS)}; do " + 'printf "@@omv %s\\n" "$m"; ' + f'if [ -e "{_DATAMODELS}/$m.json" ]; then ' + '/usr/sbin/omv-confdbadm read "$m" 2>&1; printf "\\n@@rc %s\\n" "$?"; ' + f'else echo "{_ABSENT}"; fi; done; echo "{_END}"' +) + +#: The systemd unit that serves each protocol on OMV, as ``get_services`` names it. +SHARE_SERVICES = { + "smb": "smbd", + "nfs": "nfs-server", + "ftp": "proftpd", + "rsync": "rsync", + "tftp": "tftpd-hpa", +} + +#: Where OMV binds every shared folder it exports over NFS. +_NFS_ROOT = "/export" + + +def parse_confdb_report(output: str) -> dict[str, Any]: + """``{model: its data}`` from :data:`CONFDB_READ_COMMAND`'s output; None for a model + OMV does not have. + + :raises RuntimeError: when a model could not be read or the report is cut short. + """ + lines = output.splitlines() + if _END not in (line.strip() for line in lines): + raise RuntimeError("OMV's configuration was not read to the end") + models: dict[str, Any] = {} + for model, body in _blocks(lines): + models[model] = _model(model, body) + return models + + +def _blocks(lines: list[str]) -> list[tuple[str, list[str]]]: + """Each model's lines, ``@@absent`` or its JSON and ``@@rc``, under its name.""" + blocks: list[tuple[str, list[str]]] = [] + for line in lines: + text = line.strip() + if text.startswith("@@omv "): + blocks.append((text[len("@@omv ") :], [])) + elif blocks and text != _END: + blocks[-1][1].append(line) + return blocks + + +def _model(model: str, body: list[str]) -> Any: + """One model's data; None when OMV has no such model. + + :raises RuntimeError: when ``omv-confdbadm`` failed on it. + """ + texts = [line.strip() for line in body] + if _ABSENT in texts: + return None + status = next((t for t in reversed(texts) if t.startswith("@@rc ")), "") + data = [line for line, text in zip(body, texts, strict=True) if not text.startswith("@@rc ")] + if status != "@@rc 0": + raise RuntimeError(f"omv-confdbadm read {model} failed: {' '.join(data)[-300:]}") + return _json.loads("\n".join(data).strip() or "null") + + +def _entries(data: Any) -> list[dict[str, Any]]: + """A list model's entries; an older OMV wraps them in a dict.""" + if isinstance(data, list): + return [e for e in data if isinstance(e, dict)] + if isinstance(data, dict): + for value in data.values(): + if isinstance(value, list): + return [e for e in value if isinstance(e, dict)] + return [] + + +def _settings(data: Any) -> dict[str, Any]: + return data if isinstance(data, dict) else {} + + +def _hosts(text: str | None) -> list[str]: + """Samba's and rsync's ``hosts allow``: separated by commas, blanks or both.""" + return (text or "").replace(",", " ").split() + + +class _Folders: + """The shared folders, each as its name, path and the file system it is on.""" + + def __init__(self, models: dict[str, Any]) -> None: + mounts = { + m.get("uuid"): str(m.get("dir", "")).rstrip("/") + for m in _entries(models.get("conf.system.filesystem.mountpoint")) + } + self._by_uuid: dict[str, tuple[str, str, str]] = {} + for folder in _entries(models.get("conf.system.sharedfolder")): + mount = mounts.get(folder.get("mntentref"), "") + rel = str(folder.get("reldirpath", "")).strip("/") + path = f"{mount}/{rel}" if rel else mount + self._by_uuid[str(folder.get("uuid"))] = (str(folder.get("name", "")), path, mount) + + def get(self, uuid: Any) -> tuple[str, str, str] | None: + return self._by_uuid.get(str(uuid or "")) + + +def _share( + protocol: str, + name: str, + folder: tuple[str, str, str], + *, + enabled: bool, + readonly: bool, + description: str = "", + export: str, + access: list[ShareAccessDict] | None = None, +) -> NASShareDict: + _, path, mount = folder + rules = access or [] + return { + "name": name, + "protocol": protocol, + "path": path, + "volume": mount, + "enabled": enabled, + "readonly": readonly, + "description": description, + "clients": [r["client"] for r in rules], + "service": SHARE_SERVICES[protocol], + "export": export, + "access": rules, + } + + +def _host_rules(hosts: list[str], readonly: bool) -> list[ShareAccessDict]: + return [{"client": h, "readonly": readonly, "options": "", "comment": ""} for h in hosts] + + +def _smb(models: dict[str, Any], folders: _Folders) -> dict[str, NASShareDict]: + service = _settings(models.get("conf.service.smb")) + on = bool(service.get("enable", False)) + shares: dict[str, NASShareDict] = {} + for entry in _entries(models.get("conf.service.smb.share")): + folder = folders.get(entry.get("sharedfolderref")) + if folder is None: + continue + readonly = bool(entry.get("readonly", False)) + share = _share( + "smb", + folder[0], + folder, + enabled=on and bool(entry.get("enable", False)), + readonly=readonly, + description=str(entry.get("comment") or ""), + export=folder[0], + access=_host_rules(_hosts(entry.get("hostsallow")), readonly), + ) + share["guest"] = entry.get("guest", "no") in ("allow", "only") + shares[f"smb:{folder[0]}"] = share + if service.get("homesenable"): + shares["smb:homes"] = { + **_share("smb", "homes", ("homes", "", ""), enabled=on, readonly=False, export="homes"), + "guest": False, + } + return shares + + +def _nfs_rule(entry: dict[str, Any]) -> ShareAccessDict: + """One NFS client entry: its client, whether it reads only, its options and comment.""" + options = [str(o) for o in (entry.get("options"), entry.get("extraoptions")) if o] + flags = [o.strip() for o in str(entry.get("options") or "").split(",")] + return { + "client": str(entry.get("client") or ""), + "readonly": "ro" in flags, + "options": ",".join(options), + "comment": str(entry.get("comment") or ""), + } + + +def _nfs(models: dict[str, Any], folders: _Folders) -> dict[str, NASShareDict]: + on = bool(_settings(models.get("conf.service.nfs")).get("enable", False)) + by_folder: dict[str, tuple[tuple[str, str, str], list[ShareAccessDict]]] = {} + for entry in _entries(models.get("conf.service.nfs.share")): + folder = folders.get(entry.get("sharedfolderref")) + if folder is not None: + by_folder.setdefault(folder[0], (folder, []))[1].append(_nfs_rule(entry)) + return { + f"nfs:{name}": _share( + "nfs", + name, + folder, + enabled=on, + readonly=all(r["readonly"] for r in access), + export=f"{_NFS_ROOT}/{name}", + access=access, + ) + for name, (folder, access) in by_folder.items() + } + + +def _ftp(models: dict[str, Any], folders: _Folders) -> dict[str, NASShareDict]: + on = bool(_settings(models.get("conf.service.ftp")).get("enable", False)) + shares: dict[str, NASShareDict] = {} + for entry in _entries(models.get("conf.service.ftp.share")): + folder = folders.get(entry.get("sharedfolderref")) + if folder is None: + continue + shares[f"ftp:{folder[0]}"] = _share( + "ftp", + folder[0], + folder, + enabled=on and bool(entry.get("enable", False)), + readonly=False, + description=str(entry.get("comment") or ""), + export=f"/{folder[0]}", + ) + return shares + + +def _rsync(models: dict[str, Any], folders: _Folders) -> dict[str, NASShareDict]: + on = bool(_settings(models.get("conf.service.rsyncd")).get("enable", False)) + shares: dict[str, NASShareDict] = {} + for entry in _entries(models.get("conf.service.rsyncd.module")): + folder = folders.get(entry.get("sharedfolderref")) + name = str(entry.get("name") or "") + if folder is None or not name: + continue + readonly = bool(entry.get("readonly", False)) + shares[f"rsync:{name}"] = _share( + "rsync", + name, + folder, + enabled=on and bool(entry.get("enable", False)), + readonly=readonly, + description=str(entry.get("comment") or ""), + export=name, + access=_host_rules(_hosts(entry.get("hostsallow")), readonly), + ) + return shares + + +def _tftp(models: dict[str, Any], folders: _Folders) -> dict[str, NASShareDict]: + service = _settings(models.get("conf.service.tftp")) + folder = folders.get(service.get("sharedfolderref")) + if folder is None: + return {} + share = _share( + "tftp", + folder[0], + folder, + enabled=bool(service.get("enable", False)), + readonly=not service.get("allownewfiles", False), + export="/", + ) + return {f"tftp:{folder[0]}": share} + + +def omv_shares(models: dict[str, Any]) -> dict[str, NASShareDict]: + """Every share in OMV's *models*, keyed ``":"``.""" + folders = _Folders(models) + shares: dict[str, NASShareDict] = {} + for read in (_smb, _nfs, _ftp, _rsync, _tftp): + shares.update(read(models, folders)) + return shares + + +class OmvSharesMixin: + """``get_shares`` from OMV's own database, through sudo.""" + + if TYPE_CHECKING: # pragma: no cover - declared for type checkers only + + def _sudo_status( + self, command: str, read_timeout: float = 100 + ) -> tuple[str, int | None]: ... + + def get_shares(self) -> dict[str, NASShareDict]: + """ + Returns every share OMV is configured with: Samba, NFS, FTP, rsync and TFTP. + + Keys are ``":"`` (``"smb:media"``, ``"nfs:backups"``); a share + takes its shared folder's name, an rsync module its own. Each names the service + that serves it (``service``), what a client names to reach it (``export``: the + Samba share, ``/export/`` over NFS, ``/`` under the FTP root), + and who may (``access``, one rule per NFS client or allowed host). ``volume`` is + the file system the shared folder is on. + + Example:: + + { + "nfs:backups": { + "name": "backups", "protocol": "nfs", + "path": "/srv/dev-disk-by-uuid-1234/backups", + "volume": "/srv/dev-disk-by-uuid-1234", + "enabled": True, "readonly": False, "description": "", + "clients": ["192.168.1.0/24"], "service": "nfs-server", + "export": "/export/backups", + "access": [{"client": "192.168.1.0/24", "readonly": False, + "options": "rw,no_subtree_check", "comment": ""}], + }, + } + + :raises RuntimeError: when OMV's configuration could not be read. + """ + output, status = self._sudo_status(CONFDB_READ_COMMAND, 60) + if status != 0: + raise RuntimeError(f"OMV's configuration could not be read: {output[-300:]}") + return omv_shares(parse_confdb_report(output)) diff --git a/napalm_openmediavault/openmediavault.py b/napalm_openmediavault/openmediavault.py index bcbaacb..9b77fff 100644 --- a/napalm_openmediavault/openmediavault.py +++ b/napalm_openmediavault/openmediavault.py @@ -7,7 +7,7 @@ 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 +* SMB, NFS, FTP, rsync and TFTP shares from OMV's own database (``_shares``) Connects via SSH. Sudo access is required for smartctl and mdadm. All optional_args from LinuxDriver are accepted (pkg_manager, sudo_password, …). @@ -28,7 +28,6 @@ from napalm_device_types import FingerprintRule, StorageDriver from napalm_device_types.models import ( DiskPoolDict, LogicalVolumeDict, - NASShareDict, PhysicalDiskDict, ReplicationJobDict, StorageQuotaDict, @@ -39,6 +38,7 @@ from napalm_linux.linux import LinuxDriver from napalm_openmediavault._local_accounts import OmvLocalAccountsMixin from napalm_openmediavault._scheduled_jobs import OmvScheduledJobsMixin +from napalm_openmediavault._shares import OmvSharesMixin from napalm_openmediavault._time_sync import OmvTimeSyncMixin logger = logging.getLogger(__name__) @@ -162,7 +162,12 @@ def _pool_of(disk: str, members: dict[str, str]) -> str: class OpenMediaVaultDriver( - OmvLocalAccountsMixin, OmvScheduledJobsMixin, OmvTimeSyncMixin, StorageDriver, LinuxDriver + OmvSharesMixin, + OmvLocalAccountsMixin, + OmvScheduledJobsMixin, + OmvTimeSyncMixin, + StorageDriver, + LinuxDriver, ): """NAPALM driver for OpenMediaVault NAS systems. @@ -173,7 +178,8 @@ class OpenMediaVaultDriver( 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``). + time servers and zone (``_time_sync``), and its shares come from its database + (``_shares``). NAS services are ``get_storage_services()``; the systemd service list stays ``get_services()``. Two names for two different things. @@ -581,56 +587,6 @@ class OpenMediaVaultDriver( 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]: @@ -705,103 +661,3 @@ class OpenMediaVaultDriver( 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 diff --git a/pyproject.toml b/pyproject.toml index 77cb0af..441c004 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta" [project] name = "napalm-openmediavault" -version = "0.3.0" +version = "0.4.0" description = "NAPALM driver for OpenMediaVault NAS (SSH)" readme = "README.md" requires-python = ">=3.12" @@ -27,8 +27,8 @@ classifiers = [ ] dependencies = [ "napalm>=4.0", - "napalm-device-types>=4.35.0", - "napalm-linux>=0.17.0", + "napalm-device-types>=4.58.0", # NASShareDict service/export/access, ShareAccessDict + "napalm-linux>=0.27.0", # PosixSharesMixin under OmvSharesMixin ] [project.optional-dependencies] diff --git a/tests/test_shares.py b/tests/test_shares.py new file mode 100644 index 0000000..8a1a137 --- /dev/null +++ b/tests/test_shares.py @@ -0,0 +1,327 @@ +"""OpenMediaVault's shares, read from its own database (NetOrk/netork#3104). + +OMV keeps every share in ``config.xml``: a shared folder (``conf.system.sharedfolder``) +on a mounted file system (``conf.system.filesystem.mountpoint``), and per service the +shares made of it -- ``conf.service.smb.share``, ``conf.service.nfs.share`` (one entry +per client), ``conf.service.ftp.share``, ``conf.service.rsyncd.module`` and the TFTP +plugin's one folder. ``config.xml`` is root's, so ``omv-confdbadm`` runs through sudo, +all models in one round trip. A plugin that is not installed has no data model and no +shares; a read that fails raises, so it never reads as a NAS without shares. + +Each share names the service that serves it, as ``get_services`` names it, what a +client names to reach it, and who may. The data are shaped like OMV 8.8's. +""" + +from __future__ import annotations + +import json +import re + +import pytest + +from napalm_openmediavault.openmediavault import OpenMediaVaultDriver + +DISK = "/srv/dev-disk-by-uuid-5777" +FOLDERS = [ + {"uuid": "f-backups", "name": "Backups", "mntentref": "m-data", "reldirpath": "Backups/"}, + {"uuid": "f-media", "name": "media", "mntentref": "m-data", "reldirpath": "media/"}, + {"uuid": "f-scan", "name": "scan", "mntentref": "m-data", "reldirpath": "docroot/consume/"}, + {"uuid": "f-tftp", "name": "tftproot", "mntentref": "m-data", "reldirpath": "tftproot/"}, +] +MOUNTS = [{"uuid": "m-data", "dir": DISK, "fsname": "/dev/mapper/vg_data-lv_data"}] +SMB_SHARES = [ + { + "uuid": "s1", + "enable": True, + "sharedfolderref": "f-backups", + "comment": "", + "guest": "no", + "readonly": False, + "browseable": True, + "hostsallow": "", + "hostsdeny": "", + }, + { + "uuid": "s2", + "enable": True, + "sharedfolderref": "f-media", + "comment": "Films", + "guest": "allow", + "readonly": True, + "browseable": True, + "hostsallow": "10.40.100.0/24, 10.11.100.0/24", + "hostsdeny": "", + }, + { + "uuid": "s3", + "enable": False, + "sharedfolderref": "f-scan", + "comment": "", + "guest": "no", + "readonly": False, + "browseable": True, + "hostsallow": "", + "hostsdeny": "", + }, +] +NFS_SHARES = [ + { + "uuid": "n1", + "sharedfolderref": "f-scan", + "mntentref": "m-data", + "client": "172.22.0.0/16", + "options": "rw", + "comment": "", + "extraoptions": "fsid=0,no_subtree_check,async", + }, + { + "uuid": "n2", + "sharedfolderref": "f-scan", + "mntentref": "m-data", + "client": "10.40.100.0/24", + "options": "ro", + "comment": "SERVER", + "extraoptions": "", + }, + { + "uuid": "n3", + "sharedfolderref": "f-media", + "mntentref": "m-data", + "client": "10.42.100.0/24", + "options": "ro", + "comment": "", + "extraoptions": "", + }, +] +FTP_SHARES = [{"uuid": "t1", "enable": True, "sharedfolderref": "f-media", "comment": "Up"}] +RSYNC_MODULES = [ + { + "uuid": "r1", + "enable": True, + "sharedfolderref": "f-backups", + "name": "backup", + "comment": "Nightly", + "readonly": False, + "hostsallow": "10.40.100.5", + "hostsdeny": "", + } +] + + +def _settings(**overrides): + models = { + "conf.system.sharedfolder": FOLDERS, + "conf.system.filesystem.mountpoint": MOUNTS, + "conf.service.smb": {"enable": True, "homesenable": False}, + "conf.service.smb.share": SMB_SHARES, + "conf.service.nfs": {"enable": True, "versions": "4,4.1,4.2"}, + "conf.service.nfs.share": NFS_SHARES, + "conf.service.ftp": {"enable": True, "port": 21}, + "conf.service.ftp.share": FTP_SHARES, + "conf.service.rsyncd": {"enable": True, "port": 873}, + "conf.service.rsyncd.module": RSYNC_MODULES, + "conf.service.tftp": {"enable": True, "port": 69, "sharedfolderref": "f-tftp"}, + } + models.update(overrides) + return models + + +class Nas: + """omv-confdbadm as ``_sudo_status`` sees it: one call that reads every model. + + A model set to None is not installed (its plugin is not); one set to "fail" makes + omv-confdbadm fail on it. + """ + + def __init__(self, models: dict, *, cut: bool = False, status: int = 0) -> None: + self.models = models + self.cut = cut + self.status = status + self.commands: list[str] = [] + + def sudo_status(self, command: str, read_timeout: float = 100) -> tuple[str, int | None]: + self.commands.append(command) + assert "/usr/sbin/omv-confdbadm read" in command, command + wanted = re.search(r"for m in (.*?); do", command) + assert wanted, command + out = [] + for model in wanted.group(1).split(): + out.append(f"@@omv {model}") + value = self.models.get(model) + if value is None: + out.append("@@absent") + elif value == "fail": + out.append("Error: something broke") + out.append("@@rc 1") + else: + out.append(json.dumps(value)) + out.append("@@rc 0") + if not self.cut: + out.append("@@omv-end") + return "\n".join(out), self.status + + +def _shares(models: dict | None = None, **kwargs) -> dict: + nas = Nas(_settings() if models is None else models, **kwargs) + driver = OpenMediaVaultDriver("nas", "admin", "p") + driver._sudo_status = nas.sudo_status # type: ignore[method-assign] + return driver.get_shares() + + +class TestSmb: + def test_a_share_is_named_after_its_shared_folder(self): + assert _shares()["smb:Backups"] == { + "name": "Backups", + "protocol": "smb", + "path": f"{DISK}/Backups", + "volume": DISK, + "enabled": True, + "readonly": False, + "description": "", + "clients": [], + "service": "smbd", + "export": "Backups", + "access": [], + "guest": False, + } + + def test_guests_read_only_and_the_hosts_allowed(self): + media = _shares()["smb:media"] + + assert (media["guest"], media["readonly"], media["description"]) == (True, True, "Films") + assert media["clients"] == ["10.40.100.0/24", "10.11.100.0/24"] + assert media["access"] == [ + {"client": "10.40.100.0/24", "readonly": True, "options": "", "comment": ""}, + {"client": "10.11.100.0/24", "readonly": True, "options": "", "comment": ""}, + ] + + def test_a_share_switched_off_is_not_enabled(self): + assert _shares()["smb:scan"]["enabled"] is False + + def test_with_samba_switched_off_no_share_is_enabled(self): + shares = _shares(_settings(**{"conf.service.smb": {"enable": False}})) + + assert not any(s["enabled"] for k, s in shares.items() if k.startswith("smb:")) + + def test_the_home_directories_are_a_share_when_switched_on(self): + shares = _shares(_settings(**{"conf.service.smb": {"enable": True, "homesenable": True}})) + + assert shares["smb:homes"]["export"] == "homes" + assert shares["smb:homes"]["service"] == "smbd" + + +class TestNfs: + def test_one_share_per_folder_with_a_rule_per_client(self): + assert _shares()["nfs:scan"] == { + "name": "scan", + "protocol": "nfs", + "path": f"{DISK}/docroot/consume", + "volume": DISK, + "enabled": True, + "readonly": False, + "description": "", + "clients": ["172.22.0.0/16", "10.40.100.0/24"], + "service": "nfs-server", + "export": "/export/scan", + "access": [ + { + "client": "172.22.0.0/16", + "readonly": False, + "options": "rw,fsid=0,no_subtree_check,async", + "comment": "", + }, + { + "client": "10.40.100.0/24", + "readonly": True, + "options": "ro", + "comment": "SERVER", + }, + ], + } + + def test_read_only_when_every_client_reads_only(self): + assert _shares()["nfs:media"]["readonly"] is True + + def test_with_the_nfs_server_switched_off_none_is_enabled(self): + shares = _shares(_settings(**{"conf.service.nfs": {"enable": False}})) + + assert shares["nfs:scan"]["enabled"] is False + + +class TestFtpRsyncTftp: + def test_an_ftp_share_is_a_directory_under_the_ftp_root(self): + ftp = _shares()["ftp:media"] + + assert (ftp["service"], ftp["export"], ftp["description"]) == ("proftpd", "/media", "Up") + + def test_an_rsync_module_by_its_name(self): + module = _shares()["rsync:backup"] + + assert (module["service"], module["export"], module["path"]) == ( + "rsync", + "backup", + f"{DISK}/Backups", + ) + assert module["clients"] == ["10.40.100.5"] + assert module["description"] == "Nightly" + + def test_the_tftp_root(self): + tftp = _shares()["tftp:tftproot"] + + assert (tftp["service"], tftp["export"], tftp["path"]) == ( + "tftpd-hpa", + "/", + f"{DISK}/tftproot", + ) + + def test_a_plugin_not_installed_has_no_shares(self): + shares = _shares( + _settings( + **{ + "conf.service.ftp": None, + "conf.service.ftp.share": None, + "conf.service.tftp": None, + } + ) + ) + + assert not [k for k in shares if k.startswith(("ftp:", "tftp:"))] + assert "smb:Backups" in shares + + def test_tftp_without_a_folder_has_no_share(self): + shares = _shares( + _settings(**{"conf.service.tftp": {"enable": True, "sharedfolderref": ""}}) + ) + + assert not [k for k in shares if k.startswith("tftp:")] + + +class TestReading: + def test_one_round_trip_through_sudo(self): + nas = Nas(_settings()) + driver = OpenMediaVaultDriver("nas", "admin", "p") + driver._sudo_status = nas.sudo_status # type: ignore[method-assign] + + driver.get_shares() + + assert len(nas.commands) == 1 + + def test_a_model_that_fails_raises(self): + with pytest.raises(RuntimeError, match="conf.service.nfs.share"): + _shares(_settings(**{"conf.service.nfs.share": "fail"})) + + def test_a_report_cut_short_raises(self): + with pytest.raises(RuntimeError): + _shares(cut=True) + + def test_sudo_refusing_raises(self): + """Without root nothing was read: no NAS without shares.""" + with pytest.raises(RuntimeError): + _shares(models={}, status=1) + + def test_a_share_on_a_folder_that_is_gone_keeps_no_path(self): + smb = [{**SMB_SHARES[0], "sharedfolderref": "f-gone"}] + + assert _shares(_settings(**{"conf.service.smb.share": smb})) == { + k: v for k, v in _shares().items() if not k.startswith("smb:") + }