Compare commits
74
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5c91af6033 | ||
|
|
6a8ebfe235 | ||
|
|
3e80f7d02a | ||
|
|
6e7fe5ed5b | ||
|
|
530f04055c | ||
|
|
6ff893649c | ||
|
|
053137aff7 | ||
|
|
c4434cf54b | ||
|
|
ec88cfd734 | ||
|
|
de11d16749 | ||
|
|
27ca0667d8 | ||
|
|
0ca486bed5 | ||
|
|
248c87009f | ||
|
|
d3abda34b4 | ||
|
|
3dc24612f0 | ||
|
|
29d26e11d8 | ||
|
|
6285fa2f0a | ||
|
|
e4ae42fea0 | ||
|
|
17d9bead50 | ||
|
|
780b635174 | ||
|
|
0552663d53 | ||
|
|
522720f818 | ||
|
|
85a679fe1a | ||
|
|
836539d1fe | ||
|
|
7bb15f5af3 | ||
|
|
e7bd0c17f5 | ||
|
|
29872243ba | ||
|
|
e2eda54fe4 | ||
|
|
af3e10d194 | ||
|
|
eeeb46121f | ||
|
|
0380350a4c | ||
|
|
f9af7abaf6 | ||
|
|
f81d2cd89f | ||
|
|
071beeb68a | ||
|
|
aafb5636a9 | ||
|
|
231def768e | ||
|
|
58ee774250 | ||
|
|
d04a969eb1 | ||
|
|
6802e4d7df | ||
|
|
1e988c87f4 | ||
|
|
004c3e9322 | ||
|
|
5cce38b2bb | ||
|
|
783a4ee0cb | ||
|
|
5e71f0b471 | ||
|
|
097d9b9581 | ||
|
|
c211ba0d9e | ||
|
|
16e0fa9d5e | ||
|
|
45f5b65427 | ||
|
|
d78a55dd1a | ||
|
|
b0270d3430 | ||
|
|
b1a2950d9d | ||
|
|
14ab92b80b | ||
|
|
20d2670759 | ||
|
|
7ae94a27e2 | ||
|
|
d576357f9c | ||
|
|
51bcfc5724 | ||
|
|
6d884898c7 | ||
|
|
8b8905f0c7 | ||
|
|
a212bc8715 | ||
|
|
7f2ae6ac58 | ||
|
|
cb14f1f00f | ||
|
|
fddb5c6772 | ||
|
|
d89bb38688 | ||
|
|
5169d2438f | ||
|
|
595496549b | ||
|
|
100a6d36c5 | ||
|
|
34d80bd994 | ||
|
|
9f43b8c797 | ||
|
|
968d6583ba | ||
|
|
d569a289ba | ||
|
|
56bb999830 | ||
|
|
4885f028be | ||
|
|
96f94770cd | ||
|
|
75f46913b4 |
No files matched your search
@@ -0,0 +1,15 @@
|
||||
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
|
||||
secrets:
|
||||
PYPI_TOKEN: ${{ secrets.PYPI_TOKEN }}
|
||||
+172
@@ -0,0 +1,172 @@
|
||||
# Changelog
|
||||
|
||||
All notable changes to napalm-openwrt. The format follows
|
||||
[Keep a Changelog](https://keepachangelog.com/), versions follow
|
||||
[Semantic Versioning](https://semver.org/). Versions up to 0.6.0 were not
|
||||
recorded here; their history is the git log.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.8.0] - 2026-11-17
|
||||
|
||||
### Changed
|
||||
- Needs napalm-device-types 4.41.0 or later (`FirmwareUpgradeMixin`).
|
||||
- The SNMP agent's firewall step writes its rule through `_allow_in_management_zone`, which
|
||||
the Zabbix agent's step shares; the rule it writes is the same.
|
||||
- `get_available_updates()` raises napalm-device-types' `PackageIndexMissing` when the
|
||||
package index is not in RAM (after a reboot), for apk and opkg alike, instead of a bare
|
||||
`RuntimeError`: a caller can load the index instead of reporting a failed read
|
||||
(NetOrk/netork#2527).
|
||||
- A time sync write no longer sets `use_dhcp=0`, as the first time sync commit (#36) did;
|
||||
a router that commit wrote keeps `use_dhcp=0` until it is set back.
|
||||
|
||||
### Added
|
||||
- Firmware (napalm-device-types `FirmwareOfferMixin`, `FirmwareUpgradeMixin`,
|
||||
NetOrk/netork#2615): `get_firmware_offer()` names the newest release of the device's own
|
||||
release line that the attended sysupgrade server builds for its target (from
|
||||
`/json/v1/overview.json` of the server the device is set to, fetched by the caller at most
|
||||
once a day per server), whether owut can install it (`installable`, from 24.10 on) and the
|
||||
newest later line (`latest_major_version`). `start_firmware_upgrade(version)` runs
|
||||
`owut upgrade --version-to <version>` detached from the session; `get_update_progress()`
|
||||
follows its log until owut hands the image to sysupgrade, which keeps the configuration
|
||||
and restarts the device. A sysupgrade brings every installed package in the new image,
|
||||
which empties the overlay that package upgrades fill.
|
||||
- Zabbix agent (napalm-device-types `ZabbixAgentMixin`, NetOrk/netork#2571):
|
||||
`configure_zabbix_agent(settings)` installs the feed's `zabbix-agentd` after loading the
|
||||
package index, writes the caller's values into `/etc/zabbix_agentd.conf`, enables it in
|
||||
UCI, opens tcp/`listen_port` for the allowed sources where a firewall runs (an access
|
||||
point often runs none), enables and restarts it.
|
||||
- Time sync (napalm-device-types `TimeSyncMixin`, NetOrk/netork#2364): `get_time_sync()`
|
||||
reads the router's NTP servers and its zone from `uci -q show system`;
|
||||
`configure_time_sync()` writes both. The servers replace `system.ntp.server` and enable
|
||||
the client; `sysntpd` restarts. `use_dhcp` stays as the router has it: the servers of
|
||||
a DHCP lease (option 42) count (NetOrk/netork#2380). `dhcp_ntp_servers` names them --
|
||||
what sysntpd adds while `use_dhcp` is on, each interface's `data.ntpserver` in `ubus
|
||||
call network.interface dump` (only the `dhcp_interface` list's where it names any),
|
||||
read in the same round trip; None where netifd gives no answer. The zone is written as
|
||||
its name (`zonename`, in LuCI's spelling) and its POSIX rule (`timezone`, from
|
||||
napalm-device-types' `posix_tz`), then `/etc/init.d/system reload` and a restart of
|
||||
logd apply it -- the rule, not the name, is what libc reads (NetOrk/netork#1849). A
|
||||
value the router already has is not written again and nothing restarts. The zone
|
||||
reads by its name only where the rule in force is that zone's: a router whose rule
|
||||
differs from its `zonename`, or that has a rule only, reads as the one zone with that
|
||||
rule, or as no zone where several share it. `synchronized` is None: BusyBox ntpd keeps
|
||||
no state to read.
|
||||
- `get_host_status()` (napalm-device-types `HostStatusMixin`), over an SSH exec channel:
|
||||
whether the router needs a reboot, how full its filesystems are, and -- with
|
||||
napalm-device-types 4.32 or newer -- whether apk (OpenWrt 25.12) or opkg (before) was
|
||||
left halfway, and which of the two it read (NetOrk/netork#851).
|
||||
- Scheduled jobs (NetOrk/netork#1933, #32), through napalm-device-types'
|
||||
`PosixScheduledJobsMixin`: `get_scheduled_jobs()` reads every crontab in
|
||||
`/etc/crontabs` -- BusyBox crond has no `/etc/crontab`, `cron.d`, run-parts, anacron
|
||||
or systemd -- with the time zone from UCI and each crontab's package from `opkg`;
|
||||
`manage_scheduled_job()` enables, disables or runs one now; `put_scheduled_job()`
|
||||
and `delete_scheduled_job()` write and remove an application's own job as marked
|
||||
lines in the user's crontab. Every write changes only the job's own line, is read
|
||||
back (BusyBox `crontab` exits 0 when it could not write) and leaves cron enabled
|
||||
and restarted. A run is the command as BusyBox crond runs it (`%` is no stdin),
|
||||
bounded by `timeout` where the router has it (OpenWrt 25.x); another user's job
|
||||
runs through `start-stop-daemon -c`, as OpenWrt's BusyBox has no `su`. `@daily` and
|
||||
the other aliases are written as five fields; `@reboot` is refused, as OpenWrt's
|
||||
crond has no special times.
|
||||
- `configure_lldp_agent(interfaces)` (napalm-device-types `LldpAgentMixin`): installs
|
||||
lldpd where it is missing, writes the interfaces given as lldpd's interface list in
|
||||
UCI, enables lldpd at boot and restarts it. A VLAN device (`br-ap.10`) is written as
|
||||
the device under it (`br-ap`). It is the action for the setup the LLDP getters used
|
||||
to do on every poll (#8). Needs napalm-device-types with `LldpAgentMixin`.
|
||||
|
||||
### Changed
|
||||
- `get_ntp_servers()` and `get_ntp_peers()` read over an SSH exec channel, with the same
|
||||
reading as `get_time_sync()`, and name no servers while the NTP client is disabled
|
||||
(`system.ntp.enabled='0'`): sysntpd then starts no ntpd.
|
||||
- The floor on napalm-device-types is 4.35.0, the first release with `TimeSyncMixin`
|
||||
(it was 4.26.0 for `PosixScheduledJobsMixin`, and 4.24.0 for the shared `lldpctl`
|
||||
parser before that).
|
||||
- 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 floor on napalm is 5.1: older releases import `pkg_resources`, which a Python
|
||||
3.12 venv no longer has.
|
||||
- `get_lldp_neighbors()` and `get_lldp_neighbors_detail()` only read. They no longer
|
||||
enable and start a stopped lldpd, and no longer rewrite lldpd's interface list
|
||||
and restart it, which could happen on every poll. A device whose lldpd is stopped
|
||||
now reports no neighbours until lldpd is started, for example with
|
||||
`manage_service("lldpd", "enable")` and `manage_service("lldpd", "start")` (#8).
|
||||
|
||||
### Fixed
|
||||
- `set_hostname()` hands the name to `uci` as one shell word (the `uci()` helper of
|
||||
`uci_steps`, #43, NetOrk/netork#2456). It stood between single quotes of its own, so a name
|
||||
with a single quote ended them and the rest ran as root (`x';reboot;'`).
|
||||
- A replace `commit_config()` and `rollback()` import their config through a `mktemp`
|
||||
file made under umask 077, written, imported and removed in one command (#45,
|
||||
NetOrk/netork#2446). They wrote it as root to a fixed name in /tmp
|
||||
(`/tmp/napalm_candidate.uci`, `/tmp/napalm_rollback.uci`) and imported it with a
|
||||
second command, so a local account could place or swap the file and have its own
|
||||
config committed.
|
||||
- `push_mac_acl()` raises `ValueError` for a mode other than `"off"`, `"whitelist"` and
|
||||
`"blacklist"`, before anything is sent. An unknown mode was written as a deny list
|
||||
(#39).
|
||||
- `push_mac_acl()` and `push_radio_channel()` raise when the router refuses a step
|
||||
(`CommandErrorException`, naming the `uci` command or the wifi restart and what the
|
||||
router said). They used to return normally after a refused `uci set`, `add_list`,
|
||||
`commit` or `wifi reload`, so an ACL that never landed looked applied. Each step runs
|
||||
on an SSH exec channel of its own and as root, with its exit status checked; a
|
||||
refused change reverts what was staged, so nothing of it is committed by a later
|
||||
write, and wifi is not restarted for it. `push_mac_acl()` raises when no wifi-iface
|
||||
carries the SSID, where it did nothing, and deletes `macfilter`/`maclist` only where
|
||||
a section has them instead of hiding every delete's status behind `|| true` (#35).
|
||||
- `get_ntp_servers()` names every server of the `system.ntp.server` list; it kept only
|
||||
the first, as uci prints a list as `'a' 'b' 'c'` on one line.
|
||||
- `get_lldp_neighbors()` and `get_lldp_neighbors_detail()` keep an interface name with
|
||||
a dot whole: the neighbours of a VLAN interface such as `eth0.1` used to come back
|
||||
under `eth0` with every field empty (#26). A neighbour that names its port by MAC
|
||||
address or a local id is reported with that port instead of an empty one, and a
|
||||
chassis named by a local id or an address with that id. The detail now also
|
||||
carries the neighbour's system description and capabilities, which were always
|
||||
empty. lldpd's output is parsed by napalm-device-types' shared parser.
|
||||
- `get_lldp_neighbors()` reports a neighbour's chassis MAC as `mac` (lower case) when
|
||||
the neighbour names its chassis by one, as napalm-linux does, so netOrk can match the
|
||||
neighbour by MAC rather than by name only (#31).
|
||||
- `get_lldp_neighbors()` and `get_lldp_neighbors_detail()` raise when lldpctl fails
|
||||
(not installed, lldpd not running or unreachable), with lldpctl's message; they used
|
||||
to return no neighbours, the same answer as a device without any (#27). An empty
|
||||
result now means lldpctl ran and listed none. `get_environment()` raises when
|
||||
`/proc/stat` or `/proc/meminfo` cannot be read or parsed, instead of reporting 0 %
|
||||
CPU and 0 bytes of memory.
|
||||
- `get_arp_table()` reports an unknown age as `-1.0` (napalm-device-types'
|
||||
`ARP_AGE_UNKNOWN`) instead of `0.0`, which means "confirmed just now": neither
|
||||
`ip neigh` nor `/proc/net/arp` has an age (NetOrk/netork#1327).
|
||||
- The driver no longer removes `port` from the `optional_args` dict it is given:
|
||||
the caller's dict stays as it was (#19).
|
||||
- `manage_service()` reports a failed action or a missing init script as failed:
|
||||
only the init script's exit status decides, where any action used to come back
|
||||
as a success (#3).
|
||||
- `apply_updates()` reports a failed upgrade as failed, with the package manager's
|
||||
exit status in `error`; it used to report every upgrade as done (#11).
|
||||
- `get_environment()` reports the CPU usage of the last second, from two reads of
|
||||
`/proc/stat` one second apart; it used to report the average since boot, so a box
|
||||
busy for the last minute could show a low figure (#10).
|
||||
- `get_lldp_neighbors()` and `get_lldp_neighbors_detail()` report every neighbour
|
||||
on a port (a phone with a PC behind it, a switch without LLDP of its own); only
|
||||
the last one came back, mixed with fields of the others (#9).
|
||||
- `install_package()` and `uninstall_package()` report a failed install or removal
|
||||
as failed: only the package manager's exit status decides. They used to search the
|
||||
output for words like "error:", so an opkg dependency failure ("Collected errors:",
|
||||
"Cannot install package …") came back as a success, and a successful install of a
|
||||
package whose name contains "failed" as a failure (#28).
|
||||
|
||||
## [0.7.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`
|
||||
and a LICENSE file. **Python 3.8 and 3.9 are no longer supported**;
|
||||
napalm-device-types never ran on them.
|
||||
- napalm-device-types 4.21.1 or newer is required.
|
||||
- Exceptions the driver deliberately ignores (the snmpd community in
|
||||
`get_snmp_config()`, the network VLANs in `get_ssids()`) are now logged at debug
|
||||
level.
|
||||
- The project links point at git.netork.io instead of GitHub.
|
||||
@@ -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.
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
NAPALM community driver for **OpenWrt** routers and access-points.
|
||||
|
||||
Communicates over SSH using [Netmiko](https://github.com/ktbyers/netmiko) (`linux` device type).
|
||||
Communicates over SSH using [Netmiko](https://pypi.org/project/netmiko/) (`linux` device type).
|
||||
Requires OpenWrt **19.07** or newer.
|
||||
|
||||
## Tested devices
|
||||
@@ -17,7 +17,7 @@ Requires OpenWrt **19.07** or newer.
|
||||
|
||||
| Dependency | Minimum version |
|
||||
|---|---|
|
||||
| Python | 3.8 |
|
||||
| Python | 3.12 |
|
||||
| NAPALM | 4.0 |
|
||||
| Netmiko | 4.0 |
|
||||
|
||||
@@ -26,7 +26,7 @@ Requires OpenWrt **19.07** or newer.
|
||||
From source:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/napalm-automation-community/napalm-openwrt
|
||||
git clone https://git.netork.io/NAPALM/napalm-openwrt
|
||||
cd napalm-openwrt
|
||||
pip install -e .
|
||||
```
|
||||
@@ -37,7 +37,7 @@ pip install -e .
|
||||
from napalm import get_network_driver
|
||||
|
||||
driver = get_network_driver("openwrt")
|
||||
device = driver("192.168.1.1", "root", "")
|
||||
device = driver("192.0.2.1", "root", "")
|
||||
|
||||
device.open()
|
||||
|
||||
@@ -61,9 +61,17 @@ device.close()
|
||||
| `get_arp_table` | ✅ | Uses `ip neigh show` |
|
||||
| `get_mac_address_table` | ✅ | Uses `bridge fdb show` |
|
||||
| `get_config` | ✅ | Uses `uci export` |
|
||||
| `get_environment` | ✅ | CPU from `/proc/stat`, memory from `/proc/meminfo` |
|
||||
| `get_lldp_neighbors` | ✅ | Requires `lldpd` package installed on device |
|
||||
| `get_lldp_neighbors_detail` | ✅ | Requires `lldpd` package installed on device |
|
||||
| `get_environment` | ✅ | CPU from `/proc/stat`, memory from `/proc/meminfo`; raises when either cannot be read |
|
||||
| `get_lldp_neighbors` | ✅ | Requires `lldpd` installed and running (raises otherwise); reads only, never starts or configures it |
|
||||
| `get_lldp_neighbors_detail` | ✅ | Requires `lldpd` installed and running (raises otherwise); reads only, never starts or configures it |
|
||||
| `get_listening_sockets` | ✅ | busybox `netstat -lntup`, procd service from the process's cgroup (napalm-device-types `ListeningSocketsMixin`); over an SSH exec channel |
|
||||
| `get_host_status` | ✅ | napalm-device-types `HostStatusMixin`: whether the router needs a reboot, how full `/` (the overlay) is, and whether apk or opkg was left halfway (apk: a package with broken files or a broken script; opkg: one left `unpacked`; needs napalm-device-types 4.32); over an SSH exec channel |
|
||||
| `get_scheduled_jobs()` | ✅ | BusyBox crond's `/etc/crontabs/<user>`, time zone from `system.@system[0].zonename`, owner from `opkg search` (napalm-device-types `PosixScheduledJobsMixin`) |
|
||||
| `manage_scheduled_job(key, action, digest=)` | ✅ | enable, disable, run now (bounded by `timeout` where the router has it; another user's job through `start-stop-daemon -c`) |
|
||||
| `put_scheduled_job(spec)` / `delete_scheduled_job(key, digest=)` | ✅ | an application's own job: two marked lines in the user's crontab; `@daily` and the other aliases as five fields, `@reboot` refused (BusyBox crond has no special times) |
|
||||
| `get_ntp_servers` / `get_ntp_peers` | ✅ | `system.ntp.server` in UCI, every server of the list; none while `system.ntp.enabled` is off -- the same list as `get_time_sync()` |
|
||||
| `get_time_sync()` | ✅ | napalm-device-types `TimeSyncMixin`: the servers as above, the zone from `zonename` where the rule in `timezone` is that zone's (else the one zone with that rule, or none); `synchronized` is not readable (None) |
|
||||
| `get_firmware_offer()` | ✅ | napalm-device-types `FirmwareOfferMixin`: the newest release of the device's own line on the attended sysupgrade server (see *Firmware upgrade*) |
|
||||
|
||||
## Configuration management
|
||||
|
||||
@@ -73,10 +81,12 @@ Configuration is managed via [UCI](https://openwrt.org/docs/guide-user/base-syst
|
||||
### Merge candidate
|
||||
|
||||
```python
|
||||
device.load_merge_candidate(config="""
|
||||
device.load_merge_candidate(
|
||||
config="""
|
||||
uci set system.@system[0].hostname='my-router'
|
||||
uci set network.lan.ipaddr='10.0.0.1'
|
||||
""")
|
||||
uci set network.lan.ipaddr='192.0.2.1'
|
||||
"""
|
||||
)
|
||||
|
||||
print(device.compare_config())
|
||||
device.commit_config()
|
||||
@@ -99,6 +109,79 @@ device.commit_config()
|
||||
device.rollback()
|
||||
```
|
||||
|
||||
## LLDP agent
|
||||
|
||||
`configure_lldp_agent(interfaces)` (napalm-device-types `LldpAgentMixin`) installs
|
||||
`lldpd` where it is missing, sets its interface list (`lldpd.config.interface` in UCI)
|
||||
to the interfaces given, enables it at boot and restarts it. A VLAN device such as
|
||||
`br-ap.10` is written as the device under it (`br-ap`): lldpd sends on the L2 device.
|
||||
Which interfaces is the caller's choice; at least one is required.
|
||||
|
||||
## Zabbix agent
|
||||
|
||||
`configure_zabbix_agent(settings)` (napalm-device-types `ZabbixAgentMixin`) runs the
|
||||
feed's C agent, `zabbix-agentd`: it loads the package index (it lives in RAM), installs
|
||||
the package where it is missing, writes `Server`, `ServerActive`, `ListenPort` and
|
||||
`Hostname` into `/etc/zabbix_agentd.conf` (the old file stays as `.bak`), enables the
|
||||
agent in UCI (`zabbix_agentd.general.enabled`, without which the init script does not
|
||||
start it), opens tcp/`listen_port` for the allowed sources in the zone that owns the
|
||||
management address where a firewall runs, then enables and restarts it. Zabbix publishes
|
||||
no repository for OpenWrt; the feed is the only source.
|
||||
|
||||
## Firmware upgrade
|
||||
|
||||
A package upgrade writes the new package to the overlay while the old one stays in the
|
||||
read-only image, so the overlay only fills. A sysupgrade to the next release of the
|
||||
device's own line brings those packages, and every package installed since, in the new
|
||||
image.
|
||||
|
||||
- `get_firmware_offer()` reads `/etc/openwrt_release` and the sysupgrade server the device is
|
||||
set to (`attendedsysupgrade.@server[0].url`, else `https://sysupgrade.openwrt.org`), and
|
||||
looks the release line up in the server's `/json/v1/overview.json`. That file is fetched by
|
||||
the caller, at most once a day per server and process. `latest_version` is the newest
|
||||
release of the device's line (release candidates only where the line has no release),
|
||||
`latest_major_version` the newest later line, `installable` whether owut is installed (left
|
||||
out before 24.10, where owut does not exist). A snapshot, or a target the line does not
|
||||
build, has no offer.
|
||||
- `start_firmware_upgrade(version)` runs `owut upgrade --version-to <version>` as root,
|
||||
detached from the session, with its output in `/tmp/owut-upgrade.log`. It refuses while
|
||||
another upgrade runs or owut is missing.
|
||||
- `get_update_progress()` reads that log: `running`, then `done` once owut hands the image to
|
||||
sysupgrade (which keeps the configuration and restarts the device), or `failed` when owut
|
||||
stopped before that.
|
||||
|
||||
## Wireless writes
|
||||
|
||||
`push_mac_acl(ssid_name, mode, macs)` (napalm-device-types `MacAclMixin`) rewrites the
|
||||
MAC filter of every wifi-iface carrying the SSID and reloads wifi;
|
||||
`push_radio_channel(radio, channel)` sets a radio's channel (`0` is `auto`) and restarts
|
||||
wifi in full. Each `uci` step runs on an SSH exec channel of its own, as root, with its
|
||||
exit status checked: a refused step raises `CommandErrorException` naming it, what was
|
||||
staged is reverted, and nothing is committed or restarted. An SSID no wifi-iface
|
||||
carries raises too.
|
||||
|
||||
## Time sync
|
||||
|
||||
`configure_time_sync(ntp_servers=, timezone=)` (napalm-device-types `TimeSyncMixin`)
|
||||
writes both values into UCI's `system` config and applies them; a value the router
|
||||
already has is not written again, so nothing restarts.
|
||||
|
||||
* The servers replace the `system.ntp.server` list; the client is enabled and
|
||||
`sysntpd` restarts. `use_dhcp` stays as the router has it: the NTP servers of a DHCP
|
||||
lease (option 42) count (NetOrk/netork#2380).
|
||||
|
||||
`get_time_sync()` reads the configured servers and the zone from `uci -q show system`,
|
||||
and in the same round trip the servers a lease brought, as `dhcp_ntp_servers`: what
|
||||
sysntpd adds to ntpd's list while `use_dhcp` is on -- every interface's `data.ntpserver`
|
||||
in `ubus call network.interface dump`, or only the `dhcp_interface` list's. `[]` while
|
||||
`use_dhcp` or the client is off; None where netifd gave no answer.
|
||||
* The zone goes into `zonename` (as LuCI keeps it, with spaces for underscores) and its
|
||||
POSIX rule into `timezone`, the value libc reads -- an IANA name there leaves the
|
||||
router on UTC (NetOrk/netork#1849). `/etc/init.d/system reload` applies it, and logd
|
||||
restarts, as it reads the zone when it starts.
|
||||
|
||||
Writes run as root: OpenWrt has no sudo, so another login is refused before anything runs.
|
||||
|
||||
## Development
|
||||
|
||||
```bash
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# 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
|
||||
@@ -13,6 +12,8 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import shlex
|
||||
|
||||
from napalm.base.exceptions import (
|
||||
CommandErrorException,
|
||||
MergeConfigException,
|
||||
@@ -21,6 +22,22 @@ from napalm.base.exceptions import (
|
||||
from napalm_device_types import ConfigLifecycleMixin
|
||||
|
||||
|
||||
def _uci_import_command(config: str) -> str:
|
||||
"""One shell command that imports *config* with ``uci import`` and commits it.
|
||||
|
||||
The config goes through a ``mktemp`` file made under umask 077 and removed
|
||||
afterwards, never through a fixed name in /tmp: as root, a fixed name let a
|
||||
local account place or swap the file and have its own config committed
|
||||
(#45, NetOrk/netork#2446).
|
||||
"""
|
||||
return (
|
||||
"f=$(umask 077 && mktemp) && { "
|
||||
f"printf '%s' {shlex.quote(config)} > \"$f\" && "
|
||||
'uci import < "$f" && uci commit; '
|
||||
'rm -f "$f"; }'
|
||||
)
|
||||
|
||||
|
||||
class OpenWrtConfigMixin(ConfigLifecycleMixin):
|
||||
"""Mixin providing configuration-management NAPALM methods for OpenWrt.
|
||||
|
||||
@@ -50,7 +67,9 @@ class OpenWrtConfigMixin(ConfigLifecycleMixin):
|
||||
if self._candidate_config is None:
|
||||
raise MergeConfigException("No candidate configuration is staged.")
|
||||
|
||||
ex_cls = ReplaceConfigException if self._candidate_mode == "replace" else MergeConfigException
|
||||
ex_cls = (
|
||||
ReplaceConfigException if self._candidate_mode == "replace" else MergeConfigException
|
||||
)
|
||||
|
||||
self._backup_config = self._send_command("uci export")
|
||||
|
||||
@@ -66,10 +85,7 @@ class OpenWrtConfigMixin(ConfigLifecycleMixin):
|
||||
errors.append(f" {stripped!r}: {out}")
|
||||
self._send_command("uci commit")
|
||||
else:
|
||||
escaped = self._candidate_config.replace("'", "'\\''")
|
||||
self._send_command(f"printf '%s' '{escaped}' > /tmp/napalm_candidate.uci")
|
||||
out = self._send_command("uci import < /tmp/napalm_candidate.uci && uci commit")
|
||||
self._send_command("rm -f /tmp/napalm_candidate.uci")
|
||||
out = self._send_command(_uci_import_command(self._candidate_config))
|
||||
if out and "error" in out.lower():
|
||||
errors.append(out)
|
||||
except Exception as exc:
|
||||
@@ -90,12 +106,10 @@ class OpenWrtConfigMixin(ConfigLifecycleMixin):
|
||||
"""
|
||||
if self._backup_config is None:
|
||||
raise CommandErrorException(
|
||||
"No backup configuration available – commit_config has not been called in this session."
|
||||
"No backup configuration available – "
|
||||
"commit_config has not been called in this session."
|
||||
)
|
||||
|
||||
escaped = self._backup_config.replace("'", "'\\''")
|
||||
self._send_command(f"printf '%s' '{escaped}' > /tmp/napalm_rollback.uci")
|
||||
self._send_command("uci import < /tmp/napalm_rollback.uci && uci commit")
|
||||
self._send_command("rm -f /tmp/napalm_rollback.uci")
|
||||
self._send_command(_uci_import_command(self._backup_config))
|
||||
|
||||
self._backup_config = None
|
||||
@@ -0,0 +1,290 @@
|
||||
# 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.
|
||||
|
||||
"""The firmware OpenWrt's attended sysupgrade server offers, and installing it with owut.
|
||||
|
||||
A package upgrade on OpenWrt writes the whole new package to the overlay, while
|
||||
the old one stays in the read-only image: every upgrade costs flash, and the
|
||||
overlay only fills. A sysupgrade to the next release of the device's own line
|
||||
brings those packages in the new image, together with every package installed
|
||||
since, so the overlay is left with little more than the configuration
|
||||
(NetOrk/netork#2615).
|
||||
|
||||
**The offer** (napalm-device-types ``FirmwareOfferMixin``) comes from the
|
||||
sysupgrade server's ``/json/v1/overview.json``: every release line, its
|
||||
versions and the targets it builds. One file serves every device, so it is
|
||||
fetched by the worker, at most once a day per server and process
|
||||
(:data:`_FRESH_FOR`); a server that did not answer is not asked again for an
|
||||
hour. The server is the one the device is set to
|
||||
(``attendedsysupgrade.@server[0].url``, which owut and LuCI use), or the public
|
||||
one. ``latest_version`` is the newest release of the device's own line
|
||||
(25.12.2 → 25.12.6), release candidates only where the line has no release; a
|
||||
later line is named in ``latest_major_version`` and never offered as the
|
||||
upgrade. A snapshot, or a target the line no longer builds, has no offer.
|
||||
|
||||
**Installing** (``FirmwareUpgradeMixin``) is owut's ``upgrade``: it collects the
|
||||
installed packages, has the server build an image with them, checks it and runs
|
||||
sysupgrade, which keeps the configuration and restarts the device. owut exists
|
||||
from 24.10 on; ``installable`` says whether it is installed, and is left out on
|
||||
an older release. It runs detached from the session, ignoring its hang-up, and
|
||||
writes to :data:`_LOG`; ``get_update_progress`` reads that log. owut prints
|
||||
:data:`_INSTALLING` right before sysupgrade stops every process, the wrapper's
|
||||
status line included, so that line is the upgrade's end.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
import urllib.request
|
||||
from typing import TYPE_CHECKING, Any, Final
|
||||
|
||||
from napalm_device_types import (
|
||||
FirmwareOfferDict,
|
||||
FirmwareOfferMixin,
|
||||
FirmwareUpgradeMixin,
|
||||
UpdateProgressDict,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from napalm_device_types import CommandResult
|
||||
|
||||
#: The public sysupgrade server, owut's default.
|
||||
DEFAULT_SERVER: Final = "https://sysupgrade.openwrt.org"
|
||||
_OVERVIEW_PATH: Final = "/json/v1/overview.json"
|
||||
#: Seconds an answer is used before the server is asked again.
|
||||
_FRESH_FOR: Final = 24 * 3600
|
||||
#: Seconds a failed fetch is remembered, so a server that is down is not asked per device.
|
||||
_RETRY_AFTER: Final = 3600
|
||||
_FETCH_TIMEOUT: Final = 15
|
||||
#: overview.json is about 20 KB; anything far larger is not it.
|
||||
_MAX_BYTES: Final = 2 * 1024 * 1024
|
||||
|
||||
#: Per server URL: (monotonic time fetched, overview or None for a failed fetch).
|
||||
_OVERVIEWS: dict[str, tuple[float, dict[str, Any] | None]] = {}
|
||||
|
||||
# On the device, not here: its /tmp is RAM, where owut keeps its image too.
|
||||
_LOG: Final = "/tmp/owut-upgrade.log" # nosec B108
|
||||
_PID: Final = "/tmp/owut-upgrade.pid" # nosec B108
|
||||
_STATUS: Final = "__OWUT_RC="
|
||||
_STATUS_RE: Final = re.compile(rf"^{_STATUS}(\d+)\s*$", re.MULTILINE)
|
||||
#: What owut prints right before it hands the image to sysupgrade.
|
||||
_INSTALLING: Final = re.compile(r"^Installing \S+ and rebooting", re.MULTILINE)
|
||||
#: A release, or a release candidate: 25.12.6, 25.12.0-rc5.
|
||||
_VERSION: Final = re.compile(r"^(\d+)\.(\d+)\.(\d+)(?:-rc(\d+))?$")
|
||||
#: The first release line owut exists for.
|
||||
_OWUT_SINCE: Final = (24, 10)
|
||||
|
||||
#: One round trip as the login user: the release, the server it is set to, owut.
|
||||
_READ_DEVICE: Final = (
|
||||
"cat /etc/openwrt_release; "
|
||||
'echo "__ASU_URL=$(uci -q get attendedsysupgrade.@server[0].url)"; '
|
||||
"command -v owut >/dev/null 2>&1 && echo __OWUT=1; :"
|
||||
)
|
||||
_LOG_COMMAND: Final = f"cat {_LOG}"
|
||||
|
||||
|
||||
def _start_command(version: str) -> str:
|
||||
"""owut's upgrade, detached and deaf to the session's hang-up; refused while one runs."""
|
||||
return (
|
||||
f'if [ -f {_PID} ] && kill -0 "$(cat {_PID})" 2>/dev/null; then '
|
||||
"echo 'an upgrade is already running' >&2; exit 3; fi; "
|
||||
"command -v owut >/dev/null 2>&1 || { echo 'owut is not installed' >&2; exit 4; }; "
|
||||
f"rm -f {_LOG}; "
|
||||
f'sh -c \'echo $$ > {_PID}; trap "" HUP; owut upgrade --version-to {version}; '
|
||||
f"echo {_STATUS}$?' </dev/null >{_LOG} 2>&1 &"
|
||||
)
|
||||
|
||||
|
||||
def _version_key(version: str) -> tuple[int, int, int, float] | None:
|
||||
"""Sortable: a release candidate before its release; None for anything else."""
|
||||
match = _VERSION.match(version)
|
||||
if match is None:
|
||||
return None
|
||||
major, minor, patch, rc = match.groups()
|
||||
return int(major), int(minor), int(patch), float(rc) if rc else float("inf")
|
||||
|
||||
|
||||
def _line_of(version: str) -> str:
|
||||
"""``25.12`` of ``25.12.2``: the release line, as the server names it."""
|
||||
return ".".join(version.split(".")[:2])
|
||||
|
||||
|
||||
def _newest(versions: list[str]) -> str | None:
|
||||
"""The newest release; a release candidate only where the line has no release."""
|
||||
keyed = [(key, v) for v in versions if (key := _version_key(v)) is not None]
|
||||
releases = [(key, v) for key, v in keyed if key[3] == float("inf")]
|
||||
pool = releases or keyed
|
||||
return max(pool)[1] if pool else None
|
||||
|
||||
|
||||
def _builds(branch: dict[str, Any], target: str) -> bool:
|
||||
return (
|
||||
bool(branch.get("enabled"))
|
||||
and not branch.get("snapshot")
|
||||
and target in (branch.get("targets") or [])
|
||||
)
|
||||
|
||||
|
||||
def _fetch_json(url: str) -> dict[str, Any]:
|
||||
"""GET *url* as JSON; raises on any failure."""
|
||||
request = urllib.request.Request(url, headers={"User-Agent": "napalm-openwrt"})
|
||||
# http(s) only: _server_url gives nothing else.
|
||||
with urllib.request.urlopen(request, timeout=_FETCH_TIMEOUT) as response: # noqa: S310 # nosec B310
|
||||
data = json.loads(response.read(_MAX_BYTES))
|
||||
if not isinstance(data, dict):
|
||||
raise ValueError("overview.json is not an object")
|
||||
return data
|
||||
|
||||
|
||||
def _overview(server: str) -> dict[str, Any] | None:
|
||||
"""The server's overview, from the cache while it is fresh; None when it did not answer."""
|
||||
url = server + _OVERVIEW_PATH
|
||||
now = time.monotonic()
|
||||
cached = _OVERVIEWS.get(url)
|
||||
if cached is not None:
|
||||
fetched_at, data = cached
|
||||
if now - fetched_at < (_FRESH_FOR if data is not None else _RETRY_AFTER):
|
||||
return data
|
||||
fetched: dict[str, Any] | None
|
||||
try:
|
||||
fetched = _fetch_json(url)
|
||||
except Exception:
|
||||
fetched = None
|
||||
_OVERVIEWS[url] = (now, fetched)
|
||||
return fetched
|
||||
|
||||
|
||||
def _server_url(configured: str) -> str:
|
||||
"""The server the device is set to, if it is an http(s) URL; else the public one."""
|
||||
url = configured.strip().rstrip("/")
|
||||
return url if re.match(r"^https?://[^\s/]+", url) else DEFAULT_SERVER
|
||||
|
||||
|
||||
def _later_line(overview: dict[str, Any], line: str, target: str) -> str | None:
|
||||
"""The newest release of the newest later line that builds *target*."""
|
||||
current = _version_key(line + ".0")
|
||||
if current is None:
|
||||
return None
|
||||
later = [
|
||||
(key, str(name))
|
||||
for name in overview.get("branches") or {}
|
||||
if (key := _version_key(f"{name}.0")) is not None and key[:2] > current[:2]
|
||||
]
|
||||
for _key, name in sorted(later, reverse=True):
|
||||
newest = _latest_of_line(overview, name, target)
|
||||
if newest is not None:
|
||||
return newest
|
||||
return None
|
||||
|
||||
|
||||
def _latest_of_line(overview: dict[str, Any], line: str, target: str) -> str | None:
|
||||
"""The newest release of *line*, if the line builds *target*."""
|
||||
branch = (overview.get("branches") or {}).get(line)
|
||||
if not isinstance(branch, dict) or not _builds(branch, target):
|
||||
return None
|
||||
return _newest(list(branch.get("versions") or []))
|
||||
|
||||
|
||||
def _offer(
|
||||
overview: dict[str, Any], current: str, target: str, owut: bool
|
||||
) -> FirmwareOfferDict | None:
|
||||
"""The offer for a device on release *current* (a release, see ``_VERSION``)."""
|
||||
line = _line_of(current)
|
||||
latest = _latest_of_line(overview, line, target)
|
||||
key, latest_key = _version_key(current), _version_key(latest or "")
|
||||
if key is None or latest is None or latest_key is None:
|
||||
return None
|
||||
offer: FirmwareOfferDict = {
|
||||
"current_version": current,
|
||||
"latest_version": latest,
|
||||
"newer": latest_key > key,
|
||||
}
|
||||
if key[:2] >= _OWUT_SINCE:
|
||||
offer["installable"] = owut
|
||||
later = _later_line(overview, line, target)
|
||||
if later is not None:
|
||||
offer["latest_major_version"] = later
|
||||
return offer
|
||||
|
||||
|
||||
class OpenWrtFirmwareMixin(FirmwareOfferMixin, FirmwareUpgradeMixin):
|
||||
"""``get_firmware_offer``, ``start_firmware_upgrade`` and ``get_update_progress``."""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - the driver's
|
||||
|
||||
def run_command(
|
||||
self,
|
||||
command: str,
|
||||
*,
|
||||
privileged: bool = False,
|
||||
timeout: float = 60,
|
||||
stdin: bytes | None = None,
|
||||
) -> CommandResult: ...
|
||||
|
||||
@staticmethod
|
||||
def _parse_openwrt_release(output: str) -> dict[str, str]: ...
|
||||
|
||||
def _read_firmware_facts(self) -> tuple[dict[str, str], str, bool]:
|
||||
out = self.run_command(_READ_DEVICE).stdout
|
||||
configured = next(
|
||||
(ln.split("=", 1)[1] for ln in out.splitlines() if ln.startswith("__ASU_URL=")), ""
|
||||
)
|
||||
owut = any(ln.strip() == "__OWUT=1" for ln in out.splitlines())
|
||||
return self._parse_openwrt_release(out), _server_url(configured), owut
|
||||
|
||||
def get_firmware_offer(self) -> FirmwareOfferDict | None:
|
||||
"""The release running and the newest of its line the sysupgrade server builds.
|
||||
|
||||
None for a snapshot, a target the line does not build, or a server that
|
||||
did not answer.
|
||||
"""
|
||||
release, server, owut = self._read_firmware_facts()
|
||||
current = release.get("DISTRIB_RELEASE", "")
|
||||
target = release.get("DISTRIB_TARGET", "")
|
||||
if _version_key(current) is None or not target:
|
||||
return None
|
||||
overview = _overview(server)
|
||||
if overview is None:
|
||||
return None
|
||||
return _offer(overview, current, target, owut)
|
||||
|
||||
def start_firmware_upgrade(self, version: str) -> None:
|
||||
"""Start owut's upgrade to *version*; the device restarts at its end.
|
||||
|
||||
:raises ValueError: *version* is not a release (``25.12.6``, ``25.12.0-rc5``).
|
||||
:raises RuntimeError: a login other than root, owut missing, an upgrade running.
|
||||
"""
|
||||
if _version_key(version) is None:
|
||||
raise ValueError(f"Not an OpenWrt release: {version!r}")
|
||||
try:
|
||||
result = self.run_command(_start_command(version), privileged=True, timeout=30)
|
||||
except PermissionError as exc:
|
||||
raise RuntimeError(str(exc)) from exc
|
||||
if result.exit_code:
|
||||
reason = result.stderr.strip() or result.stdout.strip()
|
||||
raise RuntimeError(reason or f"owut did not start (exit status {result.exit_code})")
|
||||
|
||||
def get_update_progress(self) -> UpdateProgressDict:
|
||||
"""Where owut's upgrade stands, from its log (``UpdateMixin.get_update_progress``)."""
|
||||
result = self.run_command(_LOG_COMMAND)
|
||||
if result.exit_code:
|
||||
return {"state": "idle", "log": ""}
|
||||
text = result.stdout
|
||||
statuses = _STATUS_RE.findall(text)
|
||||
log = _STATUS_RE.sub("", text).strip()
|
||||
if _INSTALLING.search(text):
|
||||
return {"state": "done", "log": log}
|
||||
if statuses:
|
||||
return {"state": "failed", "log": log}
|
||||
return {"state": "running", "log": log}
|
||||
@@ -1,4 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# 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
|
||||
@@ -33,9 +32,8 @@ class OpenWrtInterfaceMixin:
|
||||
m = re.match(r"^\d+:\s+(\S+?)[@:]", line)
|
||||
if m:
|
||||
name = m.group(1)
|
||||
if (
|
||||
name not in self._EXCLUDED_INTERFACES
|
||||
and not name.startswith(self._EXCLUDED_INTERFACE_PREFIXES)
|
||||
if name not in self._EXCLUDED_INTERFACES and not name.startswith(
|
||||
self._EXCLUDED_INTERFACE_PREFIXES
|
||||
):
|
||||
interfaces.append(name)
|
||||
return sorted(set(interfaces))
|
||||
@@ -97,7 +95,7 @@ class OpenWrtInterfaceMixin:
|
||||
Example output::
|
||||
|
||||
2: eth0: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 ...
|
||||
inet 192.168.1.1/24 brd 192.168.1.255 scope global eth0
|
||||
inet 192.0.2.1/24 brd 192.0.2.255 scope global eth0
|
||||
inet6 fd00::1/64 scope global
|
||||
"""
|
||||
output = self._send_command("ip addr show")
|
||||
@@ -194,8 +192,8 @@ class OpenWrtInterfaceMixin:
|
||||
|
||||
Uses ``ip neigh show`` (preferred) which produces::
|
||||
|
||||
192.168.1.100 dev br-lan lladdr aa:bb:cc:dd:ee:ff REACHABLE
|
||||
192.168.1.1 dev br-lan lladdr 00:11:22:33:44:55 STALE
|
||||
192.0.2.100 dev br-lan lladdr aa:bb:cc:dd:ee:ff REACHABLE
|
||||
192.0.2.1 dev br-lan lladdr 00:11:22:33:44:55 STALE
|
||||
"""
|
||||
output = self._send_command(["ip neigh show", "cat /proc/net/arp"])
|
||||
arp_table = []
|
||||
@@ -210,7 +208,7 @@ class OpenWrtInterfaceMixin:
|
||||
if "FAILED" in line_s or "INCOMPLETE" in line_s:
|
||||
continue
|
||||
|
||||
# ip neigh show: "192.168.1.100 dev br-lan lladdr aa:bb:cc:dd:ee:ff REACHABLE"
|
||||
# ip neigh show: "192.0.2.100 dev br-lan lladdr aa:bb:cc:dd:ee:ff REACHABLE"
|
||||
m = re.match(
|
||||
r"^(\S+)\s+dev\s+(\S+)\s+lladdr\s+(\S+)",
|
||||
line_s,
|
||||
@@ -236,7 +234,7 @@ class OpenWrtInterfaceMixin:
|
||||
"interface": interface,
|
||||
"mac": mac_addr,
|
||||
"ip": ip_addr,
|
||||
"age": 0.0,
|
||||
"age": -1.0, # no age reported: unknown, never 0.0 ("just now")
|
||||
}
|
||||
)
|
||||
continue
|
||||
@@ -269,7 +267,7 @@ class OpenWrtInterfaceMixin:
|
||||
"interface": interface,
|
||||
"mac": mac_addr,
|
||||
"ip": ip_addr,
|
||||
"age": 0.0,
|
||||
"age": -1.0, # no age reported: unknown, never 0.0 ("just now")
|
||||
}
|
||||
)
|
||||
|
||||
@@ -368,12 +366,14 @@ class OpenWrtInterfaceMixin:
|
||||
except Exception:
|
||||
mac_addr = mac_raw
|
||||
|
||||
table.append({
|
||||
"interface": interface,
|
||||
"mac": mac_addr,
|
||||
"ip": ip_addr,
|
||||
"age": -1.0,
|
||||
"state": state,
|
||||
})
|
||||
table.append(
|
||||
{
|
||||
"interface": interface,
|
||||
"mac": mac_addr,
|
||||
"ip": ip_addr,
|
||||
"age": -1.0,
|
||||
"state": state,
|
||||
}
|
||||
)
|
||||
|
||||
return table
|
||||
@@ -0,0 +1,70 @@
|
||||
# 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.
|
||||
|
||||
"""lldpd's interface list in UCI, the step of napalm-device-types' ``LldpAgentMixin``.
|
||||
|
||||
The template installs lldpd (``ensure_package``) and enables and restarts it
|
||||
(``manage_service``); this writes ``lldpd.config.interface``, which lldpd's init
|
||||
script turns into ``-I``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from collections.abc import Sequence
|
||||
from typing import TYPE_CHECKING, Any, cast
|
||||
|
||||
from napalm_device_types import FixStepOutcomeDict, LldpAgentMixin
|
||||
|
||||
#: An interface name that may stand in single quotes in a shell line.
|
||||
_IFNAME = re.compile(r"^[A-Za-z0-9_.@-]+$")
|
||||
#: An 802.1Q device as OpenWrt names it: the device under it, a dot, the VLAN id.
|
||||
_VLAN_DEVICE = re.compile(r"^(?P<parent>.+)\.\d+$")
|
||||
_UCI_LIST = "lldpd.config.interface"
|
||||
|
||||
|
||||
def lldp_devices(interfaces: Sequence[str]) -> list[str]:
|
||||
"""The devices lldpd runs on for *interfaces*, in order and once each.
|
||||
|
||||
lldpd sends on the L2 device, so a VLAN device (``br-ap.10``) counts as the
|
||||
device under it (``br-ap``).
|
||||
|
||||
:raises ValueError: for a name that is not an interface name.
|
||||
"""
|
||||
devices: list[str] = []
|
||||
for name in interfaces:
|
||||
if not _IFNAME.match(name):
|
||||
raise ValueError(f"not an interface name: {name!r}")
|
||||
vlan = _VLAN_DEVICE.match(name)
|
||||
device = vlan.group("parent") if vlan else name
|
||||
if device not in devices:
|
||||
devices.append(device)
|
||||
return devices
|
||||
|
||||
|
||||
class OpenWrtLldpAgentMixin(LldpAgentMixin):
|
||||
"""lldpd on the interfaces the caller names, through UCI."""
|
||||
|
||||
def _write_lldp_agent_config(self, interfaces: list[str]) -> FixStepOutcomeDict:
|
||||
devices = lldp_devices(interfaces)
|
||||
commands = [
|
||||
"(uci -q get lldpd.config >/dev/null || uci set lldpd.config=lldpd)",
|
||||
f"(uci -q delete {_UCI_LIST} || true)",
|
||||
*(f"uci add_list {_UCI_LIST}='{device}'" for device in devices),
|
||||
"uci commit lldpd",
|
||||
]
|
||||
done = f"lldpd runs on {', '.join(devices)}"
|
||||
return cast(FixStepOutcomeDict, self._rc_step(" && ".join(commands), done))
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - the driver's
|
||||
|
||||
def _rc_step(self, command: str, done: str) -> dict[str, Any]: ...
|
||||
@@ -1,4 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# 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
|
||||
@@ -13,119 +12,52 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from napalm.base.models import LLDPNeighborDetailDict
|
||||
from napalm_device_types import (
|
||||
LLDPCTL_KEYVALUE_COMMAND,
|
||||
LldpNeighborDict,
|
||||
LldpNeighborRow,
|
||||
lldp_neighbors,
|
||||
lldp_neighbors_detail,
|
||||
parse_lldpctl_keyvalue,
|
||||
)
|
||||
|
||||
|
||||
class OpenWrtLLDPMixin:
|
||||
"""Mixin providing LLDP NAPALM getters."""
|
||||
|
||||
def get_lldp_neighbors(self) -> dict[str, list[dict[str, Any]]]:
|
||||
"""Return LLDP neighbors (requires ``lldpd`` to be installed on the device).
|
||||
def get_lldp_neighbors(self) -> dict[str, list[LldpNeighborDict]]:
|
||||
"""Return LLDP neighbors (requires ``lldpd`` installed and running on the device).
|
||||
|
||||
A neighbour that names its chassis by a MAC address carries it as ``mac``.
|
||||
|
||||
Uses ``lldpctl -f keyvalue`` output::
|
||||
|
||||
lldp.eth0.port.ifname=eth1
|
||||
lldp.eth0.chassis.name=router-core
|
||||
"""
|
||||
neighbors: dict[str, list[dict[str, Any]]] = {}
|
||||
for row in self._get_lldp_table():
|
||||
neighbors.setdefault(row["local_port"], []).append(
|
||||
{"hostname": row["system_name"], "port": row["port_id"]}
|
||||
)
|
||||
return neighbors
|
||||
return lldp_neighbors(self._get_lldp_table())
|
||||
|
||||
def _lldpd_fix_interface(self) -> None:
|
||||
"""Ensure lldpd UCI config uses the actual management interface.
|
||||
def _get_lldp_table(self) -> list[LldpNeighborRow]:
|
||||
"""``lldpctl -f keyvalue`` as one row per neighbour.
|
||||
|
||||
Detects the interface carrying the default route (e.g. br-lan.10 on a
|
||||
VLAN trunk) and replaces any stale/wrong interface entry in the lldpd
|
||||
UCI config. Idempotent — only writes if the config needs updating.
|
||||
Reads only: lldpd is neither started nor reconfigured here. Installing,
|
||||
starting and configuring it are the caller's (``ensure_package``,
|
||||
``manage_service``).
|
||||
|
||||
:raises ValueError: when lldpctl failed (not installed, lldpd not
|
||||
running): that is no answer, not a port without neighbours.
|
||||
"""
|
||||
mgmt_iface = self._send_command(
|
||||
"ip route show default 2>/dev/null | head -1 | grep -oE 'dev [^ ]+' | awk '{print $2}'"
|
||||
).strip()
|
||||
if not mgmt_iface:
|
||||
mgmt_iface = "br-lan"
|
||||
# LLDP is a L2 protocol — it must run on the bridge, not a VLAN subinterface.
|
||||
# Strip .VID suffix so br-ap.10 → br-ap.
|
||||
if "." in mgmt_iface:
|
||||
mgmt_iface = mgmt_iface.rsplit(".", 1)[0]
|
||||
return parse_lldpctl_keyvalue(self._send_command(LLDPCTL_KEYVALUE_COMMAND))
|
||||
|
||||
current = self._send_command("uci get lldpd.config.interface 2>/dev/null").strip()
|
||||
if mgmt_iface in current:
|
||||
return # already correct
|
||||
|
||||
# Reset the interface list to just the management interface
|
||||
self._send_command(
|
||||
"uci delete lldpd.config.interface 2>/dev/null; "
|
||||
f"uci add_list lldpd.config.interface='{mgmt_iface}' 2>/dev/null; "
|
||||
"uci commit lldpd 2>/dev/null; "
|
||||
"/etc/init.d/lldpd restart 2>/dev/null"
|
||||
)
|
||||
|
||||
def _get_lldp_table(self) -> list[dict[str, Any]]:
|
||||
"""Parse ``lldpctl -f keyvalue`` into a list of row dicts.
|
||||
|
||||
Ensures ``lldpd`` is enabled and running before querying; if it was
|
||||
not already running the daemon needs time to discover neighbors so
|
||||
the first call after a fresh install will return an empty list.
|
||||
"""
|
||||
# Ensure lldpd is running on the correct management interface
|
||||
self._send_command(
|
||||
"pgrep lldpd >/dev/null 2>&1 || "
|
||||
"(/etc/init.d/lldpd enable 2>/dev/null; /etc/init.d/lldpd start 2>/dev/null)"
|
||||
)
|
||||
self._lldpd_fix_interface()
|
||||
output = self._send_command("lldpctl -f keyvalue")
|
||||
rows: list[dict[str, Any]] = []
|
||||
|
||||
# Group by local interface prefix: lldp.<iface>.*
|
||||
entries: dict[str, dict[str, str]] = {}
|
||||
for line in output.splitlines():
|
||||
line_s = line.strip()
|
||||
if "=" not in line_s:
|
||||
continue
|
||||
key, _, value = line_s.partition("=")
|
||||
parts = key.split(".")
|
||||
# parts: ['lldp', '<iface>', <category>, <field>, ...]
|
||||
if len(parts) < 3 or parts[0] != "lldp":
|
||||
continue
|
||||
iface = parts[1]
|
||||
subkey = ".".join(parts[2:])
|
||||
entries.setdefault(iface, {})[subkey] = value
|
||||
|
||||
for iface, data in entries.items():
|
||||
rows.append(
|
||||
{
|
||||
"local_port": iface,
|
||||
"remote_chassis_id": data.get("chassis.mac", data.get("chassis.id.value", "")),
|
||||
"port_id": data.get("port.ifname", data.get("port.id.value", "")),
|
||||
"mgmt_address": data.get("chassis.mgmt-ip", ""),
|
||||
"port_description": data.get("port.descr", ""),
|
||||
"system_name": data.get("chassis.name", ""),
|
||||
}
|
||||
)
|
||||
|
||||
return rows
|
||||
|
||||
def get_lldp_neighbors_detail(self, interface: str = "") -> dict[str, list[dict[str, Any]]]:
|
||||
def get_lldp_neighbors_detail(
|
||||
self, interface: str = ""
|
||||
) -> dict[str, list[LLDPNeighborDetailDict]]:
|
||||
"""Return detailed LLDP neighbor info."""
|
||||
details: dict[str, list[dict[str, Any]]] = {}
|
||||
return lldp_neighbors_detail(self._get_lldp_table(), interface)
|
||||
|
||||
for row in self._get_lldp_table():
|
||||
if interface and row["local_port"] != interface:
|
||||
continue
|
||||
details.setdefault(row["local_port"], []).append(
|
||||
{
|
||||
"parent_interface": "",
|
||||
"remote_port": row["port_id"],
|
||||
"remote_port_description": row["port_description"],
|
||||
"remote_chassis_id": row["remote_chassis_id"],
|
||||
"remote_system_name": row["system_name"],
|
||||
"remote_system_description": "",
|
||||
"remote_system_capab": [],
|
||||
"remote_system_enable_capab": [],
|
||||
}
|
||||
)
|
||||
if TYPE_CHECKING: # pragma: no cover - the driver's
|
||||
|
||||
return details
|
||||
def _send_command(self, command: str | list[str]) -> str: ...
|
||||
+336
-206
@@ -1,4 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# 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
|
||||
@@ -19,28 +18,59 @@ Netmiko device_type: ``linux``
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
import re
|
||||
import socket
|
||||
from typing import Any
|
||||
|
||||
from netmiko import ConnectHandler
|
||||
from netmiko.exceptions import NetmikoTimeoutException, NetmikoAuthenticationException
|
||||
|
||||
from napalm_device_types import AccessPointDriver, FingerprintRule
|
||||
from napalm.base.exceptions import (
|
||||
ConnectionException,
|
||||
ConnectionClosedException,
|
||||
ConnectionException,
|
||||
)
|
||||
from napalm.base.netmiko_helpers import netmiko_args
|
||||
from napalm_device_types import (
|
||||
AccessPointDriver,
|
||||
ByteStream,
|
||||
CommandResult,
|
||||
EnsurePackageMixin,
|
||||
FingerprintRule,
|
||||
SnmpAgentMixin,
|
||||
)
|
||||
from napalm_device_types.channel import open_stream_on_transport, run_on_transport
|
||||
from napalm_device_types.host_status import HostStatusMixin
|
||||
from napalm_device_types.listening import ListeningSocketsMixin
|
||||
from napalm_device_types.ssh_host_keys import HostKeyCheck, SshHostKeyMismatch
|
||||
from netmiko import ConnectHandler
|
||||
from netmiko.exceptions import NetmikoAuthenticationException, NetmikoTimeoutException
|
||||
|
||||
from napalm_openwrt.interfaces_mixin import OpenWrtInterfaceMixin
|
||||
from napalm_openwrt.wireless_mixin import OpenWrtWirelessMixin
|
||||
from napalm_openwrt.lldp_mixin import OpenWrtLLDPMixin
|
||||
from napalm_openwrt.vlan_mixin import OpenWrtVLANMixin
|
||||
from napalm_openwrt.config_mixin import OpenWrtConfigMixin
|
||||
from napalm_openwrt.system_mixin import OpenWrtSystemMixin
|
||||
from napalm_openwrt.firmware_mixin import OpenWrtFirmwareMixin
|
||||
from napalm_openwrt.interfaces_mixin import OpenWrtInterfaceMixin
|
||||
from napalm_openwrt.lldp_agent import OpenWrtLldpAgentMixin
|
||||
from napalm_openwrt.lldp_mixin import OpenWrtLLDPMixin
|
||||
from napalm_openwrt.packages_mixin import OpenWrtPackageMixin
|
||||
from napalm_openwrt.routing_mixin import OpenWrtRoutingMixin
|
||||
from napalm_openwrt.scheduled_jobs_mixin import OpenWrtScheduledJobsMixin
|
||||
from napalm_openwrt.system_mixin import _RC_MARKER, OpenWrtSystemMixin, _split_status
|
||||
from napalm_openwrt.time_sync_mixin import OpenWrtTimeSyncMixin
|
||||
from napalm_openwrt.vlan_mixin import OpenWrtVLANMixin
|
||||
from napalm_openwrt.wireless_mixin import OpenWrtWirelessMixin
|
||||
from napalm_openwrt.zabbix_agent import OpenWrtZabbixAgentMixin
|
||||
|
||||
#: What may stand in a UCI value written in single quotes: no whitespace, quote or #.
|
||||
_SNMP_WORD = re.compile(r"^[^\s'\"#]+$")
|
||||
|
||||
|
||||
def _sources(settings: dict) -> list[str]:
|
||||
"""The allowed sources as networks, or ValueError."""
|
||||
return [
|
||||
str(ipaddress.ip_network(x.strip(), strict=False))
|
||||
for x in settings.get("allowed_sources", [])
|
||||
]
|
||||
|
||||
|
||||
#: ``reboot`` detached from the session and two seconds late: the answer comes
|
||||
#: back first, and a hang-up from the closing session does not stop it.
|
||||
_REBOOT_DETACHED = "sh -c '(trap \"\" HUP; sleep 2; reboot) </dev/null >/dev/null 2>&1 &'"
|
||||
|
||||
|
||||
class OpenWrtDriver(
|
||||
@@ -49,9 +79,18 @@ class OpenWrtDriver(
|
||||
OpenWrtWirelessMixin,
|
||||
OpenWrtLLDPMixin,
|
||||
OpenWrtConfigMixin,
|
||||
OpenWrtTimeSyncMixin,
|
||||
OpenWrtSystemMixin,
|
||||
OpenWrtPackageMixin,
|
||||
OpenWrtRoutingMixin,
|
||||
OpenWrtScheduledJobsMixin,
|
||||
OpenWrtFirmwareMixin,
|
||||
ListeningSocketsMixin,
|
||||
HostStatusMixin,
|
||||
SnmpAgentMixin,
|
||||
OpenWrtLldpAgentMixin,
|
||||
OpenWrtZabbixAgentMixin,
|
||||
EnsurePackageMixin,
|
||||
AccessPointDriver,
|
||||
):
|
||||
"""NAPALM driver for OpenWrt routers and access-points."""
|
||||
@@ -82,11 +121,13 @@ class OpenWrtDriver(
|
||||
self.timeout = timeout
|
||||
self.device: ConnectHandler | None = None
|
||||
|
||||
if optional_args is None:
|
||||
optional_args = {}
|
||||
# A copy: the caller's dict stays as it was.
|
||||
optional_args = dict(optional_args or {})
|
||||
|
||||
self.port = optional_args.pop("port", 22)
|
||||
self.netmiko_optional_args = netmiko_args(optional_args)
|
||||
# The host key to expect, and where the one seen is reported (netork#1167).
|
||||
self._host_key = HostKeyCheck(optional_args, hostname, self.port)
|
||||
|
||||
# Config management state
|
||||
self._candidate_config: str | None = None
|
||||
@@ -100,23 +141,23 @@ class OpenWrtDriver(
|
||||
def open(self) -> None:
|
||||
"""Open an SSH connection to the device."""
|
||||
try:
|
||||
self.device = ConnectHandler(
|
||||
device_type=self.NETMIKO_DEVICE_TYPE,
|
||||
host=self.hostname,
|
||||
username=self.username,
|
||||
password=self.password,
|
||||
timeout=self.timeout,
|
||||
port=self.port,
|
||||
**self.netmiko_optional_args,
|
||||
)
|
||||
with self._host_key.netmiko(self.netmiko_optional_args) as netmiko_kwargs:
|
||||
self.device = ConnectHandler(
|
||||
device_type=self.NETMIKO_DEVICE_TYPE,
|
||||
host=self.hostname,
|
||||
username=self.username,
|
||||
password=self.password,
|
||||
timeout=self.timeout,
|
||||
port=self.port,
|
||||
**netmiko_kwargs,
|
||||
)
|
||||
except SshHostKeyMismatch:
|
||||
raise # refused before the login; nothing was sent
|
||||
except NetmikoTimeoutException as exc:
|
||||
raise ConnectionException(
|
||||
f"Cannot connect to {self.hostname}: {exc}"
|
||||
) from exc
|
||||
raise ConnectionException(f"Cannot connect to {self.hostname}: {exc}") from exc
|
||||
except NetmikoAuthenticationException as exc:
|
||||
raise ConnectionException(
|
||||
f"Authentication failed for {self.hostname}: {exc}"
|
||||
) from exc
|
||||
raise ConnectionException(f"Authentication failed for {self.hostname}: {exc}") from exc
|
||||
self._host_key.observe(self.device.remote_conn_pre.get_transport())
|
||||
|
||||
def close(self) -> None:
|
||||
"""Close the SSH connection."""
|
||||
@@ -130,7 +171,7 @@ class OpenWrtDriver(
|
||||
return {"is_alive": False}
|
||||
try:
|
||||
return {"is_alive": self.device.remote_conn.transport.is_active()}
|
||||
except (socket.error, EOFError, AttributeError):
|
||||
except (OSError, EOFError, AttributeError):
|
||||
return {"is_alive": False}
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
@@ -143,6 +184,7 @@ class OpenWrtDriver(
|
||||
When a list is supplied, commands are tried in order and the first
|
||||
one that does not return an error indicator is returned.
|
||||
"""
|
||||
|
||||
def _do_send(cmd: str) -> str:
|
||||
return self.device.send_command(
|
||||
cmd,
|
||||
@@ -158,9 +200,86 @@ class OpenWrtDriver(
|
||||
return output
|
||||
return output
|
||||
return _do_send(command)
|
||||
except (socket.error, EOFError) as exc:
|
||||
except (OSError, EOFError) as exc:
|
||||
raise ConnectionClosedException(str(exc)) from exc
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Command channel (napalm-device-types CommandChannelMixin, via AccessPointDriver)
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def _transport(self) -> Any:
|
||||
"""The SSH transport netmiko already holds, for exec channels next to its shell."""
|
||||
if self.device is None:
|
||||
raise ConnectionClosedException("Not connected")
|
||||
return self.device.remote_conn_pre.get_transport()
|
||||
|
||||
def _check_privilege(self, privileged: bool) -> None:
|
||||
if privileged and self.username != "root":
|
||||
raise PermissionError(
|
||||
f"{self.hostname}: OpenWrt has no sudo; {self.username!r} cannot run as root"
|
||||
)
|
||||
|
||||
def run_command(
|
||||
self,
|
||||
command: str,
|
||||
*,
|
||||
privileged: bool = False,
|
||||
timeout: float = 60,
|
||||
stdin: bytes | None = None,
|
||||
) -> CommandResult:
|
||||
"""Run *command* on an SSH exec channel: no PTY, stderr apart, a real exit code.
|
||||
|
||||
The login is root on OpenWrt as a rule, and there is no sudo: a
|
||||
privileged command from any other login is refused before it runs.
|
||||
"""
|
||||
self._check_privilege(privileged)
|
||||
return run_on_transport(self._transport(), command, stdin=stdin, timeout=timeout)
|
||||
|
||||
def open_stream(self, command: str, *, privileged: bool = False) -> ByteStream:
|
||||
"""Start *command* on an SSH exec channel and return a stream to it."""
|
||||
self._check_privilege(privileged)
|
||||
return open_stream_on_transport(self._transport(), command)
|
||||
|
||||
def reboot_host(self) -> None:
|
||||
"""Restart the AP (``HostRebootMixin``); returns once the restart is under way.
|
||||
|
||||
Detached and two seconds late, so the answer comes back before the
|
||||
session goes down; a refusal is raised, not mistaken for that.
|
||||
|
||||
:raises RuntimeError: for a login other than root, or a refused reboot.
|
||||
"""
|
||||
try:
|
||||
result = self.run_command(_REBOOT_DETACHED, privileged=True, timeout=30)
|
||||
except PermissionError as exc:
|
||||
raise RuntimeError(str(exc)) from exc
|
||||
if result.exit_code:
|
||||
reason = result.stderr.strip() or result.stdout.strip()
|
||||
raise RuntimeError(reason or f"reboot exited with status {result.exit_code}")
|
||||
|
||||
def _run_host_status_command(self, command: str) -> str:
|
||||
"""Run the host status command for ``HostStatusMixin``; it needs no root.
|
||||
|
||||
Over an SSH exec channel of its own: busybox ash cuts a typed line at 512
|
||||
characters, and the command is longer.
|
||||
"""
|
||||
return self.run_command(command).stdout
|
||||
|
||||
def _run_listening_sockets_command(self, command: str, *, privileged: bool) -> str:
|
||||
"""Run the listening-socket command for ``ListeningSocketsMixin``.
|
||||
|
||||
Over an SSH exec channel of its own, not the interactive shell: busybox
|
||||
ash cuts a typed line at 512 characters, and the command is longer. As
|
||||
root it names every socket's process; a login other than root has no way
|
||||
to become root here, so a privileged reading comes back empty and the
|
||||
mixin reads again without attributing.
|
||||
"""
|
||||
if privileged and self.username != "root":
|
||||
return ""
|
||||
_stdin, stdout, _stderr = self.device.remote_conn_pre.exec_command(
|
||||
command, timeout=self.timeout
|
||||
)
|
||||
return stdout.read().decode("utf-8", "replace")
|
||||
|
||||
@staticmethod
|
||||
def _parse_openwrt_release(output: str) -> dict[str, str]:
|
||||
"""Parse ``/etc/openwrt_release`` key=value pairs."""
|
||||
@@ -211,18 +330,14 @@ class OpenWrtDriver(
|
||||
if model_raw and not model_raw.startswith("cat: "):
|
||||
facts["model"] = model_raw.strip().replace("\x00", "")
|
||||
else:
|
||||
facts["model"] = (
|
||||
release.get("DISTRIB_TARGET", "").replace("/", " ")
|
||||
)
|
||||
facts["model"] = release.get("DISTRIB_TARGET", "").replace("/", " ")
|
||||
|
||||
facts["os_version"] = release.get(
|
||||
"DISTRIB_DESCRIPTION",
|
||||
release.get("DISTRIB_RELEASE", "unknown"),
|
||||
)
|
||||
facts["serial_number"] = ""
|
||||
facts["uptime"] = self._parse_uptime_seconds(
|
||||
self._send_command("cat /proc/uptime")
|
||||
)
|
||||
facts["uptime"] = self._parse_uptime_seconds(self._send_command("cat /proc/uptime"))
|
||||
|
||||
# hostname and FQDN
|
||||
uname_out = self._send_command("uname -a")
|
||||
@@ -264,27 +379,15 @@ class OpenWrtDriver(
|
||||
|
||||
return configs
|
||||
|
||||
def cli(
|
||||
self, commands: list[str], encoding: str = "text"
|
||||
) -> dict[str, str]:
|
||||
def cli(self, commands: list[str], encoding: str = "text") -> dict[str, str]:
|
||||
"""Execute a list of CLI commands and return their output."""
|
||||
return {
|
||||
cmd: self._send_command(cmd)
|
||||
for cmd in commands
|
||||
}
|
||||
return {cmd: self._send_command(cmd) for cmd in commands}
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# Service management (forwarded to mixins because AccessPointDriver
|
||||
# defines NotImplementedError stubs for these)
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# UCI parsing helpers
|
||||
# ------------------------------------------------------------------
|
||||
@@ -340,18 +443,6 @@ class OpenWrtDriver(
|
||||
# Device actions
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def run_device_action(self, action: str) -> dict[str, Any]:
|
||||
"""Execute a named action on the device."""
|
||||
if action == "install_lldpd":
|
||||
return self._action_install_lldpd()
|
||||
if action == "install_auc":
|
||||
return self._action_install_auc()
|
||||
if action == "install_coreutils_base64":
|
||||
return self._action_install_coreutils_base64()
|
||||
if action == "fix_snmp":
|
||||
return self._action_fix_snmp()
|
||||
raise NotImplementedError(f"Unknown action: {action!r}")
|
||||
|
||||
def _mgmt_address(self) -> str:
|
||||
"""Return the device-side address of our own SSH session.
|
||||
|
||||
@@ -429,19 +520,25 @@ class OpenWrtDriver(
|
||||
return ""
|
||||
|
||||
@classmethod
|
||||
def _stale_snmp_rules(
|
||||
cls, fw_sections: dict[str, dict[str, str]], keep: str
|
||||
) -> list[str]:
|
||||
def _stale_snmp_rules(cls, fw_sections: dict[str, dict[str, str]], keep: str) -> list[str]:
|
||||
"""Return every SNMP rule section except ``keep``, in delete-safe order."""
|
||||
return cls._stale_rules(fw_sections, keep, word="snmp", port=161)
|
||||
|
||||
@classmethod
|
||||
def _stale_rules(
|
||||
cls, fw_sections: dict[str, dict[str, str]], keep: str, *, word: str, port: int
|
||||
) -> list[str]:
|
||||
"""Every rule section for an agent except ``keep``, in delete-safe order: its
|
||||
name or key says *word*, or it opens *port*."""
|
||||
hits = [
|
||||
key
|
||||
for key, opts in fw_sections.items()
|
||||
if opts.get("_type") == "rule"
|
||||
and key != keep
|
||||
and (
|
||||
"snmp" in cls._uci_scalar(opts.get("name", "")).lower()
|
||||
or "snmp" in key.lower()
|
||||
or cls._uci_scalar(opts.get("dest_port", "")) == "161"
|
||||
word in cls._uci_scalar(opts.get("name", "")).lower()
|
||||
or word in key.lower()
|
||||
or cls._uci_scalar(opts.get("dest_port", "")) == str(port)
|
||||
)
|
||||
]
|
||||
return sorted(hits, key=cls._uci_delete_order)
|
||||
@@ -469,182 +566,215 @@ class OpenWrtDriver(
|
||||
return int(line)
|
||||
return 0
|
||||
|
||||
def _action_fix_snmp(self) -> dict[str, Any]:
|
||||
"""Ensure snmpd is running and reachable on UDP/161.
|
||||
# ------------------------------------------------------------------
|
||||
# SNMP agent (napalm-device-types SnmpAgentMixin): the caller's values
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
On OpenWrt the usual reason SNMP stays unreachable is the firewall:
|
||||
snmpd listens, but the zone covering the management interface
|
||||
default-drops everything except SSH/HTTP/HTTPS/ICMP. A rule only
|
||||
lands in the right nftables chain when its ``src`` names the zone
|
||||
that actually owns the management network.
|
||||
def get_management_peer(self) -> str | None:
|
||||
"""The address the device sees the SSH connection come from (``SSH_CONNECTION``)."""
|
||||
parts = self._send_command("echo $SSH_CONNECTION").split()
|
||||
try:
|
||||
return str(ipaddress.ip_address(parts[0])) if parts else None
|
||||
except ValueError:
|
||||
return None
|
||||
|
||||
This action:
|
||||
def _rc_step(self, command: str, done: str) -> dict[str, Any]:
|
||||
output, status = _split_status(self._send_command(f"{command} 2>&1; echo {_RC_MARKER}$?"))
|
||||
return {"ok": status == 0, "output": done if status == 0 else output.strip()[-300:]}
|
||||
|
||||
1. Resolves the management address from ``$SSH_CONNECTION``, maps it
|
||||
to its ``network`` section and from there to the owning firewall
|
||||
zone — no guessing from rule names.
|
||||
2. Aborts with a diagnosis when that zone has no ``option name``:
|
||||
fw4 skips such a section, so any rule written against it is dead
|
||||
on arrival. Naming the zone is left to the operator because an
|
||||
inert zone becoming active changes what the AP filters.
|
||||
3. Removes stale SNMP rules from earlier versions (highest anonymous
|
||||
index first) and commits the deletion.
|
||||
4. Writes the ``allow_snmp_from_<zone>`` rule in full every run, so a
|
||||
half-written rule from a previous attempt gets repaired.
|
||||
5. Reloads the firewall and fails on any reload complaint.
|
||||
6. Verifies on the device that snmpd listens and that a udp/161
|
||||
accept rule is live in the packet filter.
|
||||
def _install_snmp_agent(self) -> dict[str, Any]:
|
||||
if self._send_command("[ -x /usr/sbin/snmpd ] && echo present").strip() == "present":
|
||||
return {"ok": True, "output": "snmpd already installed"}
|
||||
if self._pm_type() == "apk":
|
||||
return self._rc_step("apk add snmpd", "snmpd installed")
|
||||
return self._rc_step("opkg update >/dev/null 2>&1; opkg install snmpd", "snmpd installed")
|
||||
|
||||
def _write_snmp_agent_config(self, settings: dict) -> dict[str, Any]:
|
||||
"""Community, sources, contact and location in UCI's snmpd config.
|
||||
|
||||
One ``com2sec`` (``com2sec6``) per allowed source, all mapped to the
|
||||
read-only security name the stock groups use. Sections of an earlier run
|
||||
(``snmp_src*``) go first. Without sources every address may ask; with only
|
||||
IPv4 sources, IPv6 answers localhost only.
|
||||
"""
|
||||
community = settings["community"]
|
||||
if not _SNMP_WORD.match(community):
|
||||
raise ValueError("the community must be one word without quotes or #")
|
||||
sources = _sources(settings)
|
||||
v4 = [x for x in sources if ":" not in x] or (["127.0.0.1/32"] if sources else ["default"])
|
||||
v6 = [x for x in sources if ":" in x] or (["::1/128"] if sources else ["default"])
|
||||
old = self._parse_uci_sections(self._send_command("uci show snmpd 2>/dev/null"))
|
||||
stale = sorted((key for key in old if key.startswith("snmp_src")), reverse=True)
|
||||
cmds = [f"uci -q delete snmpd.{key}" for key in stale]
|
||||
for kind, first, nets in (("com2sec", "public", v4), ("com2sec6", "public6", v6)):
|
||||
for i, net in enumerate(nets):
|
||||
key = first if i == 0 else f"snmp_src{'6' if kind.endswith('6') else ''}_{i}"
|
||||
cmds += [
|
||||
f"uci set snmpd.{key}={kind}",
|
||||
f"uci set snmpd.{key}.secname='ro'",
|
||||
f"uci set snmpd.{key}.source='{net}'",
|
||||
f"uci set snmpd.{key}.community='{community}'",
|
||||
]
|
||||
for key, option in (("location", "sysLocation"), ("contact", "sysContact")):
|
||||
value = settings.get(key, "")
|
||||
if value:
|
||||
if "'" in value or "\n" in value:
|
||||
raise ValueError(f"{key} must be one line without '")
|
||||
cmds.append(f"uci set snmpd.@system[0].{option}='{value}'")
|
||||
cmds.append("uci commit snmpd")
|
||||
done = f"community set for {', '.join(sources) or 'every address'}"
|
||||
return self._rc_step("; ".join(cmds), done)
|
||||
|
||||
def _allow_snmp_sources(self, settings: dict) -> dict[str, Any]:
|
||||
"""A udp/161 accept rule in the zone that owns the management address."""
|
||||
return self._allow_in_management_zone(
|
||||
key="allow_snmp",
|
||||
name="Allow-SNMP",
|
||||
proto="udp",
|
||||
port=161,
|
||||
sources=_sources(settings),
|
||||
word="snmp",
|
||||
)
|
||||
|
||||
def _allow_in_management_zone(
|
||||
self, *, key: str, name: str, proto: str, port: int, sources: list[str], word: str
|
||||
) -> dict[str, Any]:
|
||||
"""An accept rule for *proto*/*port* in the zone that owns the management address.
|
||||
|
||||
The zone is resolved from ``$SSH_CONNECTION`` → its ``network`` section →
|
||||
the zone listing it, not guessed from rule names. A zone without ``option
|
||||
name`` is skipped by fw4, so the step fails with how to fix it instead of
|
||||
writing a dead rule. Stale rules for the same agent go (``word`` in their
|
||||
name, or *port*; highest anonymous index first); the rule, ``<key>_from_<zone>``
|
||||
named *name*, is written in full every run and limited to *sources*
|
||||
(``src_ip``; none: every source in the zone); the reload and the live packet
|
||||
filter decide success.
|
||||
"""
|
||||
lines: list[str] = []
|
||||
fw_sections = self._parse_uci_sections(self._send_command("uci show firewall 2>/dev/null"))
|
||||
zone = self._management_zone(fw_sections, lines)
|
||||
if zone is None:
|
||||
return {"ok": False, "output": "\n".join(lines)}
|
||||
named_key = f"{key}_from_{zone}" if zone else key
|
||||
stale = self._stale_rules(fw_sections, keep=named_key, word=word, port=port)
|
||||
if stale:
|
||||
deletes = "; ".join(f"uci -q delete firewall.{section}" for section in stale)
|
||||
self._send_command(f"{deletes}; uci commit firewall")
|
||||
lines.append(f"Removed stale {name} rule(s): {', '.join(stale)}")
|
||||
self._write_accept_rule(named_key, name, proto, port, sources, zone, lines)
|
||||
ok = self._reload_and_count(proto, port, lines)
|
||||
return {"ok": ok, "output": "\n".join(lines)}
|
||||
|
||||
# ── 1. Resolve the zone that owns the management address ─────────
|
||||
fw_raw = self._send_command("uci show firewall 2>/dev/null")
|
||||
fw_sections = self._parse_uci_sections(fw_raw)
|
||||
def _management_zone(
|
||||
self, fw_sections: dict[str, dict[str, str]], lines: list[str]
|
||||
) -> str | None:
|
||||
"""The zone that owns the management address; ``""`` where no zone is
|
||||
configured (the rule goes unscoped); None where no rule may be written.
|
||||
What it found goes into *lines*."""
|
||||
zones, nameless = self._firewall_zones(fw_sections)
|
||||
|
||||
address = self._mgmt_address()
|
||||
net_sections = self._parse_uci_sections(self._send_command("uci show network 2>/dev/null"))
|
||||
mgmt_net = self._mgmt_network(net_sections, address)
|
||||
lines.append(f"[firewall] Management address {address} on network {mgmt_net or '<unknown>'}")
|
||||
lines.append(f"Management address {address} on network {mgmt_net or '<unknown>'}")
|
||||
|
||||
broken_zone = (
|
||||
self._zone_for_network(fw_sections, {key: key for key in nameless}, mgmt_net)
|
||||
if mgmt_net
|
||||
else ""
|
||||
)
|
||||
if broken_zone:
|
||||
lines.append(
|
||||
f"[firewall] Zone {broken_zone} owns network {mgmt_net!r} but has no "
|
||||
f"'name' option — fw4 skips the section and drops every rule that "
|
||||
f"references it. Fix on the device, then re-run:"
|
||||
)
|
||||
lines.append(
|
||||
f"[firewall] uci set firewall.{broken_zone}.name='{mgmt_net}' "
|
||||
f"&& uci commit firewall && fw4 reload"
|
||||
)
|
||||
return {"success": False, "output": "\n".join(lines)}
|
||||
if self._nameless_zone_owns(fw_sections, nameless, mgmt_net, lines):
|
||||
return None
|
||||
|
||||
mgmt_zone = self._zone_for_network(fw_sections, zones, mgmt_net) if mgmt_net else ""
|
||||
if not mgmt_zone and "lan" in zones:
|
||||
mgmt_zone = "lan"
|
||||
if not mgmt_zone and len(zones) == 1:
|
||||
mgmt_zone = next(iter(zones))
|
||||
|
||||
if mgmt_zone:
|
||||
lines.append(f"[firewall] Management zone: {mgmt_zone!r}")
|
||||
elif zones:
|
||||
lines.append(
|
||||
f"[firewall] No zone covers the management network — zones present: "
|
||||
f"{', '.join(sorted(zones))}"
|
||||
)
|
||||
return {"success": False, "output": "\n".join(lines)}
|
||||
else:
|
||||
lines.append("[firewall] No zones configured — writing an unscoped rule")
|
||||
lines.append(f"Management zone: {mgmt_zone!r}")
|
||||
return mgmt_zone
|
||||
if zones:
|
||||
present = ", ".join(sorted(zones))
|
||||
lines.append(f"No zone covers the management network — zones present: {present}")
|
||||
return None
|
||||
lines.append("No zones configured — writing an unscoped rule")
|
||||
return ""
|
||||
|
||||
# ── 2. Drop stale SNMP rules from earlier versions of this action ─
|
||||
named_key = f"allow_snmp_from_{mgmt_zone}" if mgmt_zone else "allow_snmp"
|
||||
stale = self._stale_snmp_rules(fw_sections, keep=named_key)
|
||||
if stale:
|
||||
self._send_command(
|
||||
"; ".join(f"uci -q delete firewall.{key}" for key in stale)
|
||||
+ "; uci commit firewall"
|
||||
)
|
||||
lines.append(f"[firewall] Removed stale SNMP rule(s): {', '.join(stale)}")
|
||||
def _nameless_zone_owns(
|
||||
self,
|
||||
fw_sections: dict[str, dict[str, str]],
|
||||
nameless: list[str],
|
||||
mgmt_net: str,
|
||||
lines: list[str],
|
||||
) -> bool:
|
||||
"""Whether a zone without ``option name`` owns *mgmt_net*: fw4 skips it, so a
|
||||
rule there would be dead. How to fix it goes into *lines*."""
|
||||
if not mgmt_net:
|
||||
return False
|
||||
broken_zone = self._zone_for_network(fw_sections, {key: key for key in nameless}, mgmt_net)
|
||||
if not broken_zone:
|
||||
return False
|
||||
lines.append(
|
||||
f"Zone {broken_zone} owns network {mgmt_net!r} but has no 'name' option — "
|
||||
"fw4 skips the section and drops every rule that references it. "
|
||||
"Fix on the device, then re-run:"
|
||||
)
|
||||
lines.append(
|
||||
f" uci set firewall.{broken_zone}.name='{mgmt_net}'"
|
||||
" && uci commit firewall && fw4 reload"
|
||||
)
|
||||
return True
|
||||
|
||||
# ── 3. Write the rule in full — repairs a half-written one ────────
|
||||
def _write_accept_rule(
|
||||
self,
|
||||
named_key: str,
|
||||
name: str,
|
||||
proto: str,
|
||||
port: int,
|
||||
sources: list[str],
|
||||
zone: str,
|
||||
lines: list[str],
|
||||
) -> None:
|
||||
"""Write the rule *named_key* in full: *proto*/*port* from *sources* in *zone*."""
|
||||
rule_cmds = [
|
||||
f"uci set firewall.{named_key}=rule",
|
||||
f"uci set firewall.{named_key}.name='Allow-SNMP-netOrk'",
|
||||
f"uci set firewall.{named_key}.name='{name}'",
|
||||
f"uci set firewall.{named_key}.target='ACCEPT'",
|
||||
f"uci set firewall.{named_key}.proto='udp'",
|
||||
f"uci set firewall.{named_key}.dest_port='161'",
|
||||
f"uci set firewall.{named_key}.proto='{proto}'",
|
||||
f"uci set firewall.{named_key}.dest_port='{port}'",
|
||||
f"uci -q delete firewall.{named_key}.src_ip",
|
||||
*(f"uci add_list firewall.{named_key}.src_ip='{net}'" for net in sources),
|
||||
]
|
||||
if mgmt_zone:
|
||||
rule_cmds.append(f"uci set firewall.{named_key}.src='{mgmt_zone}'")
|
||||
if zone:
|
||||
rule_cmds.append(f"uci set firewall.{named_key}.src='{zone}'")
|
||||
else:
|
||||
rule_cmds.append(f"uci -q delete firewall.{named_key}.src")
|
||||
rule_cmds.append("uci commit firewall")
|
||||
rule_out = self._send_command("; ".join(rule_cmds) + " 2>&1").strip()
|
||||
lines.append(f"[firewall] Wrote rule {named_key!r}: {rule_out or 'ok'}")
|
||||
scope = ", ".join(sources) or "every source in the zone"
|
||||
lines.append(f"Wrote rule {named_key!r} for {scope}: {rule_out or 'ok'}")
|
||||
|
||||
# ── 4. Reload the firewall, and believe what it says ──────────────
|
||||
def _reload_and_count(self, proto: str, port: int, lines: list[str]) -> bool:
|
||||
"""Reload the firewall; True when it took the ruleset and a rule for *port* is live."""
|
||||
reload_out = self._send_command(
|
||||
"fw4 reload 2>&1 || /etc/init.d/firewall reload 2>&1"
|
||||
).strip()
|
||||
fw_ok = not self._fw_reload_failed(reload_out)
|
||||
lines.append(f"[firewall] Reload: {reload_out or 'ok'}")
|
||||
lines.append(f"Reload: {reload_out or 'ok'}")
|
||||
if not fw_ok:
|
||||
lines.append("[firewall] Reload reported invalid sections — ruleset not applied")
|
||||
|
||||
# ── 5. Ensure snmpd is enabled and running ────────────────────────
|
||||
status = self._send_command("/etc/init.d/snmpd status 2>/dev/null")
|
||||
if "running" not in status.lower() and "active" not in status.lower():
|
||||
self._send_command(
|
||||
"/etc/init.d/snmpd enable 2>/dev/null;"
|
||||
" /etc/init.d/snmpd start 2>/dev/null"
|
||||
)
|
||||
lines.append("[snmpd] Service started and enabled")
|
||||
else:
|
||||
lines.append("[snmpd] Service already running")
|
||||
|
||||
# ── 6. Verify on the device instead of assuming success ───────────
|
||||
listening = self._grep_count(
|
||||
self._send_command("ss -lun 2>/dev/null | grep -c ':161'")
|
||||
)
|
||||
lines.append(f"[probe] snmpd listening on udp/161: {'yes' if listening else 'no'}")
|
||||
|
||||
lines.append("Reload reported invalid sections — ruleset not applied")
|
||||
live = self._grep_count(
|
||||
self._send_command(
|
||||
"{ nft list ruleset 2>/dev/null || iptables-save 2>/dev/null; }"
|
||||
" | grep -c 'dport 161'"
|
||||
f" | grep -c 'dport {port}'"
|
||||
)
|
||||
)
|
||||
lines.append(f"[probe] udp/161 accept rules live in the packet filter: {live}")
|
||||
lines.append(f"{proto}/{port} accept rules live in the packet filter: {live}")
|
||||
return fw_ok and bool(live)
|
||||
|
||||
success = fw_ok and bool(listening) and bool(live)
|
||||
return {"success": success, "output": "\n".join(lines)}
|
||||
|
||||
def _action_install_coreutils_base64(self) -> dict[str, Any]:
|
||||
"""Install coreutils-base64 via the device package manager."""
|
||||
pm = self._pm_type()
|
||||
if pm == "apk":
|
||||
raw = self._send_command("apk add coreutils-base64 2>&1")
|
||||
else:
|
||||
self._send_command("opkg update 2>&1")
|
||||
raw = self._send_command("opkg install coreutils-base64 2>&1")
|
||||
out = self._clean_pkg_output(raw)
|
||||
low = out.lower()
|
||||
success = not any(kw in low for kw in ("error:", "failed", "not found", "unknown package"))
|
||||
return {"success": success, "output": out}
|
||||
|
||||
def _action_install_auc(self) -> dict[str, Any]:
|
||||
"""Install the attended sysupgrade client (auc) via opkg."""
|
||||
self._send_command("opkg update 2>&1")
|
||||
raw = self._send_command("opkg install auc 2>&1")
|
||||
out = self._clean_pkg_output(raw)
|
||||
low = out.lower()
|
||||
success = not any(kw in low for kw in ("error:", "failed", "not found", "unknown package"))
|
||||
return {"success": success, "output": out}
|
||||
|
||||
def _action_install_lldpd(self) -> dict[str, Any]:
|
||||
"""Install lldpd, add eth0 to its interface list and start the service."""
|
||||
pm = self._pm_type()
|
||||
if pm == "apk":
|
||||
raw = self._send_command("apk add lldpd 2>&1")
|
||||
else:
|
||||
self._send_command("opkg update 2>&1")
|
||||
raw = self._send_command("opkg install lldpd 2>&1")
|
||||
out = self._clean_pkg_output(raw)
|
||||
|
||||
# Configure the correct management interface and enable the service
|
||||
self._lldpd_fix_interface()
|
||||
|
||||
# Enable and start the service
|
||||
def _start_snmp_agent(self) -> dict[str, Any]:
|
||||
self._send_command(
|
||||
"/etc/init.d/lldpd enable 2>/dev/null; "
|
||||
"/etc/init.d/lldpd start 2>/dev/null"
|
||||
"/etc/init.d/snmpd enable 2>/dev/null; /etc/init.d/snmpd restart 2>/dev/null"
|
||||
)
|
||||
|
||||
low = out.lower()
|
||||
success = not any(kw in low for kw in ("error:", "failed", "not found", "unknown package"))
|
||||
return {"success": success, "output": out}
|
||||
listening = self._grep_count(self._send_command("ss -lun 2>/dev/null | grep -c ':161'"))
|
||||
return {
|
||||
"ok": bool(listening),
|
||||
"output": "snmpd enabled and listening on udp/161"
|
||||
if listening
|
||||
else "snmpd is not listening on udp/161",
|
||||
}
|
||||
@@ -1,4 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# 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
|
||||
@@ -16,6 +15,8 @@ from __future__ import annotations
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from napalm_openwrt.system_mixin import _RC_MARKER, _status_result
|
||||
|
||||
|
||||
class OpenWrtPackageMixin:
|
||||
"""Mixin providing package-management NAPALM methods."""
|
||||
@@ -99,14 +100,16 @@ class OpenWrtPackageMixin:
|
||||
name = token[: vm.start()] if vm else token
|
||||
version = vm.group(1) if vm else ""
|
||||
origin = ""
|
||||
packages.append({
|
||||
"name": name,
|
||||
"version": version,
|
||||
"installed": True,
|
||||
"description": "",
|
||||
"size": 0,
|
||||
"source": origin,
|
||||
})
|
||||
packages.append(
|
||||
{
|
||||
"name": name,
|
||||
"version": version,
|
||||
"installed": True,
|
||||
"description": "",
|
||||
"size": 0,
|
||||
"source": origin,
|
||||
}
|
||||
)
|
||||
return sorted(packages, key=lambda p: p["name"].lower())
|
||||
|
||||
def _pm_type(self) -> str:
|
||||
@@ -121,6 +124,7 @@ class OpenWrtPackageMixin:
|
||||
index is populated (OpenWrt stores it in RAM and loses it on reboot).
|
||||
"""
|
||||
import shlex
|
||||
|
||||
safe_q = shlex.quote(query)
|
||||
if self._pm_type() == "apk":
|
||||
# Refresh index (no-ops if already current, safe to run every time)
|
||||
@@ -137,14 +141,16 @@ class OpenWrtPackageMixin:
|
||||
name, version, description = m.group(1), m.group(2), (m.group(3) or "")
|
||||
else:
|
||||
name, version, description = line, "", ""
|
||||
packages.append({
|
||||
"name": name,
|
||||
"version": version,
|
||||
"installed": name in installed,
|
||||
"description": description,
|
||||
"size": 0,
|
||||
"source": "",
|
||||
})
|
||||
packages.append(
|
||||
{
|
||||
"name": name,
|
||||
"version": version,
|
||||
"installed": name in installed,
|
||||
"description": description,
|
||||
"size": 0,
|
||||
"source": "",
|
||||
}
|
||||
)
|
||||
else:
|
||||
# opkg lists live in /var/opkg-lists/ (RAM) — cleared on reboot
|
||||
self._send_command("opkg update 2>/dev/null || true")
|
||||
@@ -159,14 +165,16 @@ class OpenWrtPackageMixin:
|
||||
name = parts[0].strip()
|
||||
version = parts[1].strip() if len(parts) > 1 else ""
|
||||
description = parts[2].strip() if len(parts) > 2 else ""
|
||||
packages.append({
|
||||
"name": name,
|
||||
"version": version,
|
||||
"installed": name in installed,
|
||||
"description": description,
|
||||
"size": 0,
|
||||
"source": "",
|
||||
})
|
||||
packages.append(
|
||||
{
|
||||
"name": name,
|
||||
"version": version,
|
||||
"installed": name in installed,
|
||||
"description": description,
|
||||
"size": 0,
|
||||
"source": "",
|
||||
}
|
||||
)
|
||||
return packages
|
||||
|
||||
@staticmethod
|
||||
@@ -175,46 +183,50 @@ class OpenWrtPackageMixin:
|
||||
# Strip CSI sequences (\x1b[...X), OSC, charset designations, and
|
||||
# 2-byte DEC private sequences like ESC 7 (cursor save) / ESC 8 (restore)
|
||||
cleaned = re.sub(
|
||||
r'\x1b(?:\[[0-9;?]*[a-zA-Z]|\][^\x07]*\x07|[()][0-9A-Za-z]|[\x30-\x7e])',
|
||||
'', raw,
|
||||
r"\x1b(?:\[[0-9;?]*[a-zA-Z]|\][^\x07]*\x07|[()][0-9A-Za-z]|[\x30-\x7e])",
|
||||
"",
|
||||
raw,
|
||||
)
|
||||
# After stripping cursor-save/restore sequences, apk progress updates
|
||||
# end up concatenated on a single line. Strip those inline patterns.
|
||||
cleaned = re.sub(r'\s*\d{1,3}%\s*#*', ' ', cleaned)
|
||||
cleaned = re.sub(r"\s*\d{1,3}%\s*#*", " ", cleaned)
|
||||
lines = []
|
||||
for segment in cleaned.split('\n'):
|
||||
for segment in cleaned.split("\n"):
|
||||
# \r overwrites the line; keep only the portion after the last \r
|
||||
part = segment.split('\r')[-1].strip()
|
||||
part = segment.split("\r")[-1].strip()
|
||||
if not part:
|
||||
continue
|
||||
# Drop pure progress-bar lines (only #, spaces, digits, %)
|
||||
if re.match(r'^[#\s\d%]*$', part):
|
||||
if re.match(r"^[#\s\d%]*$", part):
|
||||
continue
|
||||
lines.append(part)
|
||||
return '\n'.join(lines)
|
||||
return "\n".join(lines)
|
||||
|
||||
def _run_pkg_command(self, command: str) -> dict[str, Any]:
|
||||
"""Run a package-manager command; only its exit status decides ``success``."""
|
||||
raw = self._send_command(f"{command} 2>&1; echo {_RC_MARKER}$?")
|
||||
return _status_result(self._clean_pkg_output(raw), command)
|
||||
|
||||
def install_package(self, name: str) -> dict[str, Any]:
|
||||
"""Install a package by name. Returns ``{"success": bool, "output": str}``."""
|
||||
"""Install a package by name. Returns ``{"success": bool, "output": str}``.
|
||||
|
||||
Only the package manager's exit status decides ``success``.
|
||||
"""
|
||||
import shlex
|
||||
|
||||
safe_name = shlex.quote(name)
|
||||
if self._pm_type() == "apk":
|
||||
raw = self._send_command(f"apk add {safe_name} 2>&1")
|
||||
else:
|
||||
raw = self._send_command(f"opkg install {safe_name} 2>&1")
|
||||
out = self._clean_pkg_output(raw)
|
||||
low = out.lower()
|
||||
success = not any(kw in low for kw in ("error:", "failed", "not found", "unknown package"))
|
||||
return {"success": success, "output": out}
|
||||
return self._run_pkg_command(f"apk add {safe_name}")
|
||||
return self._run_pkg_command(f"opkg install {safe_name}")
|
||||
|
||||
def uninstall_package(self, name: str) -> dict[str, Any]:
|
||||
"""Remove a package by name. Returns ``{"success": bool, "output": str}``."""
|
||||
"""Remove a package by name. Returns ``{"success": bool, "output": str}``.
|
||||
|
||||
Only the package manager's exit status decides ``success``.
|
||||
"""
|
||||
import shlex
|
||||
|
||||
safe_name = shlex.quote(name)
|
||||
if self._pm_type() == "apk":
|
||||
raw = self._send_command(f"apk del {safe_name} 2>&1")
|
||||
else:
|
||||
raw = self._send_command(f"opkg remove {safe_name} 2>&1")
|
||||
out = self._clean_pkg_output(raw)
|
||||
low = out.lower()
|
||||
success = not any(kw in low for kw in ("error:", "failed", "not found", "unknown package"))
|
||||
return {"success": success, "output": out}
|
||||
return self._run_pkg_command(f"apk del {safe_name}")
|
||||
return self._run_pkg_command(f"opkg remove {safe_name}")
|
||||
Whitespace-only changes.
@@ -1,4 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# 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
|
||||
@@ -124,8 +123,8 @@ class OpenWrtRoutingMixin:
|
||||
|
||||
Example ``ip route show`` output::
|
||||
|
||||
default via 192.168.1.1 dev br-wan proto dhcp src 203.0.113.1 metric 100
|
||||
192.168.1.0/24 dev br-lan proto kernel scope link src 192.168.1.1
|
||||
default via 192.0.2.1 dev br-wan proto dhcp src 203.0.113.1 metric 100
|
||||
192.0.2.0/24 dev br-lan proto kernel scope link src 192.0.2.1
|
||||
"""
|
||||
if destination:
|
||||
cmd = f"ip route show {'match ' if longer else ''}{destination}"
|
||||
@@ -142,10 +141,10 @@ class OpenWrtRoutingMixin:
|
||||
|
||||
# Determine the prefix
|
||||
# "default via ..." → prefix = "0.0.0.0/0"
|
||||
# "192.168.1.0/24 dev ..." → prefix as-is
|
||||
# "192.0.2.0/24 dev ..." → prefix as-is
|
||||
if line_s.startswith("default"):
|
||||
prefix = "0.0.0.0/0"
|
||||
rest = line_s[len("default"):].strip()
|
||||
rest = line_s[len("default") :].strip()
|
||||
else:
|
||||
parts = line_s.split()
|
||||
prefix = parts[0]
|
||||
@@ -245,7 +244,7 @@ class OpenWrtRoutingMixin:
|
||||
|
||||
Example lines::
|
||||
|
||||
1 192.168.1.1 (192.168.1.1) 1.123 ms 1.456 ms 1.789 ms
|
||||
1 192.0.2.1 (192.0.2.1) 1.123 ms 1.456 ms 1.789 ms
|
||||
2 * * *
|
||||
"""
|
||||
hops: dict[int, dict[str, Any]] = {}
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
"""Scheduled jobs on OpenWrt: BusyBox crond and the crontabs in ``/etc/crontabs`` (#32).
|
||||
|
||||
napalm-device-types' :class:`~napalm_device_types.PosixScheduledJobsMixin` does the
|
||||
work; this mixin tells it what an OpenWrt router has and what its BusyBox lacks.
|
||||
|
||||
**What there is.** BusyBox crond reads ``/etc/crontabs/<user>`` and nothing else:
|
||||
no ``/etc/crontab``, no ``cron.d``, no run-parts, no anacron, no systemd. An
|
||||
application's own job is two marked lines in the user's crontab. After every write
|
||||
the cron service is enabled and restarted -- OpenWrt does not start crond at boot
|
||||
while ``/etc/crontabs`` is empty.
|
||||
|
||||
**What BusyBox does differently** (as OpenWrt builds it, 21.02 to 25.x):
|
||||
|
||||
* ``crontab -l`` says only "can't open" for a crontab that is not there, the same as
|
||||
for one that cannot be read; the file is read directly instead, and a missing one
|
||||
is empty. ``crontab FILE`` exits 0 when it could not write: every write is read
|
||||
back.
|
||||
* crond has no special times (``FEATURE_CROND_SPECIAL_TIMES`` is off): ``@daily``
|
||||
and the other aliases are written as their five fields, ``@reboot`` is refused.
|
||||
* crond hands the whole command to ``sh -c`` -- ``%`` means nothing -- and of the
|
||||
crontab's variables takes only ``SHELL`` and ``PATH``; a run now does the same.
|
||||
* There is no ``stat``, ``cksum``, ``install`` or ``su``, and ``timeout`` only from
|
||||
25.x on. Only the crontabs are written, through ``crontab``; another user's job
|
||||
runs through ``start-stop-daemon -c``; a run is bounded by ``timeout`` where the
|
||||
router has it, else by the channel's wait.
|
||||
|
||||
Every command goes over an SSH exec channel (``run_command``), so ash's
|
||||
512-character limit on a typed line does not apply; dropbear takes 9000.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
import shlex
|
||||
from typing import ClassVar
|
||||
|
||||
from napalm_device_types import PosixScheduledJobsMixin
|
||||
from napalm_device_types._crontab import CronLine
|
||||
from napalm_device_types._scheduled_reading import Reading
|
||||
from napalm_device_types.cron import ALIASES, is_reboot
|
||||
from napalm_device_types.scheduled_jobs import (
|
||||
RUN_TIMEOUT,
|
||||
ScheduledJobRefused,
|
||||
ScheduledJobResultDict,
|
||||
ScheduledJobSpecDict,
|
||||
)
|
||||
|
||||
CRONTABS = "/etc/crontabs"
|
||||
INIT_CRON = "/etc/init.d/cron"
|
||||
|
||||
#: LuCI's zone names have spaces where the IANA names have underscores.
|
||||
TIME_ZONE_SH = "uci -q get 'system.@system[0].zonename' | tr ' ' _"
|
||||
|
||||
#: ``opkg search <path>`` prints ``<package> - <version>``; apk-based OpenWrt names none.
|
||||
OWNERS_SH = (
|
||||
"if command -v apk >/dev/null 2>&1; then cat >/dev/null; "
|
||||
"elif command -v opkg >/dev/null 2>&1; then while read -r p; do "
|
||||
"o=$(opkg search \"$p\" 2>/dev/null | sed -n '1s/ - .*//p'); "
|
||||
'[ -z "$o" ] || printf \'%s: %s\\n\' "$o" "$p"; done; '
|
||||
"else cat >/dev/null; fi"
|
||||
)
|
||||
|
||||
#: A user name the run's script may name unquoted (``~user``).
|
||||
_USER = re.compile(r"[A-Za-z_][A-Za-z0-9_.-]*")
|
||||
#: What a run keeps of the job's output.
|
||||
_OUTPUT_LIMIT = 64 * 1024
|
||||
|
||||
|
||||
def _cron_script(line: CronLine) -> str:
|
||||
"""*line*'s command the way BusyBox crond runs it: as the user, from the user's home."""
|
||||
user = line.run_as
|
||||
if not _USER.fullmatch(user):
|
||||
raise ScheduledJobRefused(f"not a user name to run as: {user!r}")
|
||||
env = "".join(
|
||||
f"export {k}={shlex.quote(line.env[k])}; " for k in ("SHELL", "PATH") if k in line.env
|
||||
)
|
||||
return (
|
||||
f"HOME=~{user}; export HOME LOGNAME={user} USER={user}; "
|
||||
f'cd "$HOME" 2>/dev/null || cd /; {env}{line.command}'
|
||||
)
|
||||
|
||||
|
||||
class OpenWrtScheduledJobsMixin(PosixScheduledJobsMixin):
|
||||
"""Scheduled jobs of an OpenWrt router: BusyBox crond's crontabs."""
|
||||
|
||||
CRON_SYSTEM_FILES: ClassVar[tuple[str, ...]] = ()
|
||||
CRON_D_DIRS: ClassVar[tuple[str, ...]] = ()
|
||||
CRON_SPOOL_DIRS: ClassVar[tuple[str, ...]] = (CRONTABS,)
|
||||
RUN_PARTS_DIRS: ClassVar[tuple[tuple[str, str], ...]] = ()
|
||||
#: OpenWrt has no anacron; the reading passes an empty path by.
|
||||
ANACRONTAB: ClassVar[str] = ""
|
||||
OWN_CRON_D_DIR: ClassVar[str | None] = None
|
||||
OWNERS_SH: ClassVar[str] = OWNERS_SH
|
||||
TIME_ZONE_SH: ClassVar[str] = TIME_ZONE_SH
|
||||
CRONTAB_AFTER_WRITE: ClassVar[tuple[str, ...] | None] = (
|
||||
"sh",
|
||||
"-c",
|
||||
f"{INIT_CRON} enable && {INIT_CRON} restart",
|
||||
)
|
||||
|
||||
def _sj_crontab(self, user: str) -> str:
|
||||
"""The crontab of *user* as the file has it; empty when there is none.
|
||||
|
||||
:raises RuntimeError: when it is there and cannot be read -- then nothing is written.
|
||||
"""
|
||||
path = f"{self.CRON_SPOOL_DIRS[0]}/{user}"
|
||||
result = self._sj_root(["sh", "-c", '[ ! -e "$1" ] || cat -- "$1"', "sh", path])
|
||||
if result.exit_code != 0:
|
||||
said = result.stderr.strip() or f"exit {result.exit_code}"
|
||||
raise RuntimeError(f"cannot read the crontab of {user}: {said}")
|
||||
return result.stdout
|
||||
|
||||
def _sj_write_crontab(self, user: str, text: str) -> None:
|
||||
"""Write through ``crontab``, then read back: BusyBox's exits 0 when it could not."""
|
||||
super()._sj_write_crontab(user, text)
|
||||
if self._sj_crontab(user) != text:
|
||||
raise RuntimeError(f"the crontab of {user} was not written")
|
||||
|
||||
def _sj_as(self, user: str, script: str) -> list[str]:
|
||||
"""*script* run by ``sh`` as *user*; OpenWrt's BusyBox has no ``su``."""
|
||||
if user == "root":
|
||||
return ["sh", "-c", script]
|
||||
# -p /dev/null: no process is "already running" -- only that file is looked at.
|
||||
ssd = ["start-stop-daemon", "-S", "-p", "/dev/null", "-c", user, "-x", "/bin/sh"]
|
||||
return [*ssd, "--", "-c", script]
|
||||
|
||||
def _sj_run(self, job: dict[str, object], reading: Reading) -> ScheduledJobResultDict:
|
||||
"""Run a cron line now as crond would, bounded by ``timeout`` where there is one."""
|
||||
line = self._sj_line(job, self._sj_text(str(job["source"])))
|
||||
argv = shlex.join(self._sj_as(line.run_as, _cron_script(line)))
|
||||
command = (
|
||||
f"if command -v timeout >/dev/null 2>&1; then exec timeout {RUN_TIMEOUT} {argv}; fi; "
|
||||
f"exec {argv}"
|
||||
)
|
||||
result = self.run_command(command, privileged=True, timeout=RUN_TIMEOUT + 30)
|
||||
said = "\n".join(p for p in (result.stdout.strip(), result.stderr.strip()) if p)
|
||||
said = said[-_OUTPUT_LIMIT:]
|
||||
if result.exit_code != 0:
|
||||
return {"success": False, "output": said or f"exit {result.exit_code}"}
|
||||
return {"success": True, "output": said or "ran"}
|
||||
|
||||
def put_scheduled_job(
|
||||
self, spec: ScheduledJobSpecDict, *, digest: str | None = None
|
||||
) -> ScheduledJobResultDict:
|
||||
"""Write the application's job; an alias as its five fields, ``@reboot`` refused.
|
||||
|
||||
:raises ScheduledJobRefused: for ``@reboot``: BusyBox crond on OpenWrt has no
|
||||
special times.
|
||||
"""
|
||||
schedule = (spec.get("schedule") or "").strip()
|
||||
if is_reboot(schedule):
|
||||
raise ScheduledJobRefused("BusyBox crond on OpenWrt does not run @reboot")
|
||||
if schedule.lower() in ALIASES:
|
||||
spec = {**spec, "schedule": ALIASES[schedule.lower()]}
|
||||
return super().put_scheduled_job(spec, digest=digest)
|
||||
+175
-344
@@ -1,4 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# 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
|
||||
@@ -13,17 +12,23 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
import time as _time
|
||||
from typing import Any
|
||||
|
||||
from napalm_device_types import PackageIndexMissing
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
#: Printed after a command so its exit status survives the shell session.
|
||||
_RC_MARKER = "__OWRT_RC="
|
||||
_RC_RE = re.compile(rf"^{_RC_MARKER}(\d+)\s*$", re.MULTILINE)
|
||||
#: What apk prints when its index is not in RAM (after a reboot).
|
||||
_APK_INDEX_MISSING = re.compile(r"opening from cache .*No such file or directory")
|
||||
#: The aggregate CPU line of ``/proc/stat``, read twice one second apart.
|
||||
_CPU_SAMPLES = "grep '^cpu ' /proc/stat; sleep 1; grep '^cpu ' /proc/stat"
|
||||
#: ``MemTotal: 124608 kB`` and ``MemAvailable:`` of ``/proc/meminfo``.
|
||||
_MEMINFO_RE = re.compile(r"^(MemTotal|MemAvailable):\s+(\d+)\s+kB\s*$", re.MULTILINE)
|
||||
|
||||
|
||||
def _split_status(raw: str) -> tuple[str, int | None]:
|
||||
@@ -32,39 +37,79 @@ def _split_status(raw: str) -> tuple[str, int | None]:
|
||||
output = _RC_RE.sub("", raw or "").strip()
|
||||
return output, int(statuses[-1]) if statuses else None
|
||||
|
||||
|
||||
def _status_result(raw: str, command: str) -> dict[str, Any]:
|
||||
"""``{"success", "output"}`` from what a command marked with ``_RC_MARKER`` printed.
|
||||
|
||||
Only the exit status decides; output without a status is no success.
|
||||
"""
|
||||
output, status = _split_status(raw)
|
||||
if status is None:
|
||||
return {"success": False, "output": output or "No exit status came back from the device."}
|
||||
if status:
|
||||
return {"success": False, "output": output or f"{command} exited with status {status}."}
|
||||
return {"success": True, "output": output}
|
||||
|
||||
|
||||
def _cpu_counters(line: str) -> tuple[int, int]:
|
||||
"""``(idle, total)`` jiffies of a ``cpu`` line.
|
||||
|
||||
The total counts user, nice, system, idle, iowait, irq and softirq.
|
||||
"""
|
||||
fields = [int(x) for x in line.split()[1:8]]
|
||||
if len(fields) < 7:
|
||||
raise ValueError(f"not a cpu line: {line!r}")
|
||||
return fields[3], sum(fields)
|
||||
|
||||
|
||||
def _cpu_usage_percent(output: str) -> float:
|
||||
"""Busy share of the time between the two ``cpu`` lines of :data:`_CPU_SAMPLES`.
|
||||
|
||||
0.0 when the counters did not move.
|
||||
|
||||
:raises ValueError: when the output does not hold two readable ``cpu`` lines.
|
||||
"""
|
||||
lines = [line for line in output.splitlines() if line.startswith("cpu ")]
|
||||
if len(lines) < 2:
|
||||
raise ValueError(f"/proc/stat gave no two cpu readings: {output[:200]!r}")
|
||||
idle1, total1 = _cpu_counters(lines[0])
|
||||
idle2, total2 = _cpu_counters(lines[1])
|
||||
elapsed = total2 - total1
|
||||
if elapsed <= 0:
|
||||
return 0.0
|
||||
return (1 - (idle2 - idle1) / elapsed) * 100
|
||||
|
||||
|
||||
def _meminfo_kib(output: str) -> tuple[int, int]:
|
||||
"""``(MemTotal, MemAvailable)`` in KiB from ``/proc/meminfo``.
|
||||
|
||||
:raises ValueError: when either is missing or not a number.
|
||||
"""
|
||||
values = dict(_MEMINFO_RE.findall(output))
|
||||
missing = [key for key in ("MemTotal", "MemAvailable") if key not in values]
|
||||
if missing:
|
||||
raise ValueError(f"/proc/meminfo has no {', '.join(missing)}: {output[:200]!r}")
|
||||
return int(values["MemTotal"]), int(values["MemAvailable"])
|
||||
|
||||
|
||||
class OpenWrtSystemMixin:
|
||||
"""Mixin providing system-level NAPALM getters (environment, NTP, SNMP, users, services, updates, device actions)."""
|
||||
"""Mixin providing system-level NAPALM getters.
|
||||
|
||||
Environment, NTP, SNMP, users, services, updates and device actions.
|
||||
"""
|
||||
|
||||
def get_environment(self) -> dict[str, Any]:
|
||||
"""Return device environment data (CPU, memory).
|
||||
|
||||
CPU usage from ``/proc/stat`` (two samples 1 second apart via ``awk``).
|
||||
CPU usage from ``/proc/stat``: the difference of two reads one second
|
||||
apart, so it is the last second, not the average since boot.
|
||||
Memory from ``/proc/meminfo``.
|
||||
|
||||
:raises ValueError: when either file could not be read or parsed; a
|
||||
failed read is no 0 % CPU and no 0 bytes of memory.
|
||||
"""
|
||||
cpu_out = self._send_command(
|
||||
"awk '/^cpu /{idle1=$5; total1=$2+$3+$4+$5+$6+$7+$8} END{print (1-(idle1/total1))*100}' /proc/stat"
|
||||
)
|
||||
mem_out = self._send_command("cat /proc/meminfo")
|
||||
|
||||
cpu_pct = 0.0
|
||||
try:
|
||||
cpu_pct = float(cpu_out.strip())
|
||||
except (ValueError, AttributeError):
|
||||
pass
|
||||
|
||||
mem_total = 0
|
||||
mem_available = 0
|
||||
for line in mem_out.splitlines():
|
||||
if line.startswith("MemTotal:"):
|
||||
try:
|
||||
mem_total = int(line.split()[1])
|
||||
except (IndexError, ValueError):
|
||||
pass
|
||||
elif line.startswith("MemAvailable:"):
|
||||
try:
|
||||
mem_available = int(line.split()[1])
|
||||
except (IndexError, ValueError):
|
||||
pass
|
||||
cpu_pct = _cpu_usage_percent(self._send_command(_CPU_SAMPLES))
|
||||
mem_total, mem_available = _meminfo_kib(self._send_command("cat /proc/meminfo"))
|
||||
|
||||
return {
|
||||
"fans": {},
|
||||
@@ -96,9 +141,7 @@ class OpenWrtSystemMixin:
|
||||
"""
|
||||
sys_out = self._send_command("uci show system 2>/dev/null || true")
|
||||
db_out = self._send_command("uci show dropbear 2>/dev/null || true")
|
||||
luci_out = self._send_command(
|
||||
"/etc/init.d/uhttpd enabled 2>/dev/null && echo 1 || echo 0"
|
||||
)
|
||||
luci_out = self._send_command("/etc/init.d/uhttpd enabled 2>/dev/null && echo 1 || echo 0")
|
||||
net_out = self._send_command("uci show network 2>/dev/null || true")
|
||||
|
||||
sys_cfg: dict[str, str] = {}
|
||||
@@ -239,7 +282,8 @@ class OpenWrtSystemMixin:
|
||||
running = (
|
||||
self._send_command(
|
||||
"/etc/init.d/snmpd running 2>/dev/null && echo active || echo inactive"
|
||||
).strip() == "active"
|
||||
).strip()
|
||||
== "active"
|
||||
)
|
||||
if not running:
|
||||
return None
|
||||
@@ -254,160 +298,10 @@ class OpenWrtSystemMixin:
|
||||
if uci_comm:
|
||||
community = uci_comm
|
||||
except Exception:
|
||||
pass
|
||||
logger.debug("snmpd community: ignored", exc_info=True)
|
||||
|
||||
return SNMPConfigDict(running=True, community=community, port=161, version="2c")
|
||||
|
||||
def _action_fix_snmp(self) -> dict[str, Any]:
|
||||
"""Install and configure snmpd on OpenWrt.
|
||||
|
||||
Installs snmpd-nossl (the daemon) and luci-app-snmpd (UCI schema +
|
||||
proper procd init script). Configures community 'public' via UCI.
|
||||
"""
|
||||
lines: list = []
|
||||
|
||||
# 1. Install packages — snmpd-nossl (daemon) + luci-app-snmpd (UCI init)
|
||||
pm = self._pm_type()
|
||||
if pm == "apk":
|
||||
raw = self._send_command("apk add snmpd-nossl luci-app-snmpd 2>&1")
|
||||
else:
|
||||
self._send_command("opkg update 2>/dev/null || true")
|
||||
raw = self._send_command("opkg install snmpd-nossl luci-app-snmpd 2>&1")
|
||||
out = self._clean_pkg_output(raw)
|
||||
low = out.lower()
|
||||
installed = not any(kw in low for kw in ("error:", "failed"))
|
||||
lines.append(f"[install] {out[-300:]}")
|
||||
|
||||
if not installed and "already installed" not in low:
|
||||
return {"success": False, "output": "\n".join(lines)}
|
||||
|
||||
# 2. Configure via UCI — modify the existing default sections only.
|
||||
# Do NOT create new named sections (causes duplicate directives in
|
||||
# the generated /var/run/snmpd.conf which crashes snmpd).
|
||||
# Also remove any stale named sections from previous fix attempts.
|
||||
# The init script reads these UCI field names to generate /var/run/snmpd.conf:
|
||||
# agent: agentaddress
|
||||
# com2sec: secname, source, community
|
||||
# group: group (name!), version, secname
|
||||
# view: viewname (not name!), type, oid
|
||||
# access: group, version, level, prefix, read, write, notify
|
||||
# Default luci-app-snmpd schema uses different field names for group/view/access,
|
||||
# so we patch all required fields explicitly.
|
||||
uci_cmds = [
|
||||
# Remove any stale named sections from previous runs
|
||||
"uci -q delete snmpd.agent",
|
||||
"uci -q delete snmpd.public",
|
||||
# agent
|
||||
"uci set snmpd.@agent[0].agentaddress='161'",
|
||||
# com2sec
|
||||
"uci set snmpd.@com2sec[0].secname='ro'",
|
||||
"uci set snmpd.@com2sec[0].source='0.0.0.0/0'",
|
||||
"uci set snmpd.@com2sec[0].community='public'",
|
||||
# group — init script reads field 'group' (not 'name')
|
||||
"uci set snmpd.@group[0].group='rogroup'",
|
||||
"uci set snmpd.@group[0].version='v2c'",
|
||||
"uci set snmpd.@group[0].secname='ro'",
|
||||
# view — init script reads field 'viewname' (not 'name')
|
||||
"uci set snmpd.@view[0].viewname='all'",
|
||||
"uci set snmpd.@view[0].type='included'",
|
||||
"uci set snmpd.@view[0].oid='.1'",
|
||||
# access — init script needs write + notify or it returns early
|
||||
"uci set snmpd.@access[0].group='rogroup'",
|
||||
"uci set snmpd.@access[0].context='none'",
|
||||
"uci set snmpd.@access[0].version='v2c'",
|
||||
"uci set snmpd.@access[0].level='noAuthNoPriv'",
|
||||
"uci set snmpd.@access[0].prefix='exact'",
|
||||
"uci set snmpd.@access[0].read='all'",
|
||||
"uci set snmpd.@access[0].write='none'",
|
||||
"uci set snmpd.@access[0].notify='none'",
|
||||
"uci commit snmpd",
|
||||
]
|
||||
for cmd in uci_cmds:
|
||||
self._send_command(f"{cmd} 2>/dev/null || true")
|
||||
lines.append("[config] Configured snmpd via UCI (all required fields set).")
|
||||
|
||||
# 3. Firewall: allow UDP 161 from the management zone
|
||||
try:
|
||||
# Use `ss` (always available on OpenWrt) to find the IP of the current SSH client
|
||||
raw_conn = self._send_command(
|
||||
"ss -tnp 2>/dev/null | awk '/ESTAB.*:22/{print $5}' | head -1 | sed 's/:[0-9]*$//'"
|
||||
).strip()
|
||||
# Strip IPv6-mapped prefix if present
|
||||
if raw_conn.startswith("::ffff:"):
|
||||
raw_conn = raw_conn[7:]
|
||||
peer_ip = raw_conn.splitlines()[-1].strip() if raw_conn else ""
|
||||
|
||||
if peer_ip and peer_ip not in ("", "0.0.0.0", "::"):
|
||||
# Determine which firewall zone owns the interface that routes to peer_ip.
|
||||
# Walk uci firewall zones: find the zone whose associated network interface
|
||||
# has an address in the same /24 as peer_ip.
|
||||
peer_prefix = peer_ip.rsplit(".", 1)[0] if "." in peer_ip else ""
|
||||
fw_out = self._send_command("uci show firewall 2>/dev/null || true")
|
||||
src_zone = "*"
|
||||
# Build map zone_name → zone_uci_key
|
||||
zone_map: dict[str, str] = {}
|
||||
for fw_line in fw_out.splitlines():
|
||||
m = re.match(r"firewall\.(\w+)\.name='([^']+)'", fw_line.strip())
|
||||
if m:
|
||||
zone_map[m.group(2)] = m.group(1)
|
||||
# For each zone find its network, then the interface IP
|
||||
for zone_name, uci_key in zone_map.items():
|
||||
net_line = self._send_command(
|
||||
f"uci -q get firewall.{uci_key}.network 2>/dev/null || true"
|
||||
).strip()
|
||||
if not net_line:
|
||||
continue
|
||||
for net_name in net_line.split():
|
||||
iface_ip = self._send_command(
|
||||
f"uci -q get network.{net_name}.ipaddr 2>/dev/null || true"
|
||||
).strip()
|
||||
if iface_ip and "." in iface_ip:
|
||||
iface_prefix = iface_ip.split("/")[0].rsplit(".", 1)[0]
|
||||
if peer_prefix and iface_prefix == peer_prefix:
|
||||
src_zone = zone_name
|
||||
break
|
||||
if src_zone != "*":
|
||||
break
|
||||
|
||||
self._send_command(
|
||||
f"uci -q delete firewall.snmp_netork 2>/dev/null; "
|
||||
f"uci set firewall.snmp_netork=rule; "
|
||||
f"uci set firewall.snmp_netork.name='Allow-SNMP-from-mgmt'; "
|
||||
f"uci set firewall.snmp_netork.src='{src_zone}'; "
|
||||
f"uci set firewall.snmp_netork.dest_port='161'; "
|
||||
f"uci set firewall.snmp_netork.proto='udp'; "
|
||||
f"uci set firewall.snmp_netork.target='ACCEPT'; "
|
||||
f"uci commit firewall; "
|
||||
f"/etc/init.d/firewall reload 2>/dev/null || true"
|
||||
)
|
||||
lines.append(f"[firewall] Added UDP:161 allow rule (src zone: {src_zone}).")
|
||||
else:
|
||||
lines.append("[firewall] Could not detect peer IP via ss — skipping firewall step.")
|
||||
except Exception as exc:
|
||||
lines.append(f"[firewall] skipped — {exc}")
|
||||
|
||||
# 4. Break any crash-loop, then start cleanly
|
||||
self._send_command("/etc/init.d/snmpd stop 2>/dev/null; true")
|
||||
_time.sleep(2)
|
||||
self._send_command("pkill -9 snmpd 2>/dev/null; true") # kill crash-loop zombie
|
||||
_time.sleep(3)
|
||||
self._send_command("/etc/init.d/snmpd enable 2>/dev/null; true")
|
||||
self._send_command("/etc/init.d/snmpd start 2>/dev/null; true")
|
||||
_time.sleep(4)
|
||||
lines.append("[service] snmpd started via procd.")
|
||||
|
||||
# 5. Check if snmpd is now active (no local snmpget on OpenWrt by default)
|
||||
status = self._send_command(
|
||||
"/etc/init.d/snmpd running 2>/dev/null && echo active || echo inactive"
|
||||
).strip()
|
||||
success = status == "active"
|
||||
if success:
|
||||
lines.append("[ok] snmpd is active.")
|
||||
else:
|
||||
lines.append(f"[warn] snmpd status: {status}")
|
||||
|
||||
return {"success": success, "output": "\n".join(lines)}
|
||||
|
||||
def get_users(self) -> dict[str, Any]:
|
||||
"""Return users configured on the device.
|
||||
|
||||
@@ -433,7 +327,13 @@ class OpenWrtSystemMixin:
|
||||
if len(parts) < 7:
|
||||
continue
|
||||
username, password_hash, uid_str, _, _, home, shell = (
|
||||
parts[0], parts[1], parts[2], parts[3], parts[4], parts[5], parts[6],
|
||||
parts[0],
|
||||
parts[1],
|
||||
parts[2],
|
||||
parts[3],
|
||||
parts[4],
|
||||
parts[5],
|
||||
parts[6],
|
||||
)
|
||||
if shell not in valid_shells:
|
||||
continue
|
||||
@@ -476,9 +376,7 @@ class OpenWrtSystemMixin:
|
||||
import json as _json
|
||||
|
||||
# -- enabled set: names from /etc/rc.d/S<priority><name> symlinks ----
|
||||
rc_out = self._send_command(
|
||||
"ls /etc/rc.d/ 2>/dev/null | grep '^S' | sed 's/^S[0-9]*//'"
|
||||
)
|
||||
rc_out = self._send_command("ls /etc/rc.d/ 2>/dev/null | grep '^S' | sed 's/^S[0-9]*//'")
|
||||
enabled: set[str] = {s.strip() for s in rc_out.splitlines() if s.strip()}
|
||||
|
||||
# -- running info from procd via ubus ---------------------------------
|
||||
@@ -496,9 +394,7 @@ class OpenWrtSystemMixin:
|
||||
continue
|
||||
instances = svc_info.get("instances", {})
|
||||
running = any(
|
||||
inst.get("running", False)
|
||||
for inst in instances.values()
|
||||
if isinstance(inst, dict)
|
||||
inst.get("running", False) for inst in instances.values() if isinstance(inst, dict)
|
||||
)
|
||||
pid = next(
|
||||
(
|
||||
@@ -522,97 +418,40 @@ class OpenWrtSystemMixin:
|
||||
result: list[dict[str, Any]] = []
|
||||
for name in sorted(all_names):
|
||||
info = service_map.get(name, {})
|
||||
result.append({
|
||||
"name": name,
|
||||
"running": info.get("running", False),
|
||||
"enabled": name in enabled,
|
||||
"pid": info.get("pid", 0),
|
||||
})
|
||||
result.append(
|
||||
{
|
||||
"name": name,
|
||||
"running": info.get("running", False),
|
||||
"enabled": name in enabled,
|
||||
"pid": info.get("pid", 0),
|
||||
}
|
||||
)
|
||||
|
||||
return result
|
||||
|
||||
def manage_service(self, name: str, action: str) -> dict[str, Any]:
|
||||
"""Execute a lifecycle action (start/stop/restart/enable/disable) on a service."""
|
||||
import re as _re
|
||||
if not _re.match(r'^[a-zA-Z0-9_\-]+$', name):
|
||||
raise ValueError(f"Invalid service name: {name!r}")
|
||||
if action not in ('start', 'stop', 'restart', 'enable', 'disable'):
|
||||
raise ValueError(f"Invalid action: {action!r}")
|
||||
output = self._send_command(f"/etc/init.d/{name} {action} 2>&1")
|
||||
return {"success": True, "output": output}
|
||||
"""Execute a lifecycle action (start/stop/restart/enable/disable) on a service.
|
||||
|
||||
def get_device_warnings(self) -> list[dict[str, Any]]:
|
||||
"""Return a list of warning dicts for issues detected on this device.
|
||||
|
||||
Currently detects:
|
||||
- lldpd not installed (LLDP neighbor discovery unavailable)
|
||||
- package updates available (uses local package cache, no network call)
|
||||
- update notifications not configured (auc not installed, opkg only)
|
||||
Only the init script's exit status decides ``success``; a missing script
|
||||
or a failed action comes back with what the device printed.
|
||||
"""
|
||||
warnings: list[dict[str, Any]] = []
|
||||
import re as _re
|
||||
|
||||
# 1. LLDP daemon
|
||||
lldpd_path = self._send_command("which lldpd 2>/dev/null").strip()
|
||||
if not lldpd_path:
|
||||
warnings.append({"code": "lldpd_not_installed"})
|
||||
|
||||
pm = self._pm_type()
|
||||
|
||||
# 2. Package updates available (local cache only – no opkg update)
|
||||
def _pkg_name(line: str, pm_type: str) -> str:
|
||||
"""Extract just the package name from an upgradable line.
|
||||
|
||||
apk: 'luci-app-firewall-26.143~abc < 26.151~def' → 'luci-app-firewall'
|
||||
opkg: 'luci-app-firewall - 1.0 - 1.1' → 'luci-app-firewall'
|
||||
"""
|
||||
import re as _re
|
||||
if pm_type == "apk":
|
||||
# Strip trailing ' < ...' then remove the version suffix (-\d...)
|
||||
name_ver = line.split(" ")[0]
|
||||
m = _re.match(r'^(.*?)-\d', name_ver)
|
||||
return m.group(1) if m else name_ver
|
||||
else:
|
||||
return line.split(" - ")[0].strip()
|
||||
|
||||
try:
|
||||
if pm == "apk":
|
||||
raw_upg = self._send_command("apk version 2>/dev/null | grep '<'")
|
||||
else:
|
||||
raw_upg = self._send_command("opkg list-upgradable 2>/dev/null")
|
||||
upgradable = [ln.strip() for ln in raw_upg.splitlines() if ln.strip()]
|
||||
except Exception:
|
||||
upgradable = []
|
||||
|
||||
if upgradable:
|
||||
pkg_names = [_pkg_name(ln, pm) for ln in upgradable]
|
||||
warnings.append({
|
||||
"code": "updates_available",
|
||||
"meta": {
|
||||
"count": len(upgradable),
|
||||
"packages": pkg_names[:10],
|
||||
},
|
||||
})
|
||||
|
||||
# 3. Attended sysupgrade client not installed (opkg systems only)
|
||||
if pm == "opkg":
|
||||
auc_path = self._send_command("which auc 2>/dev/null").strip()
|
||||
if not auc_path:
|
||||
warnings.append({"code": "update_notifications_disabled"})
|
||||
|
||||
# 4. base64 not available — needed for efficient config apply
|
||||
b64_path = self._send_command("command -v base64 2>/dev/null").strip()
|
||||
if not b64_path:
|
||||
warnings.append({"code": "no_base64"})
|
||||
|
||||
return warnings
|
||||
if not _re.match(r"^[a-zA-Z0-9_\-]+$", name):
|
||||
raise ValueError(f"Invalid service name: {name!r}")
|
||||
if action not in ("start", "stop", "restart", "enable", "disable"):
|
||||
raise ValueError(f"Invalid action: {action!r}")
|
||||
command = f"/etc/init.d/{name} {action}"
|
||||
return _status_result(self._send_command(f"{command} 2>&1; echo {_RC_MARKER}$?"), command)
|
||||
|
||||
def get_available_updates(self) -> list[dict[str, Any]]:
|
||||
"""Return list of upgradable packages from the local package manager cache.
|
||||
|
||||
OpenWrt keeps its package index in RAM. Without it -- after a reboot,
|
||||
before ``refresh_available_updates`` -- ``apk version`` only warns and
|
||||
``opkg list-upgradable`` prints nothing. Both raise here instead of
|
||||
reporting "nothing pending".
|
||||
``opkg list-upgradable`` prints nothing. Both raise
|
||||
:exc:`~napalm_device_types.PackageIndexMissing` here instead of reporting
|
||||
"nothing pending".
|
||||
"""
|
||||
if self._pm_type() == "apk":
|
||||
updates = self._updates_apk()
|
||||
@@ -627,17 +466,19 @@ class OpenWrtSystemMixin:
|
||||
if status != 0:
|
||||
raise RuntimeError(f"apk version failed (exit {status}): {output[-200:]}")
|
||||
if _APK_INDEX_MISSING.search(output):
|
||||
raise RuntimeError("The package index is not loaded (run apk update first)")
|
||||
raise PackageIndexMissing("The package index is not loaded (run apk update first)")
|
||||
updates: list[dict[str, Any]] = []
|
||||
for line in output.splitlines():
|
||||
# Output format: "pkgname-current_ver < new_ver"
|
||||
m = _re.match(r"^(.+)-(\d\S*)\s+<\s+(\S+)", line.strip())
|
||||
if m:
|
||||
updates.append({
|
||||
"name": m.group(1),
|
||||
"current_version": m.group(2),
|
||||
"new_version": m.group(3),
|
||||
})
|
||||
updates.append(
|
||||
{
|
||||
"name": m.group(1),
|
||||
"current_version": m.group(2),
|
||||
"new_version": m.group(3),
|
||||
}
|
||||
)
|
||||
return updates
|
||||
|
||||
def _updates_opkg(self) -> list[dict[str, Any]]:
|
||||
@@ -646,17 +487,19 @@ class OpenWrtSystemMixin:
|
||||
"opkg list-upgradable 2>/dev/null"
|
||||
)
|
||||
if "__NO_INDEX__" in raw:
|
||||
raise RuntimeError("The package index is not loaded (run opkg update first)")
|
||||
raise PackageIndexMissing("The package index is not loaded (run opkg update first)")
|
||||
updates: list[dict[str, Any]] = []
|
||||
for line in raw.splitlines():
|
||||
# opkg output: "pkgname - current_ver - new_ver"
|
||||
parts = [p.strip() for p in line.split(" - ")]
|
||||
if len(parts) == 3:
|
||||
updates.append({
|
||||
"name": parts[0],
|
||||
"current_version": parts[1],
|
||||
"new_version": parts[2],
|
||||
})
|
||||
updates.append(
|
||||
{
|
||||
"name": parts[0],
|
||||
"current_version": parts[1],
|
||||
"new_version": parts[2],
|
||||
}
|
||||
)
|
||||
return updates
|
||||
|
||||
def refresh_available_updates(self) -> dict[str, Any]:
|
||||
@@ -666,53 +509,35 @@ class OpenWrtSystemMixin:
|
||||
return {"success": status == 0, "output": output}
|
||||
|
||||
def apply_updates(self, packages: list[str]) -> dict[str, Any]:
|
||||
"""Upgrade the given packages using the device's package manager."""
|
||||
"""Upgrade the given packages using the device's package manager.
|
||||
|
||||
Only the package manager's exit status decides ``success``.
|
||||
"""
|
||||
import re as _re
|
||||
|
||||
for pkg in packages:
|
||||
if not _re.match(r'^[a-zA-Z0-9_\-\+\.]+$', pkg):
|
||||
if not _re.match(r"^[a-zA-Z0-9_\-\+\.]+$", pkg):
|
||||
raise ValueError(f"Invalid package name: {pkg!r}")
|
||||
pm = self._pm_type()
|
||||
pkg_args = " ".join(packages)
|
||||
if pm == "apk":
|
||||
cmd = f"apk upgrade {pkg_args} 2>&1"
|
||||
cmd = f"apk upgrade {pkg_args}"
|
||||
else:
|
||||
cmd = f"opkg upgrade {pkg_args} 2>&1"
|
||||
output = self._send_command(cmd)
|
||||
return {"success": True, "output": output}
|
||||
cmd = f"opkg upgrade {pkg_args}"
|
||||
output, status = _split_status(self._send_command(f"{cmd} 2>&1; echo {_RC_MARKER}$?"))
|
||||
if status == 0:
|
||||
return {"success": True, "output": output}
|
||||
error = (
|
||||
f"{cmd.strip()} exited with status {status}"
|
||||
if status is not None
|
||||
else "No exit status came back from the device."
|
||||
)
|
||||
return {"success": False, "output": output, "error": error}
|
||||
|
||||
# ------------------------------------------------------------------
|
||||
# NTP
|
||||
# NTP statistics (the servers: time_sync_mixin)
|
||||
# ------------------------------------------------------------------
|
||||
|
||||
def get_ntp_servers(self) -> dict[str, Any]:
|
||||
"""Return configured NTP servers from ``uci show system``.
|
||||
|
||||
UCI example::
|
||||
|
||||
system.ntp.server='0.openwrt.pool.ntp.org 1.openwrt.pool.ntp.org'
|
||||
"""
|
||||
uci_out = self._send_command("uci show system")
|
||||
servers: dict[str, Any] = {}
|
||||
|
||||
for line in uci_out.splitlines():
|
||||
# Handles both list and single-value UCI representations
|
||||
m = re.match(r"system\.ntp\.server(?:\[\d+\])?='([^']*)'", line.strip())
|
||||
if m:
|
||||
for srv in m.group(1).split():
|
||||
srv = srv.strip()
|
||||
if srv:
|
||||
servers[srv] = {}
|
||||
|
||||
return servers
|
||||
|
||||
def get_ntp_peers(self) -> dict[str, Any]:
|
||||
"""Return NTP peers from ``uci show system``.
|
||||
|
||||
OpenWrt's busybox ntpd does not differentiate peers from servers;
|
||||
the same UCI ``ntp.server`` list is returned.
|
||||
"""
|
||||
return self.get_ntp_servers()
|
||||
|
||||
def get_ntp_stats(self) -> list[dict[str, Any]]:
|
||||
"""Return NTP synchronisation statistics.
|
||||
|
||||
@@ -721,11 +546,11 @@ class OpenWrtSystemMixin:
|
||||
|
||||
``ntpq -pn`` example line::
|
||||
|
||||
*188.114.101.4 188.114.100.1 4 u 107 256 377 164.228 -13.866 2.695
|
||||
*203.0.113.104 203.0.113.100 4 u 107 256 377 164.228 -13.866 2.695
|
||||
|
||||
``chronyc sources -v`` example line::
|
||||
|
||||
^* 192.168.1.1 2 6 17 8 +2345us[ 0ns] +/- 15ms
|
||||
^* 192.0.2.1 2 6 17 8 +2345us[ 0ns] +/- 15ms
|
||||
"""
|
||||
ntpq_out = self._send_command("ntpq -pn")
|
||||
if ntpq_out and not ntpq_out.startswith(("ntpq: ", "sh: ", "ash: ", "command not found")):
|
||||
@@ -751,19 +576,21 @@ class OpenWrtSystemMixin:
|
||||
if len(parts) < 10:
|
||||
continue
|
||||
try:
|
||||
stats.append({
|
||||
"remote": parts[0],
|
||||
"referenceid": parts[1],
|
||||
"synchronized": tally == "*",
|
||||
"stratum": int(parts[2]),
|
||||
"type": parts[3],
|
||||
"when": parts[4],
|
||||
"hostpoll": int(parts[5]),
|
||||
"reachability": int(parts[6], 8), # octal
|
||||
"delay": float(parts[7]),
|
||||
"offset": float(parts[8]),
|
||||
"jitter": float(parts[9]),
|
||||
})
|
||||
stats.append(
|
||||
{
|
||||
"remote": parts[0],
|
||||
"referenceid": parts[1],
|
||||
"synchronized": tally == "*",
|
||||
"stratum": int(parts[2]),
|
||||
"type": parts[3],
|
||||
"when": parts[4],
|
||||
"hostpoll": int(parts[5]),
|
||||
"reachability": int(parts[6], 8), # octal
|
||||
"delay": float(parts[7]),
|
||||
"offset": float(parts[8]),
|
||||
"jitter": float(parts[9]),
|
||||
}
|
||||
)
|
||||
except (ValueError, IndexError):
|
||||
continue
|
||||
return stats
|
||||
@@ -780,19 +607,23 @@ class OpenWrtSystemMixin:
|
||||
continue
|
||||
tally = m.group(1)
|
||||
try:
|
||||
stats.append({
|
||||
"remote": m.group(2),
|
||||
"referenceid": "",
|
||||
"synchronized": tally == "^*",
|
||||
"stratum": int(m.group(3)),
|
||||
"type": "u",
|
||||
"when": m.group(6),
|
||||
"hostpoll": int(m.group(4)),
|
||||
"reachability": int(m.group(5), 8) if re.match(r"^[0-7]+$", m.group(5)) else 0,
|
||||
"delay": 0.0,
|
||||
"offset": 0.0,
|
||||
"jitter": 0.0,
|
||||
})
|
||||
stats.append(
|
||||
{
|
||||
"remote": m.group(2),
|
||||
"referenceid": "",
|
||||
"synchronized": tally == "^*",
|
||||
"stratum": int(m.group(3)),
|
||||
"type": "u",
|
||||
"when": m.group(6),
|
||||
"hostpoll": int(m.group(4)),
|
||||
"reachability": int(m.group(5), 8)
|
||||
if re.match(r"^[0-7]+$", m.group(5))
|
||||
else 0,
|
||||
"delay": 0.0,
|
||||
"offset": 0.0,
|
||||
"jitter": 0.0,
|
||||
}
|
||||
)
|
||||
except (ValueError, IndexError):
|
||||
continue
|
||||
return stats
|
||||
@@ -0,0 +1,358 @@
|
||||
# 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.
|
||||
|
||||
"""Time sync on OpenWrt: UCI's ``system`` config (napalm-device-types ``TimeSyncMixin``).
|
||||
|
||||
OpenWrt keeps both values in ``/etc/config/system`` (NetOrk/netork#2364):
|
||||
|
||||
* **The servers** are the ``system.ntp.server`` list, which ``/etc/init.d/sysntpd``
|
||||
hands to BusyBox ntpd while ``system.ntp.enabled`` is on. A disabled client has no
|
||||
servers: the list names nothing the clock takes time from.
|
||||
* **What DHCP brings** (option 42) counts too (NetOrk/netork#2380): while ``use_dhcp``
|
||||
is on (the default) sysntpd adds the NTP servers of every interface's lease -- or of
|
||||
the ``dhcp_interface`` list's only -- that netifd keeps as ``data.ntpserver`` in
|
||||
``ubus call network.interface dump`` (``/lib/netifd/dhcp.script`` stores udhcpc's
|
||||
``ntpsrv`` there). They are read from the same place, in the same order, as
|
||||
``dhcp_ntp_servers``; a write leaves ``use_dhcp`` as the router has it.
|
||||
* **The zone** is kept twice: ``zonename`` (the IANA name, as LuCI writes it -- with
|
||||
spaces where the IANA name has underscores) and ``timezone``, the POSIX rule
|
||||
``/etc/init.d/system`` writes to ``/tmp/TZ`` for libc. The rule is what the clock
|
||||
runs on: an IANA name written there left an AP on UTC (NetOrk/netork#1849). So the
|
||||
name is read as the zone only where the rule in force is that zone's; a rule
|
||||
without a matching name is read as the one zone that has it, or as no zone where
|
||||
several do (``CET-1CEST,...`` is Berlin, Paris, Madrid, ...).
|
||||
|
||||
Reading is one round trip as the login user: ``uci -q show system``, then netifd's
|
||||
dump (:data:`READ_WITH_DHCP`). A write reads ``uci`` alone. Every write compares
|
||||
first and sends nothing when the router already has the values -- an application
|
||||
aligns on every poll -- else sets the options, commits ``system`` and applies them:
|
||||
``/etc/init.d/sysntpd restart`` for the servers, ``/etc/init.d/system reload`` and a
|
||||
restart of logd, which reads the zone when it starts, for the zone. Writes run as
|
||||
root (``run_command(privileged=True)``); OpenWrt has no sudo.
|
||||
|
||||
``synchronized`` is None: BusyBox ntpd keeps no state another process can read, and
|
||||
``ubus call system info`` says nothing about the clock's source.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import shlex
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass, field
|
||||
from functools import lru_cache
|
||||
from importlib.resources import files
|
||||
from typing import TYPE_CHECKING, Any, ClassVar
|
||||
|
||||
from napalm_device_types import FixStepOutcomeDict
|
||||
from napalm_device_types.posix_tz import is_iana_zone, parse_posix_tz, posix_tz
|
||||
from napalm_device_types.time_sync import TIME_SYNC_VALUES, TimeSyncDict, TimeSyncMixin
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from napalm_device_types import CommandResult
|
||||
|
||||
READ_COMMAND = "uci -q show system"
|
||||
#: The line between uci's answer and netifd's in :data:`READ_WITH_DHCP`.
|
||||
DHCP_MARK = "@@napalm-openwrt: network.interface dump"
|
||||
#: ``get_time_sync``'s reading: uci's ``system`` config, then netifd's interfaces, where
|
||||
#: a lease keeps its NTP servers. Its exit code is uci's: ubus may refuse, uci may not.
|
||||
READ_WITH_DHCP = (
|
||||
f"{READ_COMMAND} && {{ echo {shlex.quote(DHCP_MARK)}; "
|
||||
"ubus call network.interface dump 2>/dev/null || true; }"
|
||||
)
|
||||
#: The rule ``/etc/init.d/system`` uses where the section names none.
|
||||
DEFAULT_RULE = "UTC"
|
||||
#: A zone of the database that stands for "not known", not for a place.
|
||||
_NO_PLACE = frozenset({"Factory"})
|
||||
#: ``system.<section>.<option>='value' ['value' ...]`` of the two sections that count.
|
||||
_OPTION = re.compile(r"^system\.(?P<section>@system\[0\]|ntp)\.(?P<option>\w+)=(?P<value>.*)$")
|
||||
_FALSE = frozenset({"0", "no", "off", "false", "disabled"})
|
||||
|
||||
|
||||
@dataclass
|
||||
class SystemUci:
|
||||
"""What ``uci -q show system`` says about the clock."""
|
||||
|
||||
has_system: bool = False
|
||||
has_ntp: bool = False
|
||||
system: dict[str, list[str]] = field(default_factory=dict)
|
||||
ntp: dict[str, list[str]] = field(default_factory=dict)
|
||||
|
||||
def _one(self, options: dict[str, list[str]], name: str) -> str | None:
|
||||
values = options.get(name)
|
||||
return values[0] if values else None
|
||||
|
||||
@property
|
||||
def configured_servers(self) -> list[str]:
|
||||
"""The list as it stands; an option of servers apart by spaces is split, as sysntpd does."""
|
||||
return [s for value in self.ntp.get("server", []) for s in value.split()]
|
||||
|
||||
@property
|
||||
def ntp_enabled(self) -> bool:
|
||||
return (self._one(self.ntp, "enabled") or "1").lower() not in _FALSE
|
||||
|
||||
@property
|
||||
def dhcp_servers(self) -> bool:
|
||||
"""Whether sysntpd adds a lease's servers: the client runs and ``use_dhcp`` is on."""
|
||||
use_dhcp = (self._one(self.ntp, "use_dhcp") or "1").lower() not in _FALSE
|
||||
return self.has_ntp and self.ntp_enabled and use_dhcp
|
||||
|
||||
@property
|
||||
def dhcp_interfaces(self) -> list[str]:
|
||||
"""The interfaces whose leases count; [] for every interface, as sysntpd does."""
|
||||
return [i for value in self.ntp.get("dhcp_interface", []) for i in value.split()]
|
||||
|
||||
@property
|
||||
def servers(self) -> list[str]:
|
||||
"""The servers the clock takes time from: none while the client is off."""
|
||||
return self.configured_servers if self.has_ntp and self.ntp_enabled else []
|
||||
|
||||
@property
|
||||
def zonename(self) -> str | None:
|
||||
"""``zonename`` as an IANA name: LuCI's spaces back to underscores."""
|
||||
name = self._one(self.system, "zonename")
|
||||
return name.strip().replace(" ", "_") if name and name.strip() else None
|
||||
|
||||
@property
|
||||
def rule(self) -> str:
|
||||
return (self._one(self.system, "timezone") or "").strip() or DEFAULT_RULE
|
||||
|
||||
@property
|
||||
def zone(self) -> str | None:
|
||||
"""The zone the clock runs in, by name; None where no single zone is it."""
|
||||
if not self.has_system:
|
||||
return None
|
||||
name = self.zonename
|
||||
named = posix_tz(name) if name and is_iana_zone(name) else None
|
||||
if name and named and same_time(self.rule, named):
|
||||
return name
|
||||
return zone_for_rule(self.rule)
|
||||
|
||||
|
||||
def parse_system_uci(output: str) -> SystemUci:
|
||||
"""``uci show system`` in parts: the first system section and the ``ntp`` one."""
|
||||
parsed = SystemUci()
|
||||
for line in output.splitlines():
|
||||
line = line.strip()
|
||||
if line.startswith("system.@system[0]="):
|
||||
parsed.has_system = True
|
||||
elif line.startswith("system.ntp="):
|
||||
parsed.has_ntp = True
|
||||
match = _OPTION.match(line)
|
||||
if match is None:
|
||||
continue
|
||||
try:
|
||||
values = shlex.split(match["value"])
|
||||
except ValueError:
|
||||
continue
|
||||
options = parsed.system if match["section"] == "@system[0]" else parsed.ntp
|
||||
options[match["option"]] = values
|
||||
return parsed
|
||||
|
||||
|
||||
def _lease_servers(entry: Any, interfaces: list[str]) -> list[str]:
|
||||
"""One interface's ``data.ntpserver``, if it is one of *interfaces* (or they are [])."""
|
||||
if not isinstance(entry, dict) or (interfaces and entry.get("interface") not in interfaces):
|
||||
return []
|
||||
data = entry.get("data")
|
||||
servers = data.get("ntpserver") if isinstance(data, dict) else None
|
||||
return servers.split() if isinstance(servers, str) else []
|
||||
|
||||
|
||||
def lease_ntp_servers(dump: str, interfaces: list[str]) -> list[str] | None:
|
||||
"""The NTP servers in netifd's ``network.interface dump``, as sysntpd collects them:
|
||||
each interface's ``data.ntpserver`` (apart by spaces) in netifd's order, of
|
||||
*interfaces* only where it names any, each once. None for no readable answer."""
|
||||
try:
|
||||
parsed = json.loads(dump)
|
||||
except ValueError:
|
||||
return None
|
||||
if not isinstance(parsed, dict) or not isinstance(parsed.get("interface"), list):
|
||||
return None
|
||||
found: list[str] = []
|
||||
for entry in parsed["interface"]:
|
||||
found.extend(s for s in _lease_servers(entry, interfaces) if s not in found)
|
||||
return found
|
||||
|
||||
|
||||
def _time_of(rule: str) -> tuple[Any, ...] | None:
|
||||
"""The offsets and transitions of *rule*, without the names it gives them."""
|
||||
parts = parse_posix_tz(rule)
|
||||
if parts is None:
|
||||
return None
|
||||
return (
|
||||
parts["utc_offset"],
|
||||
parts["dst_offset"],
|
||||
tuple(sorted((parts["dst_start"] or {}).items())),
|
||||
tuple(sorted((parts["dst_end"] or {}).items())),
|
||||
)
|
||||
|
||||
|
||||
def same_time(rule: str, other: str) -> bool:
|
||||
"""Whether two rules keep the same time: ``GMT0`` is ``UTC0`` by another name."""
|
||||
time = _time_of(rule)
|
||||
return rule == other if time is None else time == _time_of(other)
|
||||
|
||||
|
||||
@lru_cache(maxsize=1)
|
||||
def _zones_by_rule() -> dict[str, tuple[str, ...]]:
|
||||
"""Every zone of the database (not its links) by its rule, names and all."""
|
||||
source = files("tzdata").joinpath("zoneinfo", "tzdata.zi").read_text(encoding="utf-8")
|
||||
zones: defaultdict[str, list[str]] = defaultdict(list)
|
||||
for line in source.splitlines():
|
||||
if not line.startswith("Z "):
|
||||
continue
|
||||
zone = line.split()[1]
|
||||
rule = posix_tz(zone)
|
||||
if rule is not None and zone not in _NO_PLACE:
|
||||
zones[_rule_key(rule)].append(zone)
|
||||
return {rule: tuple(names) for rule, names in zones.items()}
|
||||
|
||||
|
||||
def _rule_key(rule: str) -> str:
|
||||
parts = parse_posix_tz(rule)
|
||||
return rule if parts is None else repr(sorted(parts.items()))
|
||||
|
||||
|
||||
def zone_for_rule(rule: str) -> str | None:
|
||||
"""The one zone whose rule *rule* is; None where none or several are.
|
||||
|
||||
Several zones share most rules (``CET-1CEST,M3.5.0,M10.5.0/3`` is Berlin, Paris,
|
||||
Madrid, ...): which of them a router means is not the driver's to guess. Links
|
||||
(``Asia/Calcutta``) count as the zone they point at.
|
||||
"""
|
||||
if not rule:
|
||||
return None
|
||||
zones = _zones_by_rule().get(_rule_key(rule), ())
|
||||
return zones[0] if len(zones) == 1 else None
|
||||
|
||||
|
||||
def _luci_name(zone: str) -> str:
|
||||
"""*zone* as LuCI keeps it in ``zonename``, so its zone list shows it chosen."""
|
||||
return zone.replace("_", " ")
|
||||
|
||||
|
||||
def _uci_command(*words: str) -> str:
|
||||
return shlex.join(words)
|
||||
|
||||
|
||||
class OpenWrtTimeSyncMixin(TimeSyncMixin):
|
||||
"""The servers and the zone in UCI's ``system`` config; see the module."""
|
||||
|
||||
time_sync_writes: ClassVar[frozenset[str]] = TIME_SYNC_VALUES
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - the driver's
|
||||
|
||||
def run_command(
|
||||
self,
|
||||
command: str,
|
||||
*,
|
||||
privileged: bool = False,
|
||||
timeout: float = 60,
|
||||
stdin: bytes | None = None,
|
||||
) -> CommandResult: ...
|
||||
|
||||
# -- reading ---------------------------------------------------------------------------------
|
||||
|
||||
def _ts_run_read(self, command: str) -> str:
|
||||
result = self.run_command(command, timeout=30)
|
||||
if result.exit_code != 0:
|
||||
said = result.stderr.strip() or result.stdout.strip() or f"exit {result.exit_code}"
|
||||
raise RuntimeError(f"{READ_COMMAND}: {said}")
|
||||
return result.stdout
|
||||
|
||||
def _ts_read(self) -> SystemUci:
|
||||
return parse_system_uci(self._ts_run_read(READ_COMMAND))
|
||||
|
||||
def get_time_sync(self) -> TimeSyncDict:
|
||||
"""The router's time servers and zone, and what its DHCP leases bring, in one
|
||||
round trip (:data:`READ_WITH_DHCP`).
|
||||
|
||||
``dhcp_ntp_servers`` is None where sysntpd would add a lease's servers but
|
||||
netifd gave no answer.
|
||||
|
||||
:raises RuntimeError: when uci could not be read.
|
||||
"""
|
||||
uci, _, dump = self._ts_run_read(READ_WITH_DHCP).partition(f"{DHCP_MARK}\n")
|
||||
reading = parse_system_uci(uci)
|
||||
dhcp = lease_ntp_servers(dump, reading.dhcp_interfaces) if reading.dhcp_servers else []
|
||||
return {
|
||||
"ntp_servers": reading.servers,
|
||||
"timezone": reading.zone,
|
||||
"synchronized": None,
|
||||
"daemon": None,
|
||||
"dhcp_ntp_servers": dhcp,
|
||||
}
|
||||
|
||||
def get_ntp_servers(self) -> dict[str, dict[str, Any]]:
|
||||
"""The servers of :meth:`get_time_sync`, as NAPALM's ``{server: {}}``."""
|
||||
return {server: {} for server in self._ts_read().servers}
|
||||
|
||||
def get_ntp_peers(self) -> dict[str, dict[str, Any]]:
|
||||
"""BusyBox ntpd has no peers apart from its servers: the same list."""
|
||||
return self.get_ntp_servers()
|
||||
|
||||
# -- writing ---------------------------------------------------------------------------------
|
||||
|
||||
def _ts_apply(self, commands: list[str], done: str) -> FixStepOutcomeDict:
|
||||
result = self.run_command(" && ".join(commands), privileged=True, timeout=60)
|
||||
if result.exit_code != 0:
|
||||
said = result.stderr.strip() or result.stdout.strip() or f"exit {result.exit_code}"
|
||||
return {"ok": False, "output": said[-300:]}
|
||||
return {"ok": True, "output": done}
|
||||
|
||||
def _write_ntp_servers(self, servers: list[str]) -> FixStepOutcomeDict:
|
||||
now = self._ts_read()
|
||||
if [s.lower() for s in now.servers] == [s.lower() for s in servers]:
|
||||
return {"ok": True, "output": "the router already has these servers"}
|
||||
commands = []
|
||||
if not now.has_ntp:
|
||||
commands.append(_uci_command("uci", "set", "system.ntp=timeserver"))
|
||||
if "server" in now.ntp:
|
||||
commands.append(_uci_command("uci", "delete", "system.ntp.server"))
|
||||
commands += [_uci_command("uci", "add_list", f"system.ntp.server={s}") for s in servers]
|
||||
commands += [
|
||||
"uci set system.ntp.enabled=1",
|
||||
"uci commit system",
|
||||
"/etc/init.d/sysntpd enable",
|
||||
"/etc/init.d/sysntpd restart",
|
||||
]
|
||||
return self._ts_apply(commands, f"ntpd takes time from {', '.join(servers)}")
|
||||
|
||||
def _write_time_zone(self, zone: str) -> FixStepOutcomeDict:
|
||||
rule = posix_tz(zone)
|
||||
if rule is None: # the template lets only zones of the database through
|
||||
return {"ok": False, "output": f"no POSIX rule for {zone}"}
|
||||
now = self._ts_read()
|
||||
if now.has_system and now.zonename == zone and same_time(now.rule, rule):
|
||||
return {"ok": True, "output": f"the router is already in {zone}"}
|
||||
commands = [
|
||||
_uci_command("uci", "set", f"system.@system[0].zonename={_luci_name(zone)}"),
|
||||
_uci_command("uci", "set", f"system.@system[0].timezone={rule}"),
|
||||
"uci commit system",
|
||||
"/etc/init.d/system reload",
|
||||
"/etc/init.d/log restart",
|
||||
]
|
||||
return self._ts_apply(commands, f"time zone set to {zone} ({rule})")
|
||||
|
||||
|
||||
__all__ = [
|
||||
"DHCP_MARK",
|
||||
"READ_WITH_DHCP",
|
||||
"OpenWrtTimeSyncMixin",
|
||||
"SystemUci",
|
||||
"lease_ntp_servers",
|
||||
"parse_system_uci",
|
||||
"same_time",
|
||||
"zone_for_rule",
|
||||
]
|
||||
@@ -0,0 +1,147 @@
|
||||
# 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.
|
||||
|
||||
"""UCI writes run step by step, each step's exit status checked (#35).
|
||||
|
||||
A write stages its changes with one ``uci`` command each, commits the config, then
|
||||
restarts what reads it. Every step runs on an SSH exec channel of its own, so its exit
|
||||
status is the command's own -- nothing is hidden behind ``|| true`` or a shell prompt.
|
||||
|
||||
A refused step raises :class:`CommandErrorException` naming the step and what the
|
||||
device said. A refusal before the commit reverts what was staged, so the next commit
|
||||
of the config -- by any write -- does not apply half a change; nothing is restarted.
|
||||
A refused restart comes after the commit: the change is saved, and the error says so.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
import shlex
|
||||
from collections.abc import Sequence
|
||||
from dataclasses import dataclass, field
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from napalm.base.exceptions import CommandErrorException
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - typing only
|
||||
from napalm_device_types import CommandResult
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
#: Seconds one step may take; ``wifi`` brings every radio down and up again.
|
||||
UCI_STEP_TIMEOUT = 60
|
||||
|
||||
#: ``config.section=type`` or ``config.section.option=value`` of ``uci show``.
|
||||
_SHOW_LINE = re.compile(
|
||||
r"^(?P<config>[^.=\s]+)\.(?P<section>[^.=\s]+)(?:\.(?P<option>[^=\s]+))?=(?P<value>.*)$"
|
||||
)
|
||||
|
||||
|
||||
def uci(*words: str) -> str:
|
||||
"""A ``uci`` command line, every word quoted for the shell where it needs it."""
|
||||
return shlex.join(["uci", *words])
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class UciSection:
|
||||
"""One section of ``uci show``: its name (``default_radio0``, ``@wifi-iface[0]``),
|
||||
its type and its options, each a list of values (one for an option, more for a list).
|
||||
"""
|
||||
|
||||
config: str
|
||||
name: str
|
||||
type: str
|
||||
options: dict[str, list[str]] = field(default_factory=dict)
|
||||
|
||||
@property
|
||||
def ref(self) -> str:
|
||||
"""The section as ``uci`` addresses it: ``wireless.default_radio0``."""
|
||||
return f"{self.config}.{self.name}"
|
||||
|
||||
|
||||
def _values(raw: str) -> list[str]:
|
||||
"""``'a' 'b'`` as uci prints it, a quote inside a value as ``'\\''``."""
|
||||
try:
|
||||
return shlex.split(raw)
|
||||
except ValueError:
|
||||
return [raw]
|
||||
|
||||
|
||||
def parse_uci_show(text: str) -> list[UciSection]:
|
||||
"""The sections of ``uci show <config>``, in the order printed."""
|
||||
sections: dict[str, UciSection] = {}
|
||||
for line in text.splitlines():
|
||||
m = _SHOW_LINE.match(line.strip())
|
||||
if not m:
|
||||
continue
|
||||
key = f"{m['config']}.{m['section']}"
|
||||
if m["option"] is None:
|
||||
sections[key] = UciSection(m["config"], m["section"], m["value"].strip())
|
||||
elif key in sections:
|
||||
sections[key].options[m["option"]] = _values(m["value"])
|
||||
return list(sections.values())
|
||||
|
||||
|
||||
class UciStepsMixin:
|
||||
"""Run a UCI write as checked steps; see the module."""
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - the driver's
|
||||
hostname: str
|
||||
|
||||
def run_command(
|
||||
self,
|
||||
command: str,
|
||||
*,
|
||||
privileged: bool = False,
|
||||
timeout: float = 60,
|
||||
stdin: bytes | None = None,
|
||||
) -> CommandResult: ...
|
||||
|
||||
def _uci_step(self, command: str) -> str:
|
||||
"""Run one step as root and return what it printed.
|
||||
|
||||
:raises CommandErrorException: when it exits non-zero, naming the step.
|
||||
:raises PermissionError: for a login other than root, before it runs.
|
||||
"""
|
||||
result = self.run_command(command, privileged=True, timeout=UCI_STEP_TIMEOUT)
|
||||
if result.exit_code != 0:
|
||||
said = result.stderr.strip() or result.stdout.strip()
|
||||
said = said or f"exit status {result.exit_code}"
|
||||
raise CommandErrorException(f"{self.hostname}: `{command}` failed: {said}")
|
||||
return result.stdout
|
||||
|
||||
def _uci_apply(self, config: str, changes: Sequence[str], restart: str) -> None:
|
||||
"""Stage *changes* to *config*, commit it, then run *restart*.
|
||||
|
||||
:raises CommandErrorException: for the first step refused; see the module.
|
||||
"""
|
||||
try:
|
||||
for change in changes:
|
||||
self._uci_step(change)
|
||||
self._uci_step(uci("commit", config))
|
||||
except Exception:
|
||||
self._uci_revert(config)
|
||||
raise
|
||||
try:
|
||||
self._uci_step(restart)
|
||||
except CommandErrorException as exc:
|
||||
raise CommandErrorException(
|
||||
f"{exc} -- the {config} change is committed and applies at the next restart"
|
||||
) from exc
|
||||
|
||||
def _uci_revert(self, config: str) -> None:
|
||||
"""Drop what is staged for *config*; a failure is logged, the refusal stays the error."""
|
||||
try:
|
||||
self._uci_step(uci("revert", config))
|
||||
except Exception as exc:
|
||||
logger.warning("%s: staged %s changes not reverted: %s", self.hostname, config, exc)
|
||||
@@ -1,4 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# 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
|
||||
@@ -16,6 +15,8 @@ from __future__ import annotations
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from napalm_openwrt.uci_steps import uci
|
||||
|
||||
|
||||
def _split_uci_list(value: str) -> list[str]:
|
||||
"""Split a ``uci show`` option value into its items.
|
||||
@@ -172,7 +173,7 @@ class OpenWrtVLANMixin:
|
||||
vm = re.match(r"^([\w-]+)\.(\d+)$", iface) # allow hyphens (br-ap)
|
||||
if not vm:
|
||||
continue
|
||||
parent = vm.group(1) # e.g. "eth0" or "br-ap"
|
||||
parent = vm.group(1) # e.g. "eth0" or "br-ap"
|
||||
vlan_id = str(int(vm.group(2))) # e.g. "10"
|
||||
vlans.setdefault(vlan_id, {"name": "", "tagged": [], "untagged": []})
|
||||
# sub-interface itself -> untagged egress
|
||||
@@ -210,11 +211,13 @@ class OpenWrtVLANMixin:
|
||||
# No explicit bridge-vlan section -- nothing to delete via UCI
|
||||
return
|
||||
|
||||
self.cli([
|
||||
f"uci delete network.@bridge-vlan[{idx}]",
|
||||
"uci commit network",
|
||||
"/etc/init.d/network reload",
|
||||
])
|
||||
self.cli(
|
||||
[
|
||||
f"uci delete network.@bridge-vlan[{idx}]",
|
||||
"uci commit network",
|
||||
"/etc/init.d/network reload",
|
||||
]
|
||||
)
|
||||
|
||||
def get_network_instances(self, name: str = "") -> dict[str, Any]:
|
||||
"""Return network instances (Linux network namespaces + default).
|
||||
@@ -279,9 +282,14 @@ class OpenWrtVLANMixin:
|
||||
return instances
|
||||
|
||||
def set_hostname(self, new_hostname: str) -> None:
|
||||
"""Set the system hostname via UCI and reload the system service."""
|
||||
"""Set the system hostname via UCI and reload the system service.
|
||||
|
||||
The name reaches ``uci`` as one shell word, whatever it holds
|
||||
(NetOrk/netork#2456): between single quotes of its own, a name with a
|
||||
single quote ended them and the rest ran as root.
|
||||
"""
|
||||
self._send_command(
|
||||
f"uci set system.@system[0].hostname='{new_hostname}' && "
|
||||
f"{uci('set', f'system.@system[0].hostname={new_hostname}')} && "
|
||||
f"uci commit system && "
|
||||
f"/etc/init.d/system reload"
|
||||
)
|
||||
@@ -1,4 +1,3 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
# 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
|
||||
@@ -13,11 +12,44 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from napalm.base.exceptions import CommandErrorException
|
||||
|
||||
class OpenWrtWirelessMixin:
|
||||
from napalm_openwrt.uci_steps import UciSection, UciStepsMixin, parse_uci_show, uci
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
_WIRELESS = "wireless"
|
||||
_SHOW_WIRELESS = "uci -q show wireless"
|
||||
#: Re-applies the config; enough for a MAC filter.
|
||||
_WIFI_RELOAD = "wifi reload"
|
||||
#: A full down/up of every radio; a channel needs it (see ``push_radio_channel``).
|
||||
_WIFI_RESTART = "wifi"
|
||||
_ACL_OPTIONS = ("macfilter", "maclist")
|
||||
#: The modes ``push_mac_acl`` takes, and the ``macfilter`` each writes ("off" writes none).
|
||||
_MACFILTER_BY_MODE = {"whitelist": "allow", "blacklist": "deny", "off": None}
|
||||
|
||||
|
||||
def _mac_acl_changes(sec: UciSection, mode: str, macs: list[str]) -> list[str]:
|
||||
"""The ``uci`` changes that give *sec* the ACL *mode* with *macs*.
|
||||
|
||||
"off" deletes both options; there is no value for it. Otherwise the list is
|
||||
rebuilt: deleted where the section has one, then each MAC added.
|
||||
"""
|
||||
present = [opt for opt in _ACL_OPTIONS if opt in sec.options]
|
||||
if mode == "off":
|
||||
return [uci("delete", f"{sec.ref}.{opt}") for opt in present]
|
||||
changes = [uci("set", f"{sec.ref}.macfilter={_MACFILTER_BY_MODE[mode]}")]
|
||||
if "maclist" in present:
|
||||
changes.append(uci("delete", f"{sec.ref}.maclist"))
|
||||
changes += [uci("add_list", f"{sec.ref}.maclist={mac}") for mac in macs]
|
||||
return changes
|
||||
|
||||
|
||||
class OpenWrtWirelessMixin(UciStepsMixin):
|
||||
"""Mixin providing wireless/radio NAPALM getters."""
|
||||
|
||||
def get_ssids(self) -> dict[str, Any]:
|
||||
@@ -49,7 +81,7 @@ class OpenWrtWirelessMixin:
|
||||
named_iface_sections: set = set()
|
||||
for line in uci_out.splitlines():
|
||||
line_s = line.strip()
|
||||
# named wifi-iface declaration: wireless.managed_family_2g=wifi-iface
|
||||
# named wifi-iface declaration: wireless.managed_home_2g=wifi-iface
|
||||
nm = re.match(r"wireless\.(\w+)=wifi-iface", line_s)
|
||||
if nm:
|
||||
named_iface_sections.add(nm.group(1))
|
||||
@@ -81,7 +113,7 @@ class OpenWrtWirelessMixin:
|
||||
else:
|
||||
iface_entries.setdefault(idx, {})[key] = val
|
||||
continue
|
||||
# named wifi-iface values: wireless.managed_family_2g.ssid='manivong'
|
||||
# named wifi-iface values: wireless.managed_home_2g.ssid='HomeNet'
|
||||
nm = re.match(r"wireless\.(\w+)\.(\w+)='([^']*)'", line_s)
|
||||
if nm and nm.group(1) in named_iface_sections:
|
||||
section, key, val = nm.group(1), nm.group(2), nm.group(3)
|
||||
@@ -101,8 +133,12 @@ class OpenWrtWirelessMixin:
|
||||
return ""
|
||||
|
||||
_ENC_MAP = {
|
||||
"": "Open", "none": "Open", "0": "Open",
|
||||
"wep": "WEP", "wep-open": "WEP (Open)", "wep-shared": "WEP (Shared)",
|
||||
"": "Open",
|
||||
"none": "Open",
|
||||
"0": "Open",
|
||||
"wep": "WEP",
|
||||
"wep-open": "WEP (Open)",
|
||||
"wep-shared": "WEP (Shared)",
|
||||
"psk": "WPA-PSK",
|
||||
"psk+ccmp": "WPA-PSK",
|
||||
"psk-mixed": "WPA/WPA2-PSK",
|
||||
@@ -152,7 +188,8 @@ class OpenWrtWirelessMixin:
|
||||
if vlan is not None:
|
||||
net_vlan[iface] = vlan
|
||||
except Exception:
|
||||
pass # Non-fatal: VLAN info is optional enrichment
|
||||
# Non-fatal: VLAN info is optional enrichment.
|
||||
logger.debug("network VLANs: ignored", exc_info=True)
|
||||
|
||||
# Build result; group entries with the same SSID name, merging bands
|
||||
result: dict[str, Any] = {}
|
||||
@@ -176,11 +213,17 @@ class OpenWrtWirelessMixin:
|
||||
ft_over_ds = entry.get("ft_over_ds", "1") == "1"
|
||||
client_isolation = entry.get("isolate", "0") == "1"
|
||||
_max_raw = entry.get("maxassoc")
|
||||
max_clients: int | None = int(_max_raw) if _max_raw and str(_max_raw).isdigit() else None
|
||||
max_clients: int | None = (
|
||||
int(_max_raw) if _max_raw and str(_max_raw).isdigit() else None
|
||||
)
|
||||
_disassoc_raw = entry.get("disassoc_low_ack")
|
||||
disassoc_low_ack: bool | None = (_disassoc_raw == "1") if _disassoc_raw is not None else None
|
||||
disassoc_low_ack: bool | None = (
|
||||
(_disassoc_raw == "1") if _disassoc_raw is not None else None
|
||||
)
|
||||
_max_inact_raw = entry.get("max_inactivity")
|
||||
max_inactivity: int | None = int(_max_inact_raw) if _max_inact_raw and str(_max_inact_raw).isdigit() else None
|
||||
max_inactivity: int | None = (
|
||||
int(_max_inact_raw) if _max_inact_raw and str(_max_inact_raw).isdigit() else None
|
||||
)
|
||||
key: str = entry.get("key", "") or ""
|
||||
acl_mode = _ACL_MODE_MAP.get(entry.get("macfilter", ""), "off")
|
||||
mac_list = sorted(set(iface_maclists.get(idx, [])))
|
||||
@@ -331,16 +374,18 @@ class OpenWrtWirelessMixin:
|
||||
def _flush() -> None:
|
||||
if current_station and current_station.get("mac"):
|
||||
info = ap_ifaces.get(active_iface, {})
|
||||
results.append(WirelessClientDict(
|
||||
mac=current_station["mac"],
|
||||
ssid=info.get("ssid", ""),
|
||||
radio=info.get("band") or info.get("radio", ""),
|
||||
signal=current_station.get("signal", 0),
|
||||
noise=0,
|
||||
tx_rate=current_station.get("tx_rate", 0.0),
|
||||
rx_rate=current_station.get("rx_rate", 0.0),
|
||||
uptime=current_station.get("uptime", 0),
|
||||
))
|
||||
results.append(
|
||||
WirelessClientDict(
|
||||
mac=current_station["mac"],
|
||||
ssid=info.get("ssid", ""),
|
||||
radio=info.get("band") or info.get("radio", ""),
|
||||
signal=current_station.get("signal", 0),
|
||||
noise=0,
|
||||
tx_rate=current_station.get("tx_rate", 0.0),
|
||||
rx_rate=current_station.get("rx_rate", 0.0),
|
||||
uptime=current_station.get("uptime", 0),
|
||||
)
|
||||
)
|
||||
|
||||
for line in station_out.splitlines():
|
||||
stripped = line.strip()
|
||||
@@ -410,7 +455,6 @@ class OpenWrtWirelessMixin:
|
||||
Keys are interface names (e.g. ``"wlan0"``). Values are lists of
|
||||
:class:`~napalm_device_types.models.ChannelScanEntryDict`.
|
||||
"""
|
||||
from napalm_device_types.models import ChannelScanEntryDict
|
||||
|
||||
# Step 1: discover interfaces and filter to AP mode only
|
||||
iw_out = self._send_command("iw dev 2>/dev/null || true")
|
||||
@@ -435,10 +479,7 @@ class OpenWrtWirelessMixin:
|
||||
if current_iface:
|
||||
iface_order.append((current_iface, current_type))
|
||||
|
||||
ap_ifaces = [
|
||||
name for name, itype in iface_order
|
||||
if itype.upper() in ("AP", "AP/VLAN")
|
||||
]
|
||||
ap_ifaces = [name for name, itype in iface_order if itype.upper() in ("AP", "AP/VLAN")]
|
||||
|
||||
if not ap_ifaces:
|
||||
return {}
|
||||
@@ -489,15 +530,17 @@ class OpenWrtWirelessMixin:
|
||||
# If width is still 0 try to derive from HT/VHT/HE info
|
||||
if width == 0 and current.get("_ht_width"):
|
||||
width = current["_ht_width"]
|
||||
entries.append(ChannelScanEntryDict(
|
||||
bssid=current["bssid"],
|
||||
ssid=current.get("ssid", ""),
|
||||
frequency=freq,
|
||||
channel=ch,
|
||||
signal_dbm=current.get("signal_dbm", 0),
|
||||
channel_width=width,
|
||||
band=_freq_to_band(freq),
|
||||
))
|
||||
entries.append(
|
||||
ChannelScanEntryDict(
|
||||
bssid=current["bssid"],
|
||||
ssid=current.get("ssid", ""),
|
||||
frequency=freq,
|
||||
channel=ch,
|
||||
signal_dbm=current.get("signal_dbm", 0),
|
||||
channel_width=width,
|
||||
band=_freq_to_band(freq),
|
||||
)
|
||||
)
|
||||
|
||||
for line in scan_out.splitlines():
|
||||
stripped = line.strip()
|
||||
@@ -556,13 +599,17 @@ class OpenWrtWirelessMixin:
|
||||
the physical channel on many hardware/driver combinations; a full
|
||||
restart is required for channel changes to take effect.
|
||||
|
||||
Each step's exit status is checked (:mod:`napalm_openwrt.uci_steps`): a
|
||||
refused ``uci set`` (a radio that does not exist) raises, and wifi is not
|
||||
restarted for it.
|
||||
|
||||
:param radio: UCI radio name, e.g. ``"radio0"``.
|
||||
:param channel: Channel number to set; ``0`` sets UCI ``auto``.
|
||||
:raises CommandErrorException: when a step is refused, naming it.
|
||||
"""
|
||||
ch_val = "auto" if channel == 0 else str(channel)
|
||||
self._send_command(f"uci set wireless.{radio}.channel={ch_val}")
|
||||
self._send_command("uci commit wireless")
|
||||
self._send_command("wifi")
|
||||
change = uci("set", f"{_WIRELESS}.{radio}.channel={ch_val}")
|
||||
self._uci_apply(_WIRELESS, [change], _WIFI_RESTART)
|
||||
|
||||
def push_mac_acl(self, ssid_name: str, mode: str, macs: list[str]) -> None:
|
||||
"""Rewrite macfilter mode + maclist entries on every wifi-iface matching *ssid_name*.
|
||||
@@ -579,31 +626,37 @@ class OpenWrtWirelessMixin:
|
||||
A whitelist ("allow") with zero MACs blocks every client outright, so
|
||||
it is treated as equivalent to "off" instead of being pushed as-is.
|
||||
|
||||
Each step's exit status is checked (:mod:`napalm_openwrt.uci_steps`): a
|
||||
refused step raises naming itself, what was staged is reverted, and
|
||||
nothing is committed or reloaded. An option is deleted only where the
|
||||
section has it, since deleting a missing one is refused too.
|
||||
|
||||
:param ssid_name: SSID name to match against ``option ssid`` on each wifi-iface section.
|
||||
:param mode: ``"off"`` | ``"whitelist"`` | ``"blacklist"``.
|
||||
:param macs: MAC addresses to set as the maclist. Only the entries for the
|
||||
active mode's list are ever passed in — the caller resolves whitelist
|
||||
vs. blacklist before calling.
|
||||
:raises ValueError: for a mode other than the three, before anything is sent.
|
||||
:raises CommandErrorException: when no wifi-iface carries *ssid_name*, or
|
||||
when a step is refused.
|
||||
"""
|
||||
if mode not in _MACFILTER_BY_MODE:
|
||||
known = ", ".join(map(repr, _MACFILTER_BY_MODE))
|
||||
raise ValueError(f"unknown MAC ACL mode {mode!r}; expected one of {known}")
|
||||
effective_mode = "off" if (mode == "whitelist" and not macs) else mode
|
||||
sections = self._send_command(
|
||||
"uci show wireless | grep -oE '^wireless\\.[^.]+' | sort -u"
|
||||
).split()
|
||||
sections = [
|
||||
sec
|
||||
for sec in parse_uci_show(self._uci_step(_SHOW_WIRELESS))
|
||||
if sec.type == "wifi-iface" and sec.options.get("ssid") == [ssid_name]
|
||||
]
|
||||
if not sections:
|
||||
raise CommandErrorException(
|
||||
f"{self.hostname}: no wifi-iface carries the SSID {ssid_name!r}"
|
||||
)
|
||||
changes: list[str] = []
|
||||
for sec in sections:
|
||||
ssid_val = self._send_command(f"uci -q get {sec}.ssid 2>/dev/null || true").strip()
|
||||
if ssid_val != ssid_name:
|
||||
continue
|
||||
if effective_mode == "off":
|
||||
self._send_command(f"uci -q delete {sec}.macfilter || true")
|
||||
self._send_command(f"uci -q delete {sec}.maclist || true")
|
||||
continue
|
||||
uci_mode = "allow" if effective_mode == "whitelist" else "deny"
|
||||
self._send_command(f"uci set {sec}.macfilter='{uci_mode}'")
|
||||
self._send_command(f"uci delete {sec}.maclist 2>/dev/null || true")
|
||||
for mac in macs:
|
||||
self._send_command(f"uci add_list {sec}.maclist='{mac}'")
|
||||
self._send_command("uci commit wireless")
|
||||
self._send_command("wifi reload")
|
||||
changes += _mac_acl_changes(sec, effective_mode, macs)
|
||||
self._uci_apply(_WIRELESS, changes, _WIFI_RELOAD)
|
||||
|
||||
def get_radio_status(self) -> dict[str, Any]:
|
||||
"""Return radio status from UCI and iwinfo.
|
||||
@@ -663,10 +716,22 @@ class OpenWrtWirelessMixin:
|
||||
|
||||
# Derive channel_width from htmode string (e.g. VHT80 → 80 MHz)
|
||||
_HTMODE_WIDTH = {
|
||||
"HT20": 20, "HT40": 40,
|
||||
"VHT20": 20, "VHT40": 40, "VHT80": 80, "VHT80+80": 80, "VHT160": 160,
|
||||
"HE20": 20, "HE40": 40, "HE80": 80, "HE160": 160,
|
||||
"EHT20": 20, "EHT40": 40, "EHT80": 80, "EHT160": 160, "EHT320": 320,
|
||||
"HT20": 20,
|
||||
"HT40": 40,
|
||||
"VHT20": 20,
|
||||
"VHT40": 40,
|
||||
"VHT80": 80,
|
||||
"VHT80+80": 80,
|
||||
"VHT160": 160,
|
||||
"HE20": 20,
|
||||
"HE40": 40,
|
||||
"HE80": 80,
|
||||
"HE160": 160,
|
||||
"EHT20": 20,
|
||||
"EHT40": 40,
|
||||
"EHT80": 80,
|
||||
"EHT160": 160,
|
||||
"EHT320": 320,
|
||||
}
|
||||
channel_width = _HTMODE_WIDTH.get(htmode.upper(), 0)
|
||||
|
||||
@@ -677,7 +742,7 @@ class OpenWrtWirelessMixin:
|
||||
channel=channel,
|
||||
channel_width=channel_width,
|
||||
tx_power=tx_power,
|
||||
frequency=0.0, # enriched below via iwinfo
|
||||
frequency=0.0, # enriched below via iwinfo
|
||||
),
|
||||
"htmode": htmode,
|
||||
"country": country,
|
||||
|
||||
@@ -0,0 +1,119 @@
|
||||
# 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.
|
||||
|
||||
"""The feed's Zabbix agent, the steps of napalm-device-types' ``ZabbixAgentMixin``.
|
||||
|
||||
OpenWrt's feed has the C agent, ``zabbix-agentd`` (NetOrk/netork#2571). Its
|
||||
configuration is ``/etc/zabbix_agentd.conf``; its init script starts it only while
|
||||
UCI says ``zabbix_agentd.general.enabled=1``, and runs it as ``zabbix-agent``.
|
||||
Zabbix publishes no repository for OpenWrt, so the feed is the only source.
|
||||
|
||||
The package index lives in RAM and is gone after every restart; the template loads
|
||||
it first (``refresh_available_updates``). The firewall step opens tcp/``listen_port``
|
||||
in the zone that owns the management address, the way the SNMP agent's step opens
|
||||
udp/161 -- and only where a firewall runs: an access point often runs none.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import ipaddress
|
||||
from typing import TYPE_CHECKING, Any
|
||||
|
||||
from napalm_device_types import (
|
||||
FixStepOutcomeDict,
|
||||
ZabbixAgentMixin,
|
||||
ZabbixAgentSettingsDict,
|
||||
zabbix_agent_config,
|
||||
)
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover
|
||||
from napalm_device_types import CommandResult
|
||||
|
||||
CONFIG = "/etc/zabbix_agentd.conf"
|
||||
#: UCI's switch the init script reads; the section is made where it is missing.
|
||||
_ENABLE = (
|
||||
"uci -q get zabbix_agentd.general >/dev/null || uci set zabbix_agentd.general=zabbix_agentd; "
|
||||
"uci set zabbix_agentd.general.enabled='1' && uci commit zabbix_agentd"
|
||||
)
|
||||
#: Prints ``on`` while a packet filter runs: fw4's table, or fw3's enabled service.
|
||||
_FIREWALL_RUNS = (
|
||||
"{ nft list table inet fw4 >/dev/null 2>&1 || /etc/init.d/firewall enabled; } && echo on"
|
||||
)
|
||||
|
||||
|
||||
def _failed(result: CommandResult, what: str) -> FixStepOutcomeDict:
|
||||
detail = (result.stderr or result.stdout or "").strip()[-300:]
|
||||
return {"ok": False, "output": f"{what}: {detail or result.exit_code}"}
|
||||
|
||||
|
||||
class OpenWrtZabbixAgentMixin(ZabbixAgentMixin):
|
||||
"""``zabbix-agentd`` from the feed, enabled in UCI."""
|
||||
|
||||
ZABBIX_AGENT_PACKAGE = "zabbix-agentd"
|
||||
ZABBIX_AGENT_SERVICE = "zabbix_agentd"
|
||||
#: The feed is the only source.
|
||||
_add_zabbix_repository = None # type: ignore[assignment]
|
||||
|
||||
def _write_zabbix_agent_config(self, settings: ZabbixAgentSettingsDict) -> FixStepOutcomeDict:
|
||||
read = self.run_command(f"cat {CONFIG}", privileged=True)
|
||||
if read.exit_code:
|
||||
return _failed(read, f"reading {CONFIG}")
|
||||
text, changes = zabbix_agent_config(read.stdout, settings)
|
||||
if changes:
|
||||
# The old file next to it; cat keeps owner and mode (zabbix-agent's).
|
||||
written = self.run_command(
|
||||
f"cp -p {CONFIG} {CONFIG}.bak && cat > {CONFIG}",
|
||||
privileged=True,
|
||||
stdin=text.encode(),
|
||||
)
|
||||
if written.exit_code:
|
||||
return _failed(written, f"writing {CONFIG}")
|
||||
enabled = self.run_command(_ENABLE, privileged=True)
|
||||
if enabled.exit_code:
|
||||
return _failed(enabled, "enabling the agent in UCI")
|
||||
said = "; ".join(changes) if changes else f"{CONFIG} already says it"
|
||||
return {"ok": True, "output": f"{said}; enabled in UCI"}
|
||||
|
||||
def _allow_zabbix_agent_sources(self, settings: ZabbixAgentSettingsDict) -> FixStepOutcomeDict:
|
||||
sources = [
|
||||
str(ipaddress.ip_network(s.strip(), strict=False)) for s in settings["allowed_sources"]
|
||||
]
|
||||
if not sources:
|
||||
return {"ok": True, "output": "no sources given; firewall unchanged"}
|
||||
if self._send_command(_FIREWALL_RUNS).strip() != "on":
|
||||
return {"ok": True, "output": "no firewall runs; nothing to open"}
|
||||
outcome = self._allow_in_management_zone(
|
||||
key="allow_zabbix_agent",
|
||||
name="Allow-Zabbix-Agent",
|
||||
proto="tcp",
|
||||
port=int(settings["listen_port"]),
|
||||
sources=sources,
|
||||
word="zabbix",
|
||||
)
|
||||
return {"ok": bool(outcome["ok"]), "output": str(outcome["output"])}
|
||||
|
||||
if TYPE_CHECKING: # pragma: no cover - the driver's
|
||||
|
||||
def run_command(
|
||||
self,
|
||||
command: str,
|
||||
*,
|
||||
privileged: bool = False,
|
||||
timeout: float = 60,
|
||||
stdin: bytes | None = None,
|
||||
) -> CommandResult: ...
|
||||
|
||||
def _send_command(self, command: str) -> str: ...
|
||||
|
||||
def _allow_in_management_zone(
|
||||
self, *, key: str, name: str, proto: str, port: int, sources: list[str], word: str
|
||||
) -> dict[str, Any]: ...
|
||||
+55
-20
@@ -1,55 +1,90 @@
|
||||
[build-system]
|
||||
requires = ["setuptools>=64", "wheel"]
|
||||
requires = ["setuptools>=77"]
|
||||
build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "napalm-openwrt"
|
||||
version = "0.1.0"
|
||||
version = "0.8.0"
|
||||
description = "NAPALM driver for OpenWrt routers/access-points"
|
||||
readme = "README.md"
|
||||
license = { text = "Apache-2.0" }
|
||||
requires-python = ">=3.8"
|
||||
license = "Apache-2.0"
|
||||
requires-python = ">=3.12"
|
||||
authors = [
|
||||
{ name = "Christian Manivong" },
|
||||
]
|
||||
classifiers = [
|
||||
"Topic :: Utilities",
|
||||
"License :: OSI Approved :: Apache Software License",
|
||||
"Programming Language :: Python :: 3",
|
||||
"Programming Language :: Python :: 3.8",
|
||||
"Programming Language :: Python :: 3.9",
|
||||
"Programming Language :: Python :: 3.10",
|
||||
"Programming Language :: Python :: 3.11",
|
||||
"Programming Language :: Python :: 3.12",
|
||||
"Operating System :: POSIX :: Linux",
|
||||
"Operating System :: MacOS",
|
||||
]
|
||||
dependencies = [
|
||||
"napalm>=4.0.0",
|
||||
"napalm_device_types>=0.1.0",
|
||||
"napalm>=5.1", # older releases import pkg_resources, which a 3.12 venv lacks
|
||||
"napalm_device_types>=4.41.0", # FirmwareUpgradeMixin
|
||||
"netmiko>=4.0.0",
|
||||
"paramiko>=5.0.0", # CVE-2026-44405
|
||||
"netaddr",
|
||||
"netaddr>=0.7.19", # IPAddress; below it the package has none (CI lowest job)
|
||||
]
|
||||
|
||||
[project.optional-dependencies]
|
||||
dev = [
|
||||
"pytest",
|
||||
"pytest-cov",
|
||||
"black",
|
||||
"ruff",
|
||||
]
|
||||
dev = ["pytest>=8", "pytest-cov>=5", "mypy>=1.11", "ruff>=0.6"]
|
||||
|
||||
[project.entry-points."napalm.drivers"]
|
||||
openwrt = "napalm_openwrt:OpenWrtDriver"
|
||||
|
||||
[project.urls]
|
||||
Repository = "https://github.com/napalm-automation-community/napalm-openwrt"
|
||||
Repository = "https://git.netork.io/NAPALM/napalm-openwrt"
|
||||
Issues = "https://git.netork.io/NAPALM/napalm-openwrt/issues"
|
||||
Changelog = "https://git.netork.io/NAPALM/napalm-openwrt/src/branch/main/CHANGELOG.md"
|
||||
|
||||
[tool.setuptools.packages.find]
|
||||
where = ["."]
|
||||
include = ["napalm_openwrt*"]
|
||||
|
||||
[tool.setuptools.package-data]
|
||||
napalm_openwrt = ["py.typed"]
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 100
|
||||
target-version = "py38"
|
||||
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.12"
|
||||
strict = true
|
||||
# napalm itself is untyped, so every driver subclasses Any.
|
||||
disallow_subclassing_any = false
|
||||
|
||||
[[tool.mypy.overrides]]
|
||||
module = ["napalm.*", "netmiko.*", "paramiko.*", "netaddr.*"]
|
||||
ignore_missing_imports = true
|
||||
|
||||
[[tool.mypy.overrides]]
|
||||
# Not yet under strict mypy (quality baseline); may only shrink.
|
||||
module = [
|
||||
"napalm_openwrt.config_mixin",
|
||||
"napalm_openwrt.interfaces_mixin",
|
||||
"napalm_openwrt.openwrt",
|
||||
"napalm_openwrt.packages_mixin",
|
||||
"napalm_openwrt.routing_mixin",
|
||||
"napalm_openwrt.system_mixin",
|
||||
"napalm_openwrt.vlan_mixin",
|
||||
"napalm_openwrt.wireless_mixin",
|
||||
]
|
||||
ignore_errors = true
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
|
||||
[tool.coverage.run]
|
||||
source = ["napalm_openwrt"]
|
||||
|
||||
[tool.coverage.report]
|
||||
fail_under = 65
|
||||
@@ -0,0 +1,52 @@
|
||||
{
|
||||
"coverage_floor": 65.0,
|
||||
"function_complexity": {
|
||||
"napalm_openwrt/config_mixin.py::OpenWrtConfigMixin.commit_config": 14,
|
||||
"napalm_openwrt/interfaces_mixin.py::OpenWrtInterfaceMixin.get_arp_table": 13,
|
||||
"napalm_openwrt/openwrt.py::OpenWrtDriver._write_snmp_agent_config": 22,
|
||||
"napalm_openwrt/packages_mixin.py::OpenWrtPackageMixin.search_packages": 12,
|
||||
"napalm_openwrt/routing_mixin.py::OpenWrtRoutingMixin._parse_traceroute_output": 12,
|
||||
"napalm_openwrt/routing_mixin.py::OpenWrtRoutingMixin.get_route_to": 12,
|
||||
"napalm_openwrt/system_mixin.py::OpenWrtSystemMixin.get_services": 14,
|
||||
"napalm_openwrt/system_mixin.py::OpenWrtSystemMixin.get_system_config": 16,
|
||||
"napalm_openwrt/system_mixin.py::OpenWrtSystemMixin.get_users": 13,
|
||||
"napalm_openwrt/vlan_mixin.py::OpenWrtVLANMixin.get_vlans": 32,
|
||||
"napalm_openwrt/wireless_mixin.py::OpenWrtWirelessMixin.get_channel_scan": 12,
|
||||
"napalm_openwrt/wireless_mixin.py::OpenWrtWirelessMixin.get_radio_status": 19,
|
||||
"napalm_openwrt/wireless_mixin.py::OpenWrtWirelessMixin.get_ssids": 51,
|
||||
"napalm_openwrt/wireless_mixin.py::OpenWrtWirelessMixin.get_wireless_clients": 27
|
||||
},
|
||||
"function_lines": {
|
||||
"napalm_openwrt/interfaces_mixin.py::OpenWrtInterfaceMixin.get_arp_table": 85,
|
||||
"napalm_openwrt/interfaces_mixin.py::OpenWrtInterfaceMixin.get_interfaces_ip": 55,
|
||||
"napalm_openwrt/interfaces_mixin.py::OpenWrtInterfaceMixin.get_mac_address_table": 53,
|
||||
"napalm_openwrt/openwrt.py::OpenWrtDriver.get_facts": 53,
|
||||
"napalm_openwrt/packages_mixin.py::OpenWrtPackageMixin.search_packages": 59,
|
||||
"napalm_openwrt/routing_mixin.py::OpenWrtRoutingMixin._parse_traceroute_output": 67,
|
||||
"napalm_openwrt/routing_mixin.py::OpenWrtRoutingMixin.get_route_to": 91,
|
||||
"napalm_openwrt/system_mixin.py::OpenWrtSystemMixin.get_services": 61,
|
||||
"napalm_openwrt/system_mixin.py::OpenWrtSystemMixin.get_snmp_information": 56,
|
||||
"napalm_openwrt/system_mixin.py::OpenWrtSystemMixin.get_system_config": 92,
|
||||
"napalm_openwrt/system_mixin.py::OpenWrtSystemMixin.get_users": 64,
|
||||
"napalm_openwrt/vlan_mixin.py::OpenWrtVLANMixin.get_network_instances": 61,
|
||||
"napalm_openwrt/vlan_mixin.py::OpenWrtVLANMixin.get_vlans": 106,
|
||||
"napalm_openwrt/wireless_mixin.py::OpenWrtWirelessMixin._parse_iw_scan": 93,
|
||||
"napalm_openwrt/wireless_mixin.py::OpenWrtWirelessMixin.get_radio_status": 133,
|
||||
"napalm_openwrt/wireless_mixin.py::OpenWrtWirelessMixin.get_ssids": 240,
|
||||
"napalm_openwrt/wireless_mixin.py::OpenWrtWirelessMixin.get_wireless_clients": 152
|
||||
},
|
||||
"mypy_relaxed": [
|
||||
"napalm_openwrt.config_mixin",
|
||||
"napalm_openwrt.interfaces_mixin",
|
||||
"napalm_openwrt.openwrt",
|
||||
"napalm_openwrt.packages_mixin",
|
||||
"napalm_openwrt.routing_mixin",
|
||||
"napalm_openwrt.system_mixin",
|
||||
"napalm_openwrt.vlan_mixin",
|
||||
"napalm_openwrt.wireless_mixin"
|
||||
],
|
||||
"python_file_lines": {},
|
||||
"untyped_public": [
|
||||
"napalm_openwrt/system_mixin.py::OpenWrtSystemMixin.get_snmp_config"
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,112 @@
|
||||
"""A public command channel (napalm-device-types ``CommandChannelMixin``, netOrk #1113).
|
||||
|
||||
netOrk sent UCI scripts and the wifi channel through the private
|
||||
``_send_command``: an interactive shell with no exit code, where a file had to
|
||||
be typed in base64 chunks or ``printf`` lines. ``run_command`` runs on an SSH
|
||||
exec channel of its own, with stdin, stderr and the exit code -- a script is
|
||||
written with ``cat`` from stdin, and ``base64`` is needed for nothing.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from napalm.base.exceptions import ConnectionClosedException
|
||||
from napalm_device_types import CommandResult
|
||||
|
||||
from napalm_openwrt.openwrt import OpenWrtDriver
|
||||
|
||||
|
||||
def _driver(username: str = "root") -> OpenWrtDriver:
|
||||
with patch("napalm_openwrt.openwrt.ConnectHandler"):
|
||||
drv = OpenWrtDriver(hostname="192.0.2.15", username=username, password="")
|
||||
drv.device = MagicMock()
|
||||
return drv
|
||||
|
||||
|
||||
def test_a_command_runs_on_the_ssh_transport_with_its_stdin():
|
||||
drv = _driver()
|
||||
transport = drv.device.remote_conn_pre.get_transport.return_value
|
||||
done = CommandResult("", "", 0)
|
||||
with patch("napalm_openwrt.openwrt.run_on_transport", return_value=done) as run:
|
||||
result = drv.run_command("cat > /tmp/x.sh", stdin=b"uci commit\n", timeout=30)
|
||||
|
||||
assert result is done
|
||||
run.assert_called_once_with(transport, "cat > /tmp/x.sh", stdin=b"uci commit\n", timeout=30)
|
||||
|
||||
|
||||
def test_root_runs_privileged_commands_as_they_are():
|
||||
drv = _driver()
|
||||
with patch("napalm_openwrt.openwrt.run_on_transport") as run:
|
||||
drv.run_command("wifi", privileged=True)
|
||||
|
||||
assert run.call_args.args[1] == "wifi"
|
||||
|
||||
|
||||
def test_a_login_other_than_root_cannot_gain_root():
|
||||
"""OpenWrt has no sudo: refused before anything runs, not half done."""
|
||||
drv = _driver(username="admin")
|
||||
with patch("napalm_openwrt.openwrt.run_on_transport") as run, pytest.raises(PermissionError):
|
||||
drv.run_command("wifi", privileged=True)
|
||||
|
||||
run.assert_not_called()
|
||||
|
||||
|
||||
def test_a_stream_on_the_same_transport():
|
||||
drv = _driver()
|
||||
transport = drv.device.remote_conn_pre.get_transport.return_value
|
||||
with patch("napalm_openwrt.openwrt.open_stream_on_transport") as stream:
|
||||
drv.open_stream("logread -f")
|
||||
|
||||
stream.assert_called_once_with(transport, "logread -f")
|
||||
|
||||
|
||||
def test_not_connected():
|
||||
drv = _driver()
|
||||
drv.device = None
|
||||
with pytest.raises(ConnectionClosedException):
|
||||
drv.run_command("true")
|
||||
|
||||
|
||||
def test_no_warnings_of_its_own():
|
||||
"""base64 is no longer needed for anything, so a missing one is no warning;
|
||||
lldpd, auc and the updates are facts the caller reads (netOrk #1111)."""
|
||||
assert not any(
|
||||
"get_device_warnings" in vars(c)
|
||||
for c in OpenWrtDriver.__mro__
|
||||
if c.__module__.startswith("napalm_openwrt")
|
||||
)
|
||||
|
||||
|
||||
class TestRebootHost:
|
||||
"""``reboot_host`` (napalm-device-types ``HostRebootMixin``): netOrk sent
|
||||
``/sbin/reboot`` through the private ``_send_command`` and could not tell a
|
||||
refusal from the session dropping (netOrk #1113)."""
|
||||
|
||||
def test_detached_so_the_answer_comes_back_first(self):
|
||||
drv = _driver()
|
||||
with patch(
|
||||
"napalm_openwrt.openwrt.run_on_transport", return_value=CommandResult("", "", 0)
|
||||
) as run:
|
||||
drv.reboot_host()
|
||||
|
||||
command = run.call_args.args[1]
|
||||
assert "reboot" in command and command.rstrip().endswith("&'")
|
||||
assert "trap" in command and "sleep" in command
|
||||
|
||||
def test_a_refusal_is_raised(self):
|
||||
drv = _driver()
|
||||
failed = CommandResult("", "reboot: Operation not permitted", 1)
|
||||
with (
|
||||
patch("napalm_openwrt.openwrt.run_on_transport", return_value=failed),
|
||||
pytest.raises(RuntimeError, match="not permitted"),
|
||||
):
|
||||
drv.reboot_host()
|
||||
|
||||
def test_a_login_other_than_root_is_refused(self):
|
||||
drv = _driver(username="admin")
|
||||
with patch("napalm_openwrt.openwrt.run_on_transport") as run, pytest.raises(RuntimeError):
|
||||
drv.reboot_host()
|
||||
|
||||
run.assert_not_called()
|
||||
@@ -0,0 +1,63 @@
|
||||
"""A replace commit and a rollback import their config through a private temporary file
|
||||
(#45, NetOrk/netork#2446).
|
||||
|
||||
Both wrote the config as root to a fixed name in /tmp (``/tmp/napalm_candidate.uci``,
|
||||
``/tmp/napalm_rollback.uci``) and imported it with a second command. A local account
|
||||
could place that file beforehand, or swap it in between, and have its own config
|
||||
committed. Each import is now one command: a ``mktemp`` file made under umask 077,
|
||||
written, imported and removed, named by nothing but ``"$f"``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import shlex
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_openwrt.openwrt import OpenWrtDriver
|
||||
|
||||
CONFIG = "package network\n\nconfig interface 'lan'\n\toption proto 'static'\n"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def driver():
|
||||
with patch("napalm_openwrt.openwrt.ConnectHandler"):
|
||||
drv = OpenWrtDriver(hostname="192.0.2.1", username="root", password="")
|
||||
drv._send_command = MagicMock(return_value="")
|
||||
return drv
|
||||
|
||||
|
||||
def _sent(driver) -> list[str]:
|
||||
return [call.args[0] for call in driver._send_command.call_args_list]
|
||||
|
||||
|
||||
def _assert_private_import(command: str, config: str) -> None:
|
||||
assert "/tmp/napalm" not in command
|
||||
assert command.startswith("f=$(umask 077 && mktemp) && { ")
|
||||
assert 'uci import < "$f" && uci commit' in command
|
||||
assert command.rstrip().endswith('rm -f "$f"; }')
|
||||
# The config reaches printf as one word, exactly as it is.
|
||||
words = shlex.split(command.split("printf '%s' ", 1)[1].split(' > "$f"', 1)[0])
|
||||
assert words == [config]
|
||||
|
||||
|
||||
def test_a_replace_commit_imports_through_a_private_temporary_file(driver):
|
||||
driver.load_replace_candidate(config=CONFIG)
|
||||
|
||||
driver.commit_config()
|
||||
|
||||
imports = [c for c in _sent(driver) if "uci import" in c]
|
||||
assert len(imports) == 1
|
||||
_assert_private_import(imports[0], CONFIG)
|
||||
assert not any("napalm_candidate" in c for c in _sent(driver))
|
||||
|
||||
|
||||
def test_a_rollback_imports_through_a_private_temporary_file(driver):
|
||||
backup = "package system\n\nconfig system\n\toption hostname 'it''s'\n"
|
||||
driver._backup_config = backup
|
||||
|
||||
driver.rollback()
|
||||
|
||||
[command] = _sent(driver)
|
||||
_assert_private_import(command, backup)
|
||||
+537
-251
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,269 @@
|
||||
"""The firmware OpenWrt's sysupgrade server offers, and installing it with owut.
|
||||
|
||||
netOrk upgrades an OpenWrt device to the newest release of its own release line
|
||||
instead of piling package upgrades into the overlay (NetOrk/netork#2615). The
|
||||
offer comes from the attended sysupgrade server's ``overview.json`` (its shape
|
||||
here is the real one, cut down to what matters); owut on the device builds the
|
||||
image there and runs sysupgrade.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from napalm_device_types import CommandResult
|
||||
|
||||
from napalm_openwrt import firmware_mixin
|
||||
from napalm_openwrt.openwrt import OpenWrtDriver
|
||||
|
||||
OVERVIEW = {
|
||||
"latest": ["25.12.6", "24.10.8"],
|
||||
"branches": {
|
||||
"SNAPSHOT": {
|
||||
"enabled": True,
|
||||
"snapshot": True,
|
||||
"versions": ["SNAPSHOT"],
|
||||
"name": "SNAPSHOT",
|
||||
"targets": ["ath79/generic", "ramips/mt7621"],
|
||||
},
|
||||
"25.12": {
|
||||
"enabled": True,
|
||||
"snapshot": False,
|
||||
"versions": ["25.12.6", "25.12.5", "25.12.2", "25.12.0", "25.12.0-rc5"],
|
||||
"name": "25.12",
|
||||
"targets": ["ath79/generic", "ramips/mt7621"],
|
||||
},
|
||||
"24.10": {
|
||||
"enabled": True,
|
||||
"snapshot": False,
|
||||
"versions": ["24.10.8", "24.10.2", "24.10.0"],
|
||||
"name": "24.10",
|
||||
"targets": ["ath79/generic", "ramips/mt7621"],
|
||||
},
|
||||
"23.05": {
|
||||
"enabled": True,
|
||||
"snapshot": False,
|
||||
"versions": ["23.05.6", "23.05.3", "23.05.0-rc4"],
|
||||
"name": "23.05",
|
||||
"targets": ["ath79/generic"],
|
||||
},
|
||||
},
|
||||
"upstream_url": "https://downloads.openwrt.org",
|
||||
}
|
||||
|
||||
|
||||
def _release(version: str, target: str = "ath79/generic") -> str:
|
||||
return (
|
||||
"DISTRIB_ID='OpenWrt'\n"
|
||||
f"DISTRIB_RELEASE='{version}'\n"
|
||||
"DISTRIB_REVISION='r32802-f505120278'\n"
|
||||
f"DISTRIB_TARGET='{target}'\n"
|
||||
"DISTRIB_ARCH='mips_24kc'\n"
|
||||
f"DISTRIB_DESCRIPTION='OpenWrt {version} r32802-f505120278'\n"
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _no_cached_overviews():
|
||||
firmware_mixin._OVERVIEWS.clear()
|
||||
yield
|
||||
firmware_mixin._OVERVIEWS.clear()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def driver():
|
||||
with patch("napalm_openwrt.openwrt.ConnectHandler"):
|
||||
drv = OpenWrtDriver(hostname="192.0.2.1", username="root", password="")
|
||||
drv.device = MagicMock()
|
||||
yield drv
|
||||
|
||||
|
||||
def _device(driver, version: str, *, owut: bool = True, server: str = "", target="ath79/generic"):
|
||||
"""The device answers the offer's one reading; every command is kept."""
|
||||
sent: list[str] = []
|
||||
|
||||
def run(command, *, privileged=False, timeout=60, stdin=None):
|
||||
sent.append(command)
|
||||
out = _release(version, target) + f"__ASU_URL={server}\n" + ("__OWUT=1\n" if owut else "")
|
||||
return CommandResult(exit_code=0, stdout=out, stderr="")
|
||||
|
||||
driver.run_command = run
|
||||
return sent
|
||||
|
||||
|
||||
def _offer(driver, fetched=OVERVIEW):
|
||||
with patch.object(firmware_mixin, "_fetch_json", return_value=fetched) as fetch:
|
||||
return driver.get_firmware_offer(), fetch
|
||||
|
||||
|
||||
class TestFirmwareOffer:
|
||||
def test_the_newest_point_release_of_its_own_line_is_offered(self, driver):
|
||||
_device(driver, "25.12.2")
|
||||
offer, _ = _offer(driver)
|
||||
assert offer == {
|
||||
"current_version": "25.12.2",
|
||||
"latest_version": "25.12.6",
|
||||
"newer": True,
|
||||
"installable": True,
|
||||
}
|
||||
|
||||
def test_a_device_on_the_newest_release_is_offered_nothing_newer(self, driver):
|
||||
_device(driver, "25.12.6")
|
||||
offer, _ = _offer(driver)
|
||||
assert offer is not None
|
||||
assert offer["newer"] is False
|
||||
assert offer["latest_version"] == "25.12.6"
|
||||
|
||||
def test_a_later_release_line_is_named_but_not_offered_as_the_upgrade(self, driver):
|
||||
_device(driver, "24.10.2")
|
||||
offer, _ = _offer(driver)
|
||||
assert offer is not None
|
||||
assert offer["latest_version"] == "24.10.8"
|
||||
assert offer["latest_major_version"] == "25.12.6"
|
||||
assert offer["newer"] is True
|
||||
|
||||
def test_a_release_candidate_is_offered_the_release(self, driver):
|
||||
_device(driver, "25.12.0-rc5")
|
||||
offer, _ = _offer(driver)
|
||||
assert offer is not None
|
||||
assert (offer["latest_version"], offer["newer"]) == ("25.12.6", True)
|
||||
|
||||
def test_release_candidates_are_not_offered_over_a_release(self, driver):
|
||||
overview = {
|
||||
**OVERVIEW,
|
||||
"branches": {
|
||||
"25.12": {**OVERVIEW["branches"]["25.12"], "versions": ["25.12.7-rc1", "25.12.6"]}
|
||||
},
|
||||
}
|
||||
_device(driver, "25.12.2")
|
||||
offer, _ = _offer(driver, overview)
|
||||
assert offer is not None
|
||||
assert offer["latest_version"] == "25.12.6"
|
||||
|
||||
def test_without_owut_it_cannot_be_installed_yet(self, driver):
|
||||
_device(driver, "25.12.2", owut=False)
|
||||
offer, _ = _offer(driver)
|
||||
assert offer is not None
|
||||
assert offer["installable"] is False
|
||||
|
||||
def test_a_release_before_owut_existed_never_says_installable(self, driver):
|
||||
"""owut needs 24.10 or later; on 23.05 there is nothing to install it with."""
|
||||
_device(driver, "23.05.3", owut=False)
|
||||
offer, _ = _offer(driver)
|
||||
assert offer is not None
|
||||
assert "installable" not in offer
|
||||
assert offer["latest_version"] == "23.05.6"
|
||||
|
||||
def test_a_snapshot_has_no_offer(self, driver):
|
||||
_device(driver, "SNAPSHOT")
|
||||
assert _offer(driver)[0] is None
|
||||
|
||||
def test_a_target_the_line_no_longer_builds_has_no_offer(self, driver):
|
||||
_device(driver, "23.05.3", target="ramips/mt7621")
|
||||
assert _offer(driver)[0] is None
|
||||
|
||||
def test_a_server_that_does_not_answer_is_no_offer(self, driver):
|
||||
_device(driver, "25.12.2")
|
||||
with patch.object(firmware_mixin, "_fetch_json", side_effect=OSError("timed out")):
|
||||
assert driver.get_firmware_offer() is None
|
||||
|
||||
def test_the_server_is_asked_once_for_every_device(self, driver):
|
||||
_device(driver, "25.12.2")
|
||||
_, fetch = _offer(driver)
|
||||
with patch.object(firmware_mixin, "_fetch_json", return_value=OVERVIEW) as again:
|
||||
assert driver.get_firmware_offer() is not None
|
||||
fetch.assert_called_once_with("https://sysupgrade.openwrt.org/json/v1/overview.json")
|
||||
again.assert_not_called()
|
||||
|
||||
def test_a_failed_answer_is_not_asked_again_at_once(self, driver):
|
||||
_device(driver, "25.12.2")
|
||||
with patch.object(firmware_mixin, "_fetch_json", side_effect=OSError("down")) as fetch:
|
||||
driver.get_firmware_offer()
|
||||
driver.get_firmware_offer()
|
||||
fetch.assert_called_once()
|
||||
|
||||
def test_the_server_the_device_is_set_to_is_asked(self, driver):
|
||||
_device(driver, "25.12.2", server="https://asu.example.net/")
|
||||
_, fetch = _offer(driver)
|
||||
fetch.assert_called_once_with("https://asu.example.net/json/v1/overview.json")
|
||||
|
||||
def test_a_server_that_is_not_http_is_not_asked(self, driver):
|
||||
_device(driver, "25.12.2", server="file:///etc/shadow")
|
||||
_, fetch = _offer(driver)
|
||||
fetch.assert_called_once_with("https://sysupgrade.openwrt.org/json/v1/overview.json")
|
||||
|
||||
|
||||
class TestStartFirmwareUpgrade:
|
||||
def _run(self, driver, result: CommandResult):
|
||||
calls: list[tuple[str, bool]] = []
|
||||
|
||||
def run(command, *, privileged=False, timeout=60, stdin=None):
|
||||
calls.append((command, privileged))
|
||||
return result
|
||||
|
||||
driver.run_command = run
|
||||
return calls
|
||||
|
||||
def test_owut_upgrades_to_the_version_detached_from_the_session(self, driver):
|
||||
calls = self._run(driver, CommandResult(exit_code=0, stdout="", stderr=""))
|
||||
driver.start_firmware_upgrade("25.12.6")
|
||||
((command, privileged),) = calls
|
||||
assert privileged is True
|
||||
assert "owut upgrade --version-to 25.12.6" in command
|
||||
assert 'trap "" HUP' in command
|
||||
assert "</dev/null" in command
|
||||
assert command.rstrip().endswith("&'") or command.rstrip().endswith("&")
|
||||
|
||||
@pytest.mark.parametrize("version", ["25.12.6; reboot", "SNAPSHOT", "", "25.12"])
|
||||
def test_anything_but_a_release_version_is_refused(self, driver, version):
|
||||
calls = self._run(driver, CommandResult(exit_code=0, stdout="", stderr=""))
|
||||
with pytest.raises(ValueError):
|
||||
driver.start_firmware_upgrade(version)
|
||||
assert calls == []
|
||||
|
||||
def test_a_refusal_is_raised_with_the_device_reason(self, driver):
|
||||
self._run(driver, CommandResult(exit_code=4, stdout="", stderr="owut is not installed\n"))
|
||||
with pytest.raises(RuntimeError, match="owut is not installed"):
|
||||
driver.start_firmware_upgrade("25.12.6")
|
||||
|
||||
def test_only_root_can_start_it(self, driver):
|
||||
driver.username = "admin"
|
||||
with pytest.raises(RuntimeError):
|
||||
driver.start_firmware_upgrade("25.12.6")
|
||||
|
||||
|
||||
class TestUpdateProgress:
|
||||
def _log(self, driver, log: str | None):
|
||||
def run(command, *, privileged=False, timeout=60, stdin=None):
|
||||
if log is None:
|
||||
return CommandResult(exit_code=1, stdout="", stderr="")
|
||||
return CommandResult(exit_code=0, stdout=log, stderr="")
|
||||
|
||||
driver.run_command = run
|
||||
|
||||
def test_no_upgrade_since_the_device_started_is_idle(self, driver):
|
||||
self._log(driver, None)
|
||||
assert driver.get_update_progress() == {"state": "idle", "log": ""}
|
||||
|
||||
def test_an_upgrade_without_an_end_is_running(self, driver):
|
||||
self._log(driver, "Requesting build\nBuild status: queued\n")
|
||||
progress = driver.get_update_progress()
|
||||
assert progress["state"] == "running"
|
||||
assert progress["log"] == "Requesting build\nBuild status: queued"
|
||||
|
||||
def test_installing_the_image_is_its_end(self, driver):
|
||||
"""sysupgrade stops every process, the wrapper's status line included."""
|
||||
self._log(driver, "Verified\nInstalling /tmp/firmware.bin and rebooting...\n")
|
||||
assert driver.get_update_progress()["state"] == "done"
|
||||
|
||||
def test_a_status_other_than_zero_failed(self, driver):
|
||||
self._log(driver, "Package build checks reveal errors, can't proceed\n__OWUT_RC=1\n")
|
||||
progress = driver.get_update_progress()
|
||||
assert progress["state"] == "failed"
|
||||
assert "__OWUT_RC" not in progress["log"]
|
||||
|
||||
def test_an_end_without_installing_failed(self, driver):
|
||||
"""owut ends with 0 when there was nothing to change: nothing was installed."""
|
||||
self._log(driver, "There are no changes to upgrade (see '--force')\n__OWUT_RC=0\n")
|
||||
assert driver.get_update_progress()["state"] == "failed"
|
||||
@@ -0,0 +1,70 @@
|
||||
"""The host status of an OpenWrt device (napalm-device-types ``HostStatusMixin``).
|
||||
|
||||
The command and its parse are napalm-device-types': whether the router needs a
|
||||
reboot, how full its filesystems are, and whether apk (OpenWrt 25.12) or opkg
|
||||
(before) was left halfway (NetOrk/netork#851). The driver only carries the command
|
||||
across, over an SSH exec channel, because busybox ash cuts an interactive line at
|
||||
512 characters and the command is longer.
|
||||
|
||||
The report is shaped after what the command prints on OpenWrt 25.12 (no systemd,
|
||||
no apt, one kernel under ``/lib/modules``, ``/`` an overlay); it still has to be
|
||||
checked against a real router.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
from napalm_device_types import CommandResult
|
||||
from napalm_device_types.host_status import HOST_STATUS_COMMAND, parse_host_status
|
||||
|
||||
from napalm_openwrt.openwrt import OpenWrtDriver
|
||||
|
||||
REPORT = """HSTAT_BEGIN
|
||||
[kernel]
|
||||
6.12.57
|
||||
[modules]
|
||||
6.12.57
|
||||
[pm-running]
|
||||
[apk-audit]
|
||||
s luci-app-sqm
|
||||
[filesystems]
|
||||
Filesystem 1024-blocks Used Available Capacity Mounted on
|
||||
overlayfs:/overlay 93184 5132 83392 6% /
|
||||
tmpfs 245696 304 245392 0% /tmp
|
||||
[timers]
|
||||
apt-daily-upgrade.timer
|
||||
dnf-automatic.timer
|
||||
dnf-automatic-install.timer
|
||||
[dnf-automatic]
|
||||
HSTAT_END
|
||||
"""
|
||||
|
||||
|
||||
def _driver() -> OpenWrtDriver:
|
||||
with patch("napalm_openwrt.openwrt.ConnectHandler"):
|
||||
drv = OpenWrtDriver(hostname="192.0.2.15", username="root", password="")
|
||||
drv.device = MagicMock()
|
||||
return drv
|
||||
|
||||
|
||||
def test_the_host_status_is_napalm_device_types_reading():
|
||||
drv = _driver()
|
||||
with patch(
|
||||
"napalm_openwrt.openwrt.run_on_transport", return_value=CommandResult(REPORT, "", 0)
|
||||
):
|
||||
status = drv.get_host_status()
|
||||
|
||||
assert status == parse_host_status(REPORT)
|
||||
assert status["reboot_required"] is False
|
||||
|
||||
|
||||
def test_the_command_goes_over_an_exec_channel_not_the_shell():
|
||||
drv = _driver()
|
||||
transport = drv.device.remote_conn_pre.get_transport.return_value
|
||||
done = CommandResult(REPORT, "", 0)
|
||||
with patch("napalm_openwrt.openwrt.run_on_transport", return_value=done) as run:
|
||||
drv.get_host_status()
|
||||
|
||||
assert run.call_args.args[:2] == (transport, HOST_STATUS_COMMAND)
|
||||
drv.device.send_command.assert_not_called()
|
||||
@@ -0,0 +1,89 @@
|
||||
"""What listens on an OpenWrt device, and which procd service it is (netOrk #673).
|
||||
|
||||
The command and its parse are napalm-device-types' (``ListeningSocketsMixin``):
|
||||
OpenWrt has no ``ss``, so the command falls back to busybox ``netstat``, and the
|
||||
cgroup of each process names its procd service. The driver only carries the
|
||||
command across -- over an SSH exec channel of its own, because busybox ash cuts
|
||||
an interactive line at 512 characters and the command is longer.
|
||||
|
||||
The netstat output is a real OpenWrt 25.12.2 access point's, with documentation
|
||||
addresses.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_openwrt.openwrt import OpenWrtDriver
|
||||
|
||||
REPORT = """SOCK_BEGIN
|
||||
[netstat]
|
||||
Active Internet connections (only servers)
|
||||
Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name
|
||||
tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 1604/dropbear
|
||||
tcp 0 0 0.0.0.0:443 0.0.0.0:* LISTEN 1969/uhttpd
|
||||
tcp 0 0 192.0.2.15:53 0.0.0.0:* LISTEN 1495/dnsmasq
|
||||
tcp 0 0 :::443 :::* LISTEN 1969/uhttpd
|
||||
udp 0 0 0.0.0.0:161 0.0.0.0:* 3173/snmpd
|
||||
__SS_RC=0
|
||||
[cgroups]
|
||||
1495 0::/services/dnsmasq/cfg01411c
|
||||
1604 0::/services/dropbear/instance1
|
||||
1969 0::/services/uhttpd/instance1
|
||||
3173 0::/services/snmpd/instance1
|
||||
SOCK_END
|
||||
"""
|
||||
|
||||
|
||||
def _driver(username: str = "root", report: str = REPORT) -> OpenWrtDriver:
|
||||
with patch("napalm_openwrt.openwrt.ConnectHandler"):
|
||||
drv = OpenWrtDriver(hostname="192.0.2.15", username=username, password="")
|
||||
drv.device = MagicMock()
|
||||
exec_command = drv.device.remote_conn_pre.exec_command
|
||||
exec_command.side_effect = lambda *_a, **_k: (None, io.BytesIO(report.encode()), None)
|
||||
return drv
|
||||
|
||||
|
||||
def test_every_socket_with_its_procd_service():
|
||||
reading = _driver().get_listening_sockets()
|
||||
|
||||
assert reading["attributed"] is True
|
||||
services = {(s["proto"], s["port"], s["address"]): s["unit"] for s in reading["sockets"]}
|
||||
assert services == {
|
||||
("tcp", 22, "0.0.0.0"): "dropbear",
|
||||
("tcp", 53, "192.0.2.15"): "dnsmasq",
|
||||
("tcp", 443, "0.0.0.0"): "uhttpd",
|
||||
("tcp", 443, "::"): "uhttpd",
|
||||
("udp", 161, "0.0.0.0"): "snmpd",
|
||||
}
|
||||
|
||||
|
||||
def test_the_command_goes_over_an_exec_channel_not_the_shell():
|
||||
drv = _driver()
|
||||
drv.get_listening_sockets()
|
||||
|
||||
[call] = drv.device.remote_conn_pre.exec_command.call_args_list
|
||||
assert call.args[0].startswith("sh -c '")
|
||||
drv.device.send_command.assert_not_called()
|
||||
|
||||
|
||||
def test_a_login_other_than_root_reads_without_attributing():
|
||||
drv = _driver(username="admin")
|
||||
|
||||
reading = drv.get_listening_sockets()
|
||||
|
||||
assert reading["attributed"] is False
|
||||
assert len(drv.device.remote_conn_pre.exec_command.call_args_list) == 1
|
||||
|
||||
|
||||
def test_a_report_cut_short_raises():
|
||||
with pytest.raises(ValueError):
|
||||
_driver(report=REPORT.replace("SOCK_END\n", "")).get_listening_sockets()
|
||||
|
||||
|
||||
def test_netork_finds_it():
|
||||
"""netOrk asks ``hasattr(driver, "get_listening_sockets")``."""
|
||||
assert hasattr(OpenWrtDriver, "get_listening_sockets")
|
||||
@@ -0,0 +1,115 @@
|
||||
"""configure_lldp_agent: lldpd on the interfaces the caller names (#8).
|
||||
|
||||
The LLDP getters used to start lldpd and rewrite its interface list on every
|
||||
poll. That is an action now, napalm-device-types' ``LldpAgentMixin``: the
|
||||
template installs and starts lldpd, the driver writes the list into UCI.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_openwrt import OpenWrtDriver
|
||||
|
||||
|
||||
class _Shell:
|
||||
"""Collects issued commands; *fail* makes a command containing it exit 1."""
|
||||
|
||||
def __init__(self, fail: str = ""):
|
||||
self.fail = fail
|
||||
self.issued: list[str] = []
|
||||
|
||||
def __call__(self, cmd, **kw):
|
||||
self.issued.append(cmd)
|
||||
if "__OWRT_RC" in cmd:
|
||||
if self.fail and self.fail in cmd:
|
||||
return "uci: Invalid argument\n__OWRT_RC=1"
|
||||
return "__OWRT_RC=0"
|
||||
return ""
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def shell():
|
||||
return _Shell()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def owrt(shell):
|
||||
d = OpenWrtDriver("ap", "root", "pw")
|
||||
d._send_command = shell
|
||||
d.get_packages = lambda: [{"name": "lldpd", "version": "1.0.17-1", "installed": True}]
|
||||
return d
|
||||
|
||||
|
||||
def _uci(shell) -> str:
|
||||
return next(c for c in shell.issued if "uci commit lldpd" in c)
|
||||
|
||||
|
||||
def test_install_configure_enable_and_restart(owrt, shell):
|
||||
result = owrt.configure_lldp_agent(["br-lan"])
|
||||
|
||||
assert result["success"] is True, result["output"]
|
||||
assert [s["step"] for s in result["steps"]] == ["install", "configure", "start"]
|
||||
uci = _uci(shell)
|
||||
assert "uci -q delete lldpd.config.interface" in uci
|
||||
assert "uci add_list lldpd.config.interface='br-lan'" in uci
|
||||
lldpd = [c.split(" 2>")[0] for c in shell.issued if c.startswith("/etc/init.d/lldpd")]
|
||||
assert lldpd == ["/etc/init.d/lldpd enable", "/etc/init.d/lldpd restart"]
|
||||
|
||||
|
||||
def test_the_list_is_replaced_and_a_missing_section_is_made(owrt, shell):
|
||||
owrt.configure_lldp_agent(["br-lan", "eth1"])
|
||||
|
||||
uci = _uci(shell)
|
||||
assert "uci set lldpd.config=lldpd" in uci
|
||||
assert uci.index("delete lldpd.config.interface") < uci.index("add_list")
|
||||
assert "interface='br-lan'" in uci
|
||||
assert "interface='eth1'" in uci
|
||||
|
||||
|
||||
def test_a_vlan_device_is_written_as_the_device_under_it(owrt, shell):
|
||||
# lldpd sends on the L2 device: on br-ap, not on its VLAN br-ap.10.
|
||||
owrt.configure_lldp_agent(["br-ap.10", "br-ap"])
|
||||
|
||||
uci = _uci(shell)
|
||||
assert "interface='br-ap'" in uci
|
||||
assert "br-ap.10" not in uci
|
||||
assert uci.count("add_list") == 1
|
||||
|
||||
|
||||
def test_a_name_that_is_not_an_interface_name_writes_nothing(owrt, shell):
|
||||
result = owrt.configure_lldp_agent(["br-lan'; reboot; '"])
|
||||
|
||||
assert result["success"] is False
|
||||
assert result["steps"][-1]["step"] == "configure"
|
||||
assert not any("uci" in c or "lldpd restart" in c for c in shell.issued)
|
||||
|
||||
|
||||
def test_a_refused_uci_write_leaves_lldpd_alone():
|
||||
shell = _Shell(fail="uci commit lldpd")
|
||||
d = OpenWrtDriver("ap", "root", "pw")
|
||||
d._send_command = shell
|
||||
d.get_packages = lambda: [{"name": "lldpd", "installed": True}]
|
||||
|
||||
result = d.configure_lldp_agent(["br-lan"])
|
||||
|
||||
assert result["success"] is False
|
||||
assert "Invalid argument" in result["output"]
|
||||
assert not any("/etc/init.d/lldpd" in c for c in shell.issued)
|
||||
|
||||
|
||||
def test_lldpd_is_installed_where_it_is_missing(owrt, shell):
|
||||
owrt.get_packages = lambda: []
|
||||
asked: list[str] = []
|
||||
owrt.install_package = lambda name, version="": (
|
||||
asked.append(name)
|
||||
or {
|
||||
"success": True,
|
||||
"output": f"installed {name}",
|
||||
}
|
||||
)
|
||||
|
||||
result = owrt.configure_lldp_agent(["br-lan"])
|
||||
|
||||
assert result["success"] is True
|
||||
assert asked == ["lldpd"]
|
||||
@@ -0,0 +1,120 @@
|
||||
"""install_package / uninstall_package: only the exit status decides (#28).
|
||||
|
||||
Searching the output for words like "error:" or "failed" misreads both ways:
|
||||
opkg's dependency failure says "Collected errors:" (not "error:") and a
|
||||
successful install may name a file containing "failed".
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_openwrt.openwrt import OpenWrtDriver
|
||||
|
||||
OPKG_DEPENDS_FAILED = (
|
||||
"Installing lldpd (1.0.17-1) to root...\n"
|
||||
"Collected errors:\n"
|
||||
" * satisfy_dependencies_for: Cannot satisfy the following dependencies for lldpd:\n"
|
||||
" * \tlibevent2-7 (>= 2.1.12)\n"
|
||||
" * opkg_install_cmd: Cannot install package lldpd.\n"
|
||||
"__OWRT_RC=255\n"
|
||||
)
|
||||
APK_ADD_OK_NAMING_FAILED = (
|
||||
"(1/1) Installing failed-login-notify (1.0-r1)\nOK: 12 MiB in 140 packages\n__OWRT_RC=0\n"
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def driver():
|
||||
with patch("napalm_openwrt.openwrt.ConnectHandler"):
|
||||
drv = OpenWrtDriver(hostname="192.0.2.1", username="root", password="")
|
||||
drv.device = MagicMock()
|
||||
yield drv
|
||||
|
||||
|
||||
def _answer(driver, pm: str, reply: str) -> list[str]:
|
||||
"""Answer the package-manager probe with *pm* and everything else with *reply*."""
|
||||
sent: list[str] = []
|
||||
|
||||
def send(cmd, **kwargs):
|
||||
sent.append(cmd)
|
||||
if cmd.startswith("command -v apk"):
|
||||
return "/usr/bin/apk" if pm == "apk" else "__no_apk__"
|
||||
return reply
|
||||
|
||||
driver._send_command = send
|
||||
return sent
|
||||
|
||||
|
||||
class TestInstallPackage:
|
||||
def test_opkg_dependency_failure_is_no_success(self, driver):
|
||||
sent = _answer(driver, "opkg", OPKG_DEPENDS_FAILED)
|
||||
|
||||
result = driver.install_package("lldpd")
|
||||
|
||||
assert result["success"] is False
|
||||
assert "Cannot install package lldpd" in result["output"]
|
||||
assert "__OWRT_RC" not in result["output"]
|
||||
assert sent[-1] == "opkg install lldpd 2>&1; echo __OWRT_RC=$?"
|
||||
|
||||
def test_success_whose_output_says_failed_is_success(self, driver):
|
||||
sent = _answer(driver, "apk", APK_ADD_OK_NAMING_FAILED)
|
||||
|
||||
result = driver.install_package("failed-login-notify")
|
||||
|
||||
assert result == {
|
||||
"success": True,
|
||||
"output": "(1/1) Installing failed-login-notify (1.0-r1)\nOK: 12 MiB in 140 packages",
|
||||
}
|
||||
assert sent[-1] == "apk add failed-login-notify 2>&1; echo __OWRT_RC=$?"
|
||||
|
||||
def test_marker_behind_a_progress_bar_is_still_read(self, driver):
|
||||
_answer(driver, "apk", "(1/1) Installing lldpd (1.0.17-r1)\n 100% ####\r__OWRT_RC=0\n")
|
||||
|
||||
assert driver.install_package("lldpd")["success"] is True
|
||||
|
||||
def test_output_without_a_status_is_no_success(self, driver):
|
||||
_answer(driver, "apk", "")
|
||||
|
||||
result = driver.install_package("lldpd")
|
||||
|
||||
assert result["success"] is False
|
||||
assert result["output"]
|
||||
|
||||
def test_failure_without_output_names_the_status(self, driver):
|
||||
_answer(driver, "apk", "__OWRT_RC=99\n")
|
||||
|
||||
result = driver.install_package("lldpd")
|
||||
|
||||
assert result["success"] is False
|
||||
assert "status 99" in result["output"]
|
||||
|
||||
|
||||
class TestUninstallPackage:
|
||||
def test_opkg_remove_that_failed_is_no_success(self, driver):
|
||||
sent = _answer(
|
||||
driver,
|
||||
"opkg",
|
||||
"Collected errors:\n * print_dependents_warning: Package lldpd is depended upon by:\n"
|
||||
"__OWRT_RC=255\n",
|
||||
)
|
||||
|
||||
result = driver.uninstall_package("lldpd")
|
||||
|
||||
assert result["success"] is False
|
||||
assert "depended upon" in result["output"]
|
||||
assert sent[-1] == "opkg remove lldpd 2>&1; echo __OWRT_RC=$?"
|
||||
|
||||
def test_apk_del_that_worked(self, driver):
|
||||
sent = _answer(
|
||||
driver,
|
||||
"apk",
|
||||
"(1/1) Purging failed-login-notify (1.0-r1)\nOK: 11 MiB in 139 packages\n__OWRT_RC=0\n",
|
||||
)
|
||||
|
||||
result = driver.uninstall_package("failed-login-notify")
|
||||
|
||||
assert result["success"] is True
|
||||
assert sent[-1] == "apk del failed-login-notify 2>&1; echo __OWRT_RC=$?"
|
||||
@@ -0,0 +1,454 @@
|
||||
"""Scheduled jobs on OpenWrt: BusyBox crond and the crontabs in /etc/crontabs (#32).
|
||||
|
||||
Every command is run by a real ``sh`` over a directory that stands in for the
|
||||
router, with ``PATH`` holding only applets OpenWrt's BusyBox is built with -- BusyBox's
|
||||
own where the test host has BusyBox -- (no ``stat``, ``cksum``, ``install``,
|
||||
``su`` or, before 25.x, ``timeout``). ``crontab``, ``uci``, ``opkg``, ``apk``,
|
||||
``start-stop-daemon`` and the cron init script are scripts that keep a log.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import shutil
|
||||
import subprocess
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from napalm_device_types import CommandResult, PosixScheduledJobsMixin
|
||||
from napalm_device_types._scheduled_reading import Paths, reading_command
|
||||
from napalm_device_types.scheduled_jobs import (
|
||||
RUN_TIMEOUT,
|
||||
ScheduledJobChanged,
|
||||
ScheduledJobRefused,
|
||||
)
|
||||
|
||||
from napalm_openwrt import OpenWrtDriver
|
||||
from napalm_openwrt.scheduled_jobs_mixin import OpenWrtScheduledJobsMixin
|
||||
|
||||
FAILBACK = "*/15 * * * * /usr/sbin/netork-reboot-check.sh"
|
||||
LUCI = "0 4 * * * /usr/bin/backup.sh"
|
||||
OWN = "# napalm-scheduled-job: speedtest nightly speed test\n30 2 * * * /usr/bin/speedtest\n"
|
||||
|
||||
#: Applets of OpenWrt's default BusyBox (package/utils/busybox/Config-defaults.in,
|
||||
#: 21.02 to 25.x) that these scripts or the test's own tools need.
|
||||
APPLETS = (
|
||||
"sh",
|
||||
"cat",
|
||||
"chmod",
|
||||
"printf",
|
||||
"sed",
|
||||
"cut",
|
||||
"mktemp",
|
||||
"rm",
|
||||
"mv",
|
||||
"test",
|
||||
"[",
|
||||
"tr",
|
||||
"ls",
|
||||
"echo",
|
||||
"pwd",
|
||||
"basename",
|
||||
"xargs",
|
||||
"readlink",
|
||||
)
|
||||
|
||||
#: BusyBox ``crontab``: ``-u USER -l`` lists, ``-u USER FILE`` replaces through
|
||||
#: ``USER.new`` and appends the user to ``cron.update`` -- and exits 0 when it
|
||||
#: could not create the file.
|
||||
CRONTAB = """#!/bin/sh
|
||||
echo "crontab $*" >> "$LOG"
|
||||
[ "$1" = -u ] || exit 2
|
||||
if [ "$3" = -l ]; then cat "$SPOOL/$2"; exit; fi
|
||||
if [ -n "$CRONTAB_BROKEN" ]; then echo "crontab: can't create $SPOOL/$2.new" >&2; exit 0; fi
|
||||
cat "$3" > "$SPOOL/$2.new" && mv "$SPOOL/$2.new" "$SPOOL/$2"
|
||||
echo "$2" >> "$SPOOL/cron.update"
|
||||
"""
|
||||
|
||||
UCI = """#!/bin/sh
|
||||
echo "uci $*" >> "$LOG"
|
||||
[ "$*" = "-q get system.@system[0].zonename" ] || exit 2
|
||||
[ -n "$ZONE" ] || exit 1
|
||||
echo "$ZONE"
|
||||
"""
|
||||
|
||||
OPKG = """#!/bin/sh
|
||||
[ "$1" = search ] || exit 2
|
||||
[ "$2" = "$OWNED" ] && echo "luci-app-backup - 1.0-1"
|
||||
exit 0
|
||||
"""
|
||||
|
||||
LOG_ONLY = """#!/bin/sh
|
||||
echo "$(basename "$0") $*" >> "$LOG"
|
||||
"""
|
||||
|
||||
#: Logs, then runs what follows ``--`` with the executable named by ``-x``.
|
||||
SSD = """#!/bin/sh
|
||||
echo "start-stop-daemon $*" >> "$LOG"
|
||||
x=""
|
||||
while [ "$1" != -- ]; do [ "$1" = -x ] && x="$2"; shift; done
|
||||
shift
|
||||
exec "$x" "$@"
|
||||
"""
|
||||
|
||||
#: coreutils' ``timeout SECS PROG ARGS``, which BusyBox has from OpenWrt 25.x on.
|
||||
TIMEOUT = """#!/bin/sh
|
||||
echo "timeout $1" >> "$LOG"
|
||||
shift
|
||||
exec "$@"
|
||||
"""
|
||||
|
||||
|
||||
def _tool(bin_dir: Path, name: str, body: str) -> None:
|
||||
path = bin_dir / name
|
||||
path.write_text(body)
|
||||
path.chmod(0o755)
|
||||
|
||||
|
||||
def _applets(bin_dir: Path) -> None:
|
||||
"""The applets, from BusyBox where the test host has it; ``sh`` is the host's own.
|
||||
|
||||
A distribution's BusyBox shell runs its built-in applets ahead of ``PATH``
|
||||
(``FEATURE_SH_STANDALONE``, off on OpenWrt) and would pass by the fakes.
|
||||
"""
|
||||
busybox = shutil.which("busybox")
|
||||
for applet in APPLETS:
|
||||
target = (busybox if applet != "sh" else None) or shutil.which(applet)
|
||||
assert target, f"the test host has no {applet}"
|
||||
(bin_dir / applet).symlink_to(target)
|
||||
|
||||
|
||||
class Router(OpenWrtScheduledJobsMixin):
|
||||
"""An OpenWrt router in a directory; every command runs in its shell, as the test user."""
|
||||
|
||||
def __init__(self, root: Path, **env: str) -> None:
|
||||
self.root = root
|
||||
self.CRON_SPOOL_DIRS = (str(root / "crontabs"),) # type: ignore[misc]
|
||||
init = root / "init.d" / "cron"
|
||||
self.CRONTAB_AFTER_WRITE = ("sh", "-c", f"{init} enable && {init} restart") # type: ignore[misc]
|
||||
self.env = env
|
||||
self.calls: list[dict[str, Any]] = []
|
||||
|
||||
def _sj_paths(self) -> Paths:
|
||||
# The test host may have systemd; the router never does.
|
||||
return replace(super()._sj_paths(), systemd_marker=str(self.root / "no-systemd"))
|
||||
|
||||
def run_command(
|
||||
self,
|
||||
command: str,
|
||||
*,
|
||||
privileged: bool = False,
|
||||
timeout: float = 60,
|
||||
stdin: bytes | None = None,
|
||||
) -> CommandResult:
|
||||
self.calls.append({"command": command, "privileged": privileged, "timeout": timeout})
|
||||
env = {
|
||||
"PATH": str(self.root / "bin"),
|
||||
"HOME": str(self.root),
|
||||
"LOG": str(self.root / "log"),
|
||||
"SPOOL": str(self.root / "crontabs"),
|
||||
"OWNED": "",
|
||||
**self.env,
|
||||
}
|
||||
done = subprocess.run(
|
||||
[str(self.root / "bin" / "sh"), "-c", command],
|
||||
input=stdin,
|
||||
capture_output=True,
|
||||
env=env,
|
||||
cwd=self.root,
|
||||
timeout=30,
|
||||
)
|
||||
return CommandResult(done.stdout.decode(), done.stderr.decode(), done.returncode)
|
||||
|
||||
def log(self) -> str:
|
||||
log = self.root / "log"
|
||||
return log.read_text() if log.exists() else ""
|
||||
|
||||
def crontab(self, user: str = "root") -> str:
|
||||
return (self.root / "crontabs" / user).read_text()
|
||||
|
||||
def job(self, key: str) -> dict[str, Any]:
|
||||
return next(j for j in self.get_scheduled_jobs()["jobs"] if j["key"] == key) # type: ignore[misc]
|
||||
|
||||
def job_like(self, needle: str) -> dict[str, Any]:
|
||||
jobs = self.get_scheduled_jobs()["jobs"]
|
||||
return next(j for j in jobs if needle in j["command"]) # type: ignore[misc]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def root(tmp_path: Path) -> Path:
|
||||
for d in ("bin", "crontabs", "init.d"):
|
||||
(tmp_path / d).mkdir()
|
||||
_applets(tmp_path / "bin")
|
||||
for name, body in (
|
||||
("crontab", CRONTAB),
|
||||
("uci", UCI),
|
||||
("opkg", OPKG),
|
||||
("start-stop-daemon", SSD),
|
||||
):
|
||||
_tool(tmp_path / "bin", name, body)
|
||||
_tool(tmp_path / "init.d", "cron", LOG_ONLY.replace('"$(basename "$0")', '"cron'))
|
||||
(tmp_path / "crontabs/root").write_text(f"{LUCI}\n{FAILBACK}\n")
|
||||
return tmp_path
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def router(root: Path) -> Router:
|
||||
return Router(root, ZONE="Europe/Berlin")
|
||||
|
||||
|
||||
# -- the driver ------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_the_driver_has_scheduled_jobs_through_the_posix_mixin():
|
||||
assert issubclass(OpenWrtDriver, OpenWrtScheduledJobsMixin)
|
||||
assert issubclass(OpenWrtDriver, PosixScheduledJobsMixin)
|
||||
for verb in (
|
||||
"get_scheduled_jobs",
|
||||
"manage_scheduled_job",
|
||||
"put_scheduled_job",
|
||||
"delete_scheduled_job",
|
||||
):
|
||||
assert callable(getattr(OpenWrtDriver, verb))
|
||||
|
||||
|
||||
def test_busybox_crond_reads_only_the_user_crontabs():
|
||||
assert OpenWrtDriver.CRON_SPOOL_DIRS == ("/etc/crontabs",)
|
||||
assert OpenWrtDriver.CRON_SYSTEM_FILES == ()
|
||||
assert OpenWrtDriver.CRON_D_DIRS == ()
|
||||
assert OpenWrtDriver.RUN_PARTS_DIRS == ()
|
||||
assert OpenWrtDriver.OWN_CRON_D_DIR is None
|
||||
assert OpenWrtDriver.ANACRONTAB == ""
|
||||
assert OpenWrtDriver.CRONTAB_AFTER_WRITE == (
|
||||
"sh",
|
||||
"-c",
|
||||
"/etc/init.d/cron enable && /etc/init.d/cron restart",
|
||||
)
|
||||
|
||||
|
||||
def test_the_report_fits_one_dropbear_exec_request():
|
||||
"""run_command is an exec channel: no 512-character ash line, but dropbear's MAX_CMD_LEN."""
|
||||
driver = OpenWrtDriver("ap", "root", "pw")
|
||||
assert len(reading_command(driver._sj_paths())) < 9000
|
||||
|
||||
|
||||
# -- reading ---------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_every_line_of_every_crontab_is_a_job(router: Router, root: Path):
|
||||
(root / "crontabs/root").write_text(
|
||||
f"{LUCI}\n{FAILBACK}\n#napalm-disabled: 5 5 * * * /bin/off\n{OWN}"
|
||||
)
|
||||
(root / "crontabs/nobody").write_text("*/5 * * * * /usr/bin/poll\n")
|
||||
(root / "crontabs/cron.update").write_text("root\n")
|
||||
reading = router.get_scheduled_jobs()
|
||||
assert reading["time_zone"] == "Europe/Berlin"
|
||||
jobs = {j["command"]: j for j in reading["jobs"]}
|
||||
assert set(jobs) == {
|
||||
"/usr/bin/backup.sh",
|
||||
"/usr/sbin/netork-reboot-check.sh",
|
||||
"/bin/off",
|
||||
"/usr/bin/speedtest",
|
||||
"/usr/bin/poll",
|
||||
}
|
||||
failback = jobs["/usr/sbin/netork-reboot-check.sh"]
|
||||
assert (failback["managed_by"], failback["run_as"], failback["schedule"]) == (
|
||||
"admin",
|
||||
"root",
|
||||
"*/15 * * * *",
|
||||
)
|
||||
assert failback["actions"] == ["enable", "disable", "run"]
|
||||
assert jobs["/bin/off"]["enabled"] is False
|
||||
assert jobs["/usr/bin/poll"]["run_as"] == "nobody"
|
||||
own = jobs["/usr/bin/speedtest"]
|
||||
assert (own["key"], own["managed_by"], own["description"]) == (
|
||||
"job:speedtest",
|
||||
"application",
|
||||
"nightly speed test",
|
||||
)
|
||||
assert "edit" in own["actions"] and "delete" in own["actions"]
|
||||
assert router.calls[0]["privileged"] is True
|
||||
|
||||
|
||||
def test_a_zone_name_with_spaces_is_the_iana_name(root: Path):
|
||||
reading = Router(root, ZONE="America/Port of Spain").get_scheduled_jobs()
|
||||
assert reading["time_zone"] == "America/Port_of_Spain"
|
||||
|
||||
|
||||
def test_no_zone_name_is_no_time_zone(root: Path):
|
||||
assert Router(root).get_scheduled_jobs()["time_zone"] is None
|
||||
|
||||
|
||||
def _owned(root: Path) -> Router:
|
||||
return Router(root, OWNED=str(root / "crontabs" / "root"))
|
||||
|
||||
|
||||
def test_a_crontab_opkg_owns_is_a_package_s(root: Path):
|
||||
assert _owned(root).job_like("backup.sh")["managed_by"] == "package"
|
||||
|
||||
|
||||
def test_apk_based_openwrt_names_no_owner(root: Path):
|
||||
_tool(root / "bin", "apk", LOG_ONLY)
|
||||
assert _owned(root).job_like("backup.sh")["managed_by"] == "admin"
|
||||
|
||||
|
||||
def test_without_a_package_manager_nothing_is_owned(root: Path):
|
||||
(root / "bin/opkg").unlink()
|
||||
assert _owned(root).job_like("backup.sh")["managed_by"] == "admin"
|
||||
|
||||
|
||||
# -- switching -------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_switching_a_job_off_changes_its_line_and_nothing_else(router: Router):
|
||||
job = router.job_like("backup.sh")
|
||||
result = router.manage_scheduled_job(job["key"], "disable", digest=job["digest"])
|
||||
assert result["success"] is True
|
||||
assert router.crontab() == f"#napalm-disabled: {LUCI}\n{FAILBACK}\n"
|
||||
assert "crontab -u root /" in router.log()
|
||||
assert "cron enable\ncron restart\n" in router.log()
|
||||
job = router.job(job["key"])
|
||||
router.manage_scheduled_job(job["key"], "enable", digest=job["digest"])
|
||||
assert router.crontab() == f"{LUCI}\n{FAILBACK}\n"
|
||||
|
||||
|
||||
def test_a_switch_over_a_changed_crontab_writes_nothing(router: Router, root: Path):
|
||||
job = router.job_like("backup.sh")
|
||||
(root / "crontabs/root").write_text(f"#napalm-disabled: {LUCI}\n{FAILBACK}\n")
|
||||
with pytest.raises(ScheduledJobChanged):
|
||||
router.manage_scheduled_job(job["key"], "disable", digest=job["digest"])
|
||||
assert "crontab -u" not in router.log()
|
||||
|
||||
|
||||
def test_a_write_crontab_did_not_make_raises(root: Path):
|
||||
router = Router(root, ZONE="UTC", CRONTAB_BROKEN="1")
|
||||
job = router.job_like("backup.sh")
|
||||
with pytest.raises(RuntimeError, match="not written"):
|
||||
router.manage_scheduled_job(job["key"], "disable", digest=job["digest"])
|
||||
assert router.crontab() == f"{LUCI}\n{FAILBACK}\n"
|
||||
|
||||
|
||||
# -- an application's own job ----------------------------------------------------------------
|
||||
|
||||
|
||||
def _spec(**changes: Any) -> Any:
|
||||
spec = {
|
||||
"name": "speedtest",
|
||||
"schedule": "30 2 * * *",
|
||||
"run_as": "root",
|
||||
"command": "/usr/bin/speedtest",
|
||||
"enabled": True,
|
||||
"description": "nightly speed test",
|
||||
}
|
||||
return {**spec, **changes}
|
||||
|
||||
|
||||
def test_an_own_job_is_two_marked_lines_at_the_end_of_the_crontab(router: Router):
|
||||
result = router.put_scheduled_job(_spec())
|
||||
assert result == {"success": True, "output": "job:speedtest created"}
|
||||
assert router.crontab() == f"{LUCI}\n{FAILBACK}\n{OWN}"
|
||||
assert "cron enable\ncron restart\n" in router.log()
|
||||
|
||||
|
||||
def test_changing_and_deleting_an_own_job_keep_the_failback_line(router: Router):
|
||||
router.put_scheduled_job(_spec())
|
||||
job = router.job("job:speedtest")
|
||||
router.put_scheduled_job(_spec(schedule="0 3 * * *", enabled=False), digest=job["digest"])
|
||||
assert router.crontab() == (
|
||||
f"{LUCI}\n{FAILBACK}\n# napalm-scheduled-job: speedtest nightly speed test\n"
|
||||
"#napalm-disabled: 0 3 * * * /usr/bin/speedtest\n"
|
||||
)
|
||||
job = router.job("job:speedtest")
|
||||
router.delete_scheduled_job("job:speedtest", digest=job["digest"])
|
||||
assert router.crontab() == f"{LUCI}\n{FAILBACK}\n"
|
||||
|
||||
|
||||
def test_an_own_job_starts_a_crontab_where_there_is_none(router: Router, root: Path):
|
||||
(root / "crontabs/root").unlink()
|
||||
router.put_scheduled_job(_spec())
|
||||
assert router.crontab() == OWN
|
||||
|
||||
|
||||
def test_a_crontab_that_cannot_be_read_is_never_written(router: Router, root: Path):
|
||||
(root / "crontabs/nobody").mkdir() # cat fails on it, as root too
|
||||
with pytest.raises(RuntimeError, match="cannot read the crontab of nobody"):
|
||||
router.put_scheduled_job(_spec(run_as="nobody"))
|
||||
assert "crontab -u" not in router.log()
|
||||
|
||||
|
||||
def test_an_alias_is_written_as_its_five_fields(router: Router):
|
||||
router.put_scheduled_job(_spec(schedule="@daily"))
|
||||
assert "\n0 0 * * * /usr/bin/speedtest\n" in router.crontab()
|
||||
|
||||
|
||||
def test_reboot_is_refused_busybox_crond_has_no_special_times(router: Router):
|
||||
with pytest.raises(ScheduledJobRefused, match="@reboot"):
|
||||
router.put_scheduled_job(_spec(schedule="@reboot"))
|
||||
assert router.crontab() == f"{LUCI}\n{FAILBACK}\n"
|
||||
|
||||
|
||||
# -- running now -----------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _run(router: Router, text: str, user: str = "root") -> Any:
|
||||
(router.root / "crontabs" / user).write_text(text)
|
||||
(job,) = (j for j in router.get_scheduled_jobs()["jobs"] if j["run_as"] == user)
|
||||
return router.manage_scheduled_job(job["key"], "run", digest=job["digest"])
|
||||
|
||||
|
||||
def test_a_run_is_the_command_as_busybox_crond_has_it(router: Router):
|
||||
result = _run(
|
||||
router,
|
||||
'PATH=/bin:/sbin\nMAILTO=x\n* * * * * printf \'%s %s %s\\n\' 100% "$PATH" "$LOGNAME"\n',
|
||||
)
|
||||
# BusyBox crond gives % no meaning and exports only PATH (and SHELL) of the crontab.
|
||||
assert result == {"success": True, "output": "100% /bin:/sbin root"}
|
||||
|
||||
|
||||
def test_a_run_has_the_user_s_home(router: Router):
|
||||
result = _run(router, '* * * * * echo "$HOME $USER"\n')
|
||||
assert result["output"] == "/root root"
|
||||
|
||||
|
||||
def test_a_run_is_bounded_where_the_router_has_timeout(router: Router, root: Path):
|
||||
_tool(root / "bin", "timeout", TIMEOUT)
|
||||
result = _run(router, "* * * * * echo hi\n")
|
||||
assert result == {"success": True, "output": "hi"}
|
||||
assert f"timeout {RUN_TIMEOUT}\n" in router.log()
|
||||
assert router.calls[-1]["timeout"] > RUN_TIMEOUT
|
||||
|
||||
|
||||
def test_a_run_goes_on_without_timeout(router: Router):
|
||||
result = _run(router, "* * * * * echo hi; exit 3\n")
|
||||
assert result == {"success": False, "output": "hi"}
|
||||
assert "timeout" not in router.log()
|
||||
|
||||
|
||||
def test_a_run_says_its_exit_status_when_the_job_says_nothing(router: Router):
|
||||
assert _run(router, "* * * * * exit 4\n") == {"success": False, "output": "exit 4"}
|
||||
|
||||
|
||||
def test_a_quiet_run_says_it_ran(router: Router):
|
||||
assert _run(router, "* * * * * true\n") == {"success": True, "output": "ran"}
|
||||
|
||||
|
||||
def test_another_user_s_job_runs_through_start_stop_daemon(router: Router):
|
||||
"""OpenWrt's BusyBox has no su; start-stop-daemon -c switches the user."""
|
||||
result = _run(router, "* * * * * echo as-nobody\n", user="nobody")
|
||||
assert result == {"success": True, "output": "as-nobody"}
|
||||
assert "start-stop-daemon -S -p /dev/null -c nobody -x /bin/sh -- -c " in router.log()
|
||||
|
||||
|
||||
def test_a_user_a_shell_could_misread_is_not_run(router: Router, root: Path):
|
||||
(root / "crontabs/x$(id)").write_text("* * * * * echo no\n")
|
||||
job = router.job_like("echo no")
|
||||
with pytest.raises(ScheduledJobRefused):
|
||||
router.manage_scheduled_job(job["key"], "run", digest=job["digest"])
|
||||
assert "start-stop-daemon" not in router.log()
|
||||
|
||||
|
||||
def test_the_root_login_runs_without_sudo():
|
||||
"""run_command on OpenWrt refuses privileged commands for another login; root needs no su."""
|
||||
driver = OpenWrtDriver("ap", "root", "pw")
|
||||
assert driver._sj_as("root", "true") == ["sh", "-c", "true"]
|
||||
@@ -0,0 +1,49 @@
|
||||
"""set_hostname quotes the name for the shell (NetOrk/netork#2456).
|
||||
|
||||
The name went into ``uci set system.@system[0].hostname='<name>'`` between single
|
||||
quotes of its own, so a name with a single quote ended them: ``x';reboot;'`` ran
|
||||
``reboot`` as root. The name now reaches ``uci`` as one word, whatever it holds.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import shlex
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_openwrt.openwrt import OpenWrtDriver
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def driver():
|
||||
with patch("napalm_openwrt.openwrt.ConnectHandler"):
|
||||
drv = OpenWrtDriver(hostname="192.0.2.1", username="root", password="")
|
||||
drv._send_command = MagicMock(return_value="")
|
||||
return drv
|
||||
|
||||
|
||||
def _uci_set(command: str) -> list[str]:
|
||||
"""The words of the ``uci set`` the command runs, as the shell splits them."""
|
||||
first = command.split(" && ")[0]
|
||||
return shlex.split(first)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", ["ap-garden", "x';reboot;'", "a b", "$(reboot)", "`reboot`"])
|
||||
def test_the_name_reaches_uci_as_one_word(driver, name):
|
||||
driver.set_hostname(name)
|
||||
|
||||
[command] = [call.args[0] for call in driver._send_command.call_args_list]
|
||||
assert _uci_set(command) == ["uci", "set", f"system.@system[0].hostname={name}"]
|
||||
assert command.endswith(" && uci commit system && /etc/init.d/system reload")
|
||||
|
||||
|
||||
def test_a_quote_in_the_name_runs_nothing(driver):
|
||||
driver.set_hostname("x';reboot;'")
|
||||
|
||||
[command] = [call.args[0] for call in driver._send_command.call_args_list]
|
||||
# Split as the shell does, the commands are uci's and the reload, nothing else.
|
||||
lexer = shlex.shlex(command, posix=True, punctuation_chars=True)
|
||||
words = list(lexer)
|
||||
assert "reboot" not in words
|
||||
assert words.count(";") == 0
|
||||
@@ -0,0 +1,96 @@
|
||||
"""configure_snmp_agent's values: community, sources, contact, location (netOrk #1105).
|
||||
|
||||
The old fix_snmp set no community at all and opened the management zone to every
|
||||
source; the rule was named after an application. Every value is the caller's now.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from napalm_openwrt import OpenWrtDriver
|
||||
from tests.unit.test_driver import UCI_FIREWALL_HEALTHY, UCI_NETWORK_STATIC, _FakeShell
|
||||
|
||||
SETTINGS = {
|
||||
"community": "c0mm",
|
||||
"allowed_sources": ["198.51.100.20", "fd00::20"],
|
||||
"contact": "ops",
|
||||
"location": "rack 1",
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def shell():
|
||||
return _FakeShell(
|
||||
firewall=UCI_FIREWALL_HEALTHY,
|
||||
network=UCI_NETWORK_STATIC,
|
||||
ssh_connection="198.51.100.20 51234 192.0.2.1 22",
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def owrt(shell):
|
||||
d = OpenWrtDriver("ap", "root", "pw")
|
||||
d._send_command = shell
|
||||
return d
|
||||
|
||||
|
||||
def _joined(shell):
|
||||
return " ".join(shell.issued)
|
||||
|
||||
|
||||
def test_the_steps_run_in_order_and_succeed(owrt):
|
||||
result = owrt.configure_snmp_agent(SETTINGS)
|
||||
|
||||
assert result["success"] is True
|
||||
assert [s["step"] for s in result["steps"]] == ["install", "configure", "firewall", "start"]
|
||||
|
||||
|
||||
def test_community_per_source_in_uci(owrt, shell):
|
||||
owrt.configure_snmp_agent(SETTINGS)
|
||||
|
||||
uci = _joined(shell)
|
||||
assert "uci set snmpd.public.source='198.51.100.20/32'" in uci
|
||||
assert "uci set snmpd.public.community='c0mm'" in uci
|
||||
assert "uci set snmpd.public6.source='fd00::20/128'" in uci
|
||||
assert "snmpd.@system[0].sysLocation='rack 1'" in uci
|
||||
assert "uci commit snmpd" in uci
|
||||
|
||||
|
||||
def test_without_sources_every_address_may_ask(owrt, shell):
|
||||
owrt.configure_snmp_agent({"community": "c0mm", "allowed_sources": []})
|
||||
|
||||
assert "uci set snmpd.public.source='default'" in _joined(shell)
|
||||
|
||||
|
||||
def test_ipv4_sources_only_keep_ipv6_to_localhost(owrt, shell):
|
||||
owrt.configure_snmp_agent({"community": "c0mm", "allowed_sources": ["198.51.100.20"]})
|
||||
|
||||
assert "uci set snmpd.public6.source='::1/128'" in _joined(shell)
|
||||
|
||||
|
||||
def test_the_firewall_rule_is_limited_to_the_sources_and_neutrally_named(owrt, shell):
|
||||
owrt.configure_snmp_agent(SETTINGS)
|
||||
|
||||
uci = _joined(shell)
|
||||
assert "uci add_list firewall.allow_snmp_from_lan.src_ip='198.51.100.20/32'" in uci
|
||||
assert "firewall.allow_snmp_from_lan.name='Allow-SNMP'" in uci
|
||||
assert "netork" not in uci.lower()
|
||||
|
||||
|
||||
def test_the_management_peer_is_the_ssh_client(owrt):
|
||||
assert owrt.get_management_peer() == "198.51.100.20"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("community", ["two words", "it's", ""])
|
||||
def test_a_community_that_would_break_uci_is_refused(owrt, shell, community):
|
||||
result = owrt.configure_snmp_agent({"community": community, "allowed_sources": []})
|
||||
|
||||
assert result["success"] is False
|
||||
assert "uci commit snmpd" not in _joined(shell)
|
||||
|
||||
|
||||
def test_the_old_actions_are_gone():
|
||||
gone = ("run_device_action", "_action_fix_snmp", "_action_install_lldpd", "_action_install_auc")
|
||||
for name in gone:
|
||||
assert not hasattr(OpenWrtDriver, name), name
|
||||
@@ -0,0 +1,86 @@
|
||||
"""open() hands netmiko the host key to expect, and reports the one it saw (NetOrk/netork#1167)."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import paramiko
|
||||
import pytest
|
||||
from napalm_device_types.ssh_host_keys import (
|
||||
KNOWN_KEYS_ARG,
|
||||
OBSERVER_ARG,
|
||||
SshHostKey,
|
||||
SshHostKeyMismatch,
|
||||
)
|
||||
from netmiko.exceptions import NetmikoTimeoutException
|
||||
|
||||
from napalm_openwrt.openwrt import OpenWrtDriver
|
||||
|
||||
SERVER_KEY = paramiko.ECDSAKey.generate()
|
||||
OTHER_KEY = paramiko.ECDSAKey.generate()
|
||||
HANDLER = "napalm_openwrt.openwrt.ConnectHandler"
|
||||
|
||||
|
||||
def _device() -> MagicMock:
|
||||
device = MagicMock()
|
||||
device.remote_conn_pre.get_transport.return_value.get_remote_server_key.return_value = (
|
||||
SERVER_KEY
|
||||
)
|
||||
return device
|
||||
|
||||
|
||||
def _driver(seen: list, known: SshHostKey | None = None) -> OpenWrtDriver:
|
||||
args: dict = {"port": 2222, OBSERVER_ARG: seen.append}
|
||||
if known is not None:
|
||||
args[KNOWN_KEYS_ARG] = {"2222": known.as_dict()}
|
||||
return OpenWrtDriver("192.0.2.8", "admin", "s3cret", optional_args=args)
|
||||
|
||||
|
||||
def test_first_use_lets_netmiko_accept_and_reports_the_key():
|
||||
seen: list = []
|
||||
with patch(HANDLER, return_value=_device()) as handler:
|
||||
_driver(seen).open()
|
||||
kwargs = handler.call_args.kwargs
|
||||
assert kwargs["ssh_strict"] is False
|
||||
assert kwargs["alt_host_keys"] is False
|
||||
assert kwargs["system_host_keys"] is False
|
||||
assert kwargs["port"] == 2222
|
||||
assert seen[0]["accepted"] is True
|
||||
assert seen[0]["seen"]["fingerprint"] == SshHostKey.of(SERVER_KEY).fingerprint
|
||||
assert (seen[0]["host"], seen[0]["port"]) == ("192.0.2.8", 2222)
|
||||
|
||||
|
||||
def test_a_known_key_is_the_only_one_netmiko_accepts():
|
||||
seen: list = []
|
||||
known = SshHostKey.of(SERVER_KEY)
|
||||
files: list[str] = []
|
||||
|
||||
def connect(**kwargs):
|
||||
files.append(kwargs["alt_key_file"])
|
||||
with open(kwargs["alt_key_file"]) as f:
|
||||
assert f.read().strip() == known.known_hosts_line("192.0.2.8", 2222)
|
||||
assert kwargs["ssh_strict"] is True and kwargs["alt_host_keys"] is True
|
||||
return _device()
|
||||
|
||||
with patch(HANDLER, side_effect=connect):
|
||||
_driver(seen, known).open()
|
||||
assert not os.path.exists(files[0])
|
||||
assert seen[0]["accepted"] is True
|
||||
|
||||
|
||||
def test_a_changed_key_is_refused():
|
||||
seen: list = []
|
||||
|
||||
def refuse(**kwargs):
|
||||
try:
|
||||
raise paramiko.BadHostKeyException("192.0.2.8", SERVER_KEY, OTHER_KEY)
|
||||
except paramiko.SSHException as exc: # what netmiko does with it
|
||||
raise NetmikoTimeoutException(f"A paramiko SSHException occurred: {exc}") from exc
|
||||
|
||||
driver = _driver(seen, SshHostKey.of(OTHER_KEY))
|
||||
with patch(HANDLER, side_effect=refuse):
|
||||
with pytest.raises(SshHostKeyMismatch):
|
||||
driver.open()
|
||||
assert driver.device is None
|
||||
assert seen[0]["accepted"] is False
|
||||
@@ -0,0 +1,646 @@
|
||||
"""Time sync on OpenWrt (napalm-device-types ``TimeSyncMixin``, NetOrk/netork#2364).
|
||||
|
||||
OpenWrt keeps both values in UCI's ``system`` config: the servers in the
|
||||
``system.ntp.server`` list, which sysntpd hands to BusyBox ntpd, and the zone twice --
|
||||
``zonename`` (the IANA name, as LuCI writes it: with spaces for underscores) and
|
||||
``timezone``, the POSIX rule libc reads as ``TZ``. The rule is the one that counts
|
||||
(netOrk#1849: an IANA name in ``timezone`` left the AP on UTC).
|
||||
|
||||
The device is a fake ``uci`` behind ``run_command``: it renders ``uci -q show system``
|
||||
the way uci prints it, and applies the ``uci set``/``delete``/``add_list`` lines a
|
||||
write sends, so the template's ``verify`` step reads back what was written. Behind it
|
||||
is netifd's ``ubus call network.interface dump``, where a DHCP lease's NTP servers
|
||||
(option 42) are ``data.ntpserver`` -- sysntpd hands them to ntpd too while
|
||||
``use_dhcp`` is on, and they count (NetOrk/netork#2380).
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import shlex
|
||||
from typing import Any
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from napalm_device_types import CommandResult
|
||||
from napalm_device_types.posix_tz import UnknownTimezone, posix_tz
|
||||
from napalm_device_types.time_sync import TIME_SYNC_VALUES
|
||||
|
||||
from napalm_openwrt.openwrt import OpenWrtDriver
|
||||
from napalm_openwrt.time_sync_mixin import DHCP_MARK, parse_system_uci, zone_for_rule
|
||||
|
||||
# ``uci show system`` of OpenWrt 23.05 out of the box: zonename 'UTC', the rule GMT0,
|
||||
# the four pool servers as a list.
|
||||
STOCK = """\
|
||||
system.@system[0]=system
|
||||
system.@system[0].hostname='OpenWrt'
|
||||
system.@system[0].timezone='GMT0'
|
||||
system.@system[0].zonename='UTC'
|
||||
system.@system[0].ttylogin='0'
|
||||
system.@system[0].log_size='128'
|
||||
system.@system[0].urandom_seed='0'
|
||||
system.ntp=timeserver
|
||||
system.ntp.enabled='1'
|
||||
system.ntp.enable_server='0'
|
||||
system.ntp.server='0.openwrt.pool.ntp.org' '1.openwrt.pool.ntp.org' '2.openwrt.pool.ntp.org' '3.openwrt.pool.ntp.org'
|
||||
"""
|
||||
|
||||
# An AP configured through LuCI (the reading of the get_system_config fixture in test_driver.py).
|
||||
LUCI_BERLIN = """\
|
||||
system.@system[0]=system
|
||||
system.@system[0].hostname='ap-01'
|
||||
system.@system[0].timezone='CET-1CEST,M3.5.0,M10.5.0/3'
|
||||
system.@system[0].zonename='Europe/Berlin'
|
||||
system.@system[0].log_remote='1'
|
||||
system.@system[0].log_ip='192.0.2.40'
|
||||
system.ntp=timeserver
|
||||
system.ntp.server='0.openwrt.pool.ntp.org' '1.openwrt.pool.ntp.org'
|
||||
"""
|
||||
|
||||
# LuCI's zone names have spaces where the IANA names have underscores.
|
||||
LUCI_NEW_YORK = """\
|
||||
system.@system[0]=system
|
||||
system.@system[0].timezone='EST5EDT,M3.2.0,M11.1.0'
|
||||
system.@system[0].zonename='America/New York'
|
||||
system.ntp=timeserver
|
||||
system.ntp.server='203.0.113.10'
|
||||
"""
|
||||
|
||||
# netOrk#1849: the IANA name written as the rule. libc cannot read it; the AP runs on UTC.
|
||||
NAME_AS_RULE = """\
|
||||
system.@system[0]=system
|
||||
system.@system[0].timezone='Europe/Berlin'
|
||||
system.@system[0].zonename='Europe/Berlin'
|
||||
system.ntp=timeserver
|
||||
system.ntp.server='203.0.113.10'
|
||||
"""
|
||||
|
||||
# A server list kept as one option, the servers apart by spaces: sysntpd splits it.
|
||||
ONE_OPTION = """\
|
||||
system.@system[0]=system
|
||||
system.@system[0].timezone='UTC'
|
||||
system.ntp=timeserver
|
||||
system.ntp.server='0.openwrt.pool.ntp.org 1.openwrt.pool.ntp.org'
|
||||
system.ntp.enabled='1'
|
||||
"""
|
||||
|
||||
|
||||
def _interface(name: str, ntpserver: str | None = None, **more: Any) -> dict[str, Any]:
|
||||
"""One interface of ``ubus call network.interface dump``, as netifd prints it."""
|
||||
data = {} if ntpserver is None else {"ntpserver": ntpserver}
|
||||
return {"interface": name, "up": True, "proto": "dhcp", "data": data, **more}
|
||||
|
||||
|
||||
#: A router whose WAN lease brings two NTP servers (udhcpc's ``ntpsrv``, apart by
|
||||
#: spaces, as /lib/netifd/dhcp.script stores it) and a LAN of its own.
|
||||
LEASE = {
|
||||
"interface": [
|
||||
_interface("lan", proto="static"),
|
||||
_interface("wan", "192.0.2.1 192.0.2.2", leasetime=43200),
|
||||
_interface("wan6", proto="dhcpv6"),
|
||||
]
|
||||
}
|
||||
|
||||
|
||||
def _render(sections: list[tuple[str, str, dict[str, list[str] | str]]]) -> str:
|
||||
"""*sections* as ``uci show system`` prints them."""
|
||||
lines = []
|
||||
for name, kind, options in sections:
|
||||
lines.append(f"system.{name}={kind}")
|
||||
for option, value in options.items():
|
||||
values = value if isinstance(value, list) else [value]
|
||||
lines.append(f"system.{name}.{option}=" + " ".join(_quoted(v) for v in values))
|
||||
return "\n".join(lines) + "\n"
|
||||
|
||||
|
||||
def _quoted(value: str) -> str:
|
||||
"""*value* in single quotes, a quote in it as ``'\\''``: how uci prints every value."""
|
||||
return "'" + value.replace("'", "'\\''") + "'"
|
||||
|
||||
|
||||
def _parse(output: str) -> list[tuple[str, str, dict[str, list[str] | str]]]:
|
||||
"""``uci show system`` as the fake's state (a list is a list, an option a string)."""
|
||||
sections: list[tuple[str, str, dict[str, list[str] | str]]] = []
|
||||
for line in output.splitlines():
|
||||
key, _, raw = line.partition("=")
|
||||
parts = key.split(".")
|
||||
if len(parts) == 2:
|
||||
sections.append((parts[1], raw, {}))
|
||||
continue
|
||||
values = shlex.split(raw)
|
||||
option: list[str] | str = values if raw.count("'") > 2 else values[0]
|
||||
next(s for s in sections if s[0] == parts[1])[2][parts[2]] = option
|
||||
return sections
|
||||
|
||||
|
||||
class _Uci:
|
||||
"""A router's ``system`` config behind ``run_command``; keeps every command it ran."""
|
||||
|
||||
def __init__(
|
||||
self, show: str = STOCK, fail: str = "", dump: dict[str, Any] | str | None = None
|
||||
) -> None:
|
||||
self.sections = _parse(show)
|
||||
self.fail = fail
|
||||
self.dump = {"interface": []} if dump is None else dump
|
||||
self.ran: list[tuple[str, bool]] = []
|
||||
|
||||
def writes(self) -> list[str]:
|
||||
return [c for c, _ in self.ran if not c.startswith("uci -q show system")]
|
||||
|
||||
def __call__(
|
||||
self,
|
||||
command: str,
|
||||
*,
|
||||
privileged: bool = False,
|
||||
timeout: float = 60,
|
||||
stdin: bytes | None = None,
|
||||
) -> CommandResult:
|
||||
self.ran.append((command, privileged))
|
||||
if command == "uci -q show system":
|
||||
return CommandResult(_render(self.sections), "", 0)
|
||||
if command.startswith("uci -q show system &&"):
|
||||
assert "ubus call network.interface dump" in command
|
||||
dump = self.dump if isinstance(self.dump, str) else json.dumps(self.dump, indent=1)
|
||||
return CommandResult(f"{_render(self.sections)}{DHCP_MARK}\n{dump}\n", "", 0)
|
||||
for part in command.split(" && "):
|
||||
if self.fail and self.fail in part:
|
||||
return CommandResult("", f"{self.fail}: failed", 1)
|
||||
words = shlex.split(part)
|
||||
if words[0] == "uci":
|
||||
self._uci(words[1:])
|
||||
return CommandResult("", "", 0)
|
||||
|
||||
def _section(self, name: str) -> dict[str, list[str] | str]:
|
||||
return next(s for s in self.sections if s[0] == name)[2]
|
||||
|
||||
def _uci(self, args: list[str]) -> None:
|
||||
verb, rest = args[0], args[1:]
|
||||
if verb == "commit":
|
||||
return
|
||||
key, _, value = rest[0].partition("=")
|
||||
_, section, *option = key.split(".")
|
||||
if verb == "set" and not option:
|
||||
self.sections.append((section, value, {}))
|
||||
elif verb == "set":
|
||||
self._section(section)[option[0]] = value
|
||||
elif verb == "add_list":
|
||||
options = self._section(section)
|
||||
kept = options.get(option[0], [])
|
||||
options[option[0]] = [*([kept] if isinstance(kept, str) else kept), value]
|
||||
elif verb == "delete":
|
||||
del self._section(section)[option[0]]
|
||||
else: # pragma: no cover - a command the driver does not send
|
||||
raise AssertionError(args)
|
||||
|
||||
|
||||
def _driver(uci: _Uci, username: str = "root") -> OpenWrtDriver:
|
||||
with patch("napalm_openwrt.openwrt.ConnectHandler"):
|
||||
drv = OpenWrtDriver(hostname="192.0.2.15", username=username, password="")
|
||||
drv.device = MagicMock()
|
||||
drv.run_command = uci # type: ignore[method-assign]
|
||||
return drv
|
||||
|
||||
|
||||
def _read(show: str, dump: dict[str, Any] | str | None = None) -> dict[str, Any]:
|
||||
return dict(_driver(_Uci(show, dump=dump)).get_time_sync())
|
||||
|
||||
|
||||
# -- the driver takes part ----------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_the_driver_reads_and_writes_both_values():
|
||||
drv = _driver(_Uci())
|
||||
|
||||
assert callable(getattr(drv, "get_time_sync", None))
|
||||
assert callable(getattr(drv, "configure_time_sync", None))
|
||||
assert drv.time_sync_writes == TIME_SYNC_VALUES
|
||||
|
||||
|
||||
# -- reading ------------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_a_stock_router_reads_its_pool_servers_and_utc():
|
||||
# zonename 'UTC' with the rule GMT0: the same time, so the name stands.
|
||||
assert _read(STOCK) == {
|
||||
"ntp_servers": [
|
||||
"0.openwrt.pool.ntp.org",
|
||||
"1.openwrt.pool.ntp.org",
|
||||
"2.openwrt.pool.ntp.org",
|
||||
"3.openwrt.pool.ntp.org",
|
||||
],
|
||||
"timezone": "UTC",
|
||||
"synchronized": None,
|
||||
"daemon": None,
|
||||
"dhcp_ntp_servers": [],
|
||||
}
|
||||
|
||||
|
||||
def test_the_read_is_one_round_trip_as_the_login_user():
|
||||
uci = _Uci()
|
||||
_driver(uci).get_time_sync()
|
||||
|
||||
((command, privileged),) = uci.ran
|
||||
assert command.startswith("uci -q show system &&")
|
||||
assert privileged is False
|
||||
|
||||
|
||||
# -- reading what DHCP brought ------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_a_lease_s_ntp_servers_are_read_apart_from_the_configured_ones():
|
||||
reading = _read(STOCK, LEASE)
|
||||
|
||||
assert reading["dhcp_ntp_servers"] == ["192.0.2.1", "192.0.2.2"]
|
||||
assert reading["ntp_servers"] == [
|
||||
"0.openwrt.pool.ntp.org",
|
||||
"1.openwrt.pool.ntp.org",
|
||||
"2.openwrt.pool.ntp.org",
|
||||
"3.openwrt.pool.ntp.org",
|
||||
]
|
||||
|
||||
|
||||
def test_every_interface_s_lease_counts_in_netifd_s_order_each_once():
|
||||
dump = {
|
||||
"interface": [
|
||||
_interface("wan", "192.0.2.1"),
|
||||
_interface("iot", "198.51.100.1 192.0.2.1"),
|
||||
]
|
||||
}
|
||||
|
||||
assert _read(STOCK, dump)["dhcp_ntp_servers"] == ["192.0.2.1", "198.51.100.1"]
|
||||
|
||||
|
||||
def test_an_interface_without_a_lease_or_with_an_odd_one_brings_nothing():
|
||||
dump = {
|
||||
"interface": [
|
||||
"wan",
|
||||
{"interface": "wan", "data": "192.0.2.1"},
|
||||
{"interface": "wan", "data": {"ntpserver": ["192.0.2.1"]}},
|
||||
{"interface": "wan"},
|
||||
_interface("iot", "198.51.100.1"),
|
||||
]
|
||||
}
|
||||
|
||||
assert _read(STOCK, dump)["dhcp_ntp_servers"] == ["198.51.100.1"]
|
||||
|
||||
|
||||
def test_dhcp_interface_names_the_interfaces_whose_leases_count():
|
||||
show = STOCK + "system.ntp.dhcp_interface='iot'\n"
|
||||
dump = {
|
||||
"interface": [
|
||||
_interface("wan", "192.0.2.1"),
|
||||
_interface("iot", "198.51.100.1"),
|
||||
]
|
||||
}
|
||||
|
||||
assert _read(show, dump)["dhcp_ntp_servers"] == ["198.51.100.1"]
|
||||
|
||||
|
||||
def test_use_dhcp_off_takes_nothing_from_a_lease():
|
||||
show = STOCK + "system.ntp.use_dhcp='0'\n"
|
||||
|
||||
assert _read(show, LEASE)["dhcp_ntp_servers"] == []
|
||||
|
||||
|
||||
def test_a_disabled_client_takes_nothing_from_a_lease():
|
||||
show = STOCK.replace("system.ntp.enabled='1'", "system.ntp.enabled='0'")
|
||||
|
||||
assert _read(show, LEASE)["dhcp_ntp_servers"] == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"dump", ["", "Command failed: Permission denied", "{", "[]", '{"interface": {}}']
|
||||
)
|
||||
def test_without_netifd_s_answer_dhcp_is_unknown(dump):
|
||||
assert _read(STOCK, dump)["dhcp_ntp_servers"] is None
|
||||
|
||||
|
||||
def test_without_netifd_s_answer_a_router_that_takes_nothing_from_dhcp_still_says_so():
|
||||
show = STOCK + "system.ntp.use_dhcp='0'\n"
|
||||
|
||||
assert _read(show, "")["dhcp_ntp_servers"] == []
|
||||
|
||||
|
||||
def test_a_zone_set_through_luci_reads_by_its_name():
|
||||
reading = _read(LUCI_BERLIN)
|
||||
|
||||
assert reading["timezone"] == "Europe/Berlin"
|
||||
assert reading["ntp_servers"] == ["0.openwrt.pool.ntp.org", "1.openwrt.pool.ntp.org"]
|
||||
|
||||
|
||||
def test_luci_spaces_read_as_the_iana_underscores():
|
||||
assert _read(LUCI_NEW_YORK)["timezone"] == "America/New_York"
|
||||
|
||||
|
||||
def test_a_name_whose_rule_is_not_in_force_is_not_read_as_the_zone():
|
||||
# netOrk#1849: the AP runs on UTC; reading Europe/Berlin would hide that.
|
||||
assert _read(NAME_AS_RULE)["timezone"] is None
|
||||
|
||||
|
||||
def test_a_rule_without_a_name_reads_as_the_one_zone_that_has_it():
|
||||
show = "system.@system[0]=system\nsystem.@system[0].timezone='IST-5:30'\n"
|
||||
|
||||
assert _read(show)["timezone"] == "Asia/Kolkata"
|
||||
|
||||
|
||||
def test_a_rule_many_zones_share_reads_as_no_zone():
|
||||
# Berlin, Paris, Madrid, ... all have this rule: which one is not the driver's to guess.
|
||||
show = "system.@system[0]=system\nsystem.@system[0].timezone='CET-1CEST,M3.5.0,M10.5.0/3'\n"
|
||||
|
||||
assert _read(show)["timezone"] is None
|
||||
|
||||
|
||||
def test_a_section_without_a_rule_runs_on_utc():
|
||||
# /etc/init.d/system defaults the rule to UTC.
|
||||
assert _read("system.@system[0]=system\n")["timezone"] == "Etc/UTC"
|
||||
|
||||
|
||||
def test_no_system_section_reads_no_zone():
|
||||
assert _read("")["timezone"] is None
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("rule", "zone"),
|
||||
[
|
||||
("UTC", "Etc/UTC"),
|
||||
("UTC0", "Etc/UTC"),
|
||||
("<+0545>-5:45", "Asia/Kathmandu"),
|
||||
("NZST-12NZDT,M9.5.0,M4.1.0/3", "Pacific/Auckland"),
|
||||
("GMT0", None), # Abidjan, Monrovia, Etc/GMT, ...
|
||||
("<-00>0", None), # Factory: the zone is not known
|
||||
("Europe/Berlin", None),
|
||||
("", None),
|
||||
],
|
||||
)
|
||||
def test_zone_for_rule(rule, zone):
|
||||
assert zone_for_rule(rule) == zone
|
||||
|
||||
|
||||
def test_a_server_list_kept_as_one_option_is_split_as_sysntpd_does():
|
||||
assert _read(ONE_OPTION)["ntp_servers"] == [
|
||||
"0.openwrt.pool.ntp.org",
|
||||
"1.openwrt.pool.ntp.org",
|
||||
]
|
||||
|
||||
|
||||
def test_a_disabled_client_has_no_servers():
|
||||
# sysntpd starts no ntpd: the list names sources the clock does not take time from.
|
||||
show = STOCK.replace("system.ntp.enabled='1'", "system.ntp.enabled='0'")
|
||||
|
||||
assert _read(show)["ntp_servers"] == []
|
||||
|
||||
|
||||
def test_no_ntp_section_has_no_servers():
|
||||
show = "system.@system[0]=system\nsystem.@system[0].timezone='UTC'\n"
|
||||
|
||||
assert _read(show)["ntp_servers"] == []
|
||||
|
||||
|
||||
def test_a_line_uci_would_not_print_is_passed_over():
|
||||
reading = parse_system_uci(LUCI_BERLIN + "system.@system[0].zonename='Europe/Paris\n")
|
||||
|
||||
assert reading.zone == "Europe/Berlin"
|
||||
|
||||
|
||||
def test_a_failed_read_raises():
|
||||
drv = _driver(_Uci())
|
||||
drv.run_command = lambda *a, **k: CommandResult("", "uci: Entry not found", 1) # type: ignore[method-assign]
|
||||
|
||||
with pytest.raises(RuntimeError, match="Entry not found"):
|
||||
drv.get_time_sync()
|
||||
|
||||
|
||||
# -- get_ntp_servers agrees ---------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize("show", [STOCK, LUCI_BERLIN, ONE_OPTION, NAME_AS_RULE])
|
||||
def test_get_ntp_servers_names_the_same_servers(show):
|
||||
drv = _driver(_Uci(show))
|
||||
|
||||
assert list(drv.get_ntp_servers()) == drv.get_time_sync()["ntp_servers"]
|
||||
|
||||
|
||||
def test_get_ntp_servers_reads_every_server_of_a_list():
|
||||
# It used to keep only the first of 'a' 'b' 'c'.
|
||||
assert len(_driver(_Uci(STOCK)).get_ntp_servers()) == 4
|
||||
|
||||
|
||||
def test_the_peers_are_the_servers():
|
||||
drv = _driver(_Uci(STOCK))
|
||||
|
||||
assert drv.get_ntp_peers() == drv.get_ntp_servers()
|
||||
|
||||
|
||||
def test_get_ntp_servers_of_a_disabled_client_is_empty():
|
||||
show = STOCK.replace("system.ntp.enabled='1'", "system.ntp.enabled='0'")
|
||||
|
||||
assert _driver(_Uci(show)).get_ntp_servers() == {}
|
||||
|
||||
|
||||
# -- writing the servers ------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_the_servers_replace_the_list_and_ntpd_restarts():
|
||||
uci = _Uci(STOCK)
|
||||
result = _driver(uci).configure_time_sync(ntp_servers=["203.0.113.10", "ntp.example.org"])
|
||||
|
||||
assert result["success"] is True, result["output"]
|
||||
assert [s["step"] for s in result["steps"]] == ["ntp_servers", "verify"]
|
||||
assert uci._section("ntp")["server"] == ["203.0.113.10", "ntp.example.org"]
|
||||
(write,) = uci.writes()
|
||||
assert write.endswith(
|
||||
"uci commit system && /etc/init.d/sysntpd enable && /etc/init.d/sysntpd restart"
|
||||
)
|
||||
assert all(privileged for c, privileged in uci.ran if c in uci.writes())
|
||||
|
||||
|
||||
def test_writing_servers_leaves_the_ones_dhcp_brings():
|
||||
# DHCP option 42 counts (NetOrk/netork#2380): sysntpd keeps adding a lease's servers.
|
||||
uci = _Uci(STOCK, dump=LEASE)
|
||||
result = _driver(uci).configure_time_sync(ntp_servers=["203.0.113.10"])
|
||||
|
||||
assert result["success"] is True, result["output"]
|
||||
assert "use_dhcp" not in uci._section("ntp")
|
||||
assert "use_dhcp" not in uci.writes()[0]
|
||||
|
||||
|
||||
def test_writing_servers_keeps_use_dhcp_as_the_router_has_it():
|
||||
uci = _Uci(STOCK + "system.ntp.use_dhcp='0'\n")
|
||||
result = _driver(uci).configure_time_sync(ntp_servers=["203.0.113.10"])
|
||||
|
||||
assert result["success"] is True, result["output"]
|
||||
assert uci._section("ntp")["use_dhcp"] == "0"
|
||||
assert "use_dhcp" not in uci.writes()[0]
|
||||
|
||||
|
||||
def test_the_same_servers_with_dhcp_on_write_nothing():
|
||||
uci = _Uci(LUCI_BERLIN, dump=LEASE)
|
||||
result = _driver(uci).configure_time_sync(
|
||||
ntp_servers=["0.openwrt.pool.ntp.org", "1.openwrt.pool.ntp.org"]
|
||||
)
|
||||
|
||||
assert result["success"] is True, result["output"]
|
||||
assert uci.writes() == []
|
||||
|
||||
|
||||
def test_writing_servers_enables_a_disabled_client():
|
||||
uci = _Uci(STOCK.replace("system.ntp.enabled='1'", "system.ntp.enabled='0'"))
|
||||
result = _driver(uci).configure_time_sync(ntp_servers=["203.0.113.10"])
|
||||
|
||||
assert result["success"] is True, result["output"]
|
||||
assert uci._section("ntp")["enabled"] == "1"
|
||||
assert "/etc/init.d/sysntpd enable" in uci.writes()[0]
|
||||
|
||||
|
||||
def test_a_missing_ntp_section_is_made():
|
||||
uci = _Uci("system.@system[0]=system\nsystem.@system[0].timezone='UTC'\n")
|
||||
result = _driver(uci).configure_time_sync(ntp_servers=["203.0.113.10"])
|
||||
|
||||
assert result["success"] is True, result["output"]
|
||||
assert ("ntp", "timeserver") in [(s[0], s[1]) for s in uci.sections]
|
||||
assert "uci delete system.ntp.server" not in uci.writes()[0]
|
||||
|
||||
|
||||
def test_the_same_servers_again_write_nothing():
|
||||
# netOrk aligns on every poll: an aligned router must not restart ntpd each time.
|
||||
uci = _Uci(STOCK)
|
||||
drv = _driver(uci)
|
||||
drv.configure_time_sync(ntp_servers=["203.0.113.10", "203.0.113.11"])
|
||||
uci.ran.clear()
|
||||
|
||||
result = drv.configure_time_sync(ntp_servers=["203.0.113.10", "203.0.113.11"])
|
||||
|
||||
assert result["success"] is True
|
||||
assert uci.writes() == []
|
||||
assert "already" in result["steps"][0]["output"]
|
||||
|
||||
|
||||
def test_the_same_servers_in_another_order_are_written():
|
||||
uci = _Uci(LUCI_BERLIN)
|
||||
_driver(uci).configure_time_sync(
|
||||
ntp_servers=["1.openwrt.pool.ntp.org", "0.openwrt.pool.ntp.org"]
|
||||
)
|
||||
|
||||
assert uci._section("ntp")["server"] == ["1.openwrt.pool.ntp.org", "0.openwrt.pool.ntp.org"]
|
||||
|
||||
|
||||
def test_a_refused_uci_write_restarts_nothing():
|
||||
uci = _Uci(STOCK, fail="uci commit system")
|
||||
result = _driver(uci).configure_time_sync(ntp_servers=["203.0.113.10"])
|
||||
|
||||
assert result["success"] is False
|
||||
assert result["steps"][-1]["step"] == "ntp_servers"
|
||||
assert "failed" in result["output"]
|
||||
|
||||
|
||||
def test_a_login_other_than_root_writes_nothing():
|
||||
uci = _Uci(STOCK)
|
||||
drv = _driver(uci, username="admin")
|
||||
drv.run_command = lambda c, **k: ( # type: ignore[method-assign]
|
||||
drv._check_privilege(k.get("privileged", False)) or uci(c, **k)
|
||||
)
|
||||
|
||||
result = drv.configure_time_sync(ntp_servers=["203.0.113.10"])
|
||||
|
||||
assert result["success"] is False
|
||||
assert "no sudo" in result["output"]
|
||||
assert uci.writes() == []
|
||||
|
||||
|
||||
# -- writing the zone ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_the_zone_is_written_as_name_and_rule():
|
||||
uci = _Uci(STOCK)
|
||||
result = _driver(uci).configure_time_sync(timezone="Europe/Berlin")
|
||||
|
||||
assert result["success"] is True, result["output"]
|
||||
assert [s["step"] for s in result["steps"]] == ["timezone", "verify"]
|
||||
system = uci._section("@system[0]")
|
||||
assert system["zonename"] == "Europe/Berlin"
|
||||
assert system["timezone"] == "CET-1CEST,M3.5.0,M10.5.0/3"
|
||||
|
||||
|
||||
def test_the_zone_applies_to_the_system_and_to_logd():
|
||||
# /etc/init.d/system reload writes /tmp/TZ; logd reads the zone when it starts.
|
||||
uci = _Uci(STOCK)
|
||||
_driver(uci).configure_time_sync(timezone="Europe/Berlin")
|
||||
|
||||
(write,) = uci.writes()
|
||||
assert write.endswith(
|
||||
"uci commit system && /etc/init.d/system reload && /etc/init.d/log restart"
|
||||
)
|
||||
assert "sysntpd" not in write
|
||||
|
||||
|
||||
def test_a_zone_name_is_written_as_luci_does():
|
||||
uci = _Uci(STOCK)
|
||||
result = _driver(uci).configure_time_sync(timezone="America/New_York")
|
||||
|
||||
assert result["success"] is True, result["output"]
|
||||
assert uci._section("@system[0]")["zonename"] == "America/New York"
|
||||
assert uci._section("@system[0]")["timezone"] == posix_tz("America/New_York")
|
||||
|
||||
|
||||
def test_a_rule_with_quoted_names_is_one_shell_word():
|
||||
uci = _Uci(STOCK)
|
||||
_driver(uci).configure_time_sync(timezone="Asia/Kathmandu")
|
||||
|
||||
assert uci._section("@system[0]")["timezone"] == "<+0545>-5:45"
|
||||
|
||||
|
||||
def test_the_name_as_rule_of_1849_is_repaired():
|
||||
uci = _Uci(NAME_AS_RULE)
|
||||
result = _driver(uci).configure_time_sync(timezone="Europe/Berlin")
|
||||
|
||||
assert result["success"] is True, result["output"]
|
||||
assert uci._section("@system[0]")["timezone"] == "CET-1CEST,M3.5.0,M10.5.0/3"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("show", "zone"),
|
||||
[(LUCI_BERLIN, "Europe/Berlin"), (LUCI_NEW_YORK, "America/New_York"), (STOCK, "UTC")],
|
||||
)
|
||||
def test_the_zone_it_has_writes_nothing(show, zone):
|
||||
# The stock GMT0 is UTC's time under another name: no rewrite on every poll.
|
||||
uci = _Uci(show)
|
||||
result = _driver(uci).configure_time_sync(timezone=zone)
|
||||
|
||||
assert result["success"] is True, result["output"]
|
||||
assert uci.writes() == []
|
||||
|
||||
|
||||
def test_a_zone_twice_writes_once():
|
||||
uci = _Uci(STOCK)
|
||||
drv = _driver(uci)
|
||||
drv.configure_time_sync(timezone="Pacific/Auckland")
|
||||
drv.configure_time_sync(timezone="Pacific/Auckland")
|
||||
|
||||
assert len(uci.writes()) == 1
|
||||
|
||||
|
||||
def test_both_values_in_one_run():
|
||||
uci = _Uci(STOCK)
|
||||
result = _driver(uci).configure_time_sync(
|
||||
ntp_servers=["203.0.113.10"], timezone="Europe/Berlin"
|
||||
)
|
||||
|
||||
assert result["success"] is True, result["output"]
|
||||
assert [s["step"] for s in result["steps"]] == ["ntp_servers", "timezone", "verify"]
|
||||
|
||||
|
||||
def test_a_zone_without_a_rule_is_not_written():
|
||||
# The template lets only zones of the database through; the step does not rely on it.
|
||||
uci = _Uci(STOCK)
|
||||
outcome = _driver(uci)._write_time_zone("Mars/Olympus_Mons")
|
||||
|
||||
assert outcome["ok"] is False
|
||||
assert uci.ran == []
|
||||
|
||||
|
||||
def test_a_posix_rule_as_zone_is_refused_before_anything_runs():
|
||||
uci = _Uci(STOCK)
|
||||
|
||||
with pytest.raises(UnknownTimezone):
|
||||
_driver(uci).configure_time_sync(timezone="CET-1CEST,M3.5.0,M10.5.0/3")
|
||||
assert uci.ran == []
|
||||
@@ -15,6 +15,7 @@ from __future__ import annotations
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from napalm_device_types import PackageIndexMissing
|
||||
|
||||
from napalm_openwrt.openwrt import OpenWrtDriver
|
||||
|
||||
@@ -37,7 +38,7 @@ OPKG_PENDING = "dnsmasq - 2.90-4 - 2.90-5\n"
|
||||
@pytest.fixture
|
||||
def driver():
|
||||
with patch("napalm_openwrt.openwrt.ConnectHandler"):
|
||||
drv = OpenWrtDriver(hostname="192.168.1.1", username="root", password="")
|
||||
drv = OpenWrtDriver(hostname="192.0.2.1", username="root", password="")
|
||||
drv.device = MagicMock()
|
||||
yield drv
|
||||
|
||||
@@ -60,7 +61,7 @@ class TestAvailableUpdates:
|
||||
def test_apk_without_its_index_raises_instead_of_reporting_nothing(self, driver):
|
||||
_answer(driver, "apk", APK_INDEX_MISSING)
|
||||
|
||||
with pytest.raises(RuntimeError, match="index"):
|
||||
with pytest.raises(PackageIndexMissing, match="apk update"):
|
||||
driver.get_available_updates()
|
||||
|
||||
def test_apk_with_its_index_lists_what_is_pending(self, driver):
|
||||
@@ -75,13 +76,14 @@ class TestAvailableUpdates:
|
||||
def test_apk_that_failed_raises(self, driver):
|
||||
_answer(driver, "apk", "ERROR: unable to lock database\n__OWRT_RC=99\n")
|
||||
|
||||
with pytest.raises(RuntimeError):
|
||||
with pytest.raises(RuntimeError) as raised:
|
||||
driver.get_available_updates()
|
||||
assert not isinstance(raised.value, PackageIndexMissing)
|
||||
|
||||
def test_opkg_without_its_lists_raises(self, driver):
|
||||
_answer(driver, "opkg", "__NO_INDEX__\n")
|
||||
|
||||
with pytest.raises(RuntimeError, match="index"):
|
||||
with pytest.raises(PackageIndexMissing, match="opkg update"):
|
||||
driver.get_available_updates()
|
||||
|
||||
def test_opkg_with_its_lists(self, driver):
|
||||
@@ -111,3 +113,54 @@ class TestRefresh:
|
||||
result = driver.refresh_available_updates()
|
||||
|
||||
assert result == {"success": False, "output": "ERROR: network unreachable"}
|
||||
|
||||
|
||||
class TestApplyUpdates:
|
||||
"""Only the package manager's exit status decides whether an upgrade succeeded (#11)."""
|
||||
|
||||
def test_apk_upgrade_that_worked(self, driver):
|
||||
sent = _answer(
|
||||
driver, "apk", "(1/1) Upgrading dnsmasq (2.90-r4 -> 2.90-r5)\nOK\n__OWRT_RC=0\n"
|
||||
)
|
||||
|
||||
result = driver.apply_updates(["dnsmasq"])
|
||||
|
||||
assert result == {
|
||||
"success": True,
|
||||
"output": "(1/1) Upgrading dnsmasq (2.90-r4 -> 2.90-r5)\nOK",
|
||||
}
|
||||
assert sent[-1].startswith("apk upgrade dnsmasq 2>&1")
|
||||
|
||||
def test_apk_upgrade_that_failed_is_no_success(self, driver):
|
||||
_answer(
|
||||
driver,
|
||||
"apk",
|
||||
"ERROR: unable to select packages:\n nope (no such package)\n__OWRT_RC=1\n",
|
||||
)
|
||||
|
||||
result = driver.apply_updates(["nope"])
|
||||
|
||||
assert result["success"] is False
|
||||
assert "unable to select packages" in result["output"]
|
||||
assert "status 1" in result["error"]
|
||||
|
||||
def test_opkg_upgrade_that_failed_is_no_success(self, driver):
|
||||
sent = _answer(
|
||||
driver,
|
||||
"opkg",
|
||||
" * opkg_download: Failed to download\nCollected errors:\n__OWRT_RC=255\n",
|
||||
)
|
||||
|
||||
result = driver.apply_updates(["dnsmasq"])
|
||||
|
||||
assert result["success"] is False
|
||||
assert "status 255" in result["error"]
|
||||
assert sent[-1].startswith("opkg upgrade dnsmasq 2>&1")
|
||||
|
||||
def test_output_without_a_status_is_no_success(self, driver):
|
||||
_answer(driver, "opkg", "")
|
||||
|
||||
result = driver.apply_updates(["dnsmasq"])
|
||||
|
||||
assert result["success"] is False
|
||||
assert result["error"]
|
||||
@@ -0,0 +1,305 @@
|
||||
"""Wireless writes: ``push_mac_acl`` and ``push_radio_channel`` (NAPALM/napalm-openwrt#35).
|
||||
|
||||
Each ``uci`` step runs on an exec channel of its own, with its exit status checked: a
|
||||
refused step raises and names itself, nothing staged after a refusal is committed, and
|
||||
wifi is not restarted for a change that never landed.
|
||||
|
||||
The device is a fake behind ``run_command``. ``uci -q show wireless`` answers in the
|
||||
shape OpenWrt 23.05 prints it: the stock ``default_radioN`` sections, a list option on
|
||||
one line with each value quoted, and a quote inside a value as ``'\\''``. The refusals
|
||||
are uci's and wifi's own messages: ``uci: Invalid argument`` for an option set on a
|
||||
section that does not exist, ``uci: I/O error`` for a commit that cannot write
|
||||
``/etc/config``.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import shlex
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from napalm.base.exceptions import CommandErrorException
|
||||
from napalm_device_types import CommandResult
|
||||
|
||||
from napalm_openwrt.openwrt import OpenWrtDriver
|
||||
|
||||
SHOW = "uci -q show wireless"
|
||||
|
||||
WIRELESS = """\
|
||||
wireless.radio0=wifi-device
|
||||
wireless.radio0.type='mac80211'
|
||||
wireless.radio0.path='platform/ahb/18100000.wmac'
|
||||
wireless.radio0.channel='1'
|
||||
wireless.radio0.band='2g'
|
||||
wireless.radio0.htmode='HT20'
|
||||
wireless.radio0.cell_density='0'
|
||||
wireless.default_radio0=wifi-iface
|
||||
wireless.default_radio0.device='radio0'
|
||||
wireless.default_radio0.network='lan'
|
||||
wireless.default_radio0.mode='ap'
|
||||
wireless.default_radio0.ssid='CorpWiFi'
|
||||
wireless.default_radio0.encryption='psk2'
|
||||
wireless.default_radio0.key='example-passphrase'
|
||||
wireless.default_radio0.macfilter='deny'
|
||||
wireless.default_radio0.maclist='00:00:5E:00:53:01' '00:00:5E:00:53:02'
|
||||
wireless.radio1=wifi-device
|
||||
wireless.radio1.type='mac80211'
|
||||
wireless.radio1.path='pci0000:00/0000:00:00.0'
|
||||
wireless.radio1.channel='36'
|
||||
wireless.radio1.band='5g'
|
||||
wireless.radio1.htmode='VHT80'
|
||||
wireless.default_radio1=wifi-iface
|
||||
wireless.default_radio1.device='radio1'
|
||||
wireless.default_radio1.network='lan'
|
||||
wireless.default_radio1.mode='ap'
|
||||
wireless.default_radio1.ssid='CorpWiFi'
|
||||
wireless.default_radio1.encryption='psk2'
|
||||
wireless.default_radio1.key='example-passphrase'
|
||||
wireless.guest=wifi-iface
|
||||
wireless.guest.device='radio0'
|
||||
wireless.guest.network='guest'
|
||||
wireless.guest.mode='ap'
|
||||
wireless.guest.ssid='Bob'\\''s Guest'
|
||||
wireless.guest.encryption='none'
|
||||
"""
|
||||
|
||||
INVALID_ARGUMENT = CommandResult("", "uci: Invalid argument\n", 1)
|
||||
IO_ERROR = CommandResult("", "uci: I/O error\n", 1)
|
||||
|
||||
|
||||
class _Ap:
|
||||
"""``run_command`` of an AP: answers the read, refuses the commands in *refuse*."""
|
||||
|
||||
def __init__(self, refuse: dict[str, CommandResult] | None = None) -> None:
|
||||
self.refuse = refuse or {}
|
||||
self.commands: list[str] = []
|
||||
|
||||
def __call__(
|
||||
self,
|
||||
command: str,
|
||||
*,
|
||||
privileged: bool = False,
|
||||
timeout: float = 60,
|
||||
stdin: bytes | None = None,
|
||||
) -> CommandResult:
|
||||
self.commands.append(command)
|
||||
if command in self.refuse:
|
||||
return self.refuse[command]
|
||||
if command == SHOW:
|
||||
return CommandResult(WIRELESS, "", 0)
|
||||
return CommandResult("", "", 0)
|
||||
|
||||
@property
|
||||
def argv(self) -> list[list[str]]:
|
||||
return [shlex.split(c) for c in self.commands]
|
||||
|
||||
|
||||
def _driver(ap: _Ap) -> OpenWrtDriver:
|
||||
with patch("napalm_openwrt.openwrt.ConnectHandler"):
|
||||
drv = OpenWrtDriver(hostname="192.0.2.15", username="root", password="")
|
||||
drv.device = MagicMock()
|
||||
drv.run_command = ap # type: ignore[method-assign]
|
||||
return drv
|
||||
|
||||
|
||||
def _uci(*words: str) -> str:
|
||||
return shlex.join(["uci", *words])
|
||||
|
||||
|
||||
# -- push_mac_acl ------------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_a_blacklist_is_written_to_every_section_with_the_ssid():
|
||||
ap = _Ap()
|
||||
_driver(ap).push_mac_acl("CorpWiFi", "blacklist", ["00:00:5E:00:53:0A"])
|
||||
|
||||
assert ap.commands == [
|
||||
SHOW,
|
||||
_uci("set", "wireless.default_radio0.macfilter=deny"),
|
||||
_uci("delete", "wireless.default_radio0.maclist"),
|
||||
_uci("add_list", "wireless.default_radio0.maclist=00:00:5E:00:53:0A"),
|
||||
_uci("set", "wireless.default_radio1.macfilter=deny"),
|
||||
_uci("add_list", "wireless.default_radio1.maclist=00:00:5E:00:53:0A"),
|
||||
_uci("commit", "wireless"),
|
||||
"wifi reload",
|
||||
]
|
||||
|
||||
|
||||
def test_a_whitelist_sets_allow():
|
||||
ap = _Ap()
|
||||
_driver(ap).push_mac_acl("CorpWiFi", "whitelist", ["00:00:5E:00:53:0A", "00:00:5E:00:53:0B"])
|
||||
|
||||
assert _uci("set", "wireless.default_radio1.macfilter=allow") in ap.commands
|
||||
assert _uci("add_list", "wireless.default_radio1.maclist=00:00:5E:00:53:0B") in ap.commands
|
||||
|
||||
|
||||
def test_off_deletes_only_the_options_a_section_has():
|
||||
"""A delete of a missing option exits 1; it is not sent, and no step hides its status."""
|
||||
ap = _Ap()
|
||||
_driver(ap).push_mac_acl("CorpWiFi", "off", [])
|
||||
|
||||
assert ap.commands == [
|
||||
SHOW,
|
||||
_uci("delete", "wireless.default_radio0.macfilter"),
|
||||
_uci("delete", "wireless.default_radio0.maclist"),
|
||||
_uci("commit", "wireless"),
|
||||
"wifi reload",
|
||||
]
|
||||
|
||||
|
||||
def test_a_whitelist_without_macs_is_off():
|
||||
ap = _Ap()
|
||||
_driver(ap).push_mac_acl("CorpWiFi", "whitelist", [])
|
||||
|
||||
assert not any("macfilter=allow" in c for c in ap.commands)
|
||||
assert _uci("delete", "wireless.default_radio0.macfilter") in ap.commands
|
||||
|
||||
|
||||
def test_an_ssid_with_a_quote_and_a_space_is_found():
|
||||
ap = _Ap()
|
||||
_driver(ap).push_mac_acl("Bob's Guest", "blacklist", ["00:00:5E:00:53:0A"])
|
||||
|
||||
assert _uci("set", "wireless.guest.macfilter=deny") in ap.commands
|
||||
assert not any("default_radio" in c for c in ap.commands)
|
||||
|
||||
|
||||
def test_no_section_with_the_ssid_raises_and_writes_nothing():
|
||||
ap = _Ap()
|
||||
with pytest.raises(CommandErrorException, match="Nowhere"):
|
||||
_driver(ap).push_mac_acl("Nowhere", "blacklist", ["00:00:5E:00:53:0A"])
|
||||
|
||||
assert ap.commands == [SHOW]
|
||||
|
||||
|
||||
def test_a_failed_read_raises_and_writes_nothing():
|
||||
ap = _Ap({SHOW: CommandResult("", "uci: Entry not found\n", 1)})
|
||||
with pytest.raises(CommandErrorException, match="Entry not found"):
|
||||
_driver(ap).push_mac_acl("CorpWiFi", "blacklist", ["00:00:5E:00:53:0A"])
|
||||
|
||||
assert ap.commands == [SHOW]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"refused",
|
||||
[
|
||||
_uci("set", "wireless.default_radio0.macfilter=deny"),
|
||||
_uci("delete", "wireless.default_radio0.maclist"),
|
||||
_uci("add_list", "wireless.default_radio1.maclist=00:00:5E:00:53:0A"),
|
||||
],
|
||||
)
|
||||
def test_a_refused_change_raises_naming_it_and_reverts_before_any_commit(refused):
|
||||
ap = _Ap({refused: INVALID_ARGUMENT})
|
||||
with pytest.raises(CommandErrorException) as caught:
|
||||
_driver(ap).push_mac_acl("CorpWiFi", "blacklist", ["00:00:5E:00:53:0A"])
|
||||
|
||||
assert refused in str(caught.value)
|
||||
assert "Invalid argument" in str(caught.value)
|
||||
assert ap.commands[-1] == _uci("revert", "wireless")
|
||||
assert _uci("commit", "wireless") not in ap.commands
|
||||
assert "wifi reload" not in ap.commands
|
||||
# Nothing after the refused step is sent.
|
||||
assert ap.commands.index(refused) == len(ap.commands) - 2
|
||||
|
||||
|
||||
def test_a_refused_commit_raises_and_does_not_reload_wifi():
|
||||
ap = _Ap({_uci("commit", "wireless"): IO_ERROR})
|
||||
with pytest.raises(CommandErrorException, match="I/O error"):
|
||||
_driver(ap).push_mac_acl("CorpWiFi", "blacklist", ["00:00:5E:00:53:0A"])
|
||||
|
||||
assert ap.commands[-2:] == [_uci("commit", "wireless"), _uci("revert", "wireless")]
|
||||
assert "wifi reload" not in ap.commands
|
||||
|
||||
|
||||
def test_a_failed_wifi_reload_raises_naming_it():
|
||||
ap = _Ap({"wifi reload": CommandResult("", "Command failed: Not found\n", 1)})
|
||||
with pytest.raises(CommandErrorException, match="wifi reload") as caught:
|
||||
_driver(ap).push_mac_acl("CorpWiFi", "blacklist", ["00:00:5E:00:53:0A"])
|
||||
|
||||
assert "Not found" in str(caught.value)
|
||||
assert ap.commands[-1] == "wifi reload"
|
||||
|
||||
|
||||
def test_a_failed_revert_keeps_the_refusal_as_the_error():
|
||||
ap = _Ap(
|
||||
{
|
||||
_uci("set", "wireless.default_radio0.macfilter=deny"): INVALID_ARGUMENT,
|
||||
_uci("revert", "wireless"): IO_ERROR,
|
||||
}
|
||||
)
|
||||
with pytest.raises(CommandErrorException, match="Invalid argument"):
|
||||
_driver(ap).push_mac_acl("CorpWiFi", "blacklist", ["00:00:5E:00:53:0A"])
|
||||
|
||||
|
||||
def test_every_step_runs_as_root():
|
||||
ap = MagicMock(side_effect=_Ap())
|
||||
_driver(ap).push_mac_acl("CorpWiFi", "off", [])
|
||||
|
||||
assert ap.call_args_list
|
||||
assert all(call.kwargs.get("privileged") for call in ap.call_args_list)
|
||||
|
||||
|
||||
def test_a_login_other_than_root_is_refused_before_anything_runs():
|
||||
with patch("napalm_openwrt.openwrt.ConnectHandler"):
|
||||
drv = OpenWrtDriver(hostname="192.0.2.15", username="admin", password="")
|
||||
drv.device = MagicMock()
|
||||
|
||||
with pytest.raises(PermissionError):
|
||||
drv.push_mac_acl("CorpWiFi", "off", [])
|
||||
drv.device.remote_conn_pre.get_transport.assert_not_called()
|
||||
|
||||
|
||||
# -- push_radio_channel ------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_a_channel_is_set_committed_and_wifi_restarted():
|
||||
"""``wifi`` (a full restart), not ``wifi reload``: many radios keep the old channel."""
|
||||
ap = _Ap()
|
||||
_driver(ap).push_radio_channel("radio1", 44)
|
||||
|
||||
assert ap.commands == [
|
||||
_uci("set", "wireless.radio1.channel=44"),
|
||||
_uci("commit", "wireless"),
|
||||
"wifi",
|
||||
]
|
||||
|
||||
|
||||
def test_channel_zero_is_auto():
|
||||
ap = _Ap()
|
||||
_driver(ap).push_radio_channel("radio0", 0)
|
||||
|
||||
assert ap.commands[0] == _uci("set", "wireless.radio0.channel=auto")
|
||||
|
||||
|
||||
def test_a_refused_channel_raises_and_does_not_restart_wifi():
|
||||
refused = _uci("set", "wireless.radio9.channel=6")
|
||||
ap = _Ap({refused: INVALID_ARGUMENT})
|
||||
with pytest.raises(CommandErrorException) as caught:
|
||||
_driver(ap).push_radio_channel("radio9", 6)
|
||||
|
||||
assert refused in str(caught.value)
|
||||
assert "Invalid argument" in str(caught.value)
|
||||
assert ap.commands == [refused, _uci("revert", "wireless")]
|
||||
|
||||
|
||||
def test_a_refused_channel_commit_does_not_restart_wifi():
|
||||
ap = _Ap({_uci("commit", "wireless"): IO_ERROR})
|
||||
with pytest.raises(CommandErrorException, match="I/O error"):
|
||||
_driver(ap).push_radio_channel("radio0", 6)
|
||||
|
||||
assert "wifi" not in ap.commands
|
||||
|
||||
|
||||
def test_a_failed_wifi_restart_raises_naming_it():
|
||||
ap = _Ap({"wifi": CommandResult("", "", 1)})
|
||||
with pytest.raises(CommandErrorException, match="`wifi`.*exit status 1"):
|
||||
_driver(ap).push_radio_channel("radio0", 6)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("mode", ["deny", "Blacklist", "disable", ""])
|
||||
def test_an_unknown_mode_raises_before_anything_is_sent(mode):
|
||||
"""A mode the driver does not know was written as a deny list (#39)."""
|
||||
ap = _Ap()
|
||||
with pytest.raises(ValueError, match=repr(mode)):
|
||||
_driver(ap).push_mac_acl("CorpWiFi", mode, ["00:00:5E:00:53:0A"])
|
||||
|
||||
assert ap.commands == []
|
||||
@@ -0,0 +1,236 @@
|
||||
"""configure_zabbix_agent: the feed's C agent on an access point (NetOrk/netork#2571).
|
||||
|
||||
An AP has no container engine, so the agent cannot run as a container there; the
|
||||
feed has ``zabbix-agentd``. Its init script starts it only while UCI enables it,
|
||||
and the package index lives in RAM, gone after every restart.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from napalm_device_types import CommandResult
|
||||
|
||||
from napalm_openwrt import OpenWrtDriver
|
||||
from tests.unit.test_driver import UCI_FIREWALL_HEALTHY, UCI_NETWORK_STATIC
|
||||
|
||||
CONFIG = "/etc/zabbix_agentd.conf"
|
||||
STOCK = "LogFile=/tmp/zabbix_agentd.log\nServer=127.0.0.1\nServerActive=127.0.0.1\nHostname=Zabbix server\n"
|
||||
SETTINGS = {
|
||||
"server": "zabbix.example.com",
|
||||
"server_active": "zabbix.example.com",
|
||||
"listen_port": 10050,
|
||||
"allowed_sources": ["198.51.100.20"],
|
||||
"hostname": "ap-1og",
|
||||
"release": "7.4",
|
||||
}
|
||||
|
||||
|
||||
class _Shell:
|
||||
"""The interactive shell: package manager, init scripts, UCI, the firewall."""
|
||||
|
||||
def __init__(self, *, firewall_runs=True, fail="", installed=False, nft_hits="1"):
|
||||
self.firewall_runs = firewall_runs
|
||||
self.fail = fail
|
||||
self.installed = installed
|
||||
self.nft_hits = nft_hits
|
||||
self.issued: list[str] = []
|
||||
|
||||
def __call__(self, cmd, **kw):
|
||||
self.issued.append(cmd)
|
||||
if "command -v apk" in cmd:
|
||||
return "/usr/bin/apk"
|
||||
if "apk list --installed" in cmd:
|
||||
return (
|
||||
"zabbix-agentd-7.0.32-r1 mips_24kc {zabbix} (GPL) [installed]"
|
||||
if self.installed
|
||||
else ""
|
||||
)
|
||||
if "nft list table inet fw4" in cmd:
|
||||
return "on" if self.firewall_runs else ""
|
||||
if "__OWRT_RC" in cmd:
|
||||
if self.fail and self.fail in cmd:
|
||||
return f"failed: {self.fail}\n__OWRT_RC=1"
|
||||
if cmd.startswith("apk add"):
|
||||
self.installed = True
|
||||
return "ok\n__OWRT_RC=0"
|
||||
if cmd.startswith("uci show firewall"):
|
||||
return UCI_FIREWALL_HEALTHY
|
||||
if cmd.startswith("uci show network"):
|
||||
return UCI_NETWORK_STATIC
|
||||
if "$SSH_CONNECTION" in cmd:
|
||||
return "198.51.100.20 51234 192.0.2.1 22"
|
||||
if "dport 10050" in cmd:
|
||||
return self.nft_hits
|
||||
return ""
|
||||
|
||||
|
||||
class _Channel:
|
||||
"""The exec channel: the config file and UCI's enable, as root."""
|
||||
|
||||
def __init__(self, config=STOCK, refuse=""):
|
||||
self.config = config
|
||||
self.refuse = refuse
|
||||
self.calls: list[tuple[str, bool, bytes | None]] = []
|
||||
|
||||
def __call__(self, command, *, privileged=False, timeout=60, stdin=None):
|
||||
self.calls.append((command, privileged, stdin))
|
||||
if self.refuse and self.refuse in command:
|
||||
return CommandResult("", f"{self.refuse}: refused", 1)
|
||||
if command == f"cat {CONFIG}":
|
||||
return CommandResult(self.config, "", 0)
|
||||
if f"cat > {CONFIG}" in command:
|
||||
self.config = (stdin or b"").decode()
|
||||
return CommandResult("", "", 0)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def shell():
|
||||
return _Shell()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def channel():
|
||||
return _Channel()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def owrt(shell, channel):
|
||||
d = OpenWrtDriver("ap", "root", "pw")
|
||||
d._send_command = shell
|
||||
d.run_command = channel
|
||||
return d
|
||||
|
||||
|
||||
def test_install_configure_open_and_start(owrt, shell, channel):
|
||||
result = owrt.configure_zabbix_agent(SETTINGS)
|
||||
|
||||
assert result["success"] is True, result["output"]
|
||||
assert [s["step"] for s in result["steps"]] == ["install", "configure", "firewall", "start"]
|
||||
init = [c.split(" 2>")[0] for c in shell.issued if c.startswith("/etc/init.d/zabbix_agentd")]
|
||||
assert init == ["/etc/init.d/zabbix_agentd enable", "/etc/init.d/zabbix_agentd restart"]
|
||||
|
||||
|
||||
def test_the_index_is_loaded_before_the_feed_s_package_is_added(owrt, shell):
|
||||
owrt.configure_zabbix_agent(SETTINGS)
|
||||
|
||||
pkg = [c.split(" 2>")[0] for c in shell.issued if c.startswith("apk ")]
|
||||
assert pkg[0] == "apk update"
|
||||
assert "apk add zabbix-agentd" in pkg
|
||||
|
||||
|
||||
def test_an_index_that_will_not_load_is_named_when_the_install_fails(owrt, shell):
|
||||
shell.fail = "apk "
|
||||
|
||||
result = owrt.configure_zabbix_agent(SETTINGS)
|
||||
|
||||
assert result["success"] is False
|
||||
assert "package index not loaded" in result["output"]
|
||||
|
||||
|
||||
def test_there_is_no_repository_to_fall_back_to(owrt, shell):
|
||||
shell.fail = "apk add"
|
||||
|
||||
result = owrt.configure_zabbix_agent(SETTINGS)
|
||||
|
||||
assert result["success"] is False
|
||||
assert [s["step"] for s in result["steps"]] == ["install"]
|
||||
|
||||
|
||||
def test_the_config_gets_the_caller_s_values_and_keeps_the_rest(owrt, channel):
|
||||
owrt.configure_zabbix_agent(SETTINGS)
|
||||
|
||||
assert "Server=zabbix.example.com\n" in channel.config
|
||||
assert "Hostname=ap-1og\n" in channel.config
|
||||
assert channel.config.startswith("LogFile=/tmp/zabbix_agentd.log\n")
|
||||
write = next(c for c in channel.calls if f"cat > {CONFIG}" in c[0])
|
||||
assert write[1] is True
|
||||
assert f"cp -p {CONFIG} {CONFIG}.bak" in write[0]
|
||||
|
||||
|
||||
def test_the_agent_is_enabled_in_uci(owrt, channel):
|
||||
owrt.configure_zabbix_agent(SETTINGS)
|
||||
|
||||
uci = next(c[0] for c in channel.calls if "uci commit zabbix_agentd" in c[0])
|
||||
assert "uci set zabbix_agentd.general.enabled='1'" in uci
|
||||
|
||||
|
||||
def test_a_config_that_already_says_it_is_not_written(owrt, channel):
|
||||
owrt.configure_zabbix_agent(SETTINGS)
|
||||
channel.calls.clear()
|
||||
|
||||
result = owrt.configure_zabbix_agent(SETTINGS)
|
||||
|
||||
assert result["success"] is True
|
||||
assert not any(f"cat > {CONFIG}" in c[0] for c in channel.calls)
|
||||
|
||||
|
||||
def test_a_config_that_cannot_be_read_stops_the_fix(owrt, channel, shell):
|
||||
channel.refuse = f"cat {CONFIG}"
|
||||
|
||||
result = owrt.configure_zabbix_agent(SETTINGS)
|
||||
|
||||
assert result["success"] is False
|
||||
assert result["steps"][-1]["step"] == "configure"
|
||||
assert not any(c.startswith("/etc/init.d/zabbix_agentd") for c in shell.issued)
|
||||
|
||||
|
||||
def test_the_firewall_rule_is_tcp_on_the_listen_port_for_the_sources(owrt, shell):
|
||||
owrt.configure_zabbix_agent(SETTINGS)
|
||||
|
||||
uci = " ".join(shell.issued)
|
||||
assert "uci set firewall.allow_zabbix_agent_from_lan=rule" in uci
|
||||
assert "firewall.allow_zabbix_agent_from_lan.proto='tcp'" in uci
|
||||
assert "firewall.allow_zabbix_agent_from_lan.dest_port='10050'" in uci
|
||||
assert "uci add_list firewall.allow_zabbix_agent_from_lan.src_ip='198.51.100.20/32'" in uci
|
||||
assert "netork" not in uci.lower()
|
||||
|
||||
|
||||
def test_without_a_running_firewall_nothing_is_opened(owrt, shell):
|
||||
shell.firewall_runs = False
|
||||
|
||||
result = owrt.configure_zabbix_agent(SETTINGS)
|
||||
|
||||
assert result["success"] is True
|
||||
assert not any("firewall.allow_zabbix_agent" in c for c in shell.issued)
|
||||
assert "no firewall runs" in result["output"]
|
||||
|
||||
|
||||
def test_without_sources_the_firewall_is_left_alone(owrt, shell):
|
||||
result = owrt.configure_zabbix_agent({**SETTINGS, "allowed_sources": []})
|
||||
|
||||
assert result["success"] is True
|
||||
assert not any("firewall.allow_zabbix_agent" in c for c in shell.issued)
|
||||
|
||||
|
||||
def test_a_rule_that_does_not_reach_the_packet_filter_fails(owrt, shell):
|
||||
shell.nft_hits = "0"
|
||||
|
||||
result = owrt.configure_zabbix_agent(SETTINGS)
|
||||
|
||||
assert result["success"] is False
|
||||
assert result["steps"][-1]["step"] == "firewall"
|
||||
|
||||
|
||||
def test_the_snmp_rule_is_written_as_before(owrt, shell):
|
||||
shell.nft_hits = "1"
|
||||
owrt._send_command = _SnmpShell(shell)
|
||||
|
||||
owrt._allow_snmp_sources({"community": "c", "allowed_sources": ["198.51.100.20"]})
|
||||
|
||||
uci = " ".join(shell.issued)
|
||||
assert "firewall.allow_snmp_from_lan.proto='udp'" in uci
|
||||
assert "firewall.allow_snmp_from_lan.dest_port='161'" in uci
|
||||
assert "firewall.allow_snmp_from_lan.name='Allow-SNMP'" in uci
|
||||
|
||||
|
||||
class _SnmpShell:
|
||||
"""The same shell, answering the SNMP rule's live check."""
|
||||
|
||||
def __init__(self, shell):
|
||||
self.shell = shell
|
||||
|
||||
def __call__(self, cmd, **kw):
|
||||
if "dport 161" in cmd:
|
||||
self.shell.issued.append(cmd)
|
||||
return "1"
|
||||
return self.shell(cmd, **kw)
|
||||
Reference in new issue
Block a user