feat: file shares and network mounts, the kernel's NFS server, 4.58.0 (NetOrk/netork#3104) #147
No files matched your search
@@ -7,6 +7,30 @@ recorded here; their history is the git log.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [4.58.0] - 2026-12-03
|
||||
|
||||
### Added
|
||||
- `PosixSharesMixin` (`get_shares`): the NFS exports and Samba shares an ordinary Linux
|
||||
server serves, in `StorageDriver.get_shares`' shape (NetOrk/netork#3104). NFS from the
|
||||
kernel's export table, `/var/lib/nfs/etab`, one share per export path; Samba from
|
||||
`testparm -s`. Each share names the service that serves it; a share whose server is not
|
||||
installed is left out. A driver supplies `_run_shares_command(command)`.
|
||||
- `NASShareDict`: optional `service` (the serving service, by `get_services`' name),
|
||||
`export` (what a client names to reach it), `access` (one `ShareAccessDict` per client
|
||||
rule) and `guest`. `rsync` is a protocol a share may have.
|
||||
- `KERNEL_SERVED_UNITS`: `nfs-server`.
|
||||
- `NetworkMountsMixin` (`get_network_mounts`): the NFS exports and SMB shares a host has
|
||||
mounted, from `/proc/self/mounts`, each with its server as named and as the address the
|
||||
kernel connected to, so an application can tell which host depends on which share
|
||||
(NetOrk/netork#3104). A driver supplies `_run_network_mounts_command(command)`.
|
||||
|
||||
### Changed
|
||||
- `get_services` reports a service whose server is the kernel's (`nfs-server`) as running
|
||||
while its unit is active. Its unit stays `active (exited)` with no process; before, it
|
||||
read as stopped while the kernel served.
|
||||
- `get_listening_sockets` names `nfs-server` as the unit of a socket without a process on a
|
||||
port the kernel's NFS server lists in `/proc/fs/nfsd/portlist`.
|
||||
|
||||
## [4.57.0] - 2026-12-03
|
||||
|
||||
### Added
|
||||
|
||||
@@ -280,7 +280,8 @@ advisories do the same.
|
||||
|
||||
`ListeningSocketsMixin` (`get_listening_sockets`) is mixed in the same way: every listening
|
||||
TCP and bound UDP socket from `ss -lntup`, with the systemd service or container behind it
|
||||
from `/proc/<pid>/cgroup`, in one round trip. A driver supplies
|
||||
from `/proc/<pid>/cgroup`, in one round trip. The kernel's NFS server holds its sockets without
|
||||
a process; a socket on a port `/proc/fs/nfsd/portlist` lists belongs to `nfs-server`. A driver supplies
|
||||
`_run_listening_sockets_command(command, privileged=)`; the command arrives as one `sh -c`
|
||||
argument, so a `sudo -n` prefix covers all of it. Without root `ss` names only the login
|
||||
user's processes, and the reading says so (`attributed: false`) instead of failing. A host
|
||||
@@ -489,6 +490,28 @@ here, and a driver supplies only `_run_service_command(command, *, privileged, t
|
||||
trip (`list-unit-files` plus one `systemctl show` over every loaded unit) instead of an
|
||||
`is-enabled` and a `show` per unit. A host without systemd raises `SystemdUnavailable`,
|
||||
a `NotImplementedError`, so a driver can fall back to another init system.
|
||||
A service whose server is the kernel's (`KERNEL_SERVED_UNITS`: `nfs-server`, which starts
|
||||
nfsd) is running while its unit is active: the unit stays `active (exited)` with no process
|
||||
while the kernel serves, and a stopped NFS server is `inactive`.
|
||||
|
||||
`NetworkMountsMixin` (`get_network_mounts`) is mixed in the same way: the other side of a
|
||||
file server's shares, the NFS exports and SMB shares the host has mounted, from
|
||||
`/proc/self/mounts` (`nfs`, `nfs4`, `cifs`, `smb3`). Each says the server as the mount
|
||||
names it and as the address the kernel connected to (`addr=`), the export (an NFS path, an
|
||||
SMB share's name), the mount point and whether it is read-only. Readable without root; a
|
||||
driver supplies `_run_network_mounts_command(command)`.
|
||||
|
||||
`PosixSharesMixin` (`get_shares`) is mixed in the same way: the file shares an ordinary
|
||||
Linux server serves, in `StorageDriver.get_shares`' shape -- its NFS exports from the
|
||||
kernel's export table (`/var/lib/nfs/etab`, one share per export path with one access rule
|
||||
per client) and its Samba shares from `testparm -s` (a share without `read only = No` is
|
||||
read-only, Samba's default). Each share names the service that serves it, by the name
|
||||
`get_services` reports (`nfs-server`, `smbd` on Debian, `smb` on Red Hat); a share whose
|
||||
server is not installed is left out. Everything reads without root. A driver supplies
|
||||
`_run_shares_command(command)`; a NAS driver that reads its own configuration defines
|
||||
`get_shares` itself. `NASShareDict` carries, where a driver can tell, `service`, `export`
|
||||
(what a client names: an NFS export's path, a Samba share's name), `access`
|
||||
(`ShareAccessDict`: client, read-only, options, comment) and `guest`.
|
||||
|
||||
`ScheduledJobsMixin` (`get_scheduled_jobs`, `manage_scheduled_job`, `put_scheduled_job`,
|
||||
`delete_scheduled_job`) is what a host runs on its own schedule — cron lines, run-parts
|
||||
|
||||
@@ -71,6 +71,8 @@ instead of being restated on every role that happens to need it:
|
||||
* :class:`~napalm_device_types.ping_sweep.PingSweepMixin`
|
||||
* :class:`~napalm_device_types.running_backups.RunningBackupsMixin`
|
||||
* :class:`~napalm_device_types.service_clusters.ServiceClustersMixin`
|
||||
* :class:`~napalm_device_types.network_mounts.NetworkMountsMixin`
|
||||
* :class:`~napalm_device_types.posix_shares.PosixSharesMixin`
|
||||
* :class:`~napalm_device_types.service_packages.ServicePackagesMixin`
|
||||
* :class:`~napalm_device_types.services_restart.ServicesRestartMixin`
|
||||
* :class:`~napalm_device_types.ssh_server_auth.SshServerAuthMixin`
|
||||
@@ -357,6 +359,12 @@ from napalm_device_types.models import (
|
||||
UpdateProgressDict,
|
||||
)
|
||||
from napalm_device_types.nat_vpn import NatVpnMixin
|
||||
from napalm_device_types.network_mounts import (
|
||||
NETWORK_MOUNTS_COMMAND,
|
||||
NetworkMountDict,
|
||||
NetworkMountsMixin,
|
||||
parse_network_mounts,
|
||||
)
|
||||
from napalm_device_types.opened_ports import (
|
||||
OPENED_PORTS_RECORD,
|
||||
SNMP_PURPOSE,
|
||||
@@ -387,6 +395,11 @@ from napalm_device_types.package_updates import (
|
||||
from napalm_device_types.packages import PackageManagementMixin
|
||||
from napalm_device_types.phone import PhoneDriver
|
||||
from napalm_device_types.ping_sweep import PingSweepMixin, driver_supports_ping
|
||||
from napalm_device_types.posix_shares import (
|
||||
POSIX_SHARES_COMMAND,
|
||||
PosixSharesMixin,
|
||||
parse_posix_shares,
|
||||
)
|
||||
from napalm_device_types.posix_tz import (
|
||||
DstTransitionDict,
|
||||
PosixTzDict,
|
||||
@@ -746,6 +759,13 @@ __all__ = [
|
||||
"is_interactive",
|
||||
"parse_login_sessions",
|
||||
"session_address",
|
||||
"NETWORK_MOUNTS_COMMAND",
|
||||
"NetworkMountDict",
|
||||
"NetworkMountsMixin",
|
||||
"parse_network_mounts",
|
||||
"POSIX_SHARES_COMMAND",
|
||||
"PosixSharesMixin",
|
||||
"parse_posix_shares",
|
||||
"SERVICE_PACKAGES_COMMAND",
|
||||
"SERVICES_RESTART_COMMAND",
|
||||
"ServicesRestartMixin",
|
||||
|
||||
@@ -27,6 +27,11 @@ no ``ss``; ``netstat -lntup`` lists the same sockets with ``PID/Program``, and
|
||||
the cgroups are read for its PIDs alike. On OpenWrt the cgroup names the procd
|
||||
service (``/services/<name>/<instance>``), a jailed one too, whose PID is not the
|
||||
one procd reports. A host with neither raises :class:`ListeningSocketsUnavailable`.
|
||||
|
||||
**The kernel's NFS server.** nfsd holds its sockets without a process, so no
|
||||
cgroup names its service. ``/proc/fs/nfsd/portlist``, readable by everyone, lists
|
||||
the ports it serves; a socket on one of them that no process holds belongs to
|
||||
``nfs-server``, the unit that starts it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -63,9 +68,13 @@ LISTENING_SOCKETS_COMMAND = (
|
||||
"for p in $(printf '%s\\n' \"$pids\" | sort -u); do "
|
||||
'sed "s|^|$p |" /proc/$p/cgroup 2>/dev/null; done; '
|
||||
"else echo '[no-ss]'; fi; "
|
||||
"echo '[nfsd]'; cat /proc/fs/nfsd/portlist 2>/dev/null; "
|
||||
"printf '%s%s\\n' SOCK_ END"
|
||||
)
|
||||
|
||||
#: The unit that starts the kernel's NFS server, whose sockets have no process.
|
||||
NFS_SERVER_UNIT = "nfs-server"
|
||||
|
||||
_PROTOCOLS = frozenset({"tcp", "udp"})
|
||||
#: netstat names the IPv6 sockets of net-tools ``tcp6``/``udp6``; busybox does not.
|
||||
_NETSTAT_PROTOCOLS = {"tcp": "tcp", "tcp6": "tcp", "udp": "udp", "udp6": "udp"}
|
||||
@@ -203,6 +212,22 @@ def _netstat_socket(line: str, paths: dict[int, str]) -> ListeningSocketDict | N
|
||||
_PARSERS = {"ss": _ss_socket, "netstat": _netstat_socket}
|
||||
|
||||
|
||||
def _nfsd_ports(lines: list[str]) -> set[tuple[str, int]]:
|
||||
"""``tcp 2049`` lines of ``/proc/fs/nfsd/portlist`` as ``(proto, port)``."""
|
||||
ports: set[tuple[str, int]] = set()
|
||||
for line in lines:
|
||||
parts = line.split()
|
||||
if len(parts) == 2 and parts[0] in _PROTOCOLS and parts[1].isdigit():
|
||||
ports.add((parts[0], int(parts[1])))
|
||||
return ports
|
||||
|
||||
|
||||
def _name_kernel_nfs(sockets: list[ListeningSocketDict], ports: set[tuple[str, int]]) -> None:
|
||||
for socket in sockets:
|
||||
if socket["pid"] is None and (socket["proto"], socket["port"]) in ports:
|
||||
socket["unit"] = NFS_SERVER_UNIT
|
||||
|
||||
|
||||
def parse_listening_sockets(output: str) -> list[ListeningSocketDict]:
|
||||
"""Parse what :data:`LISTENING_SOCKETS_COMMAND` printed, sorted by protocol,
|
||||
port and address.
|
||||
@@ -222,6 +247,7 @@ def parse_listening_sockets(output: str) -> list[ListeningSocketDict]:
|
||||
paths = _cgroup_paths(sections.get("cgroups", []))
|
||||
parse = _PARSERS[tool]
|
||||
sockets = [s for s in (parse(line, paths) for line in lines) if s is not None]
|
||||
_name_kernel_nfs(sockets, _nfsd_ports(sections.get("nfsd", [])))
|
||||
return sorted(
|
||||
sockets, key=lambda s: (s["proto"], s["port"], s["address"], s["interface"] or "")
|
||||
)
|
||||
|
||||
@@ -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,19 +837,6 @@ class LogicalVolumeDict(TypedDict):
|
||||
snapshots: int # number of snapshots currently held
|
||||
|
||||
|
||||
class NASShareDict(TypedDict):
|
||||
"""A network share or iSCSI target exported by the storage device."""
|
||||
|
||||
name: str
|
||||
protocol: str # "nfs", "smb", "afp", "ftp", "sftp", "iscsi", "webdav"
|
||||
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
|
||||
|
||||
|
||||
class VolumeSnapshotDict(TypedDict):
|
||||
"""A point-in-time snapshot of a logical volume or dataset."""
|
||||
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
"""The NFS exports and SMB shares a host has mounted.
|
||||
|
||||
The other side of a file server's shares (NetOrk/netork#3104): which host uses which
|
||||
export, so that an application can tell what depends on a share. Reading it is the same
|
||||
on every Linux host, so the command and its parse live here once and a driver only
|
||||
carries the command across.
|
||||
|
||||
``/proc/self/mounts`` lists every mount with its source as the client wrote it --
|
||||
``nas:/export/media``, ``[2001:db8::8]:/data``, ``//nas/media/sub`` -- and the kernel's
|
||||
options for it, among them ``addr=``: the address the kernel connected to, the server
|
||||
as an address whatever name was typed. NFS is ``nfs`` and ``nfs4``, SMB ``cifs`` and
|
||||
``smb3``; every other file system is left out. A space in a mount point is ``\\040``
|
||||
there and is decoded. Readable by everyone. The report is framed; one cut short raises,
|
||||
because a list cut short must never read as shares nobody mounts.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import TYPE_CHECKING, TypedDict
|
||||
|
||||
from napalm_device_types.terminal import strip_terminal_codes
|
||||
|
||||
_BEGIN = "MOUNTS_BEGIN"
|
||||
_END = "MOUNTS_END"
|
||||
|
||||
#: One line, POSIX ``sh``, read-only, no root needed. The frame markers are printed in
|
||||
#: two halves so that a transport which echoes the command does not show them early.
|
||||
NETWORK_MOUNTS_COMMAND = (
|
||||
"printf '%s%s\\n' MOUNTS_ BEGIN; cat /proc/self/mounts 2>/dev/null; "
|
||||
"printf '%s%s\\n' MOUNTS_ END"
|
||||
)
|
||||
|
||||
_PROTOCOLS = {"nfs": "nfs", "nfs4": "nfs", "cifs": "smb", "smb3": "smb"}
|
||||
_OCTAL = re.compile(r"\\([0-7]{3})")
|
||||
|
||||
|
||||
class NetworkMountDict(TypedDict):
|
||||
"""One NFS export or SMB share a host has mounted."""
|
||||
|
||||
protocol: str # "nfs" or "smb"
|
||||
#: The server as the mount names it: a host name, an address.
|
||||
server: str
|
||||
#: The address the kernel connected to (``addr=``); None where it does not say.
|
||||
address: str | None
|
||||
#: What was mounted: an NFS export's path, an SMB share's name.
|
||||
export: str
|
||||
mountpoint: str
|
||||
readonly: bool
|
||||
|
||||
|
||||
def _frame(output: str) -> list[str]:
|
||||
lines = [line.strip() for line in strip_terminal_codes(output).splitlines()]
|
||||
try:
|
||||
start = lines.index(_BEGIN)
|
||||
end = lines.index(_END, start)
|
||||
except ValueError:
|
||||
raise ValueError("no intact mount report in the output") from None
|
||||
return lines[start + 1 : end]
|
||||
|
||||
|
||||
def _unescape(text: str) -> str:
|
||||
return _OCTAL.sub(lambda m: chr(int(m.group(1), 8)), text)
|
||||
|
||||
|
||||
def _nfs_source(source: str) -> tuple[str, str] | None:
|
||||
"""``host:/path`` or ``[v6]:/path`` -> ``(host, path)``."""
|
||||
if source.startswith("["):
|
||||
host, sep, path = source[1:].partition("]:")
|
||||
else:
|
||||
host, sep, path = source.partition(":")
|
||||
return (host, path) if sep and host and path.startswith("/") else None
|
||||
|
||||
|
||||
def _smb_source(source: str) -> tuple[str, str] | None:
|
||||
"""``//host/share[/below]`` -> ``(host, share)``."""
|
||||
parts = source.lstrip("/").split("/")
|
||||
if not source.startswith("//") or len(parts) < 2 or not parts[0] or not parts[1]:
|
||||
return None
|
||||
return parts[0].strip("[]"), parts[1]
|
||||
|
||||
|
||||
def _mount(line: str) -> NetworkMountDict | None:
|
||||
fields = line.split()
|
||||
if len(fields) < 4 or fields[2] not in _PROTOCOLS:
|
||||
return None
|
||||
protocol = _PROTOCOLS[fields[2]]
|
||||
source = _unescape(fields[0])
|
||||
parsed = _nfs_source(source) if protocol == "nfs" else _smb_source(source)
|
||||
if parsed is None:
|
||||
return None
|
||||
options = fields[3].split(",")
|
||||
address = next((o[len("addr=") :] for o in options if o.startswith("addr=")), None)
|
||||
return {
|
||||
"protocol": protocol,
|
||||
"server": parsed[0],
|
||||
"address": address or None,
|
||||
"export": parsed[1],
|
||||
"mountpoint": _unescape(fields[1]),
|
||||
"readonly": "ro" in options,
|
||||
}
|
||||
|
||||
|
||||
def parse_network_mounts(output: str) -> list[NetworkMountDict]:
|
||||
"""Parse what :data:`NETWORK_MOUNTS_COMMAND` printed, in the order mounted.
|
||||
|
||||
:raises ValueError: when the output carries no intact report.
|
||||
"""
|
||||
return [m for m in map(_mount, _frame(output)) if m is not None]
|
||||
|
||||
|
||||
class NetworkMountsMixin:
|
||||
"""Adds :meth:`get_network_mounts` to a driver that can run a command on a Linux host.
|
||||
|
||||
The template form (README, "Function classes"): the reading and its parse are
|
||||
concrete here, and a driver supplies only :meth:`_run_network_mounts_command`.
|
||||
"""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_network_mounts_command(self, command: str) -> str:
|
||||
"""Run *command* on the host with ``sh`` and return what it printed."""
|
||||
...
|
||||
|
||||
def get_network_mounts(self) -> list[NetworkMountDict]:
|
||||
"""
|
||||
Returns the NFS exports and SMB shares the host has mounted.
|
||||
|
||||
Example::
|
||||
|
||||
[
|
||||
{"protocol": "nfs", "server": "nas.example.lan", "address": "192.0.2.8",
|
||||
"export": "/export/media", "mountpoint": "/mnt/media", "readonly": False},
|
||||
{"protocol": "smb", "server": "nas", "address": "192.0.2.8",
|
||||
"export": "Daten", "mountpoint": "/mnt/daten", "readonly": False},
|
||||
]
|
||||
|
||||
:raises ValueError: if the host's output carried no intact report.
|
||||
"""
|
||||
return parse_network_mounts(self._run_network_mounts_command(NETWORK_MOUNTS_COMMAND))
|
||||
@@ -0,0 +1,276 @@
|
||||
"""The file shares a Linux server serves itself: its NFS exports and Samba shares.
|
||||
|
||||
A NAS reports its shares from its own configuration
|
||||
(:meth:`~napalm_device_types.storage.StorageDriver.get_shares`). An ordinary Debian
|
||||
or RHEL server that exports a directory over NFS or shares one with Samba serves the
|
||||
same thing, and reading that is the same on every such host. So the command and its
|
||||
parse live here once, in ``get_shares``' shape, and a driver only carries the command
|
||||
across (NetOrk/netork#3104).
|
||||
|
||||
**NFS: the kernel's export table.** ``/var/lib/nfs/etab`` is what ``exportfs`` gave
|
||||
the kernel, one line per export and client with every option spelled out, ``rw`` or
|
||||
``ro`` among them. ``/etc/exports`` is what was meant; etab is what is served. One
|
||||
share per export path, with one access rule per client.
|
||||
|
||||
**Samba: testparm.** ``testparm -s`` prints the configuration Samba loads, includes
|
||||
resolved, without the defaults. A share without ``read only = No`` is therefore
|
||||
read-only, as Samba's default is. ``[global]``, the printers and the printer drivers
|
||||
(``[print$]``) are no shares; one switched off with ``available = No`` is a share
|
||||
that is not enabled.
|
||||
|
||||
**Which service.** Each share names the service that serves it, by the name
|
||||
``get_services`` reports: ``nfs-server`` for the kernel's NFS server, ``smbd`` for
|
||||
Samba's file server on Debian and ``smb`` on Red Hat. The command asks systemd which
|
||||
is installed. An export table or a ``testparm`` without its server installed --
|
||||
``samba-common-bin`` comes with the client tools too -- serves nothing and is left
|
||||
out. A host without systemd is read all the same, with no service named.
|
||||
|
||||
Everything is readable without root. The report is framed: one cut short raises,
|
||||
and so does ``testparm`` failing where Samba serves, because a configuration Samba
|
||||
cannot load must not read as one without shares.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from napalm_device_types.models import NASShareDict, ShareAccessDict
|
||||
from napalm_device_types.terminal import strip_terminal_codes
|
||||
|
||||
_BEGIN = "SHARES_BEGIN"
|
||||
_END = "SHARES_END"
|
||||
_NO_SYSTEMD = "__NO_SYSTEMD"
|
||||
_TP_RC_RE = re.compile(r"^__TP_RC=(\d+)$")
|
||||
|
||||
#: One line, POSIX ``sh``, read-only, no root needed. The frame markers are printed
|
||||
#: in two halves so that a transport which echoes the command does not show them early.
|
||||
POSIX_SHARES_COMMAND = (
|
||||
"PATH=$PATH:/usr/sbin:/sbin; "
|
||||
"printf '%s%s\\n' SHARES_ BEGIN; "
|
||||
"echo '[units]'; "
|
||||
"if [ -d /run/systemd/system ]; then "
|
||||
"systemctl show -p Id -p LoadState -- nfs-server.service smbd.service smb.service "
|
||||
"2>/dev/null; else echo __NO_SYSTEMD; fi; "
|
||||
"echo '[etab]'; cat /var/lib/nfs/etab 2>/dev/null; "
|
||||
"echo '[samba]'; "
|
||||
"if command -v testparm >/dev/null 2>&1; then "
|
||||
'testparm -s 2>/dev/null; echo "__TP_RC=$?"; fi; '
|
||||
"printf '%s%s\\n' SHARES_ END"
|
||||
)
|
||||
|
||||
NFS_SERVER_UNIT = "nfs-server"
|
||||
#: Samba's file server: ``smbd`` on Debian and its derivatives, ``smb`` on Red Hat's.
|
||||
SAMBA_UNITS = ("smbd", "smb")
|
||||
|
||||
#: Sections of a Samba configuration that are no file share.
|
||||
_NOT_SHARES = frozenset({"global", "printers", "print$"})
|
||||
_SECTION_RE = re.compile(r"^\[(.+)\]$")
|
||||
#: An etab line: ``/path<TAB>client(options)``.
|
||||
_ETAB_RE = re.compile(r"^(\S+)\s+(\S+?)\((.*)\)$")
|
||||
|
||||
|
||||
def _frame(output: str) -> dict[str, list[str]]:
|
||||
lines = [line.rstrip() for line in strip_terminal_codes(output).splitlines()]
|
||||
stripped = [line.strip() for line in lines]
|
||||
try:
|
||||
start = stripped.index(_BEGIN)
|
||||
end = stripped.index(_END, start)
|
||||
except ValueError:
|
||||
raise ValueError("no intact share report in the output") from None
|
||||
sections: dict[str, list[str]] = {}
|
||||
current: list[str] | None = None
|
||||
for line in lines[start + 1 : end]:
|
||||
if line in ("[units]", "[etab]", "[samba]"):
|
||||
current = sections.setdefault(line[1:-1], [])
|
||||
elif current is not None:
|
||||
current.append(line)
|
||||
return sections
|
||||
|
||||
|
||||
def _installed_units(lines: list[str]) -> set[str] | None:
|
||||
"""The units of :data:`POSIX_SHARES_COMMAND` that are installed; None without systemd."""
|
||||
if any(line.strip() == _NO_SYSTEMD for line in lines):
|
||||
return None
|
||||
installed: set[str] = set()
|
||||
unit = ""
|
||||
for line in [*lines, ""]:
|
||||
key, _, value = line.strip().partition("=")
|
||||
if key == "Id":
|
||||
unit = value.removesuffix(".service")
|
||||
elif key == "LoadState" and unit:
|
||||
if value == "loaded":
|
||||
installed.add(unit)
|
||||
unit = ""
|
||||
return installed
|
||||
|
||||
|
||||
def _options_readonly(options: str) -> bool:
|
||||
"""An NFS client entry is read-only when its last ``rw``/``ro`` says ``ro``."""
|
||||
flags = [o for o in options.split(",") if o in ("rw", "ro")]
|
||||
return bool(flags) and flags[-1] == "ro"
|
||||
|
||||
|
||||
def _nfs_shares(lines: list[str], service: str | None) -> dict[str, NASShareDict]:
|
||||
rules: dict[str, list[ShareAccessDict]] = {}
|
||||
for line in lines:
|
||||
match = _ETAB_RE.match(line.strip())
|
||||
if not match:
|
||||
continue
|
||||
path, client, options = match.groups()
|
||||
rules.setdefault(path, []).append(
|
||||
{
|
||||
"client": client,
|
||||
"readonly": _options_readonly(options),
|
||||
"options": options,
|
||||
"comment": "",
|
||||
}
|
||||
)
|
||||
shares: dict[str, NASShareDict] = {}
|
||||
for path, access in sorted(rules.items()):
|
||||
clients = [r["client"] for r in access]
|
||||
shares[f"nfs:{path}"] = {
|
||||
"name": path,
|
||||
"protocol": "nfs",
|
||||
"path": path,
|
||||
"volume": "",
|
||||
"enabled": True,
|
||||
"readonly": all(r["readonly"] for r in access),
|
||||
"description": "",
|
||||
"clients": [] if "*" in clients else clients,
|
||||
"service": service,
|
||||
"export": path,
|
||||
"access": access,
|
||||
}
|
||||
return shares
|
||||
|
||||
|
||||
def _samba_sections(lines: list[str]) -> dict[str, dict[str, str]]:
|
||||
sections: dict[str, dict[str, str]] = {}
|
||||
current: dict[str, str] | None = None
|
||||
for line in lines:
|
||||
text = line.strip()
|
||||
if not text or text.startswith(("#", ";")) or _TP_RC_RE.match(text):
|
||||
continue
|
||||
section = _SECTION_RE.match(text)
|
||||
if section:
|
||||
current = sections.setdefault(section.group(1), {})
|
||||
elif current is not None and "=" in text:
|
||||
key, _, value = text.partition("=")
|
||||
current[key.strip().lower()] = value.strip()
|
||||
return sections
|
||||
|
||||
|
||||
def _yes(value: str | None, default: bool) -> bool:
|
||||
if value is None:
|
||||
return default
|
||||
return value.strip().lower() in ("yes", "true", "1")
|
||||
|
||||
|
||||
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 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}")
|
||||
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]:
|
||||
"""Parse what :data:`POSIX_SHARES_COMMAND` printed: ``{"<protocol>:<name>": share}``.
|
||||
|
||||
An NFS share is named by its export path, a Samba share by its own name.
|
||||
|
||||
:raises ValueError: when the output carries no intact report, or ``testparm``
|
||||
failed on a host whose Samba serves.
|
||||
"""
|
||||
sections = _frame(output)
|
||||
installed = _installed_units(sections.get("units", []))
|
||||
shares: dict[str, NASShareDict] = {}
|
||||
if installed is None or NFS_SERVER_UNIT in installed:
|
||||
nfs_service = None if installed is None else NFS_SERVER_UNIT
|
||||
shares.update(_nfs_shares(sections.get("etab", []), nfs_service))
|
||||
samba = None if installed is None else next((u for u in SAMBA_UNITS if u in installed), "")
|
||||
if samba != "":
|
||||
shares.update(_samba_shares(sections.get("samba", []), samba))
|
||||
return shares
|
||||
|
||||
|
||||
class PosixSharesMixin:
|
||||
"""Adds :meth:`get_shares` to a driver that can run a command on a Linux server.
|
||||
|
||||
The template form (README, "Function classes"): the reading and its parse are
|
||||
concrete here, and a driver supplies only :meth:`_run_shares_command` -- how a
|
||||
command reaches its host. A NAS driver that reads its shares from its own
|
||||
configuration defines ``get_shares`` itself, which wins over this one.
|
||||
"""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - declared for type checkers only
|
||||
|
||||
def _run_shares_command(self, command: str) -> str:
|
||||
"""Run *command* on the host with ``sh`` and return what it printed."""
|
||||
...
|
||||
|
||||
def get_shares(self) -> dict[str, NASShareDict]:
|
||||
"""
|
||||
Returns the NFS exports and Samba shares the host serves, in the shape of
|
||||
:meth:`~napalm_device_types.storage.StorageDriver.get_shares`.
|
||||
|
||||
Each share also names the service that serves it (``service``), what a
|
||||
client names to reach it (``export``), and who may (``access``); a Samba
|
||||
share whether guests may (``guest``).
|
||||
|
||||
Example::
|
||||
|
||||
{
|
||||
"nfs:/srv/backups": {
|
||||
"name": "/srv/backups", "protocol": "nfs", "path": "/srv/backups",
|
||||
"volume": "", "enabled": True, "readonly": False,
|
||||
"description": "", "clients": ["10.0.0.0/24"],
|
||||
"service": "nfs-server", "export": "/srv/backups",
|
||||
"access": [{"client": "10.0.0.0/24", "readonly": False,
|
||||
"options": "rw,sync,no_subtree_check", "comment": ""}],
|
||||
},
|
||||
}
|
||||
|
||||
:raises ValueError: if the host's output carried no intact report, or Samba's
|
||||
configuration could not be loaded.
|
||||
"""
|
||||
return parse_posix_shares(self._run_shares_command(POSIX_SHARES_COMMAND))
|
||||
@@ -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]
|
||||
@@ -89,6 +89,11 @@ _UNIT_RE = re.compile(r"(?:[A-Za-z0-9_.:@-]|\\x[0-9A-Fa-f]{2})+")
|
||||
_MAX_UNIT_LENGTH = 255
|
||||
|
||||
_ENABLED = frozenset({"enabled", "enabled-runtime"})
|
||||
|
||||
#: Services whose server is the kernel's: the unit only starts it and stays active
|
||||
#: (``exited``) with no process while the kernel serves. ``nfs-server`` starts
|
||||
#: nfsd, under its Debian alias ``nfs-kernel-server`` too.
|
||||
KERNEL_SERVED_UNITS = frozenset({"nfs-server"})
|
||||
#: Unit file states of a service that is installed but need not be loaded.
|
||||
_INSTALLED = frozenset({"enabled", "enabled-runtime", "disabled", "indirect"})
|
||||
|
||||
@@ -204,6 +209,13 @@ def _main_pid(block: dict[str, str]) -> int:
|
||||
return 0
|
||||
|
||||
|
||||
def _running(block: dict[str, str], name: str) -> bool:
|
||||
"""Active and running, or active at all for a service the kernel serves."""
|
||||
if block.get("ActiveState") != "active":
|
||||
return False
|
||||
return block.get("SubState") == "running" or name in KERNEL_SERVED_UNITS
|
||||
|
||||
|
||||
def _loaded(blocks: list[dict[str, str]]) -> tuple[dict[str, ServiceDict], set[str]]:
|
||||
"""The loaded services, and every name they go by (aliases included)."""
|
||||
services: dict[str, ServiceDict] = {}
|
||||
@@ -213,7 +225,7 @@ def _loaded(blocks: list[dict[str, str]]) -> tuple[dict[str, ServiceDict], set[s
|
||||
if not unit.endswith(_SUFFIX) or block.get("LoadState") == "not-found":
|
||||
continue
|
||||
names.update(block.get("Names", unit).split())
|
||||
running = block.get("ActiveState") == "active" and block.get("SubState") == "running"
|
||||
running = _running(block, _base(unit))
|
||||
services[_base(unit)] = {
|
||||
"name": _base(unit),
|
||||
"running": running,
|
||||
@@ -303,7 +315,8 @@ class SystemdServicesMixin(ServiceControlMixin):
|
||||
Returns the services systemd knows, in one round trip.
|
||||
|
||||
* name (string) - the unit name without ``.service``
|
||||
* running (bool) - active and running
|
||||
* running (bool) - active and running; active for a service the kernel
|
||||
serves (:data:`KERNEL_SERVED_UNITS`), whose unit has no process
|
||||
* enabled (bool) - the unit file is enabled
|
||||
* pid (int) - the main process; 0 when not running
|
||||
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "napalm-device-types"
|
||||
version = "4.57.0"
|
||||
version = "4.58.0"
|
||||
description = "Abstract device-type base classes for NAPALM drivers"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.12"
|
||||
|
||||
@@ -31,7 +31,7 @@
|
||||
},
|
||||
"mypy_relaxed": [],
|
||||
"python_file_lines": {
|
||||
"napalm_device_types/models.py": 1297
|
||||
"napalm_device_types/models.py": 1286
|
||||
},
|
||||
"untyped_public": []
|
||||
}
|
||||
@@ -126,6 +126,53 @@ class TestParsing:
|
||||
assert parse_listening_sockets(_wire(SS.splitlines(True)[0], "")) == []
|
||||
|
||||
|
||||
def _with_nfsd(portlist: str, ss: str = SS) -> str:
|
||||
"""The report with the kernel's NFS server listing its ports."""
|
||||
return _wire(ss).replace("SOCK_END\n", f"[nfsd]\n{portlist}SOCK_END\n")
|
||||
|
||||
|
||||
class TestKernelNfsServer:
|
||||
"""The kernel's nfsd holds its sockets without a process, so no cgroup names
|
||||
its unit. /proc/fs/nfsd/portlist says which ports are nfsd's: those
|
||||
belong to nfs-server, the unit that starts it (NetOrk/netork#3104)."""
|
||||
|
||||
def test_a_socket_on_a_port_nfsd_lists_is_the_nfs_server(self):
|
||||
sockets = _by_port(parse_listening_sockets(_with_nfsd("tcp 2049\ntcp 2049\n")))
|
||||
|
||||
assert sockets[("tcp", 2049, "0.0.0.0")]["unit"] == "nfs-server"
|
||||
assert sockets[("tcp", 2049, "0.0.0.0")]["process"] is None
|
||||
|
||||
def test_both_address_families(self):
|
||||
ss = SS + "tcp LISTEN 0 64 [::]:2049 [::]:*\n"
|
||||
|
||||
sockets = _by_port(parse_listening_sockets(_with_nfsd("tcp 2049\n", ss)))
|
||||
|
||||
assert sockets[("tcp", 2049, "::")]["unit"] == "nfs-server"
|
||||
|
||||
def test_only_the_protocol_nfsd_lists(self):
|
||||
ss = SS + "udp UNCONN 0 0 0.0.0.0:2049 0.0.0.0:*\n"
|
||||
|
||||
sockets = _by_port(parse_listening_sockets(_with_nfsd("tcp 2049\n", ss)))
|
||||
|
||||
assert sockets[("udp", 2049, "0.0.0.0")]["unit"] is None
|
||||
|
||||
def test_a_process_on_that_port_keeps_its_own_unit(self):
|
||||
"""A userspace NFS server (nfs-ganesha) has a process and a cgroup."""
|
||||
line = 'tcp LISTEN 0 64 0.0.0.0:2049 0.0.0.0:* users:(("ganesha.nfsd",pid=5,fd=3))\n'
|
||||
raw = _wire(line, "5 0::/system.slice/nfs-ganesha.service\n").replace(
|
||||
"SOCK_END\n", "[nfsd]\ntcp 2049\nSOCK_END\n"
|
||||
)
|
||||
|
||||
[socket] = parse_listening_sockets(raw)
|
||||
|
||||
assert socket["unit"] == "nfs-ganesha"
|
||||
|
||||
def test_without_the_kernel_server_the_socket_stays_unnamed(self):
|
||||
sockets = _by_port(parse_listening_sockets(_with_nfsd("")))
|
||||
|
||||
assert sockets[("tcp", 2049, "0.0.0.0")]["unit"] is None
|
||||
|
||||
|
||||
class TestCgroups:
|
||||
def _unit_and_container(self, cgroup_lines: str) -> tuple:
|
||||
line = 'tcp LISTEN 0 128 0.0.0.0:1 0.0.0.0:* users:(("p",pid=5,fd=3))\n'
|
||||
@@ -314,6 +361,9 @@ class TestTheNetstatFallback:
|
||||
|
||||
|
||||
class TestTheCommand:
|
||||
def test_it_reads_the_ports_of_the_kernels_nfs_server(self):
|
||||
assert "[nfsd]'; cat /proc/fs/nfsd/portlist 2>/dev/null;" in LISTENING_SOCKETS_COMMAND
|
||||
|
||||
def test_the_frame_is_not_in_the_command_itself(self):
|
||||
"""An echoing transport prints the command back; the markers must only
|
||||
appear once the command has run."""
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
"""get_network_mounts: the NFS exports and SMB shares a host has mounted.
|
||||
|
||||
The other side of a file server's shares (NetOrk/netork#3104): which host uses which
|
||||
export. ``/proc/self/mounts`` names each mount's source as the client wrote it
|
||||
(``nas:/export/media``, ``//nas/media``) and, in its options, the address the kernel
|
||||
connected to (``addr=``) -- the server as an address, whatever name was typed.
|
||||
Readable by everyone; the same on every Linux host.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_device_types.network_mounts import (
|
||||
NETWORK_MOUNTS_COMMAND,
|
||||
NetworkMountsMixin,
|
||||
parse_network_mounts,
|
||||
)
|
||||
|
||||
MOUNTS = """\
|
||||
sysfs /sys sysfs rw,nosuid,nodev,noexec,relatime 0 0
|
||||
/dev/sda1 / ext4 rw,relatime 0 0
|
||||
nas.example.lan:/export/media /mnt/media nfs4 rw,relatime,vers=4.2,rsize=1048576,hard,proto=tcp,clientaddr=192.0.2.20,addr=192.0.2.8 0 0
|
||||
192.0.2.8:/scan /srv/scan nfs4 ro,relatime,vers=4.2,clientaddr=192.0.2.20,addr=192.0.2.8 0 0
|
||||
backup:/srv/backups /mnt/backup\\040disk nfs rw,relatime,vers=3,mountaddr=192.0.2.9,addr=192.0.2.9 0 0
|
||||
[2001:db8::8]:/export/n8n /data nfs4 rw,relatime,vers=4.2,clientaddr=2001:db8::20,addr=2001:db8::8 0 0
|
||||
//nas/Daten/Projekte /mnt/daten cifs rw,relatime,vers=3.1.1,cache=strict,username=me,addr=192.0.2.8,file_mode=0755 0 0
|
||||
//192.0.2.8/media /mnt/smb smb3 ro,relatime,vers=3.1.1,addr=192.0.2.8 0 0
|
||||
nas:/export/x /mnt/x nfs4 rw,relatime 0 0
|
||||
tmpfs /run tmpfs rw,nosuid,nodev,size=1631468k,mode=755 0 0
|
||||
"""
|
||||
|
||||
|
||||
def _wire(mounts: str = MOUNTS, *, end: bool = True) -> str:
|
||||
return f"MOUNTS_BEGIN\n{mounts}" + ("MOUNTS_END\n" if end else "")
|
||||
|
||||
|
||||
def _by_mountpoint() -> dict:
|
||||
return {m["mountpoint"]: m for m in parse_network_mounts(_wire())}
|
||||
|
||||
|
||||
class TestNfs:
|
||||
def test_an_nfs_mount_with_the_address_the_kernel_connected_to(self):
|
||||
assert _by_mountpoint()["/mnt/media"] == {
|
||||
"protocol": "nfs",
|
||||
"server": "nas.example.lan",
|
||||
"address": "192.0.2.8",
|
||||
"export": "/export/media",
|
||||
"mountpoint": "/mnt/media",
|
||||
"readonly": False,
|
||||
}
|
||||
|
||||
def test_nfs_v3_and_an_escaped_mountpoint(self):
|
||||
backup = _by_mountpoint()["/mnt/backup disk"]
|
||||
|
||||
assert (backup["server"], backup["address"], backup["export"]) == (
|
||||
"backup",
|
||||
"192.0.2.9",
|
||||
"/srv/backups",
|
||||
)
|
||||
|
||||
def test_a_read_only_mount(self):
|
||||
assert _by_mountpoint()["/srv/scan"]["readonly"] is True
|
||||
|
||||
def test_an_ipv6_server_in_brackets(self):
|
||||
n8n = _by_mountpoint()["/data"]
|
||||
|
||||
assert (n8n["server"], n8n["address"], n8n["export"]) == (
|
||||
"2001:db8::8",
|
||||
"2001:db8::8",
|
||||
"/export/n8n",
|
||||
)
|
||||
|
||||
def test_without_addr_the_address_is_unknown(self):
|
||||
assert _by_mountpoint()["/mnt/x"]["address"] is None
|
||||
|
||||
|
||||
class TestSmb:
|
||||
def test_a_cifs_mount_names_its_share(self):
|
||||
"""A path below the share is still that share's."""
|
||||
assert _by_mountpoint()["/mnt/daten"] == {
|
||||
"protocol": "smb",
|
||||
"server": "nas",
|
||||
"address": "192.0.2.8",
|
||||
"export": "Daten",
|
||||
"mountpoint": "/mnt/daten",
|
||||
"readonly": False,
|
||||
}
|
||||
|
||||
def test_smb3(self):
|
||||
smb = _by_mountpoint()["/mnt/smb"]
|
||||
|
||||
assert (smb["protocol"], smb["export"], smb["readonly"]) == ("smb", "media", True)
|
||||
|
||||
|
||||
class TestTheRest:
|
||||
def test_local_filesystems_are_left_out(self):
|
||||
assert len(parse_network_mounts(_wire())) == 7
|
||||
|
||||
def test_no_network_mount_is_an_empty_list(self):
|
||||
assert parse_network_mounts(_wire("/dev/sda1 / ext4 rw 0 0\n")) == []
|
||||
|
||||
def test_a_report_cut_short_raises(self):
|
||||
with pytest.raises(ValueError):
|
||||
parse_network_mounts(_wire(end=False))
|
||||
|
||||
def test_output_without_the_frame_raises(self):
|
||||
with pytest.raises(ValueError):
|
||||
parse_network_mounts("cat: /proc/self/mounts: No such file or directory\n")
|
||||
|
||||
def test_the_command_is_valid_sh_without_the_frame_in_it(self):
|
||||
assert subprocess.run(["sh", "-n", "-c", NETWORK_MOUNTS_COMMAND]).returncode == 0
|
||||
assert "MOUNTS_BEGIN" not in NETWORK_MOUNTS_COMMAND
|
||||
|
||||
def test_it_runs_here(self):
|
||||
out = subprocess.run(
|
||||
["sh", "-c", NETWORK_MOUNTS_COMMAND], capture_output=True, text=True, timeout=30
|
||||
).stdout
|
||||
|
||||
assert isinstance(parse_network_mounts(out), list)
|
||||
|
||||
|
||||
class _Driver(NetworkMountsMixin):
|
||||
def __init__(self, output: str) -> None:
|
||||
self.output = output
|
||||
self.commands: list[str] = []
|
||||
|
||||
def _run_network_mounts_command(self, command: str) -> str:
|
||||
self.commands.append(command)
|
||||
return self.output
|
||||
|
||||
|
||||
def test_the_mixin_runs_the_command_once():
|
||||
driver = _Driver(_wire())
|
||||
|
||||
assert len(driver.get_network_mounts()) == 7
|
||||
assert driver.commands == [NETWORK_MOUNTS_COMMAND]
|
||||
@@ -0,0 +1,286 @@
|
||||
"""get_shares on an ordinary Linux server: its NFS exports and Samba shares.
|
||||
|
||||
A NAS reports its shares from its own configuration. A Debian or RHEL server that
|
||||
exports a directory over NFS or shares one with Samba serves the same thing, and
|
||||
reading it is the same on every such host: the kernel's export table and
|
||||
``testparm -s``. Each share names the service that serves it, by the name
|
||||
``get_services`` reports (NetOrk/netork#3104).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_device_types.posix_shares import (
|
||||
POSIX_SHARES_COMMAND,
|
||||
PosixSharesMixin,
|
||||
parse_posix_shares,
|
||||
)
|
||||
|
||||
# The kernel's export table on an OpenMediaVault host, options shortened.
|
||||
ETAB = """\
|
||||
/export\t172.22.0.0/16(ro,sync,wdelay,hide,secure,root_squash,subtree_check,fsid=0,sec=sys,ro,secure,root_squash)
|
||||
/export/n8n\t10.42.100.0/24(rw,sync,wdelay,hide,secure,root_squash,no_subtree_check,fsid=b84a5859,sec=sys,rw,secure,root_squash)
|
||||
/export/scan\t172.22.0.0/16(rw,async,wdelay,hide,secure,root_squash,no_subtree_check,fsid=0,fsid=049608c9,sec=sys,rw)
|
||||
/export/scan\t10.40.100.0/24(rw,async,wdelay,hide,secure,root_squash,no_subtree_check,fsid=dedc5411,sec=sys,rw)
|
||||
/srv/public\t*(ro,sync,wdelay,hide,secure,root_squash,sec=sys,ro)
|
||||
"""
|
||||
|
||||
# testparm -s prints only what differs from Samba's defaults.
|
||||
TESTPARM = """\
|
||||
# Global parameters
|
||||
[global]
|
||||
\tmap to guest = Bad User
|
||||
\tserver string = %h server
|
||||
|
||||
|
||||
[Backups]
|
||||
\tpath = /srv/dev-disk-by-uuid-5777/Backups/
|
||||
\tread only = No
|
||||
\tvfs objects = catia fruit streams_xattr
|
||||
|
||||
|
||||
[Media]
|
||||
\tcomment = Films and music
|
||||
\tguest ok = Yes
|
||||
\tpath = /srv/media
|
||||
|
||||
|
||||
[Old]
|
||||
\tavailable = No
|
||||
\tpath = /srv/old
|
||||
\tread only = No
|
||||
|
||||
|
||||
[Office]
|
||||
\thosts allow = 10.40.100.0/24 10.11.100.0/24
|
||||
\tpath = /srv/office
|
||||
\tread only = No
|
||||
|
||||
|
||||
[printers]
|
||||
\tbrowseable = No
|
||||
\tpath = /var/spool/samba
|
||||
\tprintable = Yes
|
||||
|
||||
|
||||
[print$]
|
||||
\tpath = /var/lib/samba/printers
|
||||
"""
|
||||
|
||||
DEBIAN_UNITS = """\
|
||||
Id=nfs-server.service
|
||||
LoadState=loaded
|
||||
|
||||
Id=smbd.service
|
||||
LoadState=loaded
|
||||
|
||||
Id=smb.service
|
||||
LoadState=not-found
|
||||
"""
|
||||
|
||||
|
||||
def _wire(
|
||||
units: str = DEBIAN_UNITS,
|
||||
etab: str = ETAB,
|
||||
samba: str | None = TESTPARM,
|
||||
*,
|
||||
samba_rc: int = 0,
|
||||
end: bool = True,
|
||||
) -> str:
|
||||
"""The report as the command prints it, framed."""
|
||||
samba_part = "" if samba is None else f"{samba}__TP_RC={samba_rc}\n"
|
||||
tail = "SHARES_END\n" if end else ""
|
||||
return f"SHARES_BEGIN\n[units]\n{units}[etab]\n{etab}[samba]\n{samba_part}{tail}"
|
||||
|
||||
|
||||
class TestNfs:
|
||||
def test_an_export_with_its_clients(self):
|
||||
shares = parse_posix_shares(_wire())
|
||||
|
||||
assert shares["nfs:/export/scan"] == {
|
||||
"name": "/export/scan",
|
||||
"protocol": "nfs",
|
||||
"path": "/export/scan",
|
||||
"volume": "",
|
||||
"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,async,wdelay,hide,secure,root_squash,no_subtree_check,"
|
||||
"fsid=0,fsid=049608c9,sec=sys,rw",
|
||||
"comment": "",
|
||||
},
|
||||
{
|
||||
"client": "10.40.100.0/24",
|
||||
"readonly": False,
|
||||
"options": "rw,async,wdelay,hide,secure,root_squash,no_subtree_check,"
|
||||
"fsid=dedc5411,sec=sys,rw",
|
||||
"comment": "",
|
||||
},
|
||||
],
|
||||
}
|
||||
|
||||
def test_an_export_every_client_reads_only_is_read_only(self):
|
||||
assert parse_posix_shares(_wire())["nfs:/srv/public"]["readonly"] is True
|
||||
|
||||
def test_an_export_to_everyone(self):
|
||||
"""``*`` is every host; an empty clients list says the same."""
|
||||
assert parse_posix_shares(_wire())["nfs:/srv/public"]["clients"] == []
|
||||
|
||||
def test_one_share_per_export(self):
|
||||
nfs = [k for k in parse_posix_shares(_wire()) if k.startswith("nfs:")]
|
||||
|
||||
assert nfs == ["nfs:/export", "nfs:/export/n8n", "nfs:/export/scan", "nfs:/srv/public"]
|
||||
|
||||
def test_no_exports_is_none(self):
|
||||
assert not [k for k in parse_posix_shares(_wire(etab="")) if k.startswith("nfs:")]
|
||||
|
||||
def test_an_export_table_without_an_nfs_server_is_left_out(self):
|
||||
"""A stale etab on a host whose NFS server was removed serves nothing."""
|
||||
units = DEBIAN_UNITS.replace(
|
||||
"Id=nfs-server.service\nLoadState=loaded", "Id=nfs-server.service\nLoadState=not-found"
|
||||
)
|
||||
|
||||
assert not [k for k in parse_posix_shares(_wire(units)) if k.startswith("nfs:")]
|
||||
|
||||
|
||||
class TestSamba:
|
||||
def test_a_share_with_its_path(self):
|
||||
shares = parse_posix_shares(_wire())
|
||||
|
||||
assert shares["smb:Backups"] == {
|
||||
"name": "Backups",
|
||||
"protocol": "smb",
|
||||
"path": "/srv/dev-disk-by-uuid-5777/Backups",
|
||||
"volume": "",
|
||||
"enabled": True,
|
||||
"readonly": False,
|
||||
"description": "",
|
||||
"clients": [],
|
||||
"service": "smbd",
|
||||
"export": "Backups",
|
||||
"access": [],
|
||||
"guest": False,
|
||||
}
|
||||
|
||||
def test_samba_shares_read_only_unless_it_says_otherwise(self):
|
||||
"""``read only = yes`` is Samba's default, which testparm -s leaves out."""
|
||||
media = parse_posix_shares(_wire())["smb:Media"]
|
||||
|
||||
assert (media["readonly"], media["guest"], media["description"]) == (
|
||||
True,
|
||||
True,
|
||||
"Films and music",
|
||||
)
|
||||
|
||||
def test_a_share_switched_off_is_listed_as_not_enabled(self):
|
||||
assert parse_posix_shares(_wire())["smb:Old"]["enabled"] is False
|
||||
|
||||
def test_hosts_allow_names_the_clients(self):
|
||||
office = parse_posix_shares(_wire())["smb:Office"]
|
||||
|
||||
assert office["clients"] == ["10.40.100.0/24", "10.11.100.0/24"]
|
||||
assert office["access"] == [
|
||||
{"client": "10.40.100.0/24", "readonly": False, "options": "", "comment": ""},
|
||||
{"client": "10.11.100.0/24", "readonly": False, "options": "", "comment": ""},
|
||||
]
|
||||
|
||||
def test_global_and_the_printers_are_no_shares(self):
|
||||
smb = {k for k in parse_posix_shares(_wire()) if k.startswith("smb:")}
|
||||
|
||||
assert smb == {"smb:Backups", "smb:Media", "smb:Old", "smb:Office"}
|
||||
|
||||
def test_red_hat_names_the_server_smb(self):
|
||||
units = "Id=nfs-server.service\nLoadState=loaded\n\nId=smb.service\nLoadState=loaded\n"
|
||||
|
||||
assert parse_posix_shares(_wire(units))["smb:Backups"]["service"] == "smb"
|
||||
|
||||
def test_testparm_without_a_samba_server_is_no_share(self):
|
||||
"""samba-common-bin comes with the client tools too."""
|
||||
units = "Id=nfs-server.service\nLoadState=loaded\n"
|
||||
|
||||
assert not [k for k in parse_posix_shares(_wire(units)) if k.startswith("smb:")]
|
||||
|
||||
def test_without_testparm_there_is_no_samba_share(self):
|
||||
assert not [k for k in parse_posix_shares(_wire(samba=None)) if k.startswith("smb:")]
|
||||
|
||||
|
||||
class TestWithoutSystemd:
|
||||
def test_the_shares_are_read_with_no_service_named(self):
|
||||
shares = parse_posix_shares(_wire(units="__NO_SYSTEMD\n"))
|
||||
|
||||
assert shares["nfs:/export/scan"]["service"] is None
|
||||
assert shares["smb:Backups"]["service"] is None
|
||||
|
||||
|
||||
class TestFailures:
|
||||
def test_a_report_cut_short_raises(self):
|
||||
with pytest.raises(ValueError):
|
||||
parse_posix_shares(_wire(end=False))
|
||||
|
||||
def test_output_without_the_frame_raises(self):
|
||||
with pytest.raises(ValueError):
|
||||
parse_posix_shares("sh: 1: cat: not found\n")
|
||||
|
||||
def test_testparm_failing_where_samba_serves_raises(self):
|
||||
"""A configuration Samba cannot load must not read as no shares."""
|
||||
with pytest.raises(ValueError):
|
||||
parse_posix_shares(_wire(samba="Error loading services.\n", samba_rc=1))
|
||||
|
||||
def test_a_host_with_neither_server_has_none(self):
|
||||
assert parse_posix_shares(_wire(units="Id=nfs-server.service\nLoadState=not-found\n")) == {}
|
||||
|
||||
|
||||
class TestTheCommand:
|
||||
def test_the_frame_is_not_in_the_command_itself(self):
|
||||
assert "SHARES_BEGIN" not in POSIX_SHARES_COMMAND
|
||||
assert "SHARES_END" not in POSIX_SHARES_COMMAND
|
||||
|
||||
def test_it_is_valid_sh(self):
|
||||
assert subprocess.run(["sh", "-n", "-c", POSIX_SHARES_COMMAND]).returncode == 0
|
||||
|
||||
@pytest.mark.skipif(shutil.which("sh") is None, reason="needs a POSIX sh")
|
||||
def test_it_runs_on_a_host_without_either_server(self, tmp_path):
|
||||
for tool in ("cat", "printf"):
|
||||
if shutil.which(tool):
|
||||
(tmp_path / tool).symlink_to(shutil.which(tool))
|
||||
|
||||
out = subprocess.run(
|
||||
["/bin/sh", "-c", POSIX_SHARES_COMMAND],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
env={"PATH": str(tmp_path)},
|
||||
timeout=30,
|
||||
).stdout
|
||||
|
||||
assert isinstance(parse_posix_shares(out), dict)
|
||||
|
||||
|
||||
class _Driver(PosixSharesMixin):
|
||||
def __init__(self, output: str) -> None:
|
||||
self.output = output
|
||||
self.commands: list[str] = []
|
||||
|
||||
def _run_shares_command(self, command: str) -> str:
|
||||
self.commands.append(command)
|
||||
return self.output
|
||||
|
||||
|
||||
class TestTheMixin:
|
||||
def test_get_shares_runs_the_command_once(self):
|
||||
driver = _Driver(_wire())
|
||||
|
||||
shares = driver.get_shares()
|
||||
|
||||
assert driver.commands == [POSIX_SHARES_COMMAND]
|
||||
assert "smb:Backups" in shares
|
||||
@@ -125,6 +125,56 @@ def _by_name(services):
|
||||
return {s["name"]: s for s in services}
|
||||
|
||||
|
||||
KERNEL_NFS = """
|
||||
MainPID=0
|
||||
Id=nfs-server.service
|
||||
Names=nfs-server.service nfs-kernel-server.service
|
||||
LoadState=loaded
|
||||
ActiveState=active
|
||||
SubState=exited
|
||||
UnitFileState=enabled
|
||||
"""
|
||||
|
||||
|
||||
class TestKernelServedUnits:
|
||||
"""nfs-server only starts the kernel's nfsd: it stays active (exited), with no
|
||||
process, while the kernel serves (NetOrk/netork#3104). A stopped NFS server is
|
||||
inactive. Any other one-shot that stays active is still not running."""
|
||||
|
||||
def _services(self, units: str) -> dict:
|
||||
files = FILES.replace(
|
||||
"nfs-server.service masked ",
|
||||
"nfs-server.service enabled",
|
||||
)
|
||||
units = UNITS.replace(
|
||||
"MainPID=0\nId=nfs-server.service\nNames=nfs-server.service\nLoadState=masked\n"
|
||||
"ActiveState=inactive\nSubState=dead\nUnitFileState=masked\n",
|
||||
units.lstrip("\n"),
|
||||
)
|
||||
return _by_name(parse_systemd_services(_wire(files=files, units=units)))
|
||||
|
||||
def test_the_nfs_server_runs_while_its_unit_is_active(self):
|
||||
assert self._services(KERNEL_NFS)["nfs-server"] == {
|
||||
"name": "nfs-server",
|
||||
"running": True,
|
||||
"enabled": True,
|
||||
"pid": 0,
|
||||
}
|
||||
|
||||
def test_the_nfs_server_stopped_is_not_running(self):
|
||||
stopped = KERNEL_NFS.replace("ActiveState=active", "ActiveState=inactive").replace(
|
||||
"SubState=exited", "SubState=dead"
|
||||
)
|
||||
|
||||
assert self._services(stopped)["nfs-server"]["running"] is False
|
||||
|
||||
def test_another_one_shot_that_stays_active_is_not_running(self):
|
||||
assert self._services(KERNEL_NFS)["apparmor"]["running"] is False
|
||||
|
||||
def test_the_alias_is_no_service_of_its_own(self):
|
||||
assert "nfs-kernel-server" not in self._services(KERNEL_NFS)
|
||||
|
||||
|
||||
class TestParseSystemdServices:
|
||||
def test_a_loaded_unit_is_read_with_its_state(self):
|
||||
services = _by_name(parse_systemd_services(_wire()))
|
||||
|
||||
Reference in new issue
Block a user