Compare commits
41
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0619bb2085 | ||
|
|
70ad7883bc | ||
|
|
aa362ee905 | ||
|
|
9551b7434a | ||
|
|
6727f0a79c | ||
|
|
ed083df018 | ||
|
|
509cf01a70 | ||
|
|
c2e0ad3758 | ||
|
|
5ced67d4e4 | ||
|
|
8892a7734a | ||
|
|
a7a4e46ac2 | ||
|
|
f1524b8349 | ||
|
|
cc00c225a2 | ||
|
|
a0d28fc939 | ||
|
|
deb233617c | ||
|
|
099eef7f3e | ||
|
|
e09af917c8 | ||
|
|
c8f4a0b1f7 | ||
|
|
6b9ba25773 | ||
|
|
27ccfb3786 | ||
|
|
61ee8c8db8 | ||
|
|
57feb44a76 | ||
|
|
a88e02ea56 | ||
|
|
403899916f | ||
|
|
d477fb1a76 | ||
|
|
28e4a2a6e2 | ||
|
|
de8f041100 | ||
|
|
879e4a6d87 | ||
|
|
a69fb5cf2d | ||
|
|
481f047fff | ||
|
|
e8c09ac37c | ||
|
|
aba36b3b11 | ||
|
|
9fbbd17530 | ||
|
|
6d82fad80a | ||
|
|
5aa06a485d | ||
|
|
8b41a948be | ||
|
|
508f3dcb37 | ||
|
|
f68c758338 | ||
|
|
5742349742 | ||
|
|
ca03b6dd99 | ||
|
|
cfe730ccea |
No files matched your search
@@ -0,0 +1,17 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [main, master]
|
||||
tags: ["v*"]
|
||||
pull_request:
|
||||
|
||||
jobs:
|
||||
driver:
|
||||
uses: NAPALM/driver-standard/.gitea/workflows/driver.yml@main
|
||||
with:
|
||||
standard-ref: main
|
||||
# Until napalm-linux 0.15.0 is on PyPI.
|
||||
pre-install: "git+https://git.netork.io/NAPALM/napalm-device-types.git git+https://git.netork.io/NAPALM/napalm-linux.git"
|
||||
secrets:
|
||||
PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }}
|
||||
@@ -0,0 +1,9 @@
|
||||
__pycache__/
|
||||
*.egg-info/
|
||||
.venv/
|
||||
build/
|
||||
dist/
|
||||
.coverage
|
||||
.pytest_cache/
|
||||
.mypy_cache/
|
||||
.ruff_cache/
|
||||
+120
@@ -0,0 +1,120 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to this driver. The format follows
|
||||
[Keep a Changelog](https://keepachangelog.com/), versions follow
|
||||
[Semantic Versioning](https://semver.org/).
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
### Added
|
||||
- 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
|
||||
next time it deploys `conf.system.time`. `get_time_sync()` reads the servers and the zone
|
||||
of the web UI (`System.getTimeSettings`; no servers while NTP is switched off) and the
|
||||
host's own word on whether the clock is synchronised and by which client.
|
||||
`configure_time_sync()` writes both through `System.setTimeSettings` (switching NTP on
|
||||
for servers) and deploys only the modules that made dirty, plus `chrony` and `timezone`
|
||||
if they already were (`Config.applyChanges`); changes pending in the web UI for other
|
||||
modules stay pending. A value OMV already has is not written again, and nothing is
|
||||
written to the host's files.
|
||||
- Personal accounts on OpenMediaVault follow what the person changes
|
||||
(NetOrk/netork#2013): `add_local_account(..., replaces=[...])` takes the old keys out of
|
||||
OMV's own key store (through `UserMgmt.setUser`, applying only what that made dirty) and
|
||||
out of `~/.ssh`, `remove_local_account_keys` does the same for deleted keys and leaves the
|
||||
account open, and `add_local_account(..., clear_password=True)` removes the password
|
||||
(`usermod -p '*'`, as napalm-linux does): the account logs in with its key only and has
|
||||
no sudo. Keys the person added stay.
|
||||
- A deleted key can take the password with it on OpenMediaVault (NetOrk/netork#2033):
|
||||
through napalm-device-types' `remove_local_account_keys(..., clear_password=True)` the
|
||||
keys go through OMV's key store, the password goes (`usermod -p '*'`), and so does
|
||||
sudo. The account stays open and in `_ssh`.
|
||||
|
||||
### Changed
|
||||
- Needs napalm-device-types 4.35.0 and napalm-linux 0.17.0.
|
||||
|
||||
### Added
|
||||
- Scheduled jobs (NetOrk/netork#1933, #18), on top of napalm-linux's reading and writers.
|
||||
The web UI's "Scheduled Jobs" and the power-management schedule are read through
|
||||
`Cron.getList` (key `omv:<uuid>`, disabled ones included) instead of the lines OMV generates
|
||||
for them in `/etc/cron.d/openmediavault-userdefined` and `-powermngmt`. They are switched
|
||||
with `Cron.set` (the job unchanged but `enable`), run with `Cron.execute` and followed
|
||||
through `Exec.getOutput` (stopped after 300 s), and an application's job is made with
|
||||
`Cron.set` and removed with `Cron.delete` -- an OMV job like any other, its comment
|
||||
`napalm-scheduled-job: <name> <description>`. Each write applies the `cron` module alone,
|
||||
so changes pending in the web UI for other modules stay pending; while the `cron` module
|
||||
itself has changes pending, every write is refused, or the apply would put them live too.
|
||||
The cron files OMV
|
||||
generates (`/etc/cron.d/openmediavault-*`, `/etc/cron.hourly/openmediavault-flushmailq`,
|
||||
`/etc/cron.{daily,weekly}/openmediavault-apticron`,
|
||||
`/etc/cron.daily/openmediavault-samba-recycle`) are `platform` and only run: the Linux path
|
||||
refuses to write them, as OMV would undo the edit on its next apply. Every other job keeps
|
||||
napalm-linux's behaviour. Requires napalm-device-types 4.26.0 and napalm-linux 0.16.0.
|
||||
- netOrk's own account with a fixed uid is not made on OMV yet (NetOrk/netork#1817):
|
||||
`_account_create_with_uid` raises `NotImplementedError`, as the keys go through
|
||||
`UserMgmt`, which knows only the users it made.
|
||||
- Personal accounts the way OMV's web UI makes them (NetOrk/netork#1793), on top of
|
||||
napalm-linux's `get_local_accounts()`, `add_local_account()` and `lock_local_account()`.
|
||||
OMV's sshd lets in only `root` and `_ssh`, and OMV keeps a user's keys in its own
|
||||
database, deploying them to `/var/lib/openmediavault/ssh/authorized_keys/<user>`. So a
|
||||
new account is made by `UserMgmt.setUser` in `_ssh`, an account made outside OMV joins
|
||||
`_ssh` when it is opened, and keys are added and removed through `setUser`. Each call
|
||||
applies the modules it made dirty (`postfix`, `ssh`) and nothing else: changes left
|
||||
pending in the web UI stay pending. `setUser` takes a plain password, which netOrk does
|
||||
not have, so the hash is set with `usermod -p`. Like the web UI, `setUser` gives the
|
||||
account OMV's primary group `users`. Checked on a fresh OMV 8 (Debian 13) with the real
|
||||
driver over SSH. Requires the napalm-device-types and napalm-linux releases with
|
||||
personal accounts.
|
||||
- `set_hostname()` the way OMV's web UI renames the NAS: `Network.setGeneralSettings`
|
||||
(an FQDN sets the domain too, a bare name keeps it), then `Config.applyChanges` for the
|
||||
modules the rename made dirty plus the hostname modules already dirty. Changes left
|
||||
pending in the web UI are not deployed with it. Replaces the inherited napalm-linux
|
||||
rename (NAPALM/napalm-linux#45), whose `/etc/hostname` and `/etc/hosts` OMV would
|
||||
regenerate on its next apply.
|
||||
|
||||
### Changed
|
||||
- Python 3.12 is the floor (`requires-python = ">=3.12"`): netOrk runs every driver
|
||||
on 3.12, so 3.10 and 3.11 are no longer tested (NAPALM/driver-standard#6).
|
||||
- The SSH hardening is offered again (#20, NetOrk/netork#1950): it goes into the drop-in under
|
||||
`/etc/ssh/sshd_config.d`, which OpenMediaVault's generated `sshd_config` includes and salt
|
||||
leaves alone, never into `sshd_config` itself (`SSHD_CONFIG_GENERATED`, napalm-device-types
|
||||
4.26.0). Requires napalm-device-types 4.26.0.
|
||||
|
||||
### Fixed
|
||||
- `get_disks()` reports each disk's SMART verdict: `healthy` when smartctl's overall
|
||||
self-assessment passed (SCSI/SAS: health status `OK`), `failed` when it failed or a
|
||||
SCSI disk predicts a failure, `unknown` only when the disk gives none. The driver
|
||||
asked smartctl without `-H`, which never prints the verdict: a disk read `unknown`,
|
||||
and an ATA disk with an attribute table read `failed` from that table's
|
||||
`WHEN_FAILED` column, whatever its state.
|
||||
- `get_disks()` puts a disk in the md array only when the disk itself or one of its
|
||||
partitions is a member: `sda` no longer joins the array of `sdaa1`, nor `nvme0n1`
|
||||
that of `nvme0n11`. `/proc/mdstat` is read once per call instead of once per disk.
|
||||
- `get_disks()` reports a SCSI/SAS disk's temperature (`Current Drive Temperature`);
|
||||
it read `-1` for every SAS disk. A disk that prints `0 C` there, as QEMU's virtual
|
||||
disks do, still reads `-1`.
|
||||
- `get_disks()` raises `CommandErrorException` when `lsblk` fails or prints no device
|
||||
list, and lets a failed `/proc/mdstat` read raise; it returned `[]`, the answer for
|
||||
a NAS without disks, so every disk vanished on a transient error (#16).
|
||||
- `get_disks()` reports `warning` for a disk whose verdict passed but that counts lost
|
||||
or unreadable sectors: ATA reallocated, pending or offline-uncorrectable sectors,
|
||||
SAS grown defects, an NVMe critical-warning flag or NVMe media errors (#16).
|
||||
- A failed `smartctl` call (timeout, sudo refused, device not opened) is logged at
|
||||
warning level with the reason; it was logged at debug level and looked like a disk
|
||||
without SMART. The disk still reads `unknown` (#16).
|
||||
|
||||
## [0.3.0] - 2026-10-23
|
||||
|
||||
The first release on PyPI.
|
||||
|
||||
### Changed
|
||||
- The driver follows the NAPALM driver standard
|
||||
(https://git.netork.io/NAPALM/driver-standard): CI on Gitea runs ruff, mypy, the
|
||||
tests on Python 3.10–3.13 and at the lowest declared versions, bandit, pip-audit and
|
||||
a build check, and a release tag publishes to PyPI. The package now ships `py.typed`,
|
||||
a README and a LICENSE file. It needs napalm-device-types 4.22.0 and napalm-linux
|
||||
0.15.0. **Python 3.9 is no longer supported**; napalm-device-types never ran on it.
|
||||
- Failures the driver deliberately ignores (the OpenMediaVault version, `smartctl` for one
|
||||
disk, `/proc/mdstat`, `mdadm --detail`, a shared folder lookup) are now logged at debug
|
||||
level.
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship made available under
|
||||
the License, as indicated by a copyright notice that is included in
|
||||
or attached to the work (an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other transformations
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean, as submitted to the Licensor for inclusion
|
||||
in the Work by the copyright owner or by an individual or Legal Entity
|
||||
authorized to submit on behalf of the copyright owner. For the purposes
|
||||
of this definition, "submitted" means any form of electronic, verbal,
|
||||
or written communication sent to the Licensor or its representatives,
|
||||
including but not limited to communication on electronic mailing lists,
|
||||
source code control systems, and issue tracking systems that are managed
|
||||
by, or on behalf of, the Licensor for the purpose of discussing and
|
||||
improving the Work, but excluding communication that is conspicuously
|
||||
marked or designated in writing by the copyright owner as "Not a
|
||||
Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any Legal Entity on behalf of
|
||||
whom a Contribution has been received by the Licensor and incorporated
|
||||
within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by the combined Contribution(s) and the Work
|
||||
to which such Contribution(s) was submitted. If You institute patent
|
||||
litigation against any entity (including a cross-claim or counterclaim
|
||||
in a lawsuit) alleging that the Work or any Contribution embodied
|
||||
within the Work constitutes direct or contributory patent infringement,
|
||||
then any patent licenses granted to You under this License for that
|
||||
Work shall terminate as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or Derivative
|
||||
Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, You must include a readable copy of the
|
||||
attribution notices contained within such NOTICE file, in
|
||||
at least one of the following places: within a NOTICE text file
|
||||
distributed as part of the Derivative Works; within the Source
|
||||
form or documentation, if provided along with the Derivative
|
||||
Works; or, within a display generated by the Derivative Works,
|
||||
if and wherever such third-party notices normally appear. The
|
||||
contents of the NOTICE file are for informational purposes only
|
||||
and do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own license statement for Your modifications and
|
||||
may provide additional grant of rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of the Work,
|
||||
and to permit persons to whom the Work is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any conditions of TITLE,
|
||||
MERCHANTIBILITY, or FITNESS FOR A PARTICULAR PURPOSE.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or exemplary damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (even if such Contributor has been advised of the possibility
|
||||
of such damages).
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may offer only
|
||||
conditions consistent with this License, subject to the following
|
||||
additional conditions:
|
||||
|
||||
(a) You may offer additional warranty, indemnity, or other liability
|
||||
terms and conditions; and
|
||||
|
||||
(b) You may offer support for the Work in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format in question. It may also be
|
||||
possible to make it available with a creative commons license.
|
||||
|
||||
Copyright 2026 Christian Manivong
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
@@ -0,0 +1,90 @@
|
||||
# napalm-openmediavault
|
||||
|
||||
NAPALM driver for [OpenMediaVault](https://www.openmediavault.org/) NAS systems, built on
|
||||
[napalm-device-types](https://git.netork.io/NAPALM/napalm-device-types) (`StorageDriver`) and
|
||||
[napalm-linux](https://git.netork.io/NAPALM/napalm-linux) (`LinuxDriver`).
|
||||
|
||||
OpenMediaVault is Debian underneath, so the driver inherits everything napalm-linux does for a
|
||||
Linux host (packages, updates, services, users, processes, scheduled jobs, Docker) and adds the NAS side:
|
||||
disks, md RAID arrays, filesystems, shares and the NAS services.
|
||||
|
||||
## Tested against
|
||||
|
||||
| Model | Firmware |
|
||||
|---|---|
|
||||
| OpenMediaVault | 6.x (Debian Bullseye), 7.x (Debian Bookworm) |
|
||||
|
||||
## Connection
|
||||
|
||||
SSH, port 22 by default, through napalm-linux (Netmiko). The account needs a shell; `smartctl`
|
||||
and `mdadm` run through `sudo` (passwordless, or with `sudo_password`). Every `optional_args`
|
||||
key of napalm-linux is accepted (`port`, `pkg_manager`, `sudo_password`, …).
|
||||
|
||||
```python
|
||||
from napalm import get_network_driver
|
||||
|
||||
driver = get_network_driver("openmediavault")
|
||||
with driver("192.0.2.10", "admin", "secret", optional_args={"sudo_password": "secret"}) as nas:
|
||||
print(nas.get_facts())
|
||||
print(nas.get_disks())
|
||||
print(nas.get_shares())
|
||||
```
|
||||
|
||||
## Supported
|
||||
|
||||
| Getter / action | |
|
||||
|---|---|
|
||||
| `get_facts` | napalm-linux's facts, `os_version` is `OMV <version>` of the `openmediavault` package |
|
||||
| `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_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:<uuid>`, 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 |
|
||||
| `put_scheduled_job` | an OMV job through `Cron.set`, in the web UI like any other, its comment `napalm-scheduled-job: <name> <description>`; a multi-line command is fine |
|
||||
| `delete_scheduled_job` | an application's OMV job through `Cron.delete`; an application's Linux job as napalm-linux |
|
||||
| `get_time_sync` | the servers and the zone of OMV's web UI (`System.getTimeSettings`; no servers while NTP is off); synchronised and the client from napalm-linux's reading of the host |
|
||||
| `configure_time_sync` | servers (NTP switched on) and zone through `System.setTimeSettings`, then `Config.applyChanges` for the modules that made dirty (`chrony`, `timezone`); a value OMV already has is not written again |
|
||||
| everything of napalm-linux | packages, updates, services, users, processes, Docker, … |
|
||||
|
||||
Every scheduled-job write through RPC deploys the `cron` module alone (`Config.applyChanges`):
|
||||
changes left pending in the web UI for other modules stay pending.
|
||||
|
||||
Time sync never writes the host's files the way napalm-linux does (a chrony drop-in,
|
||||
`timedatectl set-timezone`): OpenMediaVault generates `chrony.conf` and the zone from
|
||||
`conf.system.time` and would write over them.
|
||||
|
||||
"Upgrade everything" is a full upgrade (`FULL_UPGRADE = True`): a plain `apt-get upgrade` holds
|
||||
back OpenMediaVault's own packages and the kernel.
|
||||
|
||||
The SSH hardening of napalm-linux (`harden_ssh_server`) writes only the drop-in under
|
||||
`/etc/ssh/sshd_config.d` (`SSHD_CONFIG_GENERATED = True`). OpenMediaVault generates
|
||||
`sshd_config` from its own database and would write over a change to it, but its template
|
||||
includes that directory, and salt leaves the drop-in alone. An algorithm set in the SSH
|
||||
settings' "Extra options" comes before the include and wins; the hardening sees that, puts
|
||||
its change back and says so.
|
||||
|
||||
## Not supported
|
||||
|
||||
- `get_volume_snapshots`, `get_replication_jobs`, `get_quotas` raise `NotImplementedError`.
|
||||
- Configuration changes to shares, disks or arrays.
|
||||
|
||||
## Installation
|
||||
|
||||
```bash
|
||||
pip install napalm-openmediavault
|
||||
```
|
||||
|
||||
## Development
|
||||
|
||||
The rules are in [STANDARDS.md](https://git.netork.io/NAPALM/driver-standard/src/branch/main/STANDARDS.md).
|
||||
|
||||
```bash
|
||||
python -m venv .venv && .venv/bin/pip install -e ".[dev]"
|
||||
.venv/bin/pytest --cov
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
Apache-2.0
|
||||
@@ -1,20 +0,0 @@
|
||||
Metadata-Version: 2.4
|
||||
Name: napalm-openmediavault
|
||||
Version: 0.1.0
|
||||
Summary: NAPALM driver for OpenMediaVault NAS (SSH)
|
||||
Author-email: Christian Manivong <christian@manivong.de>
|
||||
License: Apache-2.0
|
||||
Project-URL: Repository, https://github.com/chrismanivong/napalm-openmediavault
|
||||
Keywords: napalm,network,automation,nas,openmediavault,omv,storage
|
||||
Classifier: Development Status :: 3 - Alpha
|
||||
Classifier: Intended Audience :: Developers
|
||||
Classifier: Intended Audience :: System Administrators
|
||||
Classifier: License :: OSI Approved :: Apache Software License
|
||||
Classifier: Programming Language :: Python :: 3
|
||||
Classifier: Topic :: System :: Networking
|
||||
Classifier: Topic :: System :: Systems Administration
|
||||
Requires-Python: >=3.9
|
||||
Description-Content-Type: text/markdown
|
||||
Requires-Dist: napalm>=4.0
|
||||
Requires-Dist: napalm-device-types>=0.3.0
|
||||
Requires-Dist: napalm-linux>=0.1.0
|
||||
@@ -1,10 +0,0 @@
|
||||
pyproject.toml
|
||||
napalm_openmediavault/__init__.py
|
||||
napalm_openmediavault/openmediavault.py
|
||||
napalm_openmediavault.egg-info/PKG-INFO
|
||||
napalm_openmediavault.egg-info/SOURCES.txt
|
||||
napalm_openmediavault.egg-info/dependency_links.txt
|
||||
napalm_openmediavault.egg-info/entry_points.txt
|
||||
napalm_openmediavault.egg-info/requires.txt
|
||||
napalm_openmediavault.egg-info/top_level.txt
|
||||
tests/test_omv_type_label.py
|
||||
@@ -1 +0,0 @@
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
[napalm.drivers]
|
||||
openmediavault = napalm_openmediavault:OpenMediaVaultDriver
|
||||
@@ -1,3 +0,0 @@
|
||||
napalm>=4.0
|
||||
napalm-device-types>=0.3.0
|
||||
napalm-linux>=0.1.0
|
||||
@@ -1 +0,0 @@
|
||||
napalm_openmediavault
|
||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,187 @@
|
||||
"""Personal accounts on OpenMediaVault, the way its web UI makes them (NetOrk/netork#1793).
|
||||
|
||||
napalm-linux adds and locks accounts with shadow-utils and puts keys in
|
||||
``~/.ssh``. OMV needs two things more. Its sshd lets in only ``root`` and the
|
||||
``_ssh`` group (``AllowGroups root _ssh``). And it keeps a user's keys in its
|
||||
own database, from which the ``ssh`` module deploys them to
|
||||
:data:`OMV_KEYS_DIR`, a directory the user cannot write to.
|
||||
|
||||
So an account is made by ``UserMgmt.setUser`` in ``_ssh``, and its keys go
|
||||
through ``setUser`` too. Afterwards only the modules that change made dirty are
|
||||
applied: changes left pending in the web UI stay pending. ``setUser`` takes a
|
||||
plain password, and netOrk holds only the hash, so the hash is set with
|
||||
``usermod -p``; OMV keeps no password of its own. The lock is napalm-linux's,
|
||||
an expiry, which OMV leaves alone. Like the web UI, ``setUser`` gives an
|
||||
account OMV's primary group ``users``, one made outside OMV too.
|
||||
|
||||
A key the person replaced or deleted (NetOrk/netork#2013) goes from OMV's
|
||||
database the same way, and from ``~/.ssh`` as napalm-linux takes it out; the
|
||||
other keys stay. A password removed is napalm-linux's ``usermod -p '*'``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types import LocalAccountsMixin
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from napalm_device_types.models import FixStepOutcomeDict
|
||||
|
||||
#: Where OMV's ``ssh`` module writes each user's keys, one file per user.
|
||||
OMV_KEYS_DIR = "/var/lib/openmediavault/ssh/authorized_keys"
|
||||
#: The group OMV's sshd lets in.
|
||||
SSH_GROUP = "_ssh"
|
||||
#: ``setUser``'s password for "leave it as it is" (the hash is set apart); not a password.
|
||||
_KEEP_PASSWORD = "" # nosec B105
|
||||
#: What ``setUser`` needs besides the keys, as ``getUser`` returns it.
|
||||
_USER_FIELDS: dict[str, Any] = {
|
||||
"groups": [],
|
||||
"email": "",
|
||||
"disallowusermod": False,
|
||||
"comment": "",
|
||||
"shell": "",
|
||||
}
|
||||
|
||||
|
||||
def rfc4716_blob(text: str) -> str | None:
|
||||
"""The base64 of a public key, in OMV's RFC 4716 form or OpenSSH's one line."""
|
||||
lines = [line.strip() for line in text.strip().splitlines()]
|
||||
if lines and lines[0].startswith("---- BEGIN SSH2 PUBLIC KEY"):
|
||||
return _rfc4716_body(lines[1:])
|
||||
words = text.split()
|
||||
if len(words) >= 2 and words[0].startswith(("ssh-", "ecdsa-", "sk-")):
|
||||
return words[1]
|
||||
return None
|
||||
|
||||
|
||||
def _rfc4716_body(lines: list[str]) -> str | None:
|
||||
"""The base64 between the headers and the END line; None without an END line."""
|
||||
body: list[str] = []
|
||||
header = False
|
||||
for line in lines:
|
||||
if line.startswith("---- END SSH2 PUBLIC KEY"):
|
||||
return "".join(body) or None
|
||||
if header or ":" in line:
|
||||
header = line.endswith("\\") # a header continues on the next line
|
||||
continue
|
||||
body.append(line)
|
||||
return None
|
||||
|
||||
|
||||
def _holds(keys: list[str] | None, blob: str | None) -> bool:
|
||||
return blob is not None and any(rfc4716_blob(line) == blob for line in keys or [])
|
||||
|
||||
|
||||
class OmvLocalAccountsMixin(LocalAccountsMixin):
|
||||
"""napalm-linux's accounts, made and keyed through OMV's own database."""
|
||||
|
||||
if TYPE_CHECKING:
|
||||
|
||||
def _omv_rpc(
|
||||
self,
|
||||
service: str,
|
||||
method: str,
|
||||
params: dict[str, Any] | None = None,
|
||||
timeout: float = 60,
|
||||
) -> Any: ...
|
||||
|
||||
def _omv_dirty_modules(self) -> list[str]: ...
|
||||
|
||||
def _account_create(self, name: str, password_hash: str | None) -> list[list[str]]:
|
||||
"""Make *name* through ``setUser`` right away, so what it dirties is applied with it.
|
||||
|
||||
What is left is the password hash, for ``usermod``.
|
||||
|
||||
:raises RuntimeError: when OMV refuses.
|
||||
"""
|
||||
self._omv_save_user(
|
||||
{
|
||||
"name": name,
|
||||
"groups": [SSH_GROUP],
|
||||
"password": _KEEP_PASSWORD,
|
||||
"email": "",
|
||||
"disallowusermod": False,
|
||||
"sshpubkeys": [],
|
||||
"shell": self.ACCOUNT_SHELL,
|
||||
"comment": "",
|
||||
}
|
||||
)
|
||||
return [["usermod", "-p", password_hash, name]] if password_hash else []
|
||||
|
||||
def _account_create_with_uid(self, name: str, uid: int) -> list[list[str]]:
|
||||
"""Not on OMV yet (NetOrk/netork#1817): its keys go through ``UserMgmt``, which
|
||||
knows only the users it made, and whether ``setUser`` takes a uid is untested."""
|
||||
raise NotImplementedError
|
||||
|
||||
def _account_open(
|
||||
self, name: str, password_hash: str | None, *, locked: bool
|
||||
) -> list[list[str]]:
|
||||
# A user made outside the web UI is not in _ssh: sshd would refuse it.
|
||||
opened = super()._account_open(name, password_hash, locked=locked)
|
||||
return [*opened, ["gpasswd", "-a", name, SSH_GROUP]]
|
||||
|
||||
def _account_key_files(self, name: str, home: str) -> tuple[str, ...]:
|
||||
return (*super()._account_key_files(name, home), f"{OMV_KEYS_DIR}/{name}")
|
||||
|
||||
def _account_add_key(self, name: str, home: str, public_key: str) -> FixStepOutcomeDict:
|
||||
blob = rfc4716_blob(public_key)
|
||||
keys = self._account_read_keys(name, home)
|
||||
if keys is None:
|
||||
return {"ok": False, "output": f"cannot read the key files of {name}"}
|
||||
if _holds(keys, blob):
|
||||
return {"ok": True, "output": f"the key is already one {name} logs in with"}
|
||||
user = self._omv_rpc("UserMgmt", "getUser", {"name": name})
|
||||
stored = list(user.get("sshpubkeys") or [])
|
||||
if not _holds(stored, blob):
|
||||
stored.append(public_key.strip())
|
||||
applied = self._omv_set_keys(user, stored)
|
||||
if not _holds(self._account_read_keys(name, home), blob):
|
||||
where = f"{OMV_KEYS_DIR}/{name}"
|
||||
return {"ok": False, "output": f"the key is in OMV's database, not deployed to {where}"}
|
||||
return {"ok": True, "output": f"key added through OMV ({applied})"}
|
||||
|
||||
def _account_remove_keys(self, name: str, home: str) -> FixStepOutcomeDict:
|
||||
user = self._omv_rpc("UserMgmt", "getUser", {"name": name})
|
||||
said = ""
|
||||
if user.get("sshpubkeys"):
|
||||
said = f"OMV's keys of {name} removed ({self._omv_set_keys(user, [])})\n"
|
||||
outcome = super()._account_remove_keys(name, home)
|
||||
return {"ok": outcome["ok"], "output": said + outcome["output"]}
|
||||
|
||||
def _account_drop_keys(self, name: str, home: str, keys: list[str]) -> FixStepOutcomeDict:
|
||||
"""*keys* out of OMV's database, deployed, then out of ``~/.ssh``; the others stay."""
|
||||
blobs = {rfc4716_blob(key) for key in keys}
|
||||
user = self._omv_rpc("UserMgmt", "getUser", {"name": name})
|
||||
stored = list(user.get("sshpubkeys") or [])
|
||||
kept = [key for key in stored if rfc4716_blob(key) not in blobs]
|
||||
said = ""
|
||||
if len(kept) != len(stored):
|
||||
applied = self._omv_set_keys(user, kept)
|
||||
said = f"{len(stored) - len(kept)} removed from OMV's keys of {name} ({applied})\n"
|
||||
outcome = super()._account_drop_keys(name, home, keys)
|
||||
return {"ok": outcome["ok"], "output": said + outcome["output"]}
|
||||
|
||||
def _omv_set_keys(self, user: dict[str, Any], keys: list[str]) -> str:
|
||||
"""Give *user* *keys* in OMV's database and deploy them; what was applied.
|
||||
|
||||
:raises RuntimeError: when OMV refuses.
|
||||
"""
|
||||
params = {field: user.get(field, default) for field, default in _USER_FIELDS.items()}
|
||||
params.update({"name": user["name"], "password": _KEEP_PASSWORD, "sshpubkeys": keys})
|
||||
return self._omv_save_user(params)
|
||||
|
||||
def _omv_save_user(self, params: dict[str, Any]) -> str:
|
||||
"""``setUser`` with *params*, then apply what that made dirty; what was applied.
|
||||
|
||||
Modules dirty before stay pending, ``ssh`` aside: the keys need it.
|
||||
|
||||
:raises RuntimeError: when OMV refuses.
|
||||
"""
|
||||
before = set(self._omv_dirty_modules())
|
||||
self._omv_rpc("UserMgmt", "setUser", params)
|
||||
after = set(self._omv_dirty_modules())
|
||||
modules = sorted((after - before) | (after & {"ssh"}))
|
||||
if modules:
|
||||
self._omv_rpc("Config", "applyChanges", {"modules": modules, "force": False}, 600)
|
||||
return ", ".join(modules) or "nothing to apply"
|
||||
@@ -0,0 +1,425 @@
|
||||
"""Scheduled jobs on OpenMediaVault: the web UI's through RPC, the rest as on Linux (#18).
|
||||
|
||||
napalm-linux reads and writes every cron line, run-parts script and timer of the
|
||||
host (``PosixScheduledJobsMixin``). OMV writes some of those files itself, from
|
||||
its own database, and writes them again on every apply of the module they belong
|
||||
to -- an edit there would be taken back without a word:
|
||||
|
||||
* ``/etc/cron.d/openmediavault-userdefined``: the web UI's "Scheduled Jobs", and
|
||||
``/etc/cron.d/openmediavault-powermngmt``: the power-management schedule, both
|
||||
from ``conf.system.cron.job`` (module ``cron``);
|
||||
* ``/etc/cron.d/openmediavault-rsync`` (rsync jobs), ``openmediavault-mkrrdgraph``
|
||||
(the performance graphs) and the ``openmediavault-*`` files OMV's plugins write
|
||||
there the same way;
|
||||
* ``/etc/cron.hourly/openmediavault-flushmailq``, ``/etc/cron.{daily,weekly}/
|
||||
openmediavault-apticron`` and ``/etc/cron.daily/openmediavault-samba-recycle``.
|
||||
|
||||
Those are ``platform`` (:data:`GENERATED`) and the Linux path never writes them:
|
||||
such a job only runs. The lines of the two files from ``conf.system.cron.job``
|
||||
are left out of the reading altogether; the jobs ``Cron.getList`` returns stand
|
||||
in for them, keyed ``omv:<uuid>``, with the disabled ones the files leave out.
|
||||
They are switched with ``Cron.set`` (the job as it is, but ``enable``), run with
|
||||
``Cron.execute`` (followed through ``Exec.getOutput``), made and changed with
|
||||
``Cron.set`` and removed with ``Cron.delete`` -- so an application's job on OMV
|
||||
is an OMV job, in the web UI like any other. Each write applies the ``cron``
|
||||
module and nothing else (``Config.applyChanges``): changes left pending in the
|
||||
web UI for other modules stay pending. While the ``cron`` module itself has changes
|
||||
pending, every write is refused: an apply would put someone's half-finished edit
|
||||
live along with it (decided 2026-11-03, NetOrk/netork#1933).
|
||||
|
||||
The scripts OMV's package ships to the run-parts directories
|
||||
(``/etc/cron.daily/openmediavault-check_locked_users`` and the like) are not
|
||||
generated; they stay ``package`` jobs, switched as on Linux.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import fnmatch
|
||||
import json
|
||||
import time
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types import (
|
||||
PosixScheduledJobsMixin,
|
||||
ScheduledJobChanged,
|
||||
ScheduledJobRefused,
|
||||
)
|
||||
from napalm_device_types.cron import parse_cron
|
||||
from napalm_device_types.scheduled_jobs import (
|
||||
ACTIONS,
|
||||
DELETE,
|
||||
EDIT,
|
||||
RUN_TIMEOUT,
|
||||
check_spec,
|
||||
job_digest,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from napalm_device_types import ScheduledJobResultDict, ScheduledJobSpecDict
|
||||
from napalm_device_types._scheduled_reading import Reading
|
||||
from napalm_device_types.scheduled_jobs import ScheduledJobsReadingDict
|
||||
|
||||
#: The cron files OMV generates (``fnmatch`` patterns): ``platform``, never written here.
|
||||
GENERATED = (
|
||||
"/etc/cron.d/openmediavault-*",
|
||||
"/etc/cron.hourly/openmediavault-flushmailq",
|
||||
"/etc/cron.daily/openmediavault-apticron",
|
||||
"/etc/cron.weekly/openmediavault-apticron",
|
||||
"/etc/cron.daily/openmediavault-samba-recycle",
|
||||
)
|
||||
#: The files OMV writes from ``conf.system.cron.job``: their jobs are read through RPC.
|
||||
_FROM_RPC = ("/etc/cron.d/openmediavault-userdefined", "/etc/cron.d/openmediavault-powermngmt")
|
||||
#: Every type of ``conf.system.cron.job``: the web UI's jobs and the power schedule.
|
||||
_TYPES = ["userdefined", "reboot", "shutdown", "standby"]
|
||||
#: The UUID that makes ``Cron.set`` create an object (``OMV_CONFIGOBJECT_NEW_UUID``).
|
||||
NEW_UUID = "fa4b1c66-ef79-11e5-87a0-0002b3a176b4"
|
||||
#: napalm-device-types' job marker, as the comment of an OMV job (``# `` is cron's).
|
||||
COMMENT_MARKER = "napalm-scheduled-job: "
|
||||
_KEY = "omv:"
|
||||
#: The module the scheduled jobs are, in OMV's configuration.
|
||||
_MODULE = "cron"
|
||||
_APPLY = {"modules": [_MODULE], "force": False}
|
||||
#: Salt restarts cron when it deploys: give it time.
|
||||
_APPLY_TIMEOUT = 600
|
||||
_SHORTCUTS = {
|
||||
"@reboot": "reboot",
|
||||
"@hourly": "hourly",
|
||||
"@daily": "daily",
|
||||
"@midnight": "daily",
|
||||
"@weekly": "weekly",
|
||||
"@monthly": "monthly",
|
||||
"@yearly": "yearly",
|
||||
"@annually": "yearly",
|
||||
}
|
||||
#: The five time fields in cron's order, with the flag that makes one ``*/<value>``.
|
||||
_TIME_FIELDS = (
|
||||
("minute", "everynminute"),
|
||||
("hour", "everynhour"),
|
||||
("dayofmonth", "everyndayofmonth"),
|
||||
("month", None),
|
||||
("dayofweek", None),
|
||||
)
|
||||
_LISTS = tuple(name for name, _every in _TIME_FIELDS)
|
||||
_FLAGS = ("enable", "sendemail", "everynminute", "everynhour", "everyndayofmonth")
|
||||
_TEXTS = ("uuid", "execution", "comment", "type", "username", "command")
|
||||
_SWITCH = ["enable", "disable"]
|
||||
#: Seconds between two reads of a run's output; what a run keeps of it.
|
||||
_POLL = 1.0
|
||||
_OUTPUT_LIMIT = 64 * 1024
|
||||
_sleep = time.sleep
|
||||
_monotonic = time.monotonic
|
||||
|
||||
|
||||
def generated(path: str) -> bool:
|
||||
"""Whether OMV generates the cron file *path* (:data:`GENERATED`)."""
|
||||
return any(fnmatch.fnmatchcase(path, pattern) for pattern in GENERATED)
|
||||
|
||||
|
||||
def _flag(value: object) -> bool:
|
||||
return value is True or str(value).lower() in ("1", "true", "yes", "on")
|
||||
|
||||
|
||||
def cron_schedule(job: dict[str, Any]) -> str:
|
||||
"""The cron expression of an OMV job, as OMV writes it to its cron file."""
|
||||
execution = str(job.get("execution") or "exactly")
|
||||
if execution != "exactly":
|
||||
return f"@{execution}"
|
||||
words = []
|
||||
for name, every in _TIME_FIELDS:
|
||||
value = str(job.get(name, "*"))
|
||||
words.append(f"*/{value}" if every and _flag(job.get(every)) else value)
|
||||
return " ".join(words)
|
||||
|
||||
|
||||
def omv_schedule(schedule: str) -> dict[str, Any]:
|
||||
"""The fields of ``Cron.set`` that make OMV run a job on cron's *schedule*.
|
||||
|
||||
An alias is OMV's shortcut. Otherwise each field is ``*``, a ``*/n`` where OMV
|
||||
has one (minute, hour, day of month), or the list of its values: OMV takes no
|
||||
ranges, no names and no step on month or weekday; Sunday is ``7``.
|
||||
|
||||
:raises ScheduledJobRefused: for an expression cron would not take, and for a
|
||||
weekday step beside a day of month -- its values would make cron run on
|
||||
either day instead of on both.
|
||||
"""
|
||||
text = schedule.strip()
|
||||
fields: dict[str, Any] = {"execution": "exactly", "minute": ["0"], "hour": ["0"]}
|
||||
fields.update({"dayofmonth": ["*"], "month": ["*"], "dayofweek": ["*"]})
|
||||
fields.update({every: False for _name, every in _TIME_FIELDS if every})
|
||||
if text.lower() in _SHORTCUTS:
|
||||
return {**fields, "execution": _SHORTCUTS[text.lower()]}
|
||||
return {**fields, **_exactly(text)}
|
||||
|
||||
|
||||
def _exactly(text: str) -> dict[str, Any]:
|
||||
"""The time fields of ``execution: exactly`` for the five-field *text*."""
|
||||
try:
|
||||
parsed = parse_cron(text)
|
||||
except ValueError as exc:
|
||||
raise ScheduledJobRefused(str(exc)) from exc
|
||||
words = text.split()
|
||||
if words[4].startswith("*/") and not words[2].startswith("*"):
|
||||
raise ScheduledJobRefused(f"OpenMediaVault cannot step weekdays beside a day: {text!r}")
|
||||
weekdays = frozenset(7 if day == 0 else day for day in parsed.weekdays)
|
||||
values = (parsed.minutes, parsed.hours, parsed.days, parsed.months, weekdays)
|
||||
fields: dict[str, Any] = {}
|
||||
for (name, every), word, field in zip(_TIME_FIELDS, words, values, strict=True):
|
||||
step = every is not None and word.startswith("*/")
|
||||
fields[name] = _omv_field(word, field, step)
|
||||
if every:
|
||||
fields[every] = step
|
||||
return fields
|
||||
|
||||
|
||||
def _omv_field(word: str, values: frozenset[int], step: bool) -> list[str]:
|
||||
if word == "*":
|
||||
return ["*"]
|
||||
if step:
|
||||
return [str(int(word[2:]))]
|
||||
return [str(v) for v in sorted(values)]
|
||||
|
||||
|
||||
def _actions(userdefined: bool, own: bool) -> list[str]:
|
||||
if not userdefined:
|
||||
return list(_SWITCH) # no script to run: Cron.execute runs a user-defined job's
|
||||
return [*_SWITCH, "run", EDIT, DELETE] if own else [*_SWITCH, "run"]
|
||||
|
||||
|
||||
def rpc_job(raw: dict[str, Any]) -> dict[str, object]:
|
||||
"""A job of ``Cron.getList`` as a scheduled job, keyed ``omv:<uuid>``."""
|
||||
userdefined = raw.get("type", "userdefined") == "userdefined"
|
||||
comment = str(raw.get("comment") or "")
|
||||
own = userdefined and comment.startswith(COMMENT_MARKER)
|
||||
name, _, description = (
|
||||
comment[len(COMMENT_MARKER) :].partition(" ") if own else ("", "", comment)
|
||||
)
|
||||
job: dict[str, object] = {
|
||||
"key": f"{_KEY}{raw['uuid']}",
|
||||
"kind": "cron",
|
||||
"source": "omv:cron" if userdefined else "omv:powermgmt",
|
||||
"run_as": str(raw.get("username") or "root"),
|
||||
"schedule": cron_schedule(raw),
|
||||
"schedule_kind": "cron",
|
||||
"command": str(raw.get("command") or ""),
|
||||
"enabled": _flag(raw.get("enable")),
|
||||
"managed_by": "application" if own else "admin",
|
||||
"actions": _actions(userdefined, own),
|
||||
}
|
||||
extra = [_flag(raw.get("sendemail")), comment, raw.get("type")]
|
||||
job["digest"] = job_digest(job, content=json.dumps(extra))
|
||||
job.update({k: v for k, v in (("name", name), ("description", description.strip())) if v})
|
||||
return job
|
||||
|
||||
|
||||
def _set_params(raw: dict[str, Any]) -> dict[str, Any]:
|
||||
"""What ``Cron.set`` takes of a job: the time fields as lists, as ``Cron.get`` has them."""
|
||||
params: dict[str, Any] = {k: str(raw.get(k) or "") for k in _TEXTS}
|
||||
params.update({k: _flag(raw.get(k)) for k in _FLAGS})
|
||||
for k in _LISTS:
|
||||
value = raw.get(k, "*")
|
||||
params[k] = value if isinstance(value, list) else str(value).split(",")
|
||||
return params
|
||||
|
||||
|
||||
def _tail(text: str) -> str:
|
||||
return text[-_OUTPUT_LIMIT:]
|
||||
|
||||
|
||||
class OmvScheduledJobsMixin(PosixScheduledJobsMixin):
|
||||
"""napalm-linux's scheduled jobs, with OMV's own through its RPC (module docstring)."""
|
||||
|
||||
PLATFORM_SOURCES = GENERATED
|
||||
|
||||
if TYPE_CHECKING:
|
||||
|
||||
def _omv_rpc(
|
||||
self,
|
||||
service: str,
|
||||
method: str,
|
||||
params: dict[str, Any] | None = None,
|
||||
timeout: float = 60,
|
||||
) -> Any: ...
|
||||
|
||||
def _omv_dirty_modules(self) -> list[str]: ...
|
||||
|
||||
# -- reading ---------------------------------------------------------------------------------
|
||||
|
||||
def _sj_read(self) -> Reading:
|
||||
"""The Linux reading without the lines RPC stands for; a generated job only runs."""
|
||||
reading = super()._sj_read()
|
||||
reading.jobs = [j for j in reading.jobs if j["source"] not in _FROM_RPC]
|
||||
for job in reading.jobs:
|
||||
if job["managed_by"] == "platform":
|
||||
job["actions"] = [a for a in job["actions"] if a == "run"] # type: ignore[attr-defined]
|
||||
return reading
|
||||
|
||||
def _omv_jobs(self) -> list[tuple[dict[str, object], dict[str, Any]]]:
|
||||
"""Every job of ``conf.system.cron.job``, with what ``Cron.getList`` said of it.
|
||||
|
||||
:raises ValueError: when the list came back shorter than its total.
|
||||
"""
|
||||
answer = self._omv_rpc("Cron", "getList", {"start": 0, "limit": None, "type": _TYPES})
|
||||
data = answer.get("data") if isinstance(answer, dict) else None
|
||||
if not isinstance(data, list) or len(data) != answer.get("total"):
|
||||
raise ValueError("Cron.getList came back cut short")
|
||||
return [(rpc_job(raw), raw) for raw in data]
|
||||
|
||||
def get_scheduled_jobs(self) -> ScheduledJobsReadingDict:
|
||||
"""Every scheduled job of the NAS: the Linux reading, OMV's own jobs through RPC.
|
||||
|
||||
:raises ValueError: when either came back cut short.
|
||||
:raises RuntimeError: when ``Cron.getList`` failed.
|
||||
"""
|
||||
reading = self._sj_read()
|
||||
jobs = reading.jobs + [job for job, _raw in self._omv_jobs()]
|
||||
return {"jobs": jobs, "time_zone": reading.time_zone} # type: ignore[typeddict-item]
|
||||
|
||||
def _omv_job(self, key: str, digest: str) -> tuple[dict[str, object], dict[str, Any]]:
|
||||
found = next(((j, r) for j, r in self._omv_jobs() if j["key"] == key), None)
|
||||
if found is None:
|
||||
raise LookupError(f"no scheduled job {key}")
|
||||
if found[0]["digest"] != digest:
|
||||
raise ScheduledJobChanged(f"{key} changed on the NAS since it was read")
|
||||
return found
|
||||
|
||||
# -- writing ---------------------------------------------------------------------------------
|
||||
|
||||
def _omv_clean(self) -> None:
|
||||
""":raises ScheduledJobRefused: while the ``cron`` module has changes pending."""
|
||||
if _MODULE in self._omv_dirty_modules():
|
||||
raise ScheduledJobRefused(
|
||||
"OpenMediaVault has unapplied changes to its scheduled jobs; apply or "
|
||||
"revert them in its web UI first"
|
||||
)
|
||||
|
||||
def _omv_set(self, raw: dict[str, Any]) -> dict[str, Any]:
|
||||
"""``Cron.set`` *raw*, then deploy the ``cron`` module alone."""
|
||||
self._omv_clean()
|
||||
stored: dict[str, Any] = self._omv_rpc("Cron", "set", _set_params(raw))
|
||||
self._omv_rpc("Config", "applyChanges", dict(_APPLY), _APPLY_TIMEOUT)
|
||||
return stored
|
||||
|
||||
def _omv_guard(self, path: str) -> None:
|
||||
if generated(path):
|
||||
raise ScheduledJobRefused(f"OpenMediaVault generates {path}; it would undo the edit")
|
||||
|
||||
def _sj_write(self, path: str, text: str) -> None:
|
||||
self._omv_guard(path)
|
||||
super()._sj_write(path, text)
|
||||
|
||||
def _sj_switch(self, job: dict[str, object], enabled: bool) -> ScheduledJobResultDict:
|
||||
self._omv_guard(str(job["source"]))
|
||||
return super()._sj_switch(job, enabled)
|
||||
|
||||
def _sj_delete_cron(self, job: dict[str, object]) -> None:
|
||||
self._omv_guard(str(job["source"]))
|
||||
super()._sj_delete_cron(job)
|
||||
|
||||
# -- switching and running -------------------------------------------------------------------
|
||||
|
||||
def manage_scheduled_job(self, key: str, action: str, *, digest: str) -> ScheduledJobResultDict:
|
||||
"""Enable, disable or run the job *key*; an OMV job through ``Cron.*``.
|
||||
|
||||
:raises ScheduledJobChanged: when the job is no longer as *digest* says.
|
||||
:raises ScheduledJobRefused: when the job does not take *action*.
|
||||
:raises LookupError: when the NAS has no job *key*.
|
||||
"""
|
||||
if not key.startswith(_KEY):
|
||||
return super().manage_scheduled_job(key, action, digest=digest)
|
||||
if action not in ACTIONS:
|
||||
raise ScheduledJobRefused(f"unknown action {action!r}; allowed: {list(ACTIONS)}")
|
||||
job, raw = self._omv_job(key, digest)
|
||||
if action not in job["actions"]: # type: ignore[operator]
|
||||
raise ScheduledJobRefused(f"{key} cannot be told to {action} on OpenMediaVault")
|
||||
if action == "run":
|
||||
return self._omv_run(key, str(raw["uuid"]))
|
||||
self._omv_set({**raw, "enable": action == "enable"})
|
||||
return {"success": True, "output": f"{key} {action}d"}
|
||||
|
||||
def _omv_run(self, key: str, uuid: str) -> ScheduledJobResultDict:
|
||||
"""``Cron.execute``, followed to its end or stopped after ``RUN_TIMEOUT``."""
|
||||
filename = self._omv_rpc("Cron", "execute", {"uuid": uuid})
|
||||
deadline = _monotonic() + RUN_TIMEOUT
|
||||
pos, said = 0, ""
|
||||
while True:
|
||||
try:
|
||||
got = self._omv_rpc("Exec", "getOutput", {"filename": filename, "pos": pos})
|
||||
except RuntimeError as exc: # the job failed: OMV raises with its exit status
|
||||
return {"success": False, "output": _tail(f"{said}{exc}")}
|
||||
said += str(got.get("output") or "")
|
||||
pos = int(got.get("pos") or pos)
|
||||
if not got.get("running"):
|
||||
return {"success": True, "output": _tail(said.strip()) or f"{key} ran"}
|
||||
if _monotonic() >= deadline:
|
||||
self._omv_rpc("Exec", "stop", {"filename": filename})
|
||||
return {"success": False, "output": _tail(f"{said}stopped after {RUN_TIMEOUT} s")}
|
||||
_sleep(_POLL)
|
||||
|
||||
# -- an application's own jobs ---------------------------------------------------------------
|
||||
|
||||
def _omv_own(self, name: str, digest: str | None) -> dict[str, Any] | None:
|
||||
own = (
|
||||
(j, r)
|
||||
for j, r in self._omv_jobs()
|
||||
if j["managed_by"] == "application" and j.get("name") == name
|
||||
)
|
||||
found = next(own, None)
|
||||
if digest is None:
|
||||
if found is not None:
|
||||
raise ScheduledJobChanged(f"a job {name} is there already")
|
||||
return None
|
||||
if found is None:
|
||||
raise LookupError(f"no scheduled job named {name}")
|
||||
if found[0]["digest"] != digest:
|
||||
raise ScheduledJobChanged(f"{found[0]['key']} changed on the NAS since it was read")
|
||||
return found[1]
|
||||
|
||||
def put_scheduled_job(
|
||||
self, spec: ScheduledJobSpecDict, *, digest: str | None = None
|
||||
) -> ScheduledJobResultDict:
|
||||
"""Create or change the application's job ``spec["name"]`` as an OMV job.
|
||||
|
||||
:raises ScheduledJobChanged: when the job is no longer as *digest* says, or
|
||||
one of that name is there although *digest* is None.
|
||||
:raises ScheduledJobRefused: for a spec ``check_spec`` refuses, a schedule
|
||||
OMV cannot hold, or a user the NAS does not have.
|
||||
:raises LookupError: for a *digest* and no job of that name.
|
||||
"""
|
||||
check_spec(spec)
|
||||
fields = omv_schedule(spec["schedule"])
|
||||
self._sj_group(spec["run_as"])
|
||||
current = self._omv_own(spec["name"], digest)
|
||||
comment = f"{COMMENT_MARKER}{spec['name']} {spec.get('description') or ''}".rstrip()
|
||||
stored = self._omv_set(
|
||||
{
|
||||
"uuid": current["uuid"] if current else NEW_UUID,
|
||||
"sendemail": current.get("sendemail") if current else False,
|
||||
"enable": spec["enabled"],
|
||||
"type": "userdefined",
|
||||
"comment": comment,
|
||||
"username": spec["run_as"],
|
||||
"command": spec["command"].strip(),
|
||||
**fields,
|
||||
}
|
||||
)
|
||||
done = "changed" if current else "created"
|
||||
return {"success": True, "output": f"{_KEY}{stored['uuid']} {done}"}
|
||||
|
||||
def delete_scheduled_job(self, key: str, *, digest: str) -> ScheduledJobResultDict:
|
||||
"""Delete the application's job *key*; an OMV job through ``Cron.delete``.
|
||||
|
||||
:raises ScheduledJobChanged: when the job is no longer as *digest* says.
|
||||
:raises ScheduledJobRefused: when an application did not write it.
|
||||
:raises LookupError: when the NAS has no job *key*.
|
||||
"""
|
||||
if not key.startswith(_KEY):
|
||||
return super().delete_scheduled_job(key, digest=digest)
|
||||
job, raw = self._omv_job(key, digest)
|
||||
if job["managed_by"] != "application":
|
||||
raise ScheduledJobRefused(
|
||||
f"{key} was not written by an application; it is only switched"
|
||||
)
|
||||
self._omv_clean()
|
||||
self._omv_rpc("Cron", "delete", {"uuid": raw["uuid"]})
|
||||
self._omv_rpc("Config", "applyChanges", dict(_APPLY), _APPLY_TIMEOUT)
|
||||
return {"success": True, "output": f"{key} deleted"}
|
||||
@@ -0,0 +1,127 @@
|
||||
"""Time sync on OpenMediaVault: its servers and zone through its own database (NetOrk/netork#2370).
|
||||
|
||||
napalm-linux brings napalm-device-types' ``PosixTimeSyncMixin``: it reads chrony's
|
||||
files and ``timedatectl``, and writes a drop-in under ``/etc/chrony/sources.d``
|
||||
(commenting out every other source) and ``timedatectl set-timezone``. OMV generates
|
||||
``/etc/chrony/chrony.conf`` and the zone from ``conf.system.time`` (``ntp.enable``,
|
||||
``ntp.timeservers``, ``timezone``) through Salt, so such a write would be taken back
|
||||
the next time OMV deploys its time settings -- and the web UI would go on showing
|
||||
its own servers.
|
||||
|
||||
So the servers and the zone are the web UI's: read with ``System.getTimeSettings``,
|
||||
written with ``System.setTimeSettings`` -- NTP switched on, the servers as OMV keeps
|
||||
them, one comma-separated string -- and deployed with ``Config.applyChanges`` for
|
||||
the modules that change made dirty, plus ``chrony`` and ``timezone`` if they already
|
||||
were; changes left pending in the web UI for other modules stay pending. With NTP
|
||||
switched off OMV stops chronyd, and the servers it still lists count for nothing:
|
||||
none are read. A value OMV already has is not written again. Whether the clock is
|
||||
synchronised, and by which client, is still the host's own reading.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types import PosixTimeSyncMixin
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from napalm_device_types import TimeSyncDict
|
||||
from napalm_device_types.models import FixStepOutcomeDict
|
||||
|
||||
#: The fields of ``getTimeSettings`` that ``setTimeSettings`` takes back (not ``date``).
|
||||
_SET_FIELDS = ("timezone", "ntpenable", "ntptimeservers", "ntpclients")
|
||||
#: The modules OMV regenerates from ``conf.system.time``.
|
||||
_TIME_MODULES = frozenset({"chrony", "timezone"})
|
||||
_SERVER_SEPARATOR = re.compile(r"[,\s]+")
|
||||
_APPLY_TIMEOUT = 600
|
||||
|
||||
|
||||
def omv_servers(settings: dict[str, Any]) -> list[str]:
|
||||
"""The servers OMV keeps time with: none while NTP is switched off."""
|
||||
if not _enabled(settings.get("ntpenable")):
|
||||
return []
|
||||
return [s for s in _SERVER_SEPARATOR.split(str(settings.get("ntptimeservers") or "")) if s]
|
||||
|
||||
|
||||
def _enabled(value: object) -> bool:
|
||||
if isinstance(value, str):
|
||||
return value.strip().lower() in {"1", "true", "yes", "on"}
|
||||
return bool(value)
|
||||
|
||||
|
||||
class OmvTimeSyncMixin(PosixTimeSyncMixin):
|
||||
"""The POSIX time sync, with the servers and the zone of OMV's web UI (module docstring)."""
|
||||
|
||||
if TYPE_CHECKING:
|
||||
|
||||
def _omv_rpc(
|
||||
self,
|
||||
service: str,
|
||||
method: str,
|
||||
params: dict[str, Any] | None = None,
|
||||
timeout: float = 60,
|
||||
) -> Any: ...
|
||||
|
||||
def _omv_dirty_modules(self) -> list[str]: ...
|
||||
|
||||
def _omv_time_settings(self) -> dict[str, Any]:
|
||||
"""``System.getTimeSettings``.
|
||||
|
||||
:raises RuntimeError: when OMV refuses, or answers with something else.
|
||||
"""
|
||||
settings = self._omv_rpc("System", "getTimeSettings")
|
||||
if not isinstance(settings, dict):
|
||||
raise RuntimeError(f"System.getTimeSettings answered {settings!r}")
|
||||
return settings
|
||||
|
||||
def get_time_sync(self) -> TimeSyncDict:
|
||||
"""OMV's servers and zone, the host's word on whether the clock is synchronised.
|
||||
|
||||
:raises RuntimeError: when ``System.getTimeSettings`` failed.
|
||||
:raises ValueError: when the host's reading came back cut short.
|
||||
"""
|
||||
settings = self._omv_time_settings()
|
||||
host = super().get_time_sync()
|
||||
return {
|
||||
"ntp_servers": omv_servers(settings),
|
||||
"timezone": str(settings.get("timezone") or "") or None,
|
||||
"synchronized": host["synchronized"],
|
||||
"daemon": host["daemon"],
|
||||
}
|
||||
|
||||
def _write_ntp_servers(self, servers: list[str]) -> FixStepOutcomeDict:
|
||||
settings = self._omv_time_settings()
|
||||
if [s.lower() for s in omv_servers(settings)] == [s.lower() for s in servers]:
|
||||
return {"ok": True, "output": "OpenMediaVault already keeps time with these servers"}
|
||||
applied = self._omv_save_time(settings, ntpenable=True, ntptimeservers=",".join(servers))
|
||||
return {"ok": True, "output": f"set OpenMediaVault's time servers; applied {applied}"}
|
||||
|
||||
def _write_time_zone(self, zone: str) -> FixStepOutcomeDict:
|
||||
settings = self._omv_time_settings()
|
||||
if settings.get("timezone") == zone:
|
||||
return {"ok": True, "output": f"OpenMediaVault is already in {zone}"}
|
||||
applied = self._omv_save_time(settings, timezone=zone)
|
||||
return {
|
||||
"ok": True,
|
||||
"output": f"set OpenMediaVault's time zone to {zone}; applied {applied}",
|
||||
}
|
||||
|
||||
def _omv_save_time(self, settings: dict[str, Any], **changes: Any) -> str:
|
||||
"""``setTimeSettings`` with *changes* over *settings*, then apply what that made
|
||||
dirty, and the time modules already dirty; what was applied.
|
||||
|
||||
:raises RuntimeError: when OMV refuses.
|
||||
"""
|
||||
params = {field: settings[field] for field in _SET_FIELDS if field in settings}
|
||||
params.update(changes)
|
||||
before = set(self._omv_dirty_modules())
|
||||
self._omv_rpc("System", "setTimeSettings", params)
|
||||
after = set(self._omv_dirty_modules())
|
||||
modules = sorted((after - before) | (after & _TIME_MODULES))
|
||||
if modules:
|
||||
# Salt restarts chronyd and sets the zone: give it time.
|
||||
self._omv_rpc(
|
||||
"Config", "applyChanges", {"modules": modules, "force": False}, _APPLY_TIMEOUT
|
||||
)
|
||||
return ", ".join(modules) or "nothing"
|
||||
@@ -1,4 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# Licensed under the Apache License, Version 2.0
|
||||
|
||||
"""NAPALM driver for OpenMediaVault NAS systems.
|
||||
@@ -19,10 +18,13 @@ Tested against OpenMediaVault 6.x and 7.x (Debian Bullseye / Bookworm base).
|
||||
from __future__ import annotations
|
||||
|
||||
import json as _json
|
||||
import logging
|
||||
import re
|
||||
from shlex import quote as _shlex_quote
|
||||
from typing import Any
|
||||
|
||||
from napalm_device_types import FingerprintRule
|
||||
from napalm.base.exceptions import CommandErrorException
|
||||
from napalm_device_types import FingerprintRule, StorageDriver
|
||||
from napalm_device_types.models import (
|
||||
DiskPoolDict,
|
||||
LogicalVolumeDict,
|
||||
@@ -33,19 +35,145 @@ from napalm_device_types.models import (
|
||||
StorageServiceDict,
|
||||
VolumeSnapshotDict,
|
||||
)
|
||||
from napalm_device_types import StorageDriver
|
||||
from napalm_linux.linux import LinuxDriver
|
||||
|
||||
from napalm_openmediavault._local_accounts import OmvLocalAccountsMixin
|
||||
from napalm_openmediavault._scheduled_jobs import OmvScheduledJobsMixin
|
||||
from napalm_openmediavault._time_sync import OmvTimeSyncMixin
|
||||
|
||||
class OpenMediaVaultDriver(StorageDriver, LinuxDriver):
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
#: One label of a hostname (RFC 1123); OMV's own schema asks the same.
|
||||
_HOSTNAME_LABEL_RE = re.compile(r"^(?!-)[A-Za-z0-9-]{1,63}(?<!-)$")
|
||||
#: The modules OMV regenerates from ``conf.system.network.dns``. One already
|
||||
#: dirty before the rename is applied with it, or the new name would not reach it.
|
||||
_HOSTNAME_MODULES = frozenset(
|
||||
{"hostname", "hosts", "postfix", "avahi", "samba", "proftpd", "systemdnetworkd"}
|
||||
)
|
||||
_DIRTY_MODULES = "/var/lib/openmediavault/dirtymodules.json"
|
||||
|
||||
|
||||
#: Every block device, as JSON; sizes in bytes.
|
||||
_LSBLK = "lsblk -J -b -o NAME,SIZE,TYPE,ROTA,VENDOR,MODEL,SERIAL,TRAN 2>/dev/null"
|
||||
#: Identity, overall health verdict and attributes; ``-H`` alone prints the verdict.
|
||||
_SMARTCTL = "smartctl -iHA /dev/{name} 2>/dev/null"
|
||||
_SMARTCTL_TIMEOUT = 15
|
||||
#: smartctl's exit status bits 0 and 1: the command line did not parse (sudo's own
|
||||
#: refusal exits 1 as well) or the device could not be opened. Bits 2-7 describe the
|
||||
#: disk, not the call.
|
||||
_SMARTCTL_CALL_FAILED = 0b11
|
||||
#: The overall verdict of an ATA or NVMe disk: ``PASSED`` or ``FAILED!``.
|
||||
_SMART_VERDICT_RE = re.compile(r"^SMART overall-health self-assessment test result:\s*(\S+)", re.M)
|
||||
#: A SCSI/SAS disk's: ``OK``, or the failure it predicts.
|
||||
_SMART_SCSI_STATUS_RE = re.compile(r"^SMART Health Status:\s*(.+?)\s*$", re.M)
|
||||
_SMART_VERDICTS = {"PASSED": "healthy", "FAILED": "failed"}
|
||||
#: ATA attributes counting sectors the disk lost or could not read, and the raw value
|
||||
#: of each (the column after WHEN_FAILED).
|
||||
_SMART_ATA_DEGRADED = ("Reallocated_Sector_Ct", "Current_Pending_Sector", "Offline_Uncorrectable")
|
||||
_SMART_ATA_RAW_RE = re.compile(r"^\s*\d+\s+(\S+)\s+0x[0-9a-fA-F]+\s+(?:\S+\s+){6}(\d+)", re.M)
|
||||
#: An NVMe disk's own warning flags, and the media errors it counted.
|
||||
_SMART_NVME_CRITICAL_RE = re.compile(r"^Critical Warning:\s+0x([0-9a-fA-F]+)\s*$", re.M)
|
||||
_SMART_NVME_MEDIA_ERRORS_RE = re.compile(r"^Media and Data Integrity Errors:\s+([\d,]+)\s*$", re.M)
|
||||
#: A SCSI/SAS disk's reassigned blocks.
|
||||
_SMART_SCSI_DEFECTS_RE = re.compile(r"^Elements in grown defect list:\s+(\d+)\s*$", re.M)
|
||||
#: An ATA disk's temperature attribute, an NVMe disk's ``Temperature:`` line.
|
||||
_SMART_TEMP_RE = re.compile(
|
||||
r"(?:Temperature_Celsius|Current Temperature|Temperature:)[^\n]*?(\d+)\s*(?:Celsius|\(|$)"
|
||||
)
|
||||
#: A SCSI/SAS disk's; a QEMU disk without a sensor prints ``0 C``.
|
||||
_SMART_SCSI_TEMP_RE = re.compile(r"^Current Drive Temperature:\s+(\d+) C\s*$", re.M)
|
||||
#: An md array's line in /proc/mdstat, and its members: ``sda1[0]``, ``sdc1[1](F)``.
|
||||
_MDSTAT_ARRAY_RE = re.compile(r"^(md\d+)\s*:(.*)$", re.M)
|
||||
_MDSTAT_MEMBER_RE = re.compile(r"(\S+?)\[\d+\]")
|
||||
|
||||
|
||||
def smart_health(output: str) -> str:
|
||||
"""A disk's health from ``smartctl -iHA`` output.
|
||||
|
||||
``"failed"`` when the overall verdict says so; ``"warning"`` when it passed but
|
||||
the disk counts lost or unreadable sectors (ATA reallocated, pending or offline
|
||||
uncorrectable sectors, SAS grown defects) or, for NVMe, sets a critical warning
|
||||
flag or counts media errors; ``"healthy"`` otherwise; ``"unknown"`` when
|
||||
smartctl printed no verdict (no SMART support, a USB bridge without
|
||||
pass-through).
|
||||
"""
|
||||
verdict = _smart_verdict(output)
|
||||
if verdict == "healthy" and _smart_degraded(output):
|
||||
return "warning"
|
||||
return verdict
|
||||
|
||||
|
||||
def _smart_verdict(output: str) -> str:
|
||||
verdict = _SMART_VERDICT_RE.search(output)
|
||||
if verdict:
|
||||
return _SMART_VERDICTS.get(verdict.group(1).rstrip("!"), "unknown")
|
||||
status = _SMART_SCSI_STATUS_RE.search(output)
|
||||
if status:
|
||||
return "healthy" if status.group(1) == "OK" else "failed"
|
||||
return "unknown"
|
||||
|
||||
|
||||
def _smart_degraded(output: str) -> bool:
|
||||
ata = any(
|
||||
name in _SMART_ATA_DEGRADED and int(raw) > 0
|
||||
for name, raw in _SMART_ATA_RAW_RE.findall(output)
|
||||
)
|
||||
critical = _SMART_NVME_CRITICAL_RE.search(output)
|
||||
media = _SMART_NVME_MEDIA_ERRORS_RE.search(output)
|
||||
defects = _SMART_SCSI_DEFECTS_RE.search(output)
|
||||
return (
|
||||
ata
|
||||
or bool(critical and int(critical.group(1), 16))
|
||||
or bool(media and int(media.group(1).replace(",", "")))
|
||||
or bool(defects and int(defects.group(1)))
|
||||
)
|
||||
|
||||
|
||||
def smart_temperature(output: str) -> int:
|
||||
"""A disk's temperature in Celsius from ``smartctl -A`` output; ``-1`` if none."""
|
||||
found = _SMART_TEMP_RE.search(output)
|
||||
if found:
|
||||
return int(found.group(1))
|
||||
scsi = _SMART_SCSI_TEMP_RE.search(output)
|
||||
if scsi and int(scsi.group(1)) > 0:
|
||||
return int(scsi.group(1))
|
||||
return -1
|
||||
|
||||
|
||||
def md_members(mdstat: str) -> dict[str, str]:
|
||||
"""Each member device in ``/proc/mdstat``, mapped to its array: ``{"sda1": "md1"}``."""
|
||||
return {
|
||||
member: array
|
||||
for array, rest in _MDSTAT_ARRAY_RE.findall(mdstat)
|
||||
for member in _MDSTAT_MEMBER_RE.findall(rest)
|
||||
}
|
||||
|
||||
|
||||
def _pool_of(disk: str, members: dict[str, str]) -> str:
|
||||
"""The array *disk* or one of its partitions is a member of, or ``""``.
|
||||
|
||||
Linux names a partition by appending its number, after a ``p`` when the disk's
|
||||
name ends in a digit: ``sda`` owns ``sda1``, ``nvme0n1`` owns ``nvme0n1p1``;
|
||||
``sdaa1`` is not ``sda``'s, nor ``nvme0n11`` (another namespace) ``nvme0n1``'s.
|
||||
"""
|
||||
partition = r"p\d+" if disk[-1:].isdigit() else r"\d+"
|
||||
own = re.compile(rf"{re.escape(disk)}(?:{partition})?")
|
||||
return next((array for member, array in members.items() if own.fullmatch(member)), "")
|
||||
|
||||
|
||||
class OpenMediaVaultDriver(
|
||||
OmvLocalAccountsMixin, OmvScheduledJobsMixin, OmvTimeSyncMixin, StorageDriver, LinuxDriver
|
||||
):
|
||||
"""NAPALM driver for OpenMediaVault NAS systems.
|
||||
|
||||
Declares both roles it fills: a NAS built on Debian. Storage comes first,
|
||||
so netOrk shows it as storage rather than as a Linux host.
|
||||
|
||||
Inherits all Linux OS functionality from LinuxDriver (packages, services,
|
||||
users, processes, cron, Docker) -- OMV really is Debian, so apt applies --
|
||||
and adds OMV-specific storage management on top.
|
||||
users, processes, scheduled jobs, Docker) -- OMV really is Debian, so apt
|
||||
applies -- and adds OMV-specific storage management on top. The scheduled
|
||||
jobs of OMV's web UI go through its RPC (``_scheduled_jobs``), and so do its
|
||||
time servers and zone (``_time_sync``).
|
||||
|
||||
NAS services are ``get_storage_services()``; the systemd service list stays
|
||||
``get_services()``. Two names for two different things.
|
||||
@@ -65,66 +193,88 @@ class OpenMediaVaultDriver(StorageDriver, LinuxDriver):
|
||||
FingerprintRule("openmediavault", weight=9.0, mandatory=True),
|
||||
]
|
||||
|
||||
#: OMV generates sshd_config from its own database, but its template includes
|
||||
#: /etc/ssh/sshd_config.d, which salt leaves alone: the SSH hardening from
|
||||
#: napalm-linux goes into a drop-in there and never into sshd_config itself.
|
||||
SSHD_CONFIG_GENERATED = True
|
||||
|
||||
# ── Facts override ─────────────────────────────────────────────────────────
|
||||
|
||||
def get_facts(self) -> dict[str, Any]:
|
||||
"""Return device facts, overriding OMV version from dpkg."""
|
||||
facts = super().get_facts()
|
||||
try:
|
||||
ver = self._send(
|
||||
"dpkg-query -W -f='${Version}' openmediavault 2>/dev/null"
|
||||
).strip()
|
||||
ver = self._send("dpkg-query -W -f='${Version}' openmediavault 2>/dev/null").strip()
|
||||
if ver:
|
||||
facts["os_version"] = f"OMV {ver}"
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("%s: OMV version not read: ignored", self.hostname, exc_info=True)
|
||||
return facts
|
||||
|
||||
# ── Warnings ──────────────────────────────────────────────────────────────
|
||||
# ── Hostname ───────────────────────────────────────────────────────────────
|
||||
|
||||
def get_device_warnings(self) -> list[dict[str, Any]]:
|
||||
"""Return warnings, ignoring packages held back by apt-get upgrade.
|
||||
def set_hostname(self, new_hostname: str) -> None:
|
||||
"""Rename the NAS the way OMV's web UI does, through its own database.
|
||||
|
||||
On OMV, kernel and OMV-specific packages are routinely held back
|
||||
(they require dist-upgrade or omv-upgrade). Reporting them as
|
||||
"updates available" after a successful apt-get upgrade is misleading.
|
||||
We simulate the upgrade first and only warn if there are packages
|
||||
that a standard apt-get upgrade would actually install.
|
||||
LinuxDriver's rename writes ``/etc/hostname`` and ``/etc/hosts``, which
|
||||
OMV regenerates from ``conf.system.network.dns`` on its next apply. So the
|
||||
name goes to ``Network.setGeneralSettings`` -- an FQDN sets the domain as
|
||||
well, a bare name keeps it -- and ``Config.applyChanges`` deploys the
|
||||
modules the rename made dirty, plus the hostname modules that already
|
||||
were. Other changes pending in the web UI stay pending.
|
||||
|
||||
:raises ValueError: for a name that is not a valid hostname, before
|
||||
anything runs on the NAS.
|
||||
:raises RuntimeError: when OMV refuses a step.
|
||||
"""
|
||||
warnings: list[dict[str, Any]] = []
|
||||
labels = new_hostname.split(".")
|
||||
if len(new_hostname) > 253 or not all(_HOSTNAME_LABEL_RE.match(x) for x in labels):
|
||||
raise ValueError(f"not a valid hostname: {new_hostname!r}")
|
||||
current = self._omv_rpc("Network", "getGeneralSettings")
|
||||
domain = ".".join(labels[1:]) if len(labels) > 1 else current.get("domainname", "")
|
||||
before = set(self._omv_dirty_modules())
|
||||
self._omv_rpc(
|
||||
"Network", "setGeneralSettings", {"hostname": labels[0], "domainname": domain}
|
||||
)
|
||||
after = set(self._omv_dirty_modules())
|
||||
modules = sorted((after - before) | (after & _HOSTNAME_MODULES))
|
||||
if modules:
|
||||
# Salt restarts what it deploys (Samba, Postfix, networkd): give it time.
|
||||
self._omv_rpc("Config", "applyChanges", {"modules": modules, "force": False}, 600)
|
||||
|
||||
def _omv_rpc(
|
||||
self, service: str, method: str, params: dict[str, Any] | None = None, timeout: float = 60
|
||||
) -> Any:
|
||||
"""Call ``omv-rpc`` as root and return its decoded answer.
|
||||
|
||||
:raises RuntimeError: when the call fails, with OMV's answer.
|
||||
"""
|
||||
command = f"omv-rpc -u admin {service} {method}"
|
||||
if params is not None:
|
||||
command += f" {_shlex_quote(_json.dumps(params))}"
|
||||
output, status = self._sudo_status(command, timeout)
|
||||
if status != 0:
|
||||
raise RuntimeError(f"omv-rpc {service}.{method} failed: {output[-300:]}")
|
||||
lines = output.splitlines()
|
||||
return _json.loads(lines[-1]) if lines else None
|
||||
|
||||
def _omv_dirty_modules(self) -> list[str]:
|
||||
"""The modules with configuration changes not yet deployed."""
|
||||
output, _status = self._sudo_status(f"cat {_DIRTY_MODULES} 2>/dev/null || echo '[]'", 30)
|
||||
try:
|
||||
sim = self._sudo(
|
||||
"DEBIAN_FRONTEND=noninteractive apt-get upgrade --simulate 2>&1",
|
||||
read_timeout=60,
|
||||
)
|
||||
m = re.search(r'(\d+) upgraded', sim)
|
||||
upgradable_count = int(m.group(1)) if m else 0
|
||||
except Exception:
|
||||
upgradable_count = -1 # unknown — fall back to parent behaviour
|
||||
|
||||
if upgradable_count == 0:
|
||||
return [] # nothing to do with apt-get upgrade; held-back only
|
||||
if upgradable_count < 0:
|
||||
return super().get_device_warnings()
|
||||
|
||||
updates = self.get_available_updates()
|
||||
if updates:
|
||||
warnings.append({
|
||||
"code": "updates_available",
|
||||
"meta": {
|
||||
"count": upgradable_count,
|
||||
"packages": [u.get("name", "") for u in updates[:10]],
|
||||
},
|
||||
})
|
||||
return warnings
|
||||
dirty = _json.loads(output or "[]")
|
||||
except ValueError:
|
||||
return []
|
||||
return [m for m in dirty if isinstance(m, str)] if isinstance(dirty, list) else []
|
||||
|
||||
# ── Physical disks ─────────────────────────────────────────────────────────
|
||||
|
||||
def get_disks(self) -> list[PhysicalDiskDict]:
|
||||
"""Return physical disk inventory.
|
||||
|
||||
Uses ``lsblk -J`` for device enumeration and ``smartctl -iA``
|
||||
(via sudo) for health, temperature, and RPM data.
|
||||
Uses ``lsblk -J`` for device enumeration, ``smartctl -iHA`` (via sudo)
|
||||
for health, temperature, and RPM data, and ``/proc/mdstat``, read once,
|
||||
for array membership.
|
||||
|
||||
Each entry contains:
|
||||
|
||||
@@ -136,7 +286,9 @@ class OpenMediaVaultDriver(StorageDriver, LinuxDriver):
|
||||
* size (int) - raw capacity in bytes
|
||||
* rpm (int) - rotational speed; ``0`` for SSD/NVMe
|
||||
* temperature (int) - temperature in Celsius; ``-1`` if unavailable
|
||||
* health (string) - ``"healthy"``, ``"failed"``, or ``"unknown"``
|
||||
* health (string) - ``"healthy"``, ``"warning"``, ``"failed"``, or
|
||||
``"unknown"`` (see :func:`smart_health`); a smartctl call that failed is
|
||||
logged as a warning and leaves the disk ``"unknown"``
|
||||
* pool (string) - md array name if member; empty string otherwise
|
||||
|
||||
Example::
|
||||
@@ -155,18 +307,13 @@ class OpenMediaVaultDriver(StorageDriver, LinuxDriver):
|
||||
"pool": "md1",
|
||||
},
|
||||
]
|
||||
|
||||
:raises CommandErrorException: when lsblk printed no device list.
|
||||
"""
|
||||
result: list[PhysicalDiskDict] = []
|
||||
|
||||
try:
|
||||
raw = self._send(
|
||||
"lsblk -J -b -o NAME,SIZE,TYPE,ROTA,VENDOR,MODEL,SERIAL,TRAN 2>/dev/null"
|
||||
)
|
||||
lsblk = _json.loads(raw)
|
||||
except Exception:
|
||||
return result
|
||||
|
||||
for dev in lsblk.get("blockdevices", []):
|
||||
devices = self._lsblk()
|
||||
members = self._md_members()
|
||||
for dev in devices:
|
||||
if dev.get("type") != "disk":
|
||||
continue
|
||||
name = dev.get("name", "")
|
||||
@@ -187,57 +334,75 @@ class OpenMediaVaultDriver(StorageDriver, LinuxDriver):
|
||||
else:
|
||||
disk_type = "hdd"
|
||||
|
||||
temperature = -1
|
||||
health = "unknown"
|
||||
rpm = 0
|
||||
health, temperature, rpm = self._smart(name, disk_type)
|
||||
|
||||
try:
|
||||
smart = self._sudo(
|
||||
f"smartctl -iA /dev/{name} 2>/dev/null", read_timeout=15
|
||||
result.append(
|
||||
PhysicalDiskDict(
|
||||
slot=f"/dev/{name}",
|
||||
model=model,
|
||||
serial=serial,
|
||||
vendor=vendor,
|
||||
type=disk_type,
|
||||
size=size,
|
||||
rpm=rpm,
|
||||
temperature=temperature,
|
||||
health=health,
|
||||
pool=_pool_of(name, members),
|
||||
)
|
||||
if "PASSED" in smart:
|
||||
health = "healthy"
|
||||
elif "FAILED" in smart:
|
||||
health = "failed"
|
||||
temp_m = re.search(
|
||||
r"(?:Temperature_Celsius|Current Temperature|Temperature:)"
|
||||
r"[^\n]*?(\d+)\s*(?:Celsius|\(|$)",
|
||||
smart,
|
||||
)
|
||||
if temp_m:
|
||||
temperature = int(temp_m.group(1))
|
||||
if disk_type == "hdd":
|
||||
rpm_m = re.search(r"Rotation Rate:\s+(\d+)\s+rpm", smart)
|
||||
if rpm_m:
|
||||
rpm = int(rpm_m.group(1))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
result.append(PhysicalDiskDict(
|
||||
slot=f"/dev/{name}",
|
||||
model=model,
|
||||
serial=serial,
|
||||
vendor=vendor,
|
||||
type=disk_type,
|
||||
size=size,
|
||||
rpm=rpm,
|
||||
temperature=temperature,
|
||||
health=health,
|
||||
pool=self._disk_to_pool(name),
|
||||
))
|
||||
)
|
||||
|
||||
return result
|
||||
|
||||
def _disk_to_pool(self, disk_name: str) -> str:
|
||||
"""Return the md array a disk belongs to, or empty string."""
|
||||
def _lsblk(self) -> list[dict[str, Any]]:
|
||||
"""The block devices lsblk lists; a failed or garbled read raises."""
|
||||
raw = self._send(_LSBLK)
|
||||
try:
|
||||
mdstat = self._send("cat /proc/mdstat 2>/dev/null")
|
||||
for line in mdstat.splitlines():
|
||||
if disk_name in line and re.match(r'^md\d+', line):
|
||||
return line.split(":")[0].strip()
|
||||
except Exception:
|
||||
pass
|
||||
return ""
|
||||
devices = _json.loads(raw)["blockdevices"]
|
||||
except (ValueError, KeyError, TypeError) as exc:
|
||||
raise CommandErrorException(
|
||||
f"lsblk on {self.hostname} printed no device list: {raw[-300:]!r}"
|
||||
) from exc
|
||||
if not isinstance(devices, list):
|
||||
raise CommandErrorException(f"lsblk on {self.hostname}: blockdevices is no list")
|
||||
return devices
|
||||
|
||||
def _smart(self, name: str, disk_type: str) -> tuple[str, int, int]:
|
||||
"""A disk's SMART health, temperature (``-1`` if unknown) and rpm (``0``).
|
||||
|
||||
A smartctl call that failed (timeout, sudo refused, device not opened) is
|
||||
logged as a warning, so it is told apart from a disk without SMART; the
|
||||
disk stays in the inventory as ``"unknown"``.
|
||||
"""
|
||||
try:
|
||||
smart, status = self._sudo_status(
|
||||
_SMARTCTL.format(name=name), read_timeout=_SMARTCTL_TIMEOUT
|
||||
)
|
||||
except OSError as exc: # TimeoutError and the socket's own errors
|
||||
logger.warning("%s: smartctl for %s failed: %s", self.hostname, name, exc)
|
||||
return "unknown", -1, 0
|
||||
if status is not None and status & _SMARTCTL_CALL_FAILED:
|
||||
logger.warning(
|
||||
"%s: smartctl for %s failed (exit status %s): %s",
|
||||
self.hostname,
|
||||
name,
|
||||
status,
|
||||
smart[-300:],
|
||||
)
|
||||
return "unknown", -1, 0
|
||||
rpm = 0
|
||||
if disk_type == "hdd":
|
||||
rpm_m = re.search(r"Rotation Rate:\s+(\d+)\s+rpm", smart)
|
||||
if rpm_m:
|
||||
rpm = int(rpm_m.group(1))
|
||||
return smart_health(smart), smart_temperature(smart), rpm
|
||||
|
||||
def _md_members(self) -> dict[str, str]:
|
||||
"""The md array of each member device, from one read of ``/proc/mdstat``.
|
||||
|
||||
A host without the md driver has no ``/proc/mdstat`` and no members; a
|
||||
failed read raises.
|
||||
"""
|
||||
return md_members(self._send("cat /proc/mdstat 2>/dev/null"))
|
||||
|
||||
# ── md RAID pools ──────────────────────────────────────────────────────────
|
||||
|
||||
@@ -284,19 +449,17 @@ class OpenMediaVaultDriver(StorageDriver, LinuxDriver):
|
||||
return result
|
||||
|
||||
for line in mdstat.splitlines():
|
||||
m = re.match(r'^(md\d+)\s*:\s+(\S+)\s+(\S+)\s+(.*)', line)
|
||||
m = re.match(r"^(md\d+)\s*:\s+(\S+)\s+(\S+)\s+(.*)", line)
|
||||
if not m:
|
||||
continue
|
||||
|
||||
md_name, state_word, level_raw, members_raw = m.groups()
|
||||
member_disks = re.findall(r'(\w+)\[\d+\]', members_raw)
|
||||
member_disks = re.findall(r"(\w+)\[\d+\]", members_raw)
|
||||
status = "online" if state_word == "active" else "offline"
|
||||
total = 0
|
||||
|
||||
try:
|
||||
detail = self._sudo(
|
||||
f"mdadm --detail /dev/{md_name} 2>/dev/null", read_timeout=10
|
||||
)
|
||||
detail = self._sudo(f"mdadm --detail /dev/{md_name} 2>/dev/null", read_timeout=10)
|
||||
size_m = re.search(r"Array Size\s*:\s*(\d+)\s*\(", detail)
|
||||
if size_m:
|
||||
total = int(size_m.group(1)) * 1024 # kB → bytes
|
||||
@@ -305,7 +468,9 @@ class OpenMediaVaultDriver(StorageDriver, LinuxDriver):
|
||||
elif re.search(r"State\s*:.*(?:faulty|failed)", detail, re.IGNORECASE):
|
||||
status = "faulted"
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug(
|
||||
"%s: mdadm --detail for %s: ignored", self.hostname, md_name, exc_info=True
|
||||
)
|
||||
|
||||
result[md_name] = DiskPoolDict(
|
||||
name=md_name,
|
||||
@@ -392,10 +557,13 @@ class OpenMediaVaultDriver(StorageDriver, LinuxDriver):
|
||||
key = mountpoint.lstrip("/").replace("/", "-") or "root"
|
||||
pool = device.removeprefix("/dev/")
|
||||
|
||||
readonly = bool(re.search(
|
||||
rf'^{re.escape(device)}\s+\S+\s+\S+\s+(?:[^,\s]*,)*ro(?:,|\s|$)',
|
||||
mounts, re.MULTILINE,
|
||||
))
|
||||
readonly = bool(
|
||||
re.search(
|
||||
rf"^{re.escape(device)}\s+\S+\s+\S+\s+(?:[^,\s]*,)*ro(?:,|\s|$)",
|
||||
mounts,
|
||||
re.MULTILINE,
|
||||
)
|
||||
)
|
||||
|
||||
result[key] = LogicalVolumeDict(
|
||||
name=key,
|
||||
@@ -482,20 +650,25 @@ class OpenMediaVaultDriver(StorageDriver, LinuxDriver):
|
||||
Example::
|
||||
|
||||
{
|
||||
"smb": {"name": "smb", "enabled": True, "running": True, "port": 445, "version": ""},
|
||||
"nfs": {"name": "nfs", "enabled": True, "running": True, "port": 2049, "version": ""},
|
||||
"ftp": {"name": "ftp", "enabled": False,"running": False, "port": 21, "version": ""},
|
||||
"ssh": {"name": "ssh", "enabled": True, "running": True, "port": 22, "version": ""},
|
||||
"rsync": {"name": "rsync", "enabled": False,"running": False, "port": 873, "version": ""},
|
||||
"smb": {"name": "smb", "enabled": True, "running": True,
|
||||
"port": 445, "version": ""},
|
||||
"nfs": {"name": "nfs", "enabled": True, "running": True,
|
||||
"port": 2049, "version": ""},
|
||||
"ftp": {"name": "ftp", "enabled": False, "running": False,
|
||||
"port": 21, "version": ""},
|
||||
"ssh": {"name": "ssh", "enabled": True, "running": True,
|
||||
"port": 22, "version": ""},
|
||||
"rsync": {"name": "rsync", "enabled": False, "running": False,
|
||||
"port": 873, "version": ""},
|
||||
}
|
||||
"""
|
||||
_SVC_MAP = [
|
||||
# (key, systemd unit, default port)
|
||||
("smb", "smbd", 445),
|
||||
("nfs", "nfs-server", 2049),
|
||||
("ftp", "proftpd", 21),
|
||||
("ssh", "ssh", 22),
|
||||
("rsync", "rsync", 873),
|
||||
("smb", "smbd", 445),
|
||||
("nfs", "nfs-server", 2049),
|
||||
("ftp", "proftpd", 21),
|
||||
("ssh", "ssh", 22),
|
||||
("rsync", "rsync", 873),
|
||||
]
|
||||
result: dict[str, StorageServiceDict] = {}
|
||||
for key, unit, port in _SVC_MAP:
|
||||
@@ -511,7 +684,11 @@ class OpenMediaVaultDriver(StorageDriver, LinuxDriver):
|
||||
except Exception:
|
||||
running = enabled = False
|
||||
result[key] = StorageServiceDict(
|
||||
name=key, enabled=enabled, running=running, port=port, version="",
|
||||
name=key,
|
||||
enabled=enabled,
|
||||
running=running,
|
||||
port=port,
|
||||
version="",
|
||||
)
|
||||
return result
|
||||
|
||||
@@ -519,9 +696,7 @@ class OpenMediaVaultDriver(StorageDriver, LinuxDriver):
|
||||
|
||||
def get_volume_snapshots(self, volume: str = "") -> list[VolumeSnapshotDict]:
|
||||
"""Return volume snapshots (not supported on OpenMediaVault)."""
|
||||
raise NotImplementedError(
|
||||
"OpenMediaVault does not expose volume snapshots via this driver"
|
||||
)
|
||||
raise NotImplementedError("OpenMediaVault does not expose volume snapshots via this driver")
|
||||
|
||||
def get_replication_jobs(self) -> list[ReplicationJobDict]:
|
||||
"""Return replication jobs (not supported on OpenMediaVault)."""
|
||||
@@ -533,7 +708,7 @@ class OpenMediaVaultDriver(StorageDriver, LinuxDriver):
|
||||
|
||||
# ── Internal helpers ───────────────────────────────────────────────────────
|
||||
|
||||
def _omv_read(self, key: str) -> list:
|
||||
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
|
||||
@@ -549,7 +724,8 @@ class OpenMediaVaultDriver(StorageDriver, LinuxDriver):
|
||||
# Older OMV wraps the list: {"share": [...]}
|
||||
for wrapper in ("share", "rule", "entry", "mntent", "sharedfolder"):
|
||||
if wrapper in data and isinstance(data[wrapper], list):
|
||||
return data[wrapper]
|
||||
wrapped: list[dict[str, Any]] = data[wrapper]
|
||||
return wrapped
|
||||
return []
|
||||
except Exception:
|
||||
return []
|
||||
@@ -571,7 +747,7 @@ class OpenMediaVaultDriver(StorageDriver, LinuxDriver):
|
||||
break
|
||||
return f"{mnt_dir}/{rel}".rstrip("/") if rel else mnt_dir
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("%s: shared folder %s: ignored", self.hostname, uuid, exc_info=True)
|
||||
return ""
|
||||
|
||||
def _smb_shares(self) -> dict[str, NASShareDict]:
|
||||
|
||||
Whitespace-only changes.
+45
-9
@@ -1,14 +1,14 @@
|
||||
[build-system]
|
||||
requires = ["setuptools>=68", "wheel"]
|
||||
requires = ["setuptools>=77"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "napalm-openmediavault"
|
||||
version = "0.1.0"
|
||||
version = "0.3.0"
|
||||
description = "NAPALM driver for OpenMediaVault NAS (SSH)"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.9"
|
||||
license = { text = "Apache-2.0" }
|
||||
requires-python = ">=3.12"
|
||||
license = "Apache-2.0"
|
||||
authors = [
|
||||
{ name = "Christian Manivong", email = "christian@manivong.de" },
|
||||
]
|
||||
@@ -17,28 +17,64 @@ classifiers = [
|
||||
"Development Status :: 3 - Alpha",
|
||||
"Intended Audience :: Developers",
|
||||
"Intended Audience :: System Administrators",
|
||||
"License :: OSI Approved :: Apache Software License",
|
||||
"Operating System :: OS Independent",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Programming Language :: Python :: 3.12",
|
||||
"Programming Language :: Python :: 3.13",
|
||||
"Topic :: System :: Networking",
|
||||
"Topic :: System :: Systems Administration",
|
||||
"Typing :: Typed",
|
||||
]
|
||||
dependencies = [
|
||||
"napalm>=4.0",
|
||||
"napalm-device-types>=0.3.0",
|
||||
"napalm-linux>=0.1.0",
|
||||
"napalm-device-types>=4.35.0",
|
||||
"napalm-linux>=0.17.0",
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
dev = ["pytest>=8", "pytest-cov>=5", "mypy>=1.11", "ruff>=0.6"]
|
||||
|
||||
[project.entry-points."napalm.drivers"]
|
||||
openmediavault = "napalm_openmediavault:OpenMediaVaultDriver"
|
||||
|
||||
[project.urls]
|
||||
Repository = "https://github.com/chrismanivong/napalm-openmediavault"
|
||||
Repository = "https://git.netork.io/NAPALM/napalm-openmediavault"
|
||||
Issues = "https://git.netork.io/NAPALM/napalm-openmediavault/issues"
|
||||
Changelog = "https://git.netork.io/NAPALM/napalm-openmediavault/src/branch/main/CHANGELOG.md"
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
where = ["."]
|
||||
include = ["napalm_openmediavault*"]
|
||||
|
||||
[tool.setuptools.package-data]
|
||||
napalm_openmediavault = ["py.typed"]
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 100
|
||||
target-version = "py312"
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["E", "F", "I", "UP", "B"]
|
||||
|
||||
[tool.ruff.lint.per-file-ignores]
|
||||
# Recorded device output keeps its lines.
|
||||
"tests/**" = ["E501"]
|
||||
|
||||
[tool.mypy]
|
||||
python_version = "3.9"
|
||||
python_version = "3.12"
|
||||
strict = true
|
||||
# napalm itself is untyped, so every driver subclasses Any.
|
||||
disallow_subclassing_any = false
|
||||
|
||||
[[tool.mypy.overrides]]
|
||||
module = ["napalm.*", "netmiko.*", "paramiko.*"]
|
||||
ignore_missing_imports = true
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
|
||||
[tool.coverage.run]
|
||||
source = ["napalm_openmediavault"]
|
||||
|
||||
[tool.coverage.report]
|
||||
fail_under = 15
|
||||
Binary file not shown.
Binary file not shown.
+2
@@ -0,0 +1,2 @@
|
||||
Personalities : [raid0] [raid1] [raid4] [raid5] [raid6] [raid10]
|
||||
unused devices: <none>
|
||||
@@ -0,0 +1,20 @@
|
||||
smartctl 7.4 2023-08-01 r5530 [x86_64-linux-7.2.11+deb13-amd64] (local build)
|
||||
Copyright (C) 2002-23, Bruce Allen, Christian Franke, www.smartmontools.org
|
||||
|
||||
=== START OF INFORMATION SECTION ===
|
||||
Vendor: QEMU
|
||||
Product: QEMU HARDDISK
|
||||
Revision: 2.5+
|
||||
Compliance: SPC-3
|
||||
User Capacity: 34,359,738,368 bytes [34.3 GB]
|
||||
Logical block size: 512 bytes
|
||||
LU is thin provisioned, LBPRZ=0
|
||||
Device type: disk
|
||||
Local Time is: Sun Nov 1 21:08:12 2026 UTC
|
||||
SMART support is: Unavailable - device lacks SMART capability.
|
||||
|
||||
=== START OF READ SMART DATA SECTION ===
|
||||
Current Drive Temperature: 0 C
|
||||
Drive Trip Temperature: 0 C
|
||||
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
smartctl 7.5 2025-04-30 r5714 [x86_64-linux-7.0.14-26-pve] (local build)
|
||||
Copyright (C) 2002-25, Bruce Allen, Christian Franke, www.smartmontools.org
|
||||
|
||||
=== START OF INFORMATION SECTION ===
|
||||
Model Family: Supermicro SATA DOM (SuperDOM)
|
||||
Device Model: SuperMicro SSD
|
||||
Serial Number: FAKESERIAL0000000001
|
||||
LU WWN Device Id: 5 000000 000000001
|
||||
Firmware Version: SOB20R
|
||||
User Capacity: 15,837,691,904 bytes [15.8 GB]
|
||||
Sector Size: 512 bytes logical/physical
|
||||
Rotation Rate: Solid State Device
|
||||
TRIM Command: Available, deterministic, zeroed
|
||||
Device is: In smartctl database 7.5/5706
|
||||
ATA Version is: ACS-2 (minor revision not indicated)
|
||||
SATA Version is: SATA 3.1, 6.0 Gb/s (current: 6.0 Gb/s)
|
||||
Local Time is: Sun Nov 1 22:09:52 2026 CET
|
||||
SMART support is: Available - device has SMART capability.
|
||||
SMART support is: Enabled
|
||||
|
||||
=== START OF READ SMART DATA SECTION ===
|
||||
SMART overall-health self-assessment test result: PASSED
|
||||
|
||||
SMART Attributes Data Structure revision number: 1
|
||||
Vendor Specific SMART Attributes with Thresholds:
|
||||
ID# ATTRIBUTE_NAME FLAG VALUE WORST THRESH TYPE UPDATED WHEN_FAILED RAW_VALUE
|
||||
1 Raw_Read_Error_Rate 0x0000 100 100 000 Old_age Offline - 0
|
||||
5 Reallocated_Sector_Ct 0x0000 100 100 000 Old_age Offline - 0
|
||||
9 Power_On_Hours 0x0000 100 100 000 Old_age Offline - 18373
|
||||
12 Power_Cycle_Count 0x0000 100 100 000 Old_age Offline - 54
|
||||
15 User_Cpcty_Sector_Cnt 0x0000 100 100 000 Old_age Offline - 30932992
|
||||
160 Not_In_Use 0x0000 100 100 000 Old_age Offline - 0
|
||||
161 Not_In_Use 0x0000 100 100 000 Old_age Offline - 160
|
||||
163 Not_In_Use 0x0000 100 100 000 Old_age Offline - 6
|
||||
164 Not_In_Use 0x0000 100 100 000 Old_age Offline - 661737
|
||||
165 Not_In_Use 0x0000 100 100 000 Old_age Offline - 363
|
||||
166 Minimum_PE_Cycles_TLC 0x0000 100 100 000 Old_age Offline - 262
|
||||
167 Not_In_Use 0x0000 100 100 000 Old_age Offline - 316
|
||||
168 Maximum_PE_Cycles_TLC 0x0000 100 100 000 Old_age Offline - 3000
|
||||
172 Unknown_Attribute 0x0000 100 100 000 Old_age Offline - 0
|
||||
175 Program_Fail_Count_Chip 0x0000 100 100 000 Old_age Offline - 6
|
||||
177 Wear_Leveling_Count 0x0000 100 100 000 Old_age Offline - 3855
|
||||
181 Program_Fail_Cnt_Total 0x0000 100 100 000 Old_age Offline - 0
|
||||
187 Reported_Uncorrect 0x0000 100 100 000 Old_age Offline - 0
|
||||
192 Power-Off_Retract_Count 0x0000 100 100 000 Old_age Offline - 12
|
||||
194 Temperature_Celsius 0x0000 100 100 000 Old_age Offline - 34 (Min/Max 1/58)
|
||||
195 Hardware_ECC_Recovered 0x0000 100 100 000 Old_age Offline - 75
|
||||
197 Current_Pending_Sector 0x0000 100 100 000 Old_age Offline - 0
|
||||
198 Offline_Uncorrectable 0x0000 100 100 000 Old_age Offline - 0
|
||||
199 UDMA_CRC_Error_Count 0x0000 100 100 000 Old_age Offline - 0
|
||||
231 SSD_Life_Left 0x0000 100 100 000 Old_age Offline - 100
|
||||
232 Available_Reservd_Space 0x0000 100 100 000 Old_age Offline - 90
|
||||
233 NAND_Writes_1GiB 0x0000 100 100 000 Old_age Offline - 5169
|
||||
241 Lifetime_Writes_GiB 0x0000 100 100 000 Old_age Offline - 2361
|
||||
242 Lifetime_Reads_GiB 0x0000 100 100 000 Old_age Offline - 2579
|
||||
@@ -0,0 +1,43 @@
|
||||
smartctl 7.5 2025-04-30 r5714 [x86_64-linux-7.0.14-26-pve] (local build)
|
||||
Copyright (C) 2002-25, Bruce Allen, Christian Franke, www.smartmontools.org
|
||||
|
||||
=== START OF INFORMATION SECTION ===
|
||||
Model Number: CT500P5PSSD8
|
||||
Serial Number: FAKESERIAL03
|
||||
Firmware Version: P7CR402
|
||||
PCI Vendor/Subsystem ID: 0xc0a9
|
||||
IEEE OUI Identifier: 0x00a075
|
||||
Total NVM Capacity: 500,107,862,016 [500 GB]
|
||||
Unallocated NVM Capacity: 0
|
||||
Controller ID: 0
|
||||
NVMe Version: 1.4
|
||||
Number of Namespaces: 1
|
||||
Namespace 1 Size/Capacity: 500,107,862,016 [500 GB]
|
||||
Namespace 1 Formatted LBA Size: 512
|
||||
Namespace 1 IEEE EUI-64: 00a075 0000000003
|
||||
Local Time is: Sun Nov 1 22:10:17 2026 CET
|
||||
|
||||
=== START OF SMART DATA SECTION ===
|
||||
SMART overall-health self-assessment test result: PASSED
|
||||
|
||||
SMART/Health Information (NVMe Log 0x02, NSID 0x1)
|
||||
Critical Warning: 0x00
|
||||
Temperature: 40 Celsius
|
||||
Available Spare: 100%
|
||||
Available Spare Threshold: 5%
|
||||
Percentage Used: 5%
|
||||
Data Units Read: 5,484,072 [2.80 TB]
|
||||
Data Units Written: 32,786,179 [16.7 TB]
|
||||
Host Read Commands: 129,533,249
|
||||
Host Write Commands: 609,881,286
|
||||
Controller Busy Time: 960
|
||||
Power Cycles: 101
|
||||
Power On Hours: 998
|
||||
Unsafe Shutdowns: 22
|
||||
Media and Data Integrity Errors: 0
|
||||
Error Information Log Entries: 85
|
||||
Warning Comp. Temperature Time: 0
|
||||
Critical Comp. Temperature Time: 0
|
||||
Temperature Sensor 1: 40 Celsius
|
||||
Thermal Temp. 1 Transition Count: 1
|
||||
Thermal Temp. 1 Total Time: 69
|
||||
@@ -0,0 +1,39 @@
|
||||
smartctl 7.5 2025-04-30 r5714 [x86_64-linux-7.0.14-26-pve] (local build)
|
||||
Copyright (C) 2002-25, Bruce Allen, Christian Franke, www.smartmontools.org
|
||||
|
||||
=== START OF INFORMATION SECTION ===
|
||||
Vendor: HGST
|
||||
Product: HSCAC2DA4SUN400G
|
||||
Revision: A29A
|
||||
Compliance: SPC-4
|
||||
User Capacity: 399,421,472,768 bytes [399 GB]
|
||||
Logical block size: 512 bytes
|
||||
LU is resource provisioned, LBPRZ=1
|
||||
Rotation Rate: Solid State Device
|
||||
Form Factor: 2.5 inches
|
||||
Logical Unit id: 0x5000000000000002
|
||||
Serial number: FAKESERIAL02 FAKESN02
|
||||
Device type: disk
|
||||
Transport protocol: SAS (SPL-4)
|
||||
Local Time is: Sun Nov 1 22:09:52 2026 CET
|
||||
SMART support is: Available - device has SMART capability.
|
||||
SMART support is: Enabled
|
||||
Temperature Warning: Enabled
|
||||
|
||||
=== START OF READ SMART DATA SECTION ===
|
||||
SMART Health Status: OK
|
||||
|
||||
Percentage used endurance indicator: 3%
|
||||
Current Drive Temperature: 28 C
|
||||
Drive Trip Temperature: 70 C
|
||||
|
||||
Accumulated power on time, hours:minutes 54545:19
|
||||
Manufactured in week 09 of year 2015
|
||||
Specified cycle count over device lifetime: 0
|
||||
Accumulated start-stop cycles: 0
|
||||
Specified load-unload count over device lifetime: 0
|
||||
Accumulated load-unload cycles: 0
|
||||
Elements in grown defect list: 0
|
||||
|
||||
Vendor (Seagate Cache) information
|
||||
Blocks sent to initiator = 674671535507636224
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"coverage_floor": 15.0,
|
||||
"function_complexity": {
|
||||
"napalm_openmediavault/openmediavault.py::OpenMediaVaultDriver.get_disks": 11
|
||||
},
|
||||
"function_lines": {
|
||||
"napalm_openmediavault/openmediavault.py::OpenMediaVaultDriver.get_disk_pools": 81,
|
||||
"napalm_openmediavault/openmediavault.py::OpenMediaVaultDriver.get_disks": 83,
|
||||
"napalm_openmediavault/openmediavault.py::OpenMediaVaultDriver.get_storage_services": 58,
|
||||
"napalm_openmediavault/openmediavault.py::OpenMediaVaultDriver.get_volumes": 90
|
||||
},
|
||||
"mypy_relaxed": [],
|
||||
"python_file_lines": {},
|
||||
"untyped_public": []
|
||||
}
|
||||
@@ -0,0 +1,392 @@
|
||||
"""get_disks: the SMART health, the md array each disk belongs to, and failed reads.
|
||||
|
||||
smartctl prints the overall verdict only for ``-H``; ``-i`` (identity) and ``-A``
|
||||
(attributes) never do. The fake host below answers smartctl with a recorded
|
||||
``smartctl -iHA`` output and drops the verdict line when the command does not ask
|
||||
for ``-H``.
|
||||
|
||||
The recordings in ``fixtures/`` are smartmontools 7.5 on Proxmox VE (an ATA SATA DOM,
|
||||
a SAS SSD, an NVMe SSD) and 7.4 on an OMV VM (a QEMU disk without SMART), with serial
|
||||
numbers, WWNs and LU ids replaced.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import logging
|
||||
import re
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from napalm.base.exceptions import CommandErrorException
|
||||
|
||||
from napalm_openmediavault.openmediavault import OpenMediaVaultDriver, smart_health
|
||||
|
||||
FIXTURES = Path(__file__).parent / "fixtures"
|
||||
|
||||
|
||||
def _recorded(name: str) -> str:
|
||||
return (FIXTURES / name).read_text(encoding="utf-8")
|
||||
|
||||
|
||||
def _replaced(recording: str, line: str, by: str) -> str:
|
||||
"""The recording with one of its lines replaced; the line must be there."""
|
||||
assert recording.count(line) == 1, line
|
||||
return recording.replace(line, by)
|
||||
|
||||
|
||||
ATA_PASSED = _recorded("smartctl-7.5-ata-supermicro-superdom-SOB20R-passed.txt")
|
||||
NVME_PASSED = _recorded("smartctl-7.5-nvme-crucial-CT500P5PSSD8-P7CR402-passed.txt")
|
||||
SAS_OK = _recorded("smartctl-7.5-sas-hgst-HSCAC2DA4SUN400G-A29A-ok.txt")
|
||||
QEMU_NO_SMART = _recorded("smartctl-7.4-scsi-qemu-harddisk-unavailable.txt")
|
||||
|
||||
_ATA_VERDICT = "SMART overall-health self-assessment test result: PASSED\n"
|
||||
# No failing disk was at hand: the failing verdicts are smartmontools' wording put in
|
||||
# place of a recorded verdict line.
|
||||
ATA_FAILED = _replaced(
|
||||
ATA_PASSED,
|
||||
_ATA_VERDICT,
|
||||
"SMART overall-health self-assessment test result: FAILED!\n"
|
||||
"Drive failure expected in less than 24 hours. SAVE ALL DATA.\n",
|
||||
)
|
||||
SAS_PREDICTED = _replaced(
|
||||
SAS_OK,
|
||||
"SMART Health Status: OK\n",
|
||||
"SMART Health Status: FIRMWARE IMPENDING FAILURE TOO MANY BLOCK REASSIGNS [asc=5d, ascq=64]\n",
|
||||
)
|
||||
# No degraded disk was at hand either: these put a count in place of a recorded zero.
|
||||
_ATA_REALLOCATED = (
|
||||
" 5 Reallocated_Sector_Ct 0x0000 100 100 000 Old_age Offline - 0\n"
|
||||
)
|
||||
ATA_REALLOCATED = _replaced(
|
||||
ATA_PASSED, _ATA_REALLOCATED, _ATA_REALLOCATED.replace("- 0", "- 8")
|
||||
)
|
||||
_ATA_PENDING = (
|
||||
"197 Current_Pending_Sector 0x0000 100 100 000 Old_age Offline - 0\n"
|
||||
)
|
||||
ATA_PENDING = _replaced(ATA_PASSED, _ATA_PENDING, _ATA_PENDING.replace("- 0", "- 2"))
|
||||
_ATA_OFFLINE_UNC = (
|
||||
"198 Offline_Uncorrectable 0x0000 100 100 000 Old_age Offline - 0\n"
|
||||
)
|
||||
ATA_OFFLINE_UNC = _replaced(
|
||||
ATA_PASSED, _ATA_OFFLINE_UNC, _ATA_OFFLINE_UNC.replace("- 0", "- 1")
|
||||
)
|
||||
ATA_FAILED_REALLOCATED = _replaced(
|
||||
ATA_FAILED, _ATA_REALLOCATED, _ATA_REALLOCATED.replace("- 0", "- 8")
|
||||
)
|
||||
NVME_CRITICAL_WARNING = _replaced(
|
||||
NVME_PASSED,
|
||||
"Critical Warning: 0x00\n",
|
||||
"Critical Warning: 0x04\n",
|
||||
)
|
||||
NVME_MEDIA_ERRORS = _replaced(
|
||||
NVME_PASSED,
|
||||
"Media and Data Integrity Errors: 0\n",
|
||||
"Media and Data Integrity Errors: 3\n",
|
||||
)
|
||||
SAS_GROWN_DEFECTS = _replaced(
|
||||
SAS_OK, "Elements in grown defect list: 0\n", "Elements in grown defect list: 12\n"
|
||||
)
|
||||
#: What ``smartctl -iA`` prints: no verdict, but the attribute table's WHEN_FAILED header.
|
||||
ATA_WITHOUT_VERDICT = _replaced(ATA_PASSED, _ATA_VERDICT, "")
|
||||
|
||||
_VERDICT_LINE_RE = re.compile(
|
||||
r"^SMART (?:overall-health self-assessment test result|Health Status):.*\n", re.M
|
||||
)
|
||||
|
||||
|
||||
def smartctl(flags: str, recording: str) -> str:
|
||||
"""What ``smartctl -<flags>`` prints: the recording, its verdict only for ``-H``."""
|
||||
return recording if "H" in flags else _VERDICT_LINE_RE.sub("", recording)
|
||||
|
||||
|
||||
class Nas:
|
||||
"""The NAS as ``_send`` and ``_sudo_status`` see it: lsblk, /proc/mdstat, smartctl.
|
||||
|
||||
A disk's smartctl answer is its recorded output (exit status 0), an
|
||||
``(output, exit status)`` pair, or an exception the transport raises. *lsblk* and
|
||||
*mdstat* given as an exception are raised the same way.
|
||||
"""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
disks: dict[str, tuple[str, Any]],
|
||||
mdstat: str | Exception = "",
|
||||
lsblk: str | None = None,
|
||||
) -> None:
|
||||
#: name -> (tran, recorded ``smartctl -iHA`` output)
|
||||
self.disks = disks
|
||||
self.mdstat = mdstat
|
||||
self.lsblk = lsblk
|
||||
self.commands: list[str] = []
|
||||
|
||||
def send(self, command: str, read_timeout: float = 100) -> str:
|
||||
self.commands.append(command)
|
||||
if command.startswith("lsblk ") and self.lsblk is not None:
|
||||
return self.lsblk
|
||||
if command.startswith("lsblk "):
|
||||
return json.dumps(
|
||||
{
|
||||
"blockdevices": [
|
||||
{
|
||||
"name": name,
|
||||
"size": 6001175126016,
|
||||
"type": "disk",
|
||||
"rota": tran != "nvme" and "Solid State Device" not in str(recording),
|
||||
"vendor": "",
|
||||
"model": "m",
|
||||
"serial": "s",
|
||||
"tran": tran,
|
||||
}
|
||||
for name, (tran, recording) in self.disks.items()
|
||||
]
|
||||
}
|
||||
)
|
||||
if command.startswith("cat /proc/mdstat"):
|
||||
if isinstance(self.mdstat, Exception):
|
||||
raise self.mdstat
|
||||
return self.mdstat
|
||||
raise AssertionError(command)
|
||||
|
||||
def sudo_status(self, command: str, read_timeout: float = 100) -> tuple[str, int | None]:
|
||||
self.commands.append(command)
|
||||
m = re.match(r"smartctl -(\w+) /dev/(\w+)", command)
|
||||
assert m, command
|
||||
_tran, answer = self.disks[m.group(2)]
|
||||
if isinstance(answer, Exception):
|
||||
raise answer
|
||||
output, status = answer if isinstance(answer, tuple) else (answer, 0)
|
||||
return smartctl(m.group(1), output), status
|
||||
|
||||
|
||||
def _driver(nas: Nas) -> OpenMediaVaultDriver:
|
||||
driver = OpenMediaVaultDriver("nas", "admin", "p")
|
||||
driver._send = nas.send # type: ignore[method-assign]
|
||||
driver._sudo_status = nas.sudo_status # type: ignore[method-assign]
|
||||
return driver
|
||||
|
||||
|
||||
def _by_slot(nas: Nas) -> dict[str, dict]:
|
||||
return {d["slot"]: dict(d) for d in _driver(nas).get_disks()}
|
||||
|
||||
|
||||
# ── the overall verdict ─────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def test_a_passing_ata_disk_is_healthy():
|
||||
nas = Nas({"sda": ("sata", ATA_PASSED)})
|
||||
|
||||
disk = _by_slot(nas)["/dev/sda"]
|
||||
|
||||
assert disk["health"] == "healthy"
|
||||
# A solid-state disk has no rotation rate.
|
||||
assert (disk["temperature"], disk["rpm"]) == (34, 0)
|
||||
|
||||
|
||||
def test_a_failing_ata_disk_is_failed():
|
||||
nas = Nas({"sda": ("sata", ATA_FAILED)})
|
||||
|
||||
assert _by_slot(nas)["/dev/sda"]["health"] == "failed"
|
||||
|
||||
|
||||
def test_a_passing_nvme_disk_is_healthy():
|
||||
nas = Nas({"nvme0n1": ("nvme", NVME_PASSED)})
|
||||
|
||||
disk = _by_slot(nas)["/dev/nvme0n1"]
|
||||
|
||||
assert (disk["health"], disk["temperature"]) == ("healthy", 40)
|
||||
|
||||
|
||||
def test_a_sas_disk_reports_its_drive_temperature():
|
||||
nas = Nas({"sdb": ("", SAS_OK)})
|
||||
|
||||
disk = _by_slot(nas)["/dev/sdb"]
|
||||
|
||||
assert (disk["health"], disk["temperature"]) == ("healthy", 28)
|
||||
|
||||
|
||||
def test_a_disk_without_smart_has_no_temperature():
|
||||
# QEMU prints "Current Drive Temperature: 0 C" for a disk that has no sensor.
|
||||
nas = Nas({"sda": ("", QEMU_NO_SMART)})
|
||||
|
||||
disk = _by_slot(nas)["/dev/sda"]
|
||||
|
||||
assert (disk["health"], disk["temperature"]) == ("unknown", -1)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("output", "health"),
|
||||
[
|
||||
(ATA_PASSED, "healthy"),
|
||||
(ATA_FAILED, "failed"),
|
||||
(NVME_PASSED, "healthy"),
|
||||
(SAS_OK, "healthy"),
|
||||
(SAS_PREDICTED, "failed"),
|
||||
(QEMU_NO_SMART, "unknown"),
|
||||
("", "unknown"),
|
||||
# The attribute table's WHEN_FAILED column is no verdict.
|
||||
(ATA_WITHOUT_VERDICT, "unknown"),
|
||||
# A passing disk that is losing sectors is degraded (#16).
|
||||
(ATA_REALLOCATED, "warning"),
|
||||
(ATA_PENDING, "warning"),
|
||||
(ATA_OFFLINE_UNC, "warning"),
|
||||
(NVME_CRITICAL_WARNING, "warning"),
|
||||
(NVME_MEDIA_ERRORS, "warning"),
|
||||
(SAS_GROWN_DEFECTS, "warning"),
|
||||
# The verdict outranks the counters.
|
||||
(ATA_FAILED_REALLOCATED, "failed"),
|
||||
],
|
||||
ids=[
|
||||
"ata-passed",
|
||||
"ata-failed",
|
||||
"nvme-passed",
|
||||
"sas-ok",
|
||||
"sas-predicted",
|
||||
"no-smart",
|
||||
"empty",
|
||||
"when-failed-column",
|
||||
"ata-reallocated",
|
||||
"ata-pending",
|
||||
"ata-offline-uncorrectable",
|
||||
"nvme-critical-warning",
|
||||
"nvme-media-errors",
|
||||
"sas-grown-defects",
|
||||
"ata-failed-and-reallocated",
|
||||
],
|
||||
)
|
||||
def test_smart_health_reads_the_verdict_line_only(output, health):
|
||||
assert smart_health(output) == health
|
||||
|
||||
|
||||
def test_a_degraded_disk_is_reported_as_warning():
|
||||
nas = Nas({"sda": ("sata", ATA_REALLOCATED)})
|
||||
|
||||
assert _by_slot(nas)["/dev/sda"]["health"] == "warning"
|
||||
|
||||
|
||||
# ── failed reads (#16) ──────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"lsblk",
|
||||
[
|
||||
"",
|
||||
"sudo: a terminal is required to read the password",
|
||||
"lsblk: unknown column: TRAN",
|
||||
'["not", "an", "object"]',
|
||||
],
|
||||
ids=["nothing", "sudo", "lsblk-error", "not-an-object"],
|
||||
)
|
||||
def test_a_failed_lsblk_raises(lsblk):
|
||||
"""``[]`` is a NAS without disks; a failed read must not look like one."""
|
||||
nas = Nas({}, lsblk=lsblk)
|
||||
|
||||
with pytest.raises(CommandErrorException, match="lsblk"):
|
||||
_driver(nas).get_disks()
|
||||
|
||||
|
||||
def test_a_nas_without_disks_has_none():
|
||||
nas = Nas({}, lsblk='{"blockdevices": []}')
|
||||
|
||||
assert _driver(nas).get_disks() == []
|
||||
|
||||
|
||||
def test_a_smartctl_timeout_is_logged_as_a_warning(caplog):
|
||||
nas = Nas(
|
||||
{
|
||||
"sda": ("sata", TimeoutError("'smartctl -iHA /dev/sda' did not finish within 15s")),
|
||||
"sdb": ("sata", ATA_PASSED),
|
||||
}
|
||||
)
|
||||
|
||||
with caplog.at_level(logging.WARNING):
|
||||
disks = _by_slot(nas)
|
||||
|
||||
assert (disks["/dev/sda"]["health"], disks["/dev/sda"]["temperature"]) == ("unknown", -1)
|
||||
assert disks["/dev/sdb"]["health"] == "healthy"
|
||||
warned = [r for r in caplog.records if r.levelno == logging.WARNING]
|
||||
assert any("sda" in r.getMessage() and "smartctl" in r.getMessage() for r in warned)
|
||||
|
||||
|
||||
def test_a_refused_sudo_for_smartctl_is_logged_as_a_warning(caplog):
|
||||
# sudo's own refusal exits 1, which smartctl uses for "command line did not parse".
|
||||
nas = Nas({"sda": ("sata", ("sudo: a password is required", 1))})
|
||||
|
||||
with caplog.at_level(logging.WARNING):
|
||||
disk = _by_slot(nas)["/dev/sda"]
|
||||
|
||||
assert disk["health"] == "unknown"
|
||||
warned = [r.getMessage() for r in caplog.records if r.levelno == logging.WARNING]
|
||||
assert any("sda" in m and "sudo: a password is required" in m for m in warned)
|
||||
|
||||
|
||||
def test_a_disk_status_in_smartctls_exit_code_is_no_failed_call(caplog):
|
||||
# Bits 3-7 of smartctl's exit status describe the disk, not the call.
|
||||
nas = Nas({"sda": ("sata", (ATA_FAILED, 8))})
|
||||
|
||||
with caplog.at_level(logging.WARNING):
|
||||
disk = _by_slot(nas)["/dev/sda"]
|
||||
|
||||
assert disk["health"] == "failed"
|
||||
assert not [r for r in caplog.records if r.levelno >= logging.WARNING]
|
||||
|
||||
|
||||
def test_a_failed_mdstat_read_raises():
|
||||
nas = Nas({"sda": ("sata", ATA_PASSED)}, mdstat=TimeoutError("no data within 100s"))
|
||||
|
||||
with pytest.raises(TimeoutError):
|
||||
_driver(nas).get_disks()
|
||||
|
||||
|
||||
# ── md membership ───────────────────────────────────────────────────────────────
|
||||
|
||||
# The recorded hosts have no md array (MDSTAT_NO_ARRAYS), so the arrays below are
|
||||
# written out by hand to cover look-alike names and a failed member.
|
||||
MDSTAT = """\
|
||||
Personalities : [raid1] [linear] [multipath] [raid0] [raid6] [raid5] [raid4] [raid10]
|
||||
md0 : active raid1 sdab1[1] sdaa1[0]
|
||||
976630464 blocks super 1.2 [2/2] [UU]
|
||||
|
||||
md1 : active raid1 sdb1[1] sdc1[0](F)
|
||||
5860389888 blocks super 1.2 [2/1] [U_]
|
||||
|
||||
md2 : active raid1 nvme0n1p1[0] nvme1n1[1]
|
||||
976630464 blocks super 1.2 [2/2] [UU]
|
||||
|
||||
md3 : active raid1 nvme2n11[0] nvme2n12[1]
|
||||
976630464 blocks super 1.2 [2/2] [UU]
|
||||
|
||||
unused devices: <none>
|
||||
"""
|
||||
MDSTAT_NO_ARRAYS = _recorded("mdstat-omv-no-arrays.txt")
|
||||
|
||||
|
||||
def test_a_disk_is_in_the_array_its_partition_or_itself_is_in():
|
||||
names = ["sda", "sdaa", "sdc", "nvme0n1", "nvme1n1", "nvme2n1"]
|
||||
nas = Nas({n: ("sata", ATA_PASSED) for n in names}, MDSTAT)
|
||||
|
||||
pools = {slot: d["pool"] for slot, d in _by_slot(nas).items()}
|
||||
|
||||
assert pools == {
|
||||
"/dev/sda": "", # sdaa1 and sdab1 are not sda's
|
||||
"/dev/sdaa": "md0",
|
||||
"/dev/sdc": "md1", # a failed member is still a member
|
||||
"/dev/nvme0n1": "md2",
|
||||
"/dev/nvme1n1": "md2",
|
||||
"/dev/nvme2n1": "", # nvme2n11 is another namespace, not a partition
|
||||
}
|
||||
|
||||
|
||||
def test_no_disk_is_in_an_array_when_there_is_none():
|
||||
nas = Nas({n: ("", QEMU_NO_SMART) for n in ("sda", "sdb")}, MDSTAT_NO_ARRAYS)
|
||||
|
||||
assert {d["pool"] for d in _by_slot(nas).values()} == {""}
|
||||
|
||||
|
||||
def test_mdstat_is_read_once_for_all_disks():
|
||||
nas = Nas({n: ("sata", ATA_PASSED) for n in ("sda", "sdb")}, MDSTAT)
|
||||
|
||||
_driver(nas).get_disks()
|
||||
|
||||
assert sum(c.startswith("cat /proc/mdstat") for c in nas.commands) == 1
|
||||
@@ -0,0 +1,385 @@
|
||||
"""Personal accounts on OpenMediaVault, the way its web UI makes them (NetOrk/netork#1793).
|
||||
|
||||
napalm-linux adds and locks accounts with shadow-utils and keys in ``~/.ssh``.
|
||||
On OMV that is not enough: sshd lets in only ``root`` and the ``_ssh`` group,
|
||||
and a user's keys live in OMV's database, which the ``ssh`` module deploys to
|
||||
``/var/lib/openmediavault/ssh/authorized_keys/<user>``. So the account is made
|
||||
through ``UserMgmt.setUser``, the keys go through it as well, and only the
|
||||
modules that change made dirty are applied.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import shlex
|
||||
|
||||
import pytest
|
||||
from napalm_device_types import CommandResult
|
||||
|
||||
from napalm_openmediavault._local_accounts import OMV_KEYS_DIR, rfc4716_blob
|
||||
from napalm_openmediavault.openmediavault import OpenMediaVaultDriver
|
||||
|
||||
ALICE_KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAlice alice@laptop"
|
||||
#: The key Alice had before, on the laptop she lost.
|
||||
OLD_KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOld alice@lost-laptop"
|
||||
OWN_KEY = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQOwn own@desktop"
|
||||
HASH = "$6$salt$" + "x" * 86
|
||||
|
||||
|
||||
def _rfc4716(key: str) -> str:
|
||||
"""*key* as OMV stores it."""
|
||||
kind, blob, comment = key.split(" ", 2)
|
||||
lines = [blob[i : i + 70] for i in range(0, len(blob), 70)]
|
||||
return "\n".join(
|
||||
[
|
||||
"---- BEGIN SSH2 PUBLIC KEY ----",
|
||||
f'Comment: "{comment}"',
|
||||
*lines,
|
||||
"---- END SSH2 PUBLIC KEY ----",
|
||||
]
|
||||
)
|
||||
|
||||
|
||||
class Omv:
|
||||
"""omv-rpc and the dirty-modules file, as ``_sudo_status`` sees them."""
|
||||
|
||||
def __init__(self, *, dirty=("apt",), deploys=True):
|
||||
self.users: dict[str, dict] = {
|
||||
"alice": {
|
||||
"name": "alice",
|
||||
"groups": ["users", "_ssh"],
|
||||
"email": "alice@example.net",
|
||||
"disallowusermod": False,
|
||||
"comment": "Alice",
|
||||
"shell": "/bin/bash",
|
||||
"sshpubkeys": [_rfc4716(OWN_KEY)],
|
||||
}
|
||||
}
|
||||
#: What the ssh module last wrote, per user: OpenSSH lines.
|
||||
self.deployed: dict[str, list[str]] = {"alice": [OWN_KEY]}
|
||||
self.dirty = list(dirty)
|
||||
self.deploys = deploys
|
||||
self.calls: list[tuple[str, object]] = []
|
||||
|
||||
def __call__(self, command: str, read_timeout: float = 100) -> tuple[str, int | None]:
|
||||
if command.startswith("cat /var/lib/openmediavault/dirtymodules.json"):
|
||||
return json.dumps(self.dirty), 0
|
||||
argv = shlex.split(command)
|
||||
assert argv[:3] == ["omv-rpc", "-u", "admin"], command
|
||||
method = f"{argv[3]}.{argv[4]}"
|
||||
params = json.loads(argv[5]) if len(argv) > 5 else None
|
||||
self.calls.append((method, params))
|
||||
if method == "UserMgmt.getUser":
|
||||
return json.dumps(self.users[params["name"]]), 0
|
||||
if method == "UserMgmt.setUser":
|
||||
assert params["password"] == "", "OMV takes the plain password: none is sent"
|
||||
self.users[params["name"]] = {
|
||||
**params,
|
||||
"sshpubkeys": [
|
||||
k if k.startswith("----") else _rfc4716(k) for k in params["sshpubkeys"]
|
||||
],
|
||||
}
|
||||
# As OMV 8 does: the user's mail alias and keys are to be deployed.
|
||||
self.dirty += [m for m in ("postfix", "ssh") if m not in self.dirty]
|
||||
return json.dumps(params), 0
|
||||
if method == "Config.applyChanges":
|
||||
if "ssh" in params["modules"] and self.deploys:
|
||||
for name, user in self.users.items():
|
||||
self.deployed[name] = [_openssh(k) for k in user["sshpubkeys"]]
|
||||
self.dirty = [m for m in self.dirty if m not in params["modules"]]
|
||||
return "null", 0
|
||||
raise AssertionError(command)
|
||||
|
||||
def params(self, method: str) -> list:
|
||||
return [p for m, p in self.calls if m == method]
|
||||
|
||||
|
||||
def _openssh(rfc: str) -> str:
|
||||
blob = rfc4716_blob(rfc)
|
||||
kind = "ssh-ed25519" if "ZDI1NTE5" in (blob or "") else "ssh-rsa"
|
||||
return f"{kind} {blob}"
|
||||
|
||||
|
||||
class _Driver(OpenMediaVaultDriver):
|
||||
"""OMV's own calls go to *omv*; the key files sshd reads come from it too."""
|
||||
|
||||
def __init__(self, omv: Omv, home_keys: list[str] | None = None) -> None:
|
||||
super().__init__("nas", "netadmin", "p")
|
||||
self.omv = omv
|
||||
self.home_keys = home_keys if home_keys is not None else []
|
||||
self.ran: list[tuple[str, bool]] = []
|
||||
|
||||
def _sudo_status(self, command: str, read_timeout: float = 100) -> tuple[str, int | None]:
|
||||
return self.omv(command, read_timeout)
|
||||
|
||||
def run_command(self, command, *, privileged=False, timeout=60, stdin=None):
|
||||
self.ran.append((command, privileged))
|
||||
argv = shlex.split(command)
|
||||
if argv[:2] == ["test", "-e"]:
|
||||
path = argv[2]
|
||||
there = path.startswith(OMV_KEYS_DIR) and path.rsplit("/", 1)[1] in self.omv.deployed
|
||||
there = there or (path.endswith("/.ssh/authorized_keys") and bool(self.home_keys))
|
||||
return CommandResult("", "", 0 if there else 1)
|
||||
if argv[:3] == ["sudo", "-n", "-u"] and argv[4] == "cat":
|
||||
path = argv[-1]
|
||||
if path.startswith(OMV_KEYS_DIR):
|
||||
lines = self.omv.deployed[path.rsplit("/", 1)[1]]
|
||||
else:
|
||||
lines = self.home_keys
|
||||
return CommandResult("".join(f"{line}\n" for line in lines), "", 0)
|
||||
if argv[:3] == ["sudo", "-n", "-u"] and argv[4] == "rm":
|
||||
self.home_keys = []
|
||||
return CommandResult("", "", 0)
|
||||
return self._write_home_keys(argv, stdin)
|
||||
|
||||
def _write_home_keys(self, argv: list[str], stdin: bytes | None) -> CommandResult:
|
||||
"""Staging a key file as the login user, and installing it as the person."""
|
||||
if stdin is not None:
|
||||
self.staged = stdin.decode()
|
||||
return CommandResult("/tmp/tmp.1", "", 0)
|
||||
if argv[:3] == ["sudo", "-n", "-u"] and argv[4] == "mkdir":
|
||||
return CommandResult("", "", 0)
|
||||
if argv[:3] == ["sudo", "-n", "-u"] and argv[4] == "install":
|
||||
assert argv[-1] == "/home/alice/.ssh/authorized_keys", "only ~/.ssh is written"
|
||||
self.home_keys = self.staged.splitlines()
|
||||
return CommandResult("", "", 0)
|
||||
if argv[:3] == ["rm", "-f", "--"] and argv[3].startswith("/tmp/"):
|
||||
return CommandResult("", "", 0)
|
||||
raise AssertionError(shlex.join(argv))
|
||||
|
||||
|
||||
def test_omv_offers_personal_accounts_of_its_own() -> None:
|
||||
assert callable(getattr(OpenMediaVaultDriver, "add_local_account", None))
|
||||
assert callable(getattr(OpenMediaVaultDriver, "lock_local_account", None))
|
||||
assert callable(getattr(OpenMediaVaultDriver, "get_local_accounts", None))
|
||||
|
||||
|
||||
def test_the_key_file_omv_deploys_is_read_too() -> None:
|
||||
files = _Driver(Omv())._account_key_files("alice", "/home/alice")
|
||||
assert files[-1] == f"{OMV_KEYS_DIR}/alice"
|
||||
assert "/home/alice/.ssh/authorized_keys" in files
|
||||
|
||||
|
||||
def test_a_new_account_is_made_by_omv_in_its_ssh_group() -> None:
|
||||
omv = Omv()
|
||||
|
||||
commands = _Driver(omv)._account_create("bob", HASH)
|
||||
|
||||
[params] = omv.params("UserMgmt.setUser")
|
||||
assert params["name"] == "bob" and params["groups"] == ["_ssh"]
|
||||
# OMV hashes a plain password itself; netOrk has the hash only.
|
||||
assert params["password"] == "" and params["sshpubkeys"] == []
|
||||
assert commands == [["usermod", "-p", HASH, "bob"]]
|
||||
|
||||
|
||||
def test_making_an_account_applies_what_it_made_dirty_and_nothing_else() -> None:
|
||||
omv = Omv()
|
||||
|
||||
_Driver(omv)._account_create("bob", None)
|
||||
|
||||
assert omv.params("Config.applyChanges") == [{"modules": ["postfix", "ssh"], "force": False}]
|
||||
assert omv.dirty == ["apt"]
|
||||
|
||||
|
||||
def test_without_a_hash_no_password_is_set() -> None:
|
||||
assert _Driver(Omv())._account_create("bob", None) == []
|
||||
|
||||
|
||||
def test_opening_again_puts_the_account_back_into_ssh() -> None:
|
||||
commands = _Driver(Omv())._account_open("alice", HASH, locked=True)
|
||||
assert commands[-1] == ["gpasswd", "-a", "alice", "_ssh"]
|
||||
assert ["usermod", "-e", "", "-p", HASH, "alice"] in commands
|
||||
|
||||
|
||||
def test_a_key_goes_into_omvs_database_and_is_deployed() -> None:
|
||||
omv = Omv()
|
||||
|
||||
outcome = _Driver(omv)._account_add_key("alice", "/home/alice", ALICE_KEY)
|
||||
|
||||
assert outcome["ok"], outcome["output"]
|
||||
[params] = omv.params("UserMgmt.setUser")
|
||||
assert params["sshpubkeys"] == [_rfc4716(OWN_KEY), ALICE_KEY]
|
||||
# Everything else the user had stays as it was.
|
||||
assert params["email"] == "alice@example.net" and params["groups"] == ["users", "_ssh"]
|
||||
assert params["comment"] == "Alice" and params["shell"] == "/bin/bash"
|
||||
# Only what the change made dirty is applied: the pending apt change stays.
|
||||
assert omv.params("Config.applyChanges") == [{"modules": ["postfix", "ssh"], "force": False}]
|
||||
assert omv.dirty == ["apt"]
|
||||
assert any("AAAAC3NzaC1lZDI1NTE5AAAAIAlice" in k for k in omv.deployed["alice"])
|
||||
|
||||
|
||||
def test_a_key_already_there_is_not_added_again() -> None:
|
||||
omv = Omv()
|
||||
|
||||
outcome = _Driver(omv)._account_add_key("alice", "/home/alice", OWN_KEY)
|
||||
|
||||
assert outcome["ok"] and "already" in outcome["output"]
|
||||
assert omv.params("UserMgmt.setUser") == []
|
||||
|
||||
|
||||
def test_a_key_omv_does_not_deploy_fails_the_step() -> None:
|
||||
outcome = _Driver(Omv(deploys=False))._account_add_key("alice", "/home/alice", ALICE_KEY)
|
||||
|
||||
assert not outcome["ok"]
|
||||
assert "not deployed" in outcome["output"]
|
||||
|
||||
|
||||
def test_locking_empties_omvs_keys_and_the_home_ones() -> None:
|
||||
omv = Omv()
|
||||
driver = _Driver(omv, home_keys=[ALICE_KEY])
|
||||
|
||||
outcome = driver._account_remove_keys("alice", "/home/alice")
|
||||
|
||||
assert outcome["ok"], outcome["output"]
|
||||
[params] = omv.params("UserMgmt.setUser")
|
||||
assert params["sshpubkeys"] == []
|
||||
assert omv.deployed["alice"] == [] and driver.home_keys == []
|
||||
|
||||
|
||||
def test_an_account_omv_holds_no_key_for_is_not_written() -> None:
|
||||
omv = Omv()
|
||||
omv.users["alice"]["sshpubkeys"] = []
|
||||
omv.deployed["alice"] = []
|
||||
|
||||
outcome = _Driver(omv, home_keys=[ALICE_KEY])._account_remove_keys("alice", "/home/alice")
|
||||
|
||||
assert outcome["ok"], outcome["output"]
|
||||
assert omv.params("UserMgmt.setUser") == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("text", "blob"),
|
||||
[
|
||||
(_rfc4716(ALICE_KEY), "AAAAC3NzaC1lZDI1NTE5AAAAIAlice"),
|
||||
(
|
||||
'---- BEGIN SSH2 PUBLIC KEY ----\nComment: "a long \\\ncomment"\nAAAA\nBBBB\n'
|
||||
"---- END SSH2 PUBLIC KEY ----",
|
||||
"AAAABBBB",
|
||||
),
|
||||
(ALICE_KEY, "AAAAC3NzaC1lZDI1NTE5AAAAIAlice"),
|
||||
("nonsense", None),
|
||||
],
|
||||
)
|
||||
def test_the_key_omv_stores_is_read_back_as_its_base64(text: str, blob: str | None) -> None:
|
||||
assert rfc4716_blob(text) == blob
|
||||
|
||||
|
||||
def test_netorks_own_account_with_a_fixed_uid_is_not_made_on_omv_yet() -> None:
|
||||
"""Its keys go through UserMgmt, which knows only the users it made (NetOrk/netork#1817)."""
|
||||
import pytest
|
||||
|
||||
with pytest.raises(NotImplementedError):
|
||||
_Driver(Omv())._account_create_with_uid("netork", 900)
|
||||
|
||||
|
||||
# -- what a person changes follows them (NetOrk/netork#2013) ----------------------------
|
||||
|
||||
|
||||
def test_a_replaced_key_goes_from_omvs_database_and_the_others_stay() -> None:
|
||||
omv = Omv()
|
||||
omv.users["alice"]["sshpubkeys"] = [_rfc4716(OLD_KEY), _rfc4716(OWN_KEY)]
|
||||
omv.deployed["alice"] = [OLD_KEY, OWN_KEY]
|
||||
|
||||
outcome = _Driver(omv)._account_drop_keys("alice", "/home/alice", [OLD_KEY])
|
||||
|
||||
assert outcome["ok"], outcome["output"]
|
||||
[params] = omv.params("UserMgmt.setUser")
|
||||
assert params["sshpubkeys"] == [_rfc4716(OWN_KEY)]
|
||||
# Everything else the user had stays as it was, and only what it dirtied is applied.
|
||||
assert params["email"] == "alice@example.net" and params["groups"] == ["users", "_ssh"]
|
||||
assert omv.params("Config.applyChanges") == [{"modules": ["postfix", "ssh"], "force": False}]
|
||||
assert [rfc4716_blob(k) for k in omv.deployed["alice"]] == [rfc4716_blob(OWN_KEY)]
|
||||
assert "removed from OMV's keys" in outcome["output"]
|
||||
|
||||
|
||||
def test_a_replaced_key_in_the_home_goes_too_as_the_person() -> None:
|
||||
omv = Omv()
|
||||
driver = _Driver(omv, home_keys=[OLD_KEY, ALICE_KEY])
|
||||
|
||||
outcome = driver._account_drop_keys("alice", "/home/alice", [OLD_KEY])
|
||||
|
||||
assert outcome["ok"], outcome["output"]
|
||||
assert driver.home_keys == [ALICE_KEY]
|
||||
# The key was not in OMV's database: nothing is saved or applied there.
|
||||
assert omv.params("UserMgmt.setUser") == []
|
||||
assert omv.params("Config.applyChanges") == []
|
||||
|
||||
|
||||
def test_a_removed_key_omv_does_not_deploy_away_fails_the_step() -> None:
|
||||
omv = Omv(deploys=False)
|
||||
|
||||
outcome = _Driver(omv)._account_drop_keys("alice", "/home/alice", [OWN_KEY])
|
||||
|
||||
assert not outcome["ok"]
|
||||
assert "still has" in outcome["output"]
|
||||
|
||||
|
||||
def test_clearing_the_password_is_napalm_linuxs_and_omv_sends_none() -> None:
|
||||
# OMV keeps no password of its own: setUser is never given one (Omv asserts it).
|
||||
assert _Driver(Omv())._account_clear_password("alice") == [["usermod", "-p", "*", "alice"]]
|
||||
|
||||
|
||||
class _Account(_Driver):
|
||||
"""The account's reads too, for a whole run through the mixin."""
|
||||
|
||||
def run_command(self, command, *, privileged=False, timeout=60, stdin=None):
|
||||
answers = {
|
||||
"id -un": "netadmin\n",
|
||||
"getent passwd alice": "alice:x:1001:100::/home/alice:/bin/bash\n",
|
||||
"getent shadow alice": "alice:$6$old:20000:0:99999:7:::\n",
|
||||
"id -Gn alice": "users _ssh\n",
|
||||
"sudo -l -U alice": "User alice is not allowed to run sudo on nas.\n",
|
||||
}
|
||||
if command in answers:
|
||||
self.ran.append((command, privileged))
|
||||
return CommandResult(answers[command], "", 0)
|
||||
if shlex.split(command)[0] in {"usermod", "gpasswd", "rm"} and privileged:
|
||||
self.ran.append((command, privileged))
|
||||
return CommandResult("", "", 0)
|
||||
return super().run_command(command, privileged=privileged, timeout=timeout, stdin=stdin)
|
||||
|
||||
|
||||
def test_a_person_who_replaced_a_key_and_removed_the_password_gets_both_on_omv() -> None:
|
||||
omv = Omv()
|
||||
omv.users["alice"]["sshpubkeys"] = [_rfc4716(OLD_KEY), _rfc4716(OWN_KEY)]
|
||||
omv.deployed["alice"] = [OLD_KEY, OWN_KEY]
|
||||
driver = _Account(omv)
|
||||
|
||||
result = driver.add_local_account("alice", ALICE_KEY, replaces=[OLD_KEY], clear_password=True)
|
||||
|
||||
assert result["success"], result["output"]
|
||||
assert ("usermod -p '*' alice", True) in driver.ran
|
||||
assert omv.users["alice"]["sshpubkeys"] == [_rfc4716(OWN_KEY), _rfc4716(ALICE_KEY)]
|
||||
account = result["account"]
|
||||
assert account is not None
|
||||
assert [rfc4716_blob(k) for k in account["authorized_keys"] or []] == [
|
||||
rfc4716_blob(OWN_KEY),
|
||||
rfc4716_blob(ALICE_KEY),
|
||||
]
|
||||
|
||||
|
||||
def test_a_deleted_key_goes_through_omv_and_the_account_stays_open() -> None:
|
||||
omv = Omv()
|
||||
driver = _Account(omv)
|
||||
|
||||
result = driver.remove_local_account_keys("alice", [OWN_KEY])
|
||||
|
||||
assert result["success"], result["output"]
|
||||
assert omv.users["alice"]["sshpubkeys"] == []
|
||||
assert not [c for c, _ in driver.ran if c.startswith(("usermod", "gpasswd"))]
|
||||
|
||||
|
||||
def test_a_deleted_key_takes_the_password_and_sudo_with_it_on_omv() -> None:
|
||||
"""NetOrk/netork#2033: the key goes through OMV, the password with usermod as on
|
||||
napalm-linux, and sudo; the account stays open and in _ssh."""
|
||||
omv = Omv()
|
||||
driver = _Account(omv)
|
||||
|
||||
result = driver.remove_local_account_keys("alice", [OWN_KEY], clear_password=True)
|
||||
|
||||
assert result["success"], result["output"]
|
||||
assert [s["step"] for s in result["steps"]] == ["keys", "password", "sudo"]
|
||||
assert omv.users["alice"]["sshpubkeys"] == []
|
||||
assert ("usermod -p '*' alice", True) in driver.ran
|
||||
assert ("rm -f -- /etc/sudoers.d/80-account-alice", True) in driver.ran
|
||||
assert not [c for c, _ in driver.ran if c.startswith("gpasswd -d alice _ssh")]
|
||||
@@ -0,0 +1,12 @@
|
||||
"""The pending updates are a fact, not a warning of the driver's (netOrk #1111).
|
||||
|
||||
The override counted "N upgraded" in apt's simulation -- nothing on a German
|
||||
host -- and hid held-back packages, which FULL_UPGRADE installs. The caller
|
||||
names updates_available from get_available_updates.
|
||||
"""
|
||||
|
||||
from napalm_openmediavault.openmediavault import OpenMediaVaultDriver
|
||||
|
||||
|
||||
def test_no_warnings_of_its_own():
|
||||
assert "get_device_warnings" not in vars(OpenMediaVaultDriver)
|
||||
@@ -9,10 +9,12 @@ def test_type_label_is_storage():
|
||||
|
||||
def test_type_label_overrides_linux():
|
||||
from napalm_linux.linux import LinuxDriver
|
||||
|
||||
assert LinuxDriver.TYPE_LABEL == "Linux"
|
||||
assert OpenMediaVaultDriver.TYPE_LABEL != LinuxDriver.TYPE_LABEL
|
||||
|
||||
|
||||
def test_storage_device_flag_removed():
|
||||
assert not hasattr(OpenMediaVaultDriver, "storage_device"), \
|
||||
assert not hasattr(OpenMediaVaultDriver, "storage_device"), (
|
||||
"storage_device is superseded by TYPE_LABEL = 'Storage'"
|
||||
)
|
||||
@@ -0,0 +1,707 @@
|
||||
"""Scheduled jobs on OpenMediaVault: the web UI's through RPC, the rest as on Linux (#18).
|
||||
|
||||
OMV writes its cron files itself, from its own database: the web UI's "Scheduled
|
||||
Jobs" (and the power-management schedule) go to ``/etc/cron.d/openmediavault-*``
|
||||
on every apply of the ``cron`` module, rsync jobs, the mail-queue flush and the
|
||||
apticron run likewise. An edit there would be taken back without a word. So those
|
||||
files are ``platform`` and never written through the Linux path; the lines of the
|
||||
web UI's file are replaced by the jobs ``Cron.getList`` returns, and those are
|
||||
switched, run, made and removed through ``Cron.*`` -- then ``Config.applyChanges``
|
||||
for ``cron`` alone, so changes someone left pending in the web UI stay pending.
|
||||
|
||||
The NAS below is synthetic: the report napalm-linux's reader prints, and the RPC
|
||||
answers ``omv-rpc`` gives, in OMV 8's shapes (``Cron.getList`` keeps each time
|
||||
field a comma-separated string, ``Cron.set`` takes lists).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import shlex
|
||||
|
||||
import pytest
|
||||
from napalm_device_types import (
|
||||
CommandResult,
|
||||
ScheduledJobChanged,
|
||||
ScheduledJobRefused,
|
||||
)
|
||||
|
||||
from napalm_openmediavault import _scheduled_jobs as sj
|
||||
from napalm_openmediavault.openmediavault import OpenMediaVaultDriver
|
||||
|
||||
NEW = "fa4b1c66-ef79-11e5-87a0-0002b3a176b4"
|
||||
SYNC = "2c1d3e4f-0a1b-4c2d-8e3f-405162738495"
|
||||
WEEKLY = "3d2e4f50-1b2c-4d3e-9f40-5162738495a6"
|
||||
OWN = "4e3f5061-2c3d-4e4f-a051-62738495a6b7"
|
||||
POWER = "5f406172-3d4e-4f50-b162-738495a6b7c8"
|
||||
|
||||
REPORT = """SJ_BEGIN
|
||||
[system /etc/cron.d/openmediavault-userdefined]
|
||||
|# This file is auto-generated by openmediavault (https://www.openmediavault.org)
|
||||
|SHELL=/bin/sh
|
||||
|15 2 * * 1,3 root /var/lib/openmediavault/cron.d/userdefined-2c1d3e4f-0a1b-4c2d-8e3f-405162738495 >/dev/null 2>&1
|
||||
[system /etc/cron.d/openmediavault-powermngmt]
|
||||
|0 23 * * * root systemctl poweroff >/dev/null 2>&1
|
||||
[system /etc/cron.d/openmediavault-rsync]
|
||||
|0 3 * * * root /var/lib/openmediavault/cron.d/rsync-6a7b8c9d >/dev/null 2>&1
|
||||
[system /etc/cron.d/certbot]
|
||||
|0 */12 * * * root certbot -q renew
|
||||
[run-parts hourly 1 1234 /etc/cron.hourly/openmediavault-flushmailq]
|
||||
[run-parts daily 1 5678 /etc/cron.daily/openmediavault-check_locked_users]
|
||||
[tz]
|
||||
/usr/share/zoneinfo/Europe/Berlin
|
||||
[owners]
|
||||
certbot: /etc/cron.d/certbot
|
||||
openmediavault: /etc/cron.daily/openmediavault-check_locked_users
|
||||
SJ_END
|
||||
"""
|
||||
|
||||
|
||||
def _job(uuid: str, **fields: object) -> dict[str, object]:
|
||||
job: dict[str, object] = {
|
||||
"uuid": uuid,
|
||||
"enable": True,
|
||||
"execution": "exactly",
|
||||
"sendemail": False,
|
||||
"comment": "",
|
||||
"type": "userdefined",
|
||||
"minute": "0",
|
||||
"everynminute": False,
|
||||
"hour": "0",
|
||||
"everynhour": False,
|
||||
"month": "*",
|
||||
"dayofmonth": "*",
|
||||
"everyndayofmonth": False,
|
||||
"dayofweek": "*",
|
||||
"username": "root",
|
||||
"command": "true",
|
||||
}
|
||||
job.update(fields)
|
||||
return job
|
||||
|
||||
|
||||
def _jobs() -> list[dict[str, object]]:
|
||||
return [
|
||||
_job(
|
||||
SYNC,
|
||||
minute="15",
|
||||
everynminute=True,
|
||||
hour="2",
|
||||
dayofweek="1,3",
|
||||
comment="Nightly sync",
|
||||
command="rsync -a /srv/a /srv/b",
|
||||
),
|
||||
_job(WEEKLY, enable=False, execution="weekly", username="backup", command="backup.sh"),
|
||||
_job(
|
||||
OWN,
|
||||
execution="daily",
|
||||
sendemail=True,
|
||||
comment="napalm-scheduled-job: cleanup Remove old snapshots",
|
||||
command="cleanup --old\necho done",
|
||||
),
|
||||
_job(POWER, type="shutdown", hour="23", command="systemctl poweroff"),
|
||||
]
|
||||
|
||||
|
||||
class Nas:
|
||||
"""An OMV NAS as the driver sees it: ``run_command`` and ``omv-rpc`` through sudo."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.jobs = _jobs()
|
||||
self.dirty = ["apt"]
|
||||
self.users = {"root": "root", "backup": "backup"}
|
||||
self.commands: list[str] = []
|
||||
self.calls: list[tuple[str, object]] = []
|
||||
self.listed = None # what Cron.getList says, if not the jobs
|
||||
self.output = [("hello\n", True), ("world\n", False)]
|
||||
self.fail = ""
|
||||
|
||||
def run_command(self, command, *, privileged=False, timeout=60, stdin=None):
|
||||
self.commands.append(command)
|
||||
if command.startswith("printf '%s%s\\n' SJ_"):
|
||||
return CommandResult(REPORT, "", 0)
|
||||
if command.startswith("t=$(mktemp)"):
|
||||
return CommandResult("/tmp/tmp.Staged", "", 0)
|
||||
argv = shlex.split(command)
|
||||
if argv[0] == "stat":
|
||||
return CommandResult("644 root root\n", "", 0)
|
||||
if argv[:3] == ["id", "-gn", "--"]:
|
||||
group = self.users.get(argv[3])
|
||||
return CommandResult(group or "", "" if group else "no such user", 0 if group else 1)
|
||||
return CommandResult("", "", 0)
|
||||
|
||||
def sudo_status(self, command: str, read_timeout: float = 100):
|
||||
if command.startswith("cat ") and "dirtymodules" in command:
|
||||
return json.dumps(self.dirty), 0
|
||||
argv = shlex.split(command)
|
||||
assert argv[:3] == ["omv-rpc", "-u", "admin"], command
|
||||
method = f"{argv[3]}.{argv[4]}"
|
||||
params = json.loads(argv[5]) if len(argv) > 5 else None
|
||||
self.calls.append((method, params))
|
||||
if method == self.fail:
|
||||
return "ERROR: the job failed: exit 3", 1
|
||||
return json.dumps(self._answer(method, params)), 0
|
||||
|
||||
def _answer(self, method: str, params): # noqa: C901 - one branch per RPC method
|
||||
if method == "Cron.getList":
|
||||
assert params["type"] == ["userdefined", "reboot", "shutdown", "standby"]
|
||||
data = self.jobs if self.listed is None else self.listed
|
||||
return {"total": len(self.jobs), "data": data}
|
||||
if method == "Cron.set":
|
||||
stored = {k: ",".join(v) if isinstance(v, list) else v for k, v in params.items()}
|
||||
if stored["uuid"] == NEW:
|
||||
stored["uuid"] = "6b7c8d9e-4e5f-4061-8273-8495a6b7c8d9"
|
||||
self.jobs.append(stored)
|
||||
else:
|
||||
self.jobs = [stored if j["uuid"] == stored["uuid"] else j for j in self.jobs]
|
||||
self.dirty.append("cron")
|
||||
return stored
|
||||
if method == "Cron.delete":
|
||||
self.jobs = [j for j in self.jobs if j["uuid"] != params["uuid"]]
|
||||
self.dirty.append("cron")
|
||||
return {}
|
||||
if method == "Cron.execute":
|
||||
return "/tmp/bgstatusQx1"
|
||||
if method == "Exec.getOutput":
|
||||
chunk, running = self.output.pop(0)
|
||||
return {
|
||||
"filename": params["filename"],
|
||||
"pos": params["pos"] + len(chunk),
|
||||
"output": chunk,
|
||||
"running": running,
|
||||
}
|
||||
if method == "Exec.stop":
|
||||
return None
|
||||
if method == "Config.applyChanges":
|
||||
self.dirty = [m for m in self.dirty if m not in params["modules"]]
|
||||
return None
|
||||
raise AssertionError(method)
|
||||
|
||||
def called(self, method: str) -> list[object]:
|
||||
return [params for m, params in self.calls if m == method]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def nas() -> Nas:
|
||||
return Nas()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def driver(nas: Nas) -> OpenMediaVaultDriver:
|
||||
d = OpenMediaVaultDriver("nas", "admin", "p")
|
||||
d.run_command = nas.run_command # type: ignore[method-assign]
|
||||
d._sudo_status = nas.sudo_status # type: ignore[method-assign]
|
||||
return d
|
||||
|
||||
|
||||
def _by_key(driver: OpenMediaVaultDriver) -> dict[str, dict[str, object]]:
|
||||
return {str(j["key"]): dict(j) for j in driver.get_scheduled_jobs()["jobs"]}
|
||||
|
||||
|
||||
# -- what OMV offers -------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_omv_offers_every_verb_of_the_contract():
|
||||
for verb in (
|
||||
"get_scheduled_jobs",
|
||||
"manage_scheduled_job",
|
||||
"put_scheduled_job",
|
||||
"delete_scheduled_job",
|
||||
):
|
||||
assert callable(getattr(OpenMediaVaultDriver, verb)), verb
|
||||
|
||||
|
||||
def test_every_file_omv_generates_is_platform():
|
||||
for path in (
|
||||
"/etc/cron.d/openmediavault-userdefined",
|
||||
"/etc/cron.d/openmediavault-powermngmt",
|
||||
"/etc/cron.d/openmediavault-rsync",
|
||||
"/etc/cron.d/openmediavault-mkrrdgraph",
|
||||
"/etc/cron.hourly/openmediavault-flushmailq",
|
||||
"/etc/cron.daily/openmediavault-apticron",
|
||||
"/etc/cron.weekly/openmediavault-apticron",
|
||||
"/etc/cron.daily/openmediavault-samba-recycle",
|
||||
):
|
||||
assert sj.generated(path), path
|
||||
assert not sj.generated("/etc/cron.d/certbot")
|
||||
assert not sj.generated("/etc/cron.daily/openmediavault-check_locked_users")
|
||||
|
||||
|
||||
# -- reading ---------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_the_web_ui_jobs_come_from_rpc(driver):
|
||||
job = _by_key(driver)[f"omv:{SYNC}"]
|
||||
|
||||
assert job["kind"] == "cron"
|
||||
assert job["source"] == "omv:cron"
|
||||
assert job["schedule"] == "*/15 2 * * 1,3"
|
||||
assert job["schedule_kind"] == "cron"
|
||||
assert (job["run_as"], job["command"], job["enabled"]) == (
|
||||
"root",
|
||||
"rsync -a /srv/a /srv/b",
|
||||
True,
|
||||
)
|
||||
assert job["managed_by"] == "admin"
|
||||
assert job["actions"] == ["enable", "disable", "run"]
|
||||
assert job["description"] == "Nightly sync"
|
||||
|
||||
|
||||
def test_the_generated_lines_of_the_web_ui_jobs_are_not_reported_twice(driver):
|
||||
sources = {str(j["source"]) for j in driver.get_scheduled_jobs()["jobs"]}
|
||||
|
||||
assert "/etc/cron.d/openmediavault-userdefined" not in sources
|
||||
assert "/etc/cron.d/openmediavault-powermngmt" not in sources
|
||||
|
||||
|
||||
def test_a_shortcut_is_the_cron_alias_and_a_disabled_job_is_reported(driver):
|
||||
job = _by_key(driver)[f"omv:{WEEKLY}"]
|
||||
|
||||
assert (job["schedule"], job["enabled"], job["run_as"]) == ("@weekly", False, "backup")
|
||||
|
||||
|
||||
def test_an_applications_job_is_known_by_its_comment(driver):
|
||||
job = _by_key(driver)[f"omv:{OWN}"]
|
||||
|
||||
assert job["managed_by"] == "application"
|
||||
assert (job["name"], job["description"]) == ("cleanup", "Remove old snapshots")
|
||||
assert job["actions"] == ["enable", "disable", "run", "edit", "delete"]
|
||||
assert job["command"] == "cleanup --old\necho done"
|
||||
|
||||
|
||||
def test_a_power_management_job_is_switched_but_not_run(driver):
|
||||
job = _by_key(driver)[f"omv:{POWER}"]
|
||||
|
||||
assert job["source"] == "omv:powermgmt"
|
||||
assert job["schedule"] == "0 23 * * *"
|
||||
assert job["actions"] == ["enable", "disable"]
|
||||
|
||||
|
||||
def test_the_rest_of_the_host_is_read_as_on_linux(driver):
|
||||
reading = driver.get_scheduled_jobs()
|
||||
certbot = next(j for j in reading["jobs"] if j["source"] == "/etc/cron.d/certbot")
|
||||
package = _by_key(driver)["run-parts:/etc/cron.daily/openmediavault-check_locked_users"]
|
||||
|
||||
assert reading["time_zone"] == "Europe/Berlin"
|
||||
assert certbot["managed_by"] == "package"
|
||||
assert certbot["actions"] == ["enable", "disable", "run"]
|
||||
assert package["managed_by"] == "package"
|
||||
|
||||
|
||||
def test_a_generated_job_is_platform_and_only_runs(driver):
|
||||
jobs = _by_key(driver)
|
||||
rsync = next(j for j in jobs.values() if j["source"] == "/etc/cron.d/openmediavault-rsync")
|
||||
flush = jobs["run-parts:/etc/cron.hourly/openmediavault-flushmailq"]
|
||||
|
||||
for job in (rsync, flush):
|
||||
assert job["managed_by"] == "platform"
|
||||
assert job["actions"] == ["run"]
|
||||
|
||||
|
||||
def test_a_list_cut_short_raises(driver, nas):
|
||||
nas.listed = nas.jobs[:2]
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
driver.get_scheduled_jobs()
|
||||
|
||||
|
||||
def test_a_failed_list_raises(driver, nas):
|
||||
nas.fail = "Cron.getList"
|
||||
|
||||
with pytest.raises(RuntimeError):
|
||||
driver.get_scheduled_jobs()
|
||||
|
||||
|
||||
def test_the_digest_sees_a_change_of_the_email_setting(driver, nas):
|
||||
before = _by_key(driver)[f"omv:{SYNC}"]["digest"]
|
||||
nas.jobs[0]["sendemail"] = True
|
||||
|
||||
assert _by_key(driver)[f"omv:{SYNC}"]["digest"] != before
|
||||
|
||||
|
||||
# -- never a generated file ------------------------------------------------------------------
|
||||
|
||||
|
||||
_WRITES = {"install", "crontab", "chmod", "rm", "tee", "mv", "cp", "sed", "systemctl"}
|
||||
#: What reads a file or runs a job, and so may name a generated file.
|
||||
_READS = {"cat", "timeout", "id"}
|
||||
|
||||
|
||||
def _wrote(nas: Nas) -> list[str]:
|
||||
"""Every command but the report that writes, or that names a generated file to do so."""
|
||||
commands = [c for c in nas.commands if not c.startswith("printf '%s%s\\n' SJ_")]
|
||||
return [
|
||||
c
|
||||
for c in commands
|
||||
if shlex.split(c)[0] in _WRITES
|
||||
or ("openmediavault-" in c and shlex.split(c)[0] not in _READS)
|
||||
]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("action", ["enable", "disable"])
|
||||
def test_a_generated_job_is_never_switched_by_the_linux_path(driver, nas, action):
|
||||
for job in _by_key(driver).values():
|
||||
if job["managed_by"] != "platform":
|
||||
continue
|
||||
with pytest.raises(ScheduledJobRefused):
|
||||
driver.manage_scheduled_job(str(job["key"]), action, digest=str(job["digest"]))
|
||||
|
||||
assert _wrote(nas) == []
|
||||
|
||||
|
||||
def test_the_linux_writers_refuse_a_generated_file(driver, nas):
|
||||
flush = _by_key(driver)["run-parts:/etc/cron.hourly/openmediavault-flushmailq"]
|
||||
|
||||
with pytest.raises(ScheduledJobRefused):
|
||||
driver._sj_write("/etc/cron.d/openmediavault-userdefined", "* * * * * root true\n")
|
||||
with pytest.raises(ScheduledJobRefused):
|
||||
driver._sj_switch(flush, False)
|
||||
with pytest.raises(ScheduledJobRefused):
|
||||
driver._sj_delete_cron({"source": "/etc/cron.d/openmediavault-rsync", "name": "x"})
|
||||
assert _wrote(nas) == []
|
||||
|
||||
|
||||
def test_the_linux_writers_still_write_any_other_file(driver, nas):
|
||||
driver._sj_write("/etc/cron.d/certbot", "0 */12 * * * root certbot -q renew\n")
|
||||
driver._sj_delete_cron({"source": "/etc/cron.d/tidy", "name": "tidy", "run_as": "root"})
|
||||
|
||||
assert any(c.startswith("install") and c.endswith("/etc/cron.d/certbot") for c in nas.commands)
|
||||
assert shlex.join(["rm", "-f", "--", "/etc/cron.d/tidy"]) in nas.commands
|
||||
|
||||
|
||||
def test_a_generated_cron_line_still_runs(driver, nas):
|
||||
rsync = next(
|
||||
j for j in _by_key(driver).values() if j["source"] == "/etc/cron.d/openmediavault-rsync"
|
||||
)
|
||||
nas.run_command = _with_file(nas, "/etc/cron.d/openmediavault-rsync") # type: ignore[method-assign]
|
||||
driver.run_command = nas.run_command # type: ignore[method-assign]
|
||||
|
||||
result = driver.manage_scheduled_job(str(rsync["key"]), "run", digest=str(rsync["digest"]))
|
||||
|
||||
assert result["success"] is True
|
||||
assert any("rsync-6a7b8c9d" in c for c in nas.commands)
|
||||
assert _wrote(nas) == []
|
||||
|
||||
|
||||
def _with_file(nas: Nas, path: str):
|
||||
text = "0 3 * * * root /var/lib/openmediavault/cron.d/rsync-6a7b8c9d >/dev/null 2>&1\n"
|
||||
original = nas.run_command
|
||||
|
||||
def run_command(command, **kwargs):
|
||||
if command == shlex.join(["cat", "--", path]):
|
||||
nas.commands.append(command)
|
||||
return CommandResult(text, "", 0)
|
||||
return original(command, **kwargs)
|
||||
|
||||
return run_command
|
||||
|
||||
|
||||
def test_any_other_job_keeps_the_linux_behaviour(driver, nas):
|
||||
job = _by_key(driver)["run-parts:/etc/cron.daily/openmediavault-check_locked_users"]
|
||||
|
||||
driver.manage_scheduled_job(str(job["key"]), "disable", digest=str(job["digest"]))
|
||||
|
||||
assert (
|
||||
shlex.join(["chmod", "-x", "--", "/etc/cron.daily/openmediavault-check_locked_users"])
|
||||
in nas.commands
|
||||
)
|
||||
assert nas.called("Cron.set") == []
|
||||
|
||||
|
||||
# -- switching and running a web UI job ------------------------------------------------------
|
||||
|
||||
|
||||
def test_disable_sets_the_job_unchanged_but_enable(driver, nas):
|
||||
job = _by_key(driver)[f"omv:{SYNC}"]
|
||||
|
||||
result = driver.manage_scheduled_job(job["key"], "disable", digest=job["digest"])
|
||||
|
||||
(sent,) = nas.called("Cron.set")
|
||||
assert sent == {
|
||||
**_jobs()[0],
|
||||
"enable": False,
|
||||
"minute": ["15"],
|
||||
"hour": ["2"],
|
||||
"month": ["*"],
|
||||
"dayofmonth": ["*"],
|
||||
"dayofweek": ["1", "3"],
|
||||
}
|
||||
assert result["success"] is True
|
||||
assert nas.called("Config.applyChanges") == [{"modules": ["cron"], "force": False}]
|
||||
assert nas.dirty == ["apt"]
|
||||
assert _by_key(driver)[f"omv:{SYNC}"]["enabled"] is False
|
||||
|
||||
|
||||
def test_enable_switches_a_disabled_job_on(driver, nas):
|
||||
job = _by_key(driver)[f"omv:{WEEKLY}"]
|
||||
|
||||
driver.manage_scheduled_job(job["key"], "enable", digest=job["digest"])
|
||||
|
||||
assert nas.called("Cron.set")[0]["enable"] is True
|
||||
|
||||
|
||||
def test_a_job_changed_since_it_was_read_is_not_written(driver, nas):
|
||||
job = _by_key(driver)[f"omv:{SYNC}"]
|
||||
nas.jobs[0]["command"] = "rsync -a /srv/a /srv/c"
|
||||
|
||||
with pytest.raises(ScheduledJobChanged):
|
||||
driver.manage_scheduled_job(job["key"], "disable", digest=job["digest"])
|
||||
assert nas.called("Cron.set") == []
|
||||
assert nas.called("Config.applyChanges") == []
|
||||
|
||||
|
||||
def test_an_unknown_job_is_a_lookup_error(driver):
|
||||
with pytest.raises(LookupError):
|
||||
driver.manage_scheduled_job("omv:00000000-0000-4000-8000-000000000000", "run", digest="x")
|
||||
|
||||
|
||||
def test_an_unknown_action_is_refused(driver):
|
||||
job = _by_key(driver)[f"omv:{SYNC}"]
|
||||
|
||||
with pytest.raises(ScheduledJobRefused):
|
||||
driver.manage_scheduled_job(job["key"], "edit", digest=job["digest"])
|
||||
|
||||
|
||||
def test_a_power_management_job_is_not_run(driver, nas):
|
||||
job = _by_key(driver)[f"omv:{POWER}"]
|
||||
|
||||
with pytest.raises(ScheduledJobRefused):
|
||||
driver.manage_scheduled_job(job["key"], "run", digest=job["digest"])
|
||||
assert nas.called("Cron.execute") == []
|
||||
|
||||
|
||||
def test_run_follows_the_output_to_the_end(driver, nas, monkeypatch):
|
||||
monkeypatch.setattr(sj, "_sleep", lambda _s: None)
|
||||
job = _by_key(driver)[f"omv:{SYNC}"]
|
||||
|
||||
result = driver.manage_scheduled_job(job["key"], "run", digest=job["digest"])
|
||||
|
||||
assert nas.called("Cron.execute") == [{"uuid": SYNC}]
|
||||
assert nas.called("Exec.getOutput") == [
|
||||
{"filename": "/tmp/bgstatusQx1", "pos": 0},
|
||||
{"filename": "/tmp/bgstatusQx1", "pos": 6},
|
||||
]
|
||||
assert result == {"success": True, "output": "hello\nworld"}
|
||||
|
||||
|
||||
def test_a_run_that_fails_says_so(driver, nas, monkeypatch):
|
||||
monkeypatch.setattr(sj, "_sleep", lambda _s: None)
|
||||
job = _by_key(driver)[f"omv:{SYNC}"]
|
||||
nas.output = [("hello\n", True)]
|
||||
|
||||
def status(command: str, read_timeout: float = 100):
|
||||
"""The job ends with exit 3: OMV raises from the next ``Exec.getOutput``."""
|
||||
if "getOutput" in command and '"pos": 6' in command:
|
||||
return "ERROR: the job failed: exit 3", 1
|
||||
return nas.sudo_status(command, read_timeout)
|
||||
|
||||
driver._sudo_status = status # type: ignore[method-assign]
|
||||
result = driver.manage_scheduled_job(job["key"], "run", digest=job["digest"])
|
||||
|
||||
assert result["success"] is False
|
||||
assert "hello" in result["output"]
|
||||
assert "exit 3" in result["output"]
|
||||
|
||||
|
||||
def test_a_run_past_the_timeout_is_stopped(driver, nas, monkeypatch):
|
||||
clock = iter(range(0, 10_000, 200))
|
||||
monkeypatch.setattr(sj, "_sleep", lambda _s: None)
|
||||
monkeypatch.setattr(sj, "_monotonic", lambda: next(clock))
|
||||
nas.output = [("tick\n", True)] * 10
|
||||
job = _by_key(driver)[f"omv:{SYNC}"]
|
||||
|
||||
result = driver.manage_scheduled_job(job["key"], "run", digest=job["digest"])
|
||||
|
||||
assert nas.called("Exec.stop") == [{"filename": "/tmp/bgstatusQx1"}]
|
||||
assert result["success"] is False
|
||||
assert "stopped after 300 s" in result["output"]
|
||||
|
||||
|
||||
# -- an application's own job ----------------------------------------------------------------
|
||||
|
||||
|
||||
def _spec(**fields):
|
||||
spec = {
|
||||
"name": "rotate",
|
||||
"schedule": "*/10 1-3 * * 0",
|
||||
"run_as": "backup",
|
||||
"command": "rotate-logs\necho rotated",
|
||||
"enabled": True,
|
||||
"description": "Rotate the logs",
|
||||
}
|
||||
spec.update(fields)
|
||||
return spec
|
||||
|
||||
|
||||
def test_put_creates_an_omv_job(driver, nas):
|
||||
result = driver.put_scheduled_job(_spec())
|
||||
|
||||
(sent,) = nas.called("Cron.set")
|
||||
assert sent == {
|
||||
"uuid": NEW,
|
||||
"enable": True,
|
||||
"execution": "exactly",
|
||||
"sendemail": False,
|
||||
"comment": "napalm-scheduled-job: rotate Rotate the logs",
|
||||
"type": "userdefined",
|
||||
"minute": ["10"],
|
||||
"everynminute": True,
|
||||
"hour": ["1", "2", "3"],
|
||||
"everynhour": False,
|
||||
"month": ["*"],
|
||||
"dayofmonth": ["*"],
|
||||
"everyndayofmonth": False,
|
||||
"dayofweek": ["7"],
|
||||
"username": "backup",
|
||||
"command": "rotate-logs\necho rotated",
|
||||
}
|
||||
assert nas.called("Config.applyChanges") == [{"modules": ["cron"], "force": False}]
|
||||
assert result == {"success": True, "output": "omv:6b7c8d9e-4e5f-4061-8273-8495a6b7c8d9 created"}
|
||||
job = _by_key(driver)["omv:6b7c8d9e-4e5f-4061-8273-8495a6b7c8d9"]
|
||||
assert (job["managed_by"], job["name"], job["schedule"]) == (
|
||||
"application",
|
||||
"rotate",
|
||||
"*/10 1,2,3 * * 7",
|
||||
)
|
||||
|
||||
|
||||
def test_put_changes_the_applications_job_and_keeps_its_email_setting(driver, nas):
|
||||
job = _by_key(driver)[f"omv:{OWN}"]
|
||||
|
||||
result = driver.put_scheduled_job(
|
||||
_spec(name="cleanup", schedule="@daily", run_as="root"), digest=job["digest"]
|
||||
)
|
||||
|
||||
(sent,) = nas.called("Cron.set")
|
||||
assert (sent["uuid"], sent["execution"], sent["sendemail"]) == (OWN, "daily", True)
|
||||
assert result["output"] == f"omv:{OWN} changed"
|
||||
|
||||
|
||||
def test_put_of_a_name_already_there_without_digest_is_a_change_unseen(driver, nas):
|
||||
with pytest.raises(ScheduledJobChanged):
|
||||
driver.put_scheduled_job(_spec(name="cleanup"))
|
||||
assert nas.called("Cron.set") == []
|
||||
|
||||
|
||||
def test_put_with_a_digest_for_a_job_not_there_is_a_lookup_error(driver):
|
||||
with pytest.raises(LookupError):
|
||||
driver.put_scheduled_job(_spec(), digest="0123456789abcdef")
|
||||
|
||||
|
||||
def test_put_over_a_changed_job_is_refused(driver, nas):
|
||||
job = _by_key(driver)[f"omv:{OWN}"]
|
||||
nas.jobs[2]["command"] = "something else"
|
||||
|
||||
with pytest.raises(ScheduledJobChanged):
|
||||
driver.put_scheduled_job(_spec(name="cleanup"), digest=job["digest"])
|
||||
assert nas.called("Cron.set") == []
|
||||
|
||||
|
||||
def test_put_for_a_user_the_nas_does_not_have_is_refused(driver, nas):
|
||||
with pytest.raises(ScheduledJobRefused):
|
||||
driver.put_scheduled_job(_spec(run_as="nobody"))
|
||||
assert nas.called("Cron.set") == []
|
||||
|
||||
|
||||
def test_put_of_an_invalid_spec_is_refused_before_anything_runs(driver, nas):
|
||||
with pytest.raises(ScheduledJobRefused):
|
||||
driver.put_scheduled_job(_spec(schedule="61 * * * *"))
|
||||
assert nas.calls == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("schedule", "execution"),
|
||||
[
|
||||
("@reboot", "reboot"),
|
||||
("@hourly", "hourly"),
|
||||
("@daily", "daily"),
|
||||
("@midnight", "daily"),
|
||||
("@weekly", "weekly"),
|
||||
("@monthly", "monthly"),
|
||||
("@yearly", "yearly"),
|
||||
("@annually", "yearly"),
|
||||
],
|
||||
)
|
||||
def test_a_cron_alias_is_omvs_shortcut(schedule, execution):
|
||||
assert sj.omv_schedule(schedule)["execution"] == execution
|
||||
|
||||
|
||||
def test_a_step_on_month_and_weekday_is_written_as_its_values():
|
||||
fields = sj.omv_schedule("0 0 * */4 1-5/2")
|
||||
|
||||
assert fields["month"] == ["1", "5", "9"]
|
||||
assert fields["dayofweek"] == ["1", "3", "5"]
|
||||
|
||||
|
||||
def test_a_day_field_keeps_its_star_meaning():
|
||||
"""``1-31`` is not ``*``: with a weekday set, cron runs on either."""
|
||||
assert sj.omv_schedule("0 0 1-31 * 1")["dayofmonth"] == [str(d) for d in range(1, 32)]
|
||||
|
||||
|
||||
def test_a_schedule_cron_would_not_take_is_refused():
|
||||
with pytest.raises(ScheduledJobRefused):
|
||||
sj.omv_schedule("61 * * * *")
|
||||
|
||||
|
||||
def test_a_weekday_step_beside_a_day_of_month_is_refused():
|
||||
"""OMV has no ``*/n`` for weekdays; its values would turn cron's AND into an OR."""
|
||||
with pytest.raises(ScheduledJobRefused):
|
||||
sj.omv_schedule("0 0 1 * */2")
|
||||
|
||||
|
||||
def test_a_cron_schedule_reads_back_from_omvs_fields():
|
||||
for schedule in ("*/10 1,2,3 * * 7", "0 0 */2 1,6 *", "@reboot", "@yearly"):
|
||||
fields = {
|
||||
k: ",".join(v) if isinstance(v, list) else v
|
||||
for k, v in sj.omv_schedule(schedule).items()
|
||||
}
|
||||
assert sj.cron_schedule(fields) == schedule
|
||||
|
||||
|
||||
# -- deleting --------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_delete_removes_the_applications_job(driver, nas):
|
||||
job = _by_key(driver)[f"omv:{OWN}"]
|
||||
|
||||
result = driver.delete_scheduled_job(job["key"], digest=job["digest"])
|
||||
|
||||
assert nas.called("Cron.delete") == [{"uuid": OWN}]
|
||||
assert nas.called("Config.applyChanges") == [{"modules": ["cron"], "force": False}]
|
||||
assert result == {"success": True, "output": f"omv:{OWN} deleted"}
|
||||
|
||||
|
||||
def test_delete_of_an_admins_job_is_refused(driver, nas):
|
||||
job = _by_key(driver)[f"omv:{SYNC}"]
|
||||
|
||||
with pytest.raises(ScheduledJobRefused):
|
||||
driver.delete_scheduled_job(job["key"], digest=job["digest"])
|
||||
assert nas.called("Cron.delete") == []
|
||||
|
||||
|
||||
def test_delete_of_a_changed_job_is_refused(driver, nas):
|
||||
job = _by_key(driver)[f"omv:{OWN}"]
|
||||
nas.jobs[2]["enable"] = False
|
||||
|
||||
with pytest.raises(ScheduledJobChanged):
|
||||
driver.delete_scheduled_job(job["key"], digest=job["digest"])
|
||||
assert nas.called("Cron.delete") == []
|
||||
|
||||
|
||||
def test_delete_of_any_other_job_is_the_linux_one(driver, nas):
|
||||
certbot = next(
|
||||
j for j in driver.get_scheduled_jobs()["jobs"] if j["source"] == "/etc/cron.d/certbot"
|
||||
)
|
||||
|
||||
with pytest.raises(ScheduledJobRefused):
|
||||
driver.delete_scheduled_job(certbot["key"], digest=certbot["digest"])
|
||||
assert _wrote(nas) == []
|
||||
|
||||
|
||||
def test_a_cron_module_with_changes_pending_refuses_every_write(driver, nas):
|
||||
"""An apply would put someone's half-finished web-UI edit live along with ours."""
|
||||
nas.dirty = ["apt", "cron"]
|
||||
job = _by_key(driver)[f"omv:{SYNC}"]
|
||||
with pytest.raises(ScheduledJobRefused, match="unapplied changes"):
|
||||
driver.manage_scheduled_job(job["key"], "disable", digest=job["digest"])
|
||||
assert nas.called("Cron.set") == [] and nas.called("Config.applyChanges") == []
|
||||
@@ -0,0 +1,154 @@
|
||||
"""OpenMediaVault renames itself through its own database, not through /etc.
|
||||
|
||||
The rename napalm-linux offers (``hostnamectl``, ``/etc/hosts``) would be taken
|
||||
back by the next apply of OMV's settings, which regenerates both from
|
||||
``conf.system.network.dns``. So the name goes where OMV's web UI puts it:
|
||||
``Network.setGeneralSettings``, then ``Config.applyChanges`` -- for the modules
|
||||
the rename made dirty only, so changes someone left pending in the web UI
|
||||
(here ``apt`` and ``rsyslog``) are not deployed along with it.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import shlex
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_openmediavault.openmediavault import OpenMediaVaultDriver
|
||||
|
||||
_RENAME_DIRTIES = ["hostname", "hosts", "postfix", "avahi", "samba", "systemdnetworkd"]
|
||||
|
||||
|
||||
class Omv:
|
||||
"""The NAS as ``_sudo_status`` sees it: omv-rpc calls and the dirty-modules file."""
|
||||
|
||||
def __init__(self, *, dirty=("apt", "rsyslog"), fail=""):
|
||||
self.settings = {"hostname": "nas", "domainname": "home.example"}
|
||||
self.dirty = list(dirty)
|
||||
self.fail = fail
|
||||
self.calls: list[tuple[str, str, object]] = []
|
||||
self.commands: list[str] = []
|
||||
|
||||
def __call__(self, command: str, read_timeout: float = 100) -> tuple[str, int | None]:
|
||||
self.commands.append(command)
|
||||
if command.startswith("cat /var/lib/openmediavault/dirtymodules.json"):
|
||||
return json.dumps(self.dirty), 0
|
||||
argv = shlex.split(command)
|
||||
assert argv[:3] == ["omv-rpc", "-u", "admin"], command
|
||||
service, method = argv[3], argv[4]
|
||||
params = json.loads(argv[5]) if len(argv) > 5 else None
|
||||
self.calls.append((service, method, params))
|
||||
if f"{service}.{method}" == self.fail:
|
||||
return '{"response":null,"error":{"message":"boom"}}', 1
|
||||
if (service, method) == ("Network", "getGeneralSettings"):
|
||||
return json.dumps(self.settings), 0
|
||||
if (service, method) == ("Network", "setGeneralSettings"):
|
||||
self.settings = params
|
||||
self.dirty += [m for m in _RENAME_DIRTIES if m not in self.dirty]
|
||||
return json.dumps(params), 0
|
||||
if (service, method) == ("Config", "applyChanges"):
|
||||
self.dirty = [m for m in self.dirty if m not in params["modules"]]
|
||||
return "null", 0
|
||||
raise AssertionError(command)
|
||||
|
||||
def call(self, method: str):
|
||||
return [params for s, m, params in self.calls if f"{s}.{m}" == method]
|
||||
|
||||
|
||||
def _driver(omv: Omv) -> OpenMediaVaultDriver:
|
||||
driver = OpenMediaVaultDriver("nas", "admin", "p")
|
||||
driver._sudo_status = omv # type: ignore[method-assign]
|
||||
return driver
|
||||
|
||||
|
||||
def test_bare_name_keeps_the_domain():
|
||||
omv = Omv()
|
||||
|
||||
_driver(omv).set_hostname("nas2")
|
||||
|
||||
assert omv.call("Network.setGeneralSettings") == [
|
||||
{"hostname": "nas2", "domainname": "home.example"}
|
||||
]
|
||||
|
||||
|
||||
def test_fqdn_sets_the_domain_too():
|
||||
omv = Omv()
|
||||
|
||||
_driver(omv).set_hostname("nas2.lab.example")
|
||||
|
||||
assert omv.call("Network.setGeneralSettings") == [
|
||||
{"hostname": "nas2", "domainname": "lab.example"}
|
||||
]
|
||||
|
||||
|
||||
def test_only_what_the_rename_made_dirty_is_applied():
|
||||
omv = Omv()
|
||||
|
||||
_driver(omv).set_hostname("nas2")
|
||||
|
||||
assert omv.call("Config.applyChanges") == [{"modules": sorted(_RENAME_DIRTIES), "force": False}]
|
||||
assert omv.dirty == ["apt", "rsyslog"]
|
||||
|
||||
|
||||
def test_a_hostname_module_already_dirty_is_applied_as_well():
|
||||
omv = Omv(dirty=("apt", "samba"))
|
||||
|
||||
_driver(omv).set_hostname("nas2")
|
||||
|
||||
(apply,) = omv.call("Config.applyChanges")
|
||||
assert "samba" in apply["modules"]
|
||||
assert "apt" not in apply["modules"]
|
||||
|
||||
|
||||
def test_nothing_dirty_nothing_applied():
|
||||
omv = Omv()
|
||||
omv.settings = {"hostname": "nas2", "domainname": "home.example"}
|
||||
|
||||
driver = _driver(omv)
|
||||
driver._sudo_status = _no_new_dirt(omv) # type: ignore[method-assign]
|
||||
driver.set_hostname("nas2")
|
||||
|
||||
assert omv.call("Config.applyChanges") == []
|
||||
|
||||
|
||||
def _no_new_dirt(omv: Omv):
|
||||
"""OMV marks nothing dirty when the settings did not change."""
|
||||
|
||||
def status(command: str, read_timeout: float = 100):
|
||||
if "setGeneralSettings" in command:
|
||||
omv.calls.append(("Network", "setGeneralSettings", json.loads(shlex.split(command)[5])))
|
||||
return json.dumps(omv.settings), 0
|
||||
return omv(command, read_timeout)
|
||||
|
||||
return status
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["", "nas_2", "-nas", "nas.", "a" * 64, "nas;reboot", "$(id)"])
|
||||
def test_invalid_name_runs_nothing(name):
|
||||
omv = Omv()
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
_driver(omv).set_hostname(name)
|
||||
|
||||
assert omv.commands == []
|
||||
|
||||
|
||||
def test_unreadable_settings_change_nothing():
|
||||
omv = Omv(fail="Network.getGeneralSettings")
|
||||
|
||||
with pytest.raises(RuntimeError, match="getGeneralSettings"):
|
||||
_driver(omv).set_hostname("nas2")
|
||||
|
||||
assert omv.call("Network.setGeneralSettings") == []
|
||||
|
||||
|
||||
def test_failed_apply_raises():
|
||||
omv = Omv(fail="Config.applyChanges")
|
||||
|
||||
with pytest.raises(RuntimeError, match="applyChanges"):
|
||||
_driver(omv).set_hostname("nas2")
|
||||
|
||||
|
||||
def test_offered_as_a_capability():
|
||||
assert callable(getattr(OpenMediaVaultDriver, "set_hostname", None))
|
||||
@@ -0,0 +1,23 @@
|
||||
"""OpenMediaVault writes sshd_config itself, from its own database.
|
||||
|
||||
The Linux driver offers to harden the SSH server by writing a drop-in under
|
||||
/etc/ssh/sshd_config.d (NetOrk/netork#1027). OMV's template ends with
|
||||
``Include /etc/ssh/sshd_config.d/*.conf`` and salt manages only sshd_config,
|
||||
so the drop-in survives the next apply of the SSH settings
|
||||
(``omv-salt deploy run ssh``) and the hardening is offered. Only sshd_config
|
||||
itself is off limits: that apply would write over it, so an OMV whose
|
||||
sshd_config does not include the directory is left alone
|
||||
(``SSHD_CONFIG_GENERATED``).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from napalm_openmediavault.openmediavault import OpenMediaVaultDriver
|
||||
|
||||
|
||||
def test_offers_ssh_hardening():
|
||||
assert callable(getattr(OpenMediaVaultDriver, "harden_ssh_server", None))
|
||||
|
||||
|
||||
def test_writes_only_the_dropin():
|
||||
assert OpenMediaVaultDriver.SSHD_CONFIG_GENERATED is True
|
||||
@@ -0,0 +1,337 @@
|
||||
"""OpenMediaVault keeps its time servers and zone in its own database (NetOrk/netork#2370).
|
||||
|
||||
OMV generates ``/etc/chrony/chrony.conf`` and the zone from ``conf.system.time``
|
||||
(``ntp.enable``, ``ntp.timeservers``, ``timezone``) through Salt. napalm-linux's
|
||||
POSIX write -- a drop-in under ``sources.d`` with every other source commented out,
|
||||
``timedatectl set-timezone`` -- would be taken back the next time OMV deploys its
|
||||
time settings, and the web UI would keep showing its own servers. So the servers
|
||||
and the zone are read from and written to ``System.getTimeSettings`` /
|
||||
``setTimeSettings``, then ``Config.applyChanges`` deploys the modules that change
|
||||
made dirty (``chrony``, ``timezone``) -- and nothing someone left pending in the
|
||||
web UI for other modules. Whether the clock is synchronised, and by which client,
|
||||
is still the host's reading.
|
||||
|
||||
The answers are shaped like OMV 7's ``System.getTimeSettings`` (``date`` aside, the
|
||||
fields of ``conf.system.time``; the servers one comma-separated string).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import shlex
|
||||
|
||||
import pytest
|
||||
from napalm_device_types import CommandResult, UnknownTimezone
|
||||
|
||||
from napalm_openmediavault.openmediavault import OpenMediaVaultDriver
|
||||
|
||||
#: The host's own reading, as PosixTimeSyncMixin's command prints it on OMV 7: chronyd
|
||||
#: runs, with the chrony.conf OMV generated, and a selected source.
|
||||
READING = """\
|
||||
@@ts timedatectl
|
||||
Timezone=Europe/Berlin
|
||||
NTP=yes
|
||||
NTPSynchronized=yes
|
||||
@@ts zone
|
||||
Europe/Berlin
|
||||
@@ts active
|
||||
chrony chrony active
|
||||
chronyd chrony active
|
||||
systemd-timesyncd systemd-timesyncd inactive
|
||||
@@ts timesync
|
||||
@@ts chronyc
|
||||
MS Name/IP address Stratum Poll Reach LastRx Last sample
|
||||
===============================================================================
|
||||
^* 192.0.2.1 2 6 377 40 -45us[ -63us] +/- 10ms
|
||||
@@ts chrony 0 main /etc/chrony/chrony.conf
|
||||
# This file is auto-generated by openmediavault (https://www.openmediavault.org)
|
||||
# WARNING: Do not edit this file, your changes will get lost.
|
||||
pool pool.ntp.org iburst
|
||||
driftfile /var/lib/chrony/chrony.drift
|
||||
makestep 1.0 3
|
||||
rtcsync
|
||||
|
||||
@@ts end
|
||||
"""
|
||||
|
||||
#: ``System.getTimeSettings`` on OMV 7, as ``omv-rpc`` prints it.
|
||||
SETTINGS = {
|
||||
"date": {"local": "Tue Nov 11 10:00:00 2026", "ISO8601": "2026-11-11T10:00:00+01:00"},
|
||||
"timezone": "Europe/Berlin",
|
||||
"ntpenable": True,
|
||||
"ntptimeservers": "pool.ntp.org",
|
||||
"ntpclients": "192.0.2.0/24",
|
||||
}
|
||||
|
||||
#: What OMV marks dirty when ``conf.system.time`` changes.
|
||||
_TIME_MODULES = {"ntptimeservers": "chrony", "ntpenable": "chrony", "timezone": "timezone"}
|
||||
|
||||
|
||||
class Omv:
|
||||
"""The NAS: omv-rpc and the dirty-modules file as ``_sudo_status`` sees them, and the
|
||||
host's reading as ``run_command`` does."""
|
||||
|
||||
def __init__(self, *, settings=None, dirty=("apt", "rsyslog"), fail=""):
|
||||
self.settings = dict(SETTINGS if settings is None else settings)
|
||||
self.dirty = list(dirty)
|
||||
self.fail = fail
|
||||
self.calls: list[tuple[str, str, object]] = []
|
||||
self.commands: list[tuple[str, bool]] = []
|
||||
|
||||
def sudo_status(self, command: str, read_timeout: float = 100) -> tuple[str, int | None]:
|
||||
if command.startswith("cat /var/lib/openmediavault/dirtymodules.json"):
|
||||
return json.dumps(self.dirty), 0
|
||||
argv = shlex.split(command)
|
||||
assert argv[:3] == ["omv-rpc", "-u", "admin"], command
|
||||
service, method = argv[3], argv[4]
|
||||
params = json.loads(argv[5]) if len(argv) > 5 else None
|
||||
self.calls.append((service, method, params))
|
||||
if f"{service}.{method}" == self.fail:
|
||||
return '{"response":null,"error":{"message":"boom"}}', 1
|
||||
if (service, method) == ("System", "getTimeSettings"):
|
||||
return json.dumps(self.settings), 0
|
||||
if (service, method) == ("System", "setTimeSettings"):
|
||||
assert isinstance(params, dict)
|
||||
for field, value in params.items():
|
||||
if self.settings.get(field) != value and _TIME_MODULES.get(field):
|
||||
if _TIME_MODULES[field] not in self.dirty:
|
||||
self.dirty.append(_TIME_MODULES[field])
|
||||
self.settings.update(params)
|
||||
return json.dumps(params), 0
|
||||
if (service, method) == ("Config", "applyChanges"):
|
||||
assert isinstance(params, dict)
|
||||
self.dirty = [m for m in self.dirty if m not in params["modules"]]
|
||||
return "null", 0
|
||||
raise AssertionError(command)
|
||||
|
||||
def run_command(self, command, *, privileged=False, timeout=60, stdin=None): # type: ignore[no-untyped-def]
|
||||
self.commands.append((command, privileged))
|
||||
assert "@@ts" in command, command
|
||||
return CommandResult(READING, "", 0)
|
||||
|
||||
def call(self, method: str) -> list[object]:
|
||||
return [params for s, m, params in self.calls if f"{s}.{m}" == method]
|
||||
|
||||
|
||||
def _driver(omv: Omv) -> OpenMediaVaultDriver:
|
||||
driver = OpenMediaVaultDriver("nas", "admin", "p")
|
||||
driver._sudo_status = omv.sudo_status # type: ignore[method-assign]
|
||||
driver.run_command = omv.run_command # type: ignore[method-assign]
|
||||
return driver
|
||||
|
||||
|
||||
# -- reading ---------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_servers_and_zone_are_omvs_the_clock_is_the_hosts():
|
||||
omv = Omv(settings={**SETTINGS, "ntptimeservers": "ntp1.example.org,192.0.2.1"})
|
||||
|
||||
assert _driver(omv).get_time_sync() == {
|
||||
"ntp_servers": ["ntp1.example.org", "192.0.2.1"],
|
||||
"timezone": "Europe/Berlin",
|
||||
"synchronized": True,
|
||||
"daemon": "chrony",
|
||||
}
|
||||
|
||||
|
||||
def test_the_reading_changes_nothing():
|
||||
omv = Omv()
|
||||
|
||||
_driver(omv).get_time_sync()
|
||||
|
||||
assert [m for _s, m, _p in omv.calls] == ["getTimeSettings"]
|
||||
assert not any(privileged for _c, privileged in omv.commands)
|
||||
|
||||
|
||||
def test_servers_separated_by_spaces_as_well():
|
||||
omv = Omv(settings={**SETTINGS, "ntptimeservers": " ntp1.example.org, ntp2.example.org "})
|
||||
|
||||
assert _driver(omv).get_time_sync()["ntp_servers"] == ["ntp1.example.org", "ntp2.example.org"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("off", [False, "0", "false", None])
|
||||
def test_ntp_switched_off_is_no_servers(off):
|
||||
"""OMV stops chronyd with NTP off: the servers it still lists keep nothing."""
|
||||
omv = Omv(settings={**SETTINGS, "ntpenable": off})
|
||||
|
||||
assert _driver(omv).get_time_sync()["ntp_servers"] == []
|
||||
|
||||
|
||||
def test_ntp_on_as_the_database_spells_it():
|
||||
omv = Omv(settings={**SETTINGS, "ntpenable": "1"})
|
||||
|
||||
assert _driver(omv).get_time_sync()["ntp_servers"] == ["pool.ntp.org"]
|
||||
|
||||
|
||||
def test_an_answer_that_is_no_object_raises():
|
||||
omv = Omv()
|
||||
driver = _driver(omv)
|
||||
driver._sudo_status = lambda command, read_timeout=100: ("null", 0) # type: ignore[method-assign]
|
||||
|
||||
with pytest.raises(RuntimeError, match="getTimeSettings"):
|
||||
driver.get_time_sync()
|
||||
|
||||
|
||||
def test_no_zone_stored_is_none():
|
||||
omv = Omv(settings={**SETTINGS, "timezone": ""})
|
||||
|
||||
assert _driver(omv).get_time_sync()["timezone"] is None
|
||||
|
||||
|
||||
def test_unreadable_settings_raise():
|
||||
omv = Omv(fail="System.getTimeSettings")
|
||||
|
||||
with pytest.raises(RuntimeError, match="getTimeSettings"):
|
||||
_driver(omv).get_time_sync()
|
||||
|
||||
|
||||
# -- writing ---------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_servers_go_through_omvs_settings():
|
||||
omv = Omv()
|
||||
|
||||
result = _driver(omv).configure_time_sync(ntp_servers=["ntp1.example.org", "192.0.2.1"])
|
||||
|
||||
assert result["success"], result["output"]
|
||||
assert omv.call("System.setTimeSettings") == [
|
||||
{
|
||||
"timezone": "Europe/Berlin",
|
||||
"ntpenable": True,
|
||||
"ntptimeservers": "ntp1.example.org,192.0.2.1",
|
||||
"ntpclients": "192.0.2.0/24",
|
||||
}
|
||||
]
|
||||
assert [s["step"] for s in result["steps"]] == ["ntp_servers", "verify"]
|
||||
|
||||
|
||||
def test_servers_switch_ntp_on():
|
||||
omv = Omv(settings={**SETTINGS, "ntpenable": False})
|
||||
|
||||
_driver(omv).configure_time_sync(ntp_servers=["ntp1.example.org"])
|
||||
|
||||
(params,) = omv.call("System.setTimeSettings")
|
||||
assert isinstance(params, dict)
|
||||
assert params["ntpenable"] is True
|
||||
|
||||
|
||||
def test_only_what_the_change_made_dirty_is_applied():
|
||||
omv = Omv()
|
||||
|
||||
_driver(omv).configure_time_sync(ntp_servers=["ntp1.example.org"])
|
||||
|
||||
assert omv.call("Config.applyChanges") == [{"modules": ["chrony"], "force": False}]
|
||||
assert omv.dirty == ["apt", "rsyslog"]
|
||||
|
||||
|
||||
def test_zone_goes_through_omvs_settings():
|
||||
omv = Omv()
|
||||
|
||||
result = _driver(omv).configure_time_sync(timezone="America/New_York")
|
||||
|
||||
assert result["success"], result["output"]
|
||||
(params,) = omv.call("System.setTimeSettings")
|
||||
assert isinstance(params, dict)
|
||||
assert params["timezone"] == "America/New_York"
|
||||
assert params["ntptimeservers"] == "pool.ntp.org"
|
||||
assert omv.call("Config.applyChanges") == [{"modules": ["timezone"], "force": False}]
|
||||
|
||||
|
||||
def test_a_time_module_already_dirty_is_applied_as_well():
|
||||
omv = Omv(dirty=("apt", "timezone"))
|
||||
|
||||
_driver(omv).configure_time_sync(ntp_servers=["ntp1.example.org"])
|
||||
|
||||
(apply,) = omv.call("Config.applyChanges")
|
||||
assert isinstance(apply, dict)
|
||||
assert apply["modules"] == ["chrony", "timezone"]
|
||||
|
||||
|
||||
def test_nothing_on_the_host_itself_is_written():
|
||||
"""No drop-in, no commented-out line, no ``timedatectl``: OMV would take them back."""
|
||||
omv = Omv()
|
||||
|
||||
_driver(omv).configure_time_sync(ntp_servers=["ntp1.example.org"], timezone="Europe/Paris")
|
||||
|
||||
assert not any(privileged for _c, privileged in omv.commands)
|
||||
|
||||
|
||||
def test_the_same_values_again_change_nothing():
|
||||
omv = Omv()
|
||||
|
||||
result = _driver(omv).configure_time_sync(
|
||||
ntp_servers=["POOL.ntp.org"], timezone="Europe/Berlin"
|
||||
)
|
||||
|
||||
assert result["success"], result["output"]
|
||||
assert omv.call("System.setTimeSettings") == []
|
||||
assert omv.call("Config.applyChanges") == []
|
||||
|
||||
|
||||
def test_written_twice_is_written_once():
|
||||
omv = Omv()
|
||||
driver = _driver(omv)
|
||||
|
||||
driver.configure_time_sync(ntp_servers=["ntp1.example.org"], timezone="Europe/Paris")
|
||||
driver.configure_time_sync(ntp_servers=["ntp1.example.org"], timezone="Europe/Paris")
|
||||
|
||||
assert len(omv.call("System.setTimeSettings")) == 2 # servers, zone: the first time only
|
||||
assert len(omv.call("Config.applyChanges")) == 2
|
||||
|
||||
|
||||
def test_both_in_one_run():
|
||||
omv = Omv()
|
||||
|
||||
result = _driver(omv).configure_time_sync(
|
||||
ntp_servers=["ntp1.example.org"], timezone="Europe/Paris"
|
||||
)
|
||||
|
||||
assert result["success"], result["output"]
|
||||
assert [s["step"] for s in result["steps"]] == ["ntp_servers", "timezone", "verify"]
|
||||
assert omv.settings["ntptimeservers"] == "ntp1.example.org"
|
||||
assert omv.settings["timezone"] == "Europe/Paris"
|
||||
|
||||
|
||||
def test_a_refused_setting_fails_the_step_and_applies_nothing():
|
||||
omv = Omv(fail="System.setTimeSettings")
|
||||
|
||||
result = _driver(omv).configure_time_sync(ntp_servers=["ntp1.example.org"])
|
||||
|
||||
assert not result["success"]
|
||||
assert result["steps"][-1]["step"] == "ntp_servers"
|
||||
assert "setTimeSettings" in result["steps"][-1]["output"]
|
||||
assert omv.call("Config.applyChanges") == []
|
||||
|
||||
|
||||
def test_a_failed_apply_fails_the_step():
|
||||
omv = Omv(fail="Config.applyChanges")
|
||||
|
||||
result = _driver(omv).configure_time_sync(timezone="Europe/Paris")
|
||||
|
||||
assert not result["success"]
|
||||
assert result["steps"][-1]["step"] == "timezone"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("kwargs", "error"),
|
||||
[
|
||||
({"ntp_servers": ["bad server"]}, ValueError),
|
||||
({"ntp_servers": []}, ValueError),
|
||||
({"timezone": "CET-1CEST,M3.5.0,M10.5.0/3"}, UnknownTimezone),
|
||||
({}, ValueError),
|
||||
],
|
||||
)
|
||||
def test_the_contracts_refusals_run_nothing(kwargs, error):
|
||||
omv = Omv()
|
||||
|
||||
with pytest.raises(error):
|
||||
_driver(omv).configure_time_sync(**kwargs)
|
||||
|
||||
assert omv.calls == []
|
||||
assert omv.commands == []
|
||||
|
||||
|
||||
def test_offered_as_a_capability_for_both_values():
|
||||
assert callable(getattr(OpenMediaVaultDriver, "get_time_sync", None))
|
||||
assert callable(getattr(OpenMediaVaultDriver, "configure_time_sync", None))
|
||||
assert OpenMediaVaultDriver.time_sync_writes == frozenset({"ntp_servers", "timezone"})
|
||||
Reference in new issue
Block a user