From dd1b74a0104bd2a33beecb08553f717bbcf103e2 Mon Sep 17 00:00:00 2001 From: Christian Manivong Date: Thu, 3 Dec 2026 18:45:06 +0100 Subject: [PATCH] refactor: the share shapes in share_models, Samba's parse in parts (NetOrk/netork#3104) The standard's ratchet: models.py may not grow, and a new function stays within complexity 10. NASShareDict and ShareAccessDict move to share_models; models re-exports both, so every import keeps working. --- napalm_device_types/models.py | 40 +----------------- napalm_device_types/posix_shares.py | 64 ++++++++++++++++++----------- napalm_device_types/share_models.py | 49 ++++++++++++++++++++++ tests/quality_baseline.json | 2 +- 4 files changed, 91 insertions(+), 64 deletions(-) create mode 100644 napalm_device_types/share_models.py diff --git a/napalm_device_types/models.py b/napalm_device_types/models.py index 9cba46d..571e965 100644 --- a/napalm_device_types/models.py +++ b/napalm_device_types/models.py @@ -30,6 +30,8 @@ from napalm_device_types.host_firewall_models import NetfilterRuleDict as Netfil from napalm_device_types.kernel_models import KernelFactsDict as KernelFactsDict from napalm_device_types.os_models import ProcessDict as ProcessDict from napalm_device_types.os_models import UserDict as UserDict +from napalm_device_types.share_models import NASShareDict as NASShareDict +from napalm_device_types.share_models import ShareAccessDict as ShareAccessDict from napalm_device_types.snmp_health_profile import SnmpHealthProfile as SnmpHealthProfile from napalm_device_types.snmp_health_profile import SnmpInterfacesSpec as SnmpInterfacesSpec from napalm_device_types.snmp_health_profile import SnmpMemorySpec as SnmpMemorySpec @@ -835,44 +837,6 @@ class LogicalVolumeDict(TypedDict): snapshots: int # number of snapshots currently held -class ShareAccessDict(TypedDict): - """One rule of who may reach a share: an NFS export's client entry, an address - Samba's ``hosts allow`` names.""" - - client: str # an address, a network, a host name or a pattern ("*", "*.lan") - readonly: bool - options: str # the rule's options as the server spells them; empty where it has none - comment: str - - -class NASShareDict(TypedDict): - """A network share or iSCSI target exported by the storage device. - - The optional keys say how a share is reached, where the driver can tell - (NetOrk/netork#3104): which of the host's services serves it, what a client - names to reach it, and who may. - """ - - name: str - protocol: str # "nfs", "smb", "afp", "ftp", "sftp", "iscsi", "webdav", "rsync" - path: str # local filesystem path or iSCSI target IQN - volume: str # logical volume or dataset this share is backed by - enabled: bool - readonly: bool - description: str - clients: list[str] # IP/subnet allow-list; empty list = all hosts allowed - #: The service that serves it, by the name ``get_services`` reports (``smbd``, - #: ``nfs-server``, ``proftpd``); None where the driver cannot say. - service: NotRequired[str | None] - #: What a client names to reach it: an NFS export's path (``/export/media``), a - #: Samba share's name, an rsync module's name. - export: NotRequired[str] - #: Who may reach it, one rule per client entry, in the server's order. - access: NotRequired[list[ShareAccessDict]] - #: Open to guests, without an account of the host's (Samba's ``guest ok``). - guest: NotRequired[bool] - - class VolumeSnapshotDict(TypedDict): """A point-in-time snapshot of a logical volume or dataset.""" diff --git a/napalm_device_types/posix_shares.py b/napalm_device_types/posix_shares.py index b41cdeb..d396a5b 100644 --- a/napalm_device_types/posix_shares.py +++ b/napalm_device_types/posix_shares.py @@ -167,36 +167,50 @@ def _yes(value: str | None, default: bool) -> bool: return value.strip().lower() in ("yes", "true", "1") -def _samba_shares(lines: list[str], service: str | None) -> dict[str, NASShareDict]: +def _testparm_loaded(lines: list[str]) -> bool: + """Whether testparm ran; False without testparm on the host. + + :raises ValueError: when it could not load Samba's configuration. + """ statuses = [m.group(1) for m in map(_TP_RC_RE.match, (x.strip() for x in lines)) if m] if not statuses: - return {} # no testparm on the host + return False if statuses[-1] != "0": detail = " ".join(x.strip() for x in lines if not _TP_RC_RE.match(x.strip()))[:200] raise ValueError(f"testparm could not load Samba's configuration: {detail}") - shares: dict[str, NASShareDict] = {} - for name, params in _samba_sections(lines).items(): - if name.lower() in _NOT_SHARES or _yes(params.get("printable"), False): - continue - readonly = _yes(params.get("read only"), True) - clients = params.get("hosts allow", "").replace(",", " ").split() - shares[f"smb:{name}"] = { - "name": name, - "protocol": "smb", - "path": params.get("path", "").rstrip("/") or params.get("path", ""), - "volume": "", - "enabled": _yes(params.get("available"), True), - "readonly": readonly, - "description": params.get("comment", ""), - "clients": clients, - "service": service, - "export": name, - "access": [ - {"client": c, "readonly": readonly, "options": "", "comment": ""} for c in clients - ], - "guest": _yes(params.get("guest ok"), False), - } - return shares + return True + + +def _samba_share(name: str, params: dict[str, str], service: str | None) -> NASShareDict: + readonly = _yes(params.get("read only"), True) + clients = params.get("hosts allow", "").replace(",", " ").split() + path = params.get("path", "") + return { + "name": name, + "protocol": "smb", + "path": path.rstrip("/") or path, + "volume": "", + "enabled": _yes(params.get("available"), True), + "readonly": readonly, + "description": params.get("comment", ""), + "clients": clients, + "service": service, + "export": name, + "access": [ + {"client": c, "readonly": readonly, "options": "", "comment": ""} for c in clients + ], + "guest": _yes(params.get("guest ok"), False), + } + + +def _samba_shares(lines: list[str], service: str | None) -> dict[str, NASShareDict]: + if not _testparm_loaded(lines): + return {} + return { + f"smb:{name}": _samba_share(name, params, service) + for name, params in _samba_sections(lines).items() + if name.lower() not in _NOT_SHARES and not _yes(params.get("printable"), False) + } def parse_posix_shares(output: str) -> dict[str, NASShareDict]: diff --git a/napalm_device_types/share_models.py b/napalm_device_types/share_models.py new file mode 100644 index 0000000..a0515dd --- /dev/null +++ b/napalm_device_types/share_models.py @@ -0,0 +1,49 @@ +"""The shapes of a file server's shares (NetOrk/netork#3104). + +A storage driver's ``get_shares`` and a Linux host's (``PosixSharesMixin``) answer in +:class:`NASShareDict`; ``models`` re-exports both names, where they used to live. +""" + +from __future__ import annotations + +from typing import NotRequired + +from typing_extensions import TypedDict + + +class ShareAccessDict(TypedDict): + """One rule of who may reach a share: an NFS export's client entry, an address + Samba's ``hosts allow`` names.""" + + client: str # an address, a network, a host name or a pattern ("*", "*.lan") + readonly: bool + options: str # the rule's options as the server spells them; empty where it has none + comment: str + + +class NASShareDict(TypedDict): + """A network share or iSCSI target exported by the storage device. + + The optional keys say how a share is reached, where the driver can tell + (NetOrk/netork#3104): which of the host's services serves it, what a client + names to reach it, and who may. + """ + + name: str + protocol: str # "nfs", "smb", "afp", "ftp", "sftp", "iscsi", "webdav", "rsync" + path: str # local filesystem path or iSCSI target IQN + volume: str # logical volume or dataset this share is backed by + enabled: bool + readonly: bool + description: str + clients: list[str] # IP/subnet allow-list; empty list = all hosts allowed + #: The service that serves it, by the name ``get_services`` reports (``smbd``, + #: ``nfs-server``, ``proftpd``); None where the driver cannot say. + service: NotRequired[str | None] + #: What a client names to reach it: an NFS export's path (``/export/media``), a + #: Samba share's name, an rsync module's name. + export: NotRequired[str] + #: Who may reach it, one rule per client entry, in the server's order. + access: NotRequired[list[ShareAccessDict]] + #: Open to guests, without an account of the host's (Samba's ``guest ok``). + guest: NotRequired[bool] diff --git a/tests/quality_baseline.json b/tests/quality_baseline.json index e8a0c5f..e58db2a 100644 --- a/tests/quality_baseline.json +++ b/tests/quality_baseline.json @@ -31,7 +31,7 @@ }, "mypy_relaxed": [], "python_file_lines": { - "napalm_device_types/models.py": 1297 + "napalm_device_types/models.py": 1286 }, "untyped_public": [] }