Compare commits
53
Commits
v0.7.0
...
5c91af6033
| 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 |
No files matched your search
+147
@@ -7,6 +7,153 @@ 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.
|
||||
|
||||
@@ -17,7 +17,7 @@ Requires OpenWrt **19.07** or newer.
|
||||
|
||||
| Dependency | Minimum version |
|
||||
|---|---|
|
||||
| Python | 3.10 |
|
||||
| Python | 3.12 |
|
||||
| NAPALM | 4.0 |
|
||||
| Netmiko | 4.0 |
|
||||
|
||||
@@ -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,10 +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
|
||||
|
||||
@@ -77,7 +84,7 @@ Configuration is managed via [UCI](https://openwrt.org/docs/guide-user/base-syst
|
||||
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'
|
||||
"""
|
||||
)
|
||||
|
||||
@@ -102,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
|
||||
|
||||
@@ -12,6 +12,8 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import shlex
|
||||
|
||||
from napalm.base.exceptions import (
|
||||
CommandErrorException,
|
||||
MergeConfigException,
|
||||
@@ -20,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.
|
||||
|
||||
@@ -67,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:
|
||||
@@ -95,9 +110,6 @@ class OpenWrtConfigMixin(ConfigLifecycleMixin):
|
||||
"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}
|
||||
@@ -95,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")
|
||||
@@ -192,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 = []
|
||||
@@ -208,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,
|
||||
@@ -234,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
|
||||
@@ -267,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")
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@@ -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]: ...
|
||||
@@ -12,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: ...
|
||||
+123
-44
@@ -36,19 +36,25 @@ from napalm_device_types import (
|
||||
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.config_mixin import OpenWrtConfigMixin
|
||||
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'\"#]+$")
|
||||
@@ -73,11 +79,17 @@ class OpenWrtDriver(
|
||||
OpenWrtWirelessMixin,
|
||||
OpenWrtLLDPMixin,
|
||||
OpenWrtConfigMixin,
|
||||
OpenWrtTimeSyncMixin,
|
||||
OpenWrtSystemMixin,
|
||||
OpenWrtPackageMixin,
|
||||
OpenWrtRoutingMixin,
|
||||
OpenWrtScheduledJobsMixin,
|
||||
OpenWrtFirmwareMixin,
|
||||
ListeningSocketsMixin,
|
||||
HostStatusMixin,
|
||||
SnmpAgentMixin,
|
||||
OpenWrtLldpAgentMixin,
|
||||
OpenWrtZabbixAgentMixin,
|
||||
EnsurePackageMixin,
|
||||
AccessPointDriver,
|
||||
):
|
||||
@@ -109,8 +121,8 @@ 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)
|
||||
@@ -244,6 +256,14 @@ class OpenWrtDriver(
|
||||
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``.
|
||||
|
||||
@@ -502,15 +522,23 @@ class OpenWrtDriver(
|
||||
@classmethod
|
||||
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)
|
||||
@@ -598,40 +626,59 @@ class OpenWrtDriver(
|
||||
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.
|
||||
"""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 SNMP rules go (highest anonymous index first);
|
||||
the rule is written in full every run and limited to the allowed sources
|
||||
(``src_ip``); the reload and the live packet filter decide success.
|
||||
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] = []
|
||||
sources = _sources(settings)
|
||||
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)}
|
||||
|
||||
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"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"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 {"ok": 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:
|
||||
@@ -640,31 +687,61 @@ class OpenWrtDriver(
|
||||
mgmt_zone = next(iter(zones))
|
||||
if mgmt_zone:
|
||||
lines.append(f"Management zone: {mgmt_zone!r}")
|
||||
elif zones:
|
||||
return mgmt_zone
|
||||
if zones:
|
||||
present = ", ".join(sorted(zones))
|
||||
lines.append(f"No zone covers the management network — zones present: {present}")
|
||||
return {"ok": False, "output": "\n".join(lines)}
|
||||
else:
|
||||
lines.append("No zones configured — writing an unscoped rule")
|
||||
return None
|
||||
lines.append("No zones configured — writing an unscoped rule")
|
||||
return ""
|
||||
|
||||
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:
|
||||
deletes = "; ".join(f"uci -q delete firewall.{key}" for key in stale)
|
||||
self._send_command(f"{deletes}; uci commit firewall")
|
||||
lines.append(f"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
|
||||
|
||||
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'",
|
||||
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")
|
||||
@@ -672,6 +749,8 @@ class OpenWrtDriver(
|
||||
scope = ", ".join(sources) or "every source in the zone"
|
||||
lines.append(f"Wrote rule {named_key!r} for {scope}: {rule_out or 'ok'}")
|
||||
|
||||
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()
|
||||
@@ -682,11 +761,11 @@ class OpenWrtDriver(
|
||||
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"udp/161 accept rules live in the packet filter: {live}")
|
||||
return {"ok": fw_ok and bool(live), "output": "\n".join(lines)}
|
||||
lines.append(f"{proto}/{port} accept rules live in the packet filter: {live}")
|
||||
return fw_ok and bool(live)
|
||||
|
||||
def _start_snmp_agent(self) -> dict[str, Any]:
|
||||
self._send_command(
|
||||
|
||||
@@ -15,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."""
|
||||
@@ -200,30 +202,31 @@ class OpenWrtPackageMixin:
|
||||
lines.append(part)
|
||||
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}")
|
||||
@@ -123,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}"
|
||||
@@ -141,7 +141,7 @@ 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()
|
||||
@@ -244,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)
|
||||
@@ -16,6 +16,8 @@ import logging
|
||||
import re
|
||||
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.
|
||||
@@ -23,6 +25,10 @@ _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,6 +38,60 @@ def _split_status(raw: str) -> tuple[str, int | None]:
|
||||
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.
|
||||
|
||||
@@ -41,34 +101,15 @@ class OpenWrtSystemMixin:
|
||||
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": {},
|
||||
@@ -389,23 +430,28 @@ class OpenWrtSystemMixin:
|
||||
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."""
|
||||
"""Execute a lifecycle action (start/stop/restart/enable/disable) on a service.
|
||||
|
||||
Only the init script's exit status decides ``success``; a missing script
|
||||
or a failed action comes back with what the device printed.
|
||||
"""
|
||||
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}
|
||||
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()
|
||||
@@ -420,7 +466,7 @@ 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"
|
||||
@@ -441,7 +487,7 @@ 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"
|
||||
@@ -463,7 +509,10 @@ 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:
|
||||
@@ -472,45 +521,23 @@ class OpenWrtSystemMixin:
|
||||
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.
|
||||
|
||||
@@ -519,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")):
|
||||
|
||||
@@ -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)
|
||||
@@ -15,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.
|
||||
@@ -280,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"
|
||||
)
|
||||
@@ -16,10 +16,40 @@ import logging
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
from napalm.base.exceptions import CommandErrorException
|
||||
|
||||
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}
|
||||
|
||||
class OpenWrtWirelessMixin:
|
||||
|
||||
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]:
|
||||
@@ -51,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))
|
||||
@@ -83,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)
|
||||
@@ -569,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*.
|
||||
@@ -592,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.
|
||||
|
||||
@@ -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]: ...
|
||||
+6
-9
@@ -4,26 +4,24 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "napalm-openwrt"
|
||||
version = "0.7.0"
|
||||
version = "0.8.0"
|
||||
description = "NAPALM driver for OpenWrt routers/access-points"
|
||||
readme = "README.md"
|
||||
license = "Apache-2.0"
|
||||
requires-python = ">=3.10"
|
||||
requires-python = ">=3.12"
|
||||
authors = [
|
||||
{ name = "Christian Manivong" },
|
||||
]
|
||||
classifiers = [
|
||||
"Topic :: Utilities",
|
||||
"Programming Language :: Python :: 3",
|
||||
"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>=4.21.1",
|
||||
"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>=0.7.19", # IPAddress; below it the package has none (CI lowest job)
|
||||
@@ -49,7 +47,7 @@ napalm_openwrt = ["py.typed"]
|
||||
|
||||
[tool.ruff]
|
||||
line-length = 100
|
||||
target-version = "py310"
|
||||
target-version = "py312"
|
||||
|
||||
[tool.ruff.lint]
|
||||
select = ["E", "F", "I", "UP", "B"]
|
||||
@@ -59,7 +57,7 @@ select = ["E", "F", "I", "UP", "B"]
|
||||
"tests/**" = ["E501"]
|
||||
|
||||
[tool.mypy]
|
||||
python_version = "3.10"
|
||||
python_version = "3.12"
|
||||
strict = true
|
||||
# napalm itself is untyped, so every driver subclasses Any.
|
||||
disallow_subclassing_any = false
|
||||
@@ -73,7 +71,6 @@ ignore_missing_imports = true
|
||||
module = [
|
||||
"napalm_openwrt.config_mixin",
|
||||
"napalm_openwrt.interfaces_mixin",
|
||||
"napalm_openwrt.lldp_mixin",
|
||||
"napalm_openwrt.openwrt",
|
||||
"napalm_openwrt.packages_mixin",
|
||||
"napalm_openwrt.routing_mixin",
|
||||
|
||||
@@ -3,7 +3,6 @@
|
||||
"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._allow_snmp_sources": 22,
|
||||
"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,
|
||||
@@ -21,7 +20,6 @@
|
||||
"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._allow_snmp_sources": 90,
|
||||
"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,
|
||||
@@ -40,7 +38,6 @@
|
||||
"mypy_relaxed": [
|
||||
"napalm_openwrt.config_mixin",
|
||||
"napalm_openwrt.interfaces_mixin",
|
||||
"napalm_openwrt.lldp_mixin",
|
||||
"napalm_openwrt.openwrt",
|
||||
"napalm_openwrt.packages_mixin",
|
||||
"napalm_openwrt.routing_mixin",
|
||||
|
||||
@@ -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)
|
||||
+440
-214
@@ -3,6 +3,7 @@
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
from napalm_device_types import LLDPCTL_KEYVALUE_COMMAND, CommandResult
|
||||
|
||||
from napalm_openwrt.openwrt import OpenWrtDriver
|
||||
|
||||
@@ -16,7 +17,7 @@ def driver():
|
||||
"""Return a driver instance with a mocked Netmiko connection."""
|
||||
with patch("napalm_openwrt.openwrt.ConnectHandler"):
|
||||
drv = OpenWrtDriver(
|
||||
hostname="192.168.1.1",
|
||||
hostname="192.0.2.1",
|
||||
username="root",
|
||||
password="",
|
||||
)
|
||||
@@ -62,16 +63,16 @@ IP_ADDR_SHOW = """\
|
||||
link/ether b0:95:75:aa:bb:cc brd ff:ff:ff:ff:ff:ff
|
||||
4: br-lan: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default qlen 1000
|
||||
link/ether b0:95:75:aa:bb:cc brd ff:ff:ff:ff:ff:ff
|
||||
inet 192.168.1.1/24 brd 192.168.1.255 scope global br-lan
|
||||
inet 192.0.2.1/24 brd 192.0.2.255 scope global br-lan
|
||||
valid_lft forever preferred_lft forever
|
||||
inet6 fd00::1/64 scope global
|
||||
valid_lft forever preferred_lft forever
|
||||
"""
|
||||
|
||||
IP_NEIGH_SHOW = """\
|
||||
192.168.1.100 dev br-lan lladdr aa:bb:cc:dd:ee:ff REACHABLE
|
||||
192.168.1.101 dev br-lan lladdr 11:22:33:44:55:66 STALE
|
||||
192.168.1.102 dev br-lan FAILED
|
||||
192.0.2.100 dev br-lan lladdr aa:bb:cc:dd:ee:ff REACHABLE
|
||||
192.0.2.101 dev br-lan lladdr 11:22:33:44:55:66 STALE
|
||||
192.0.2.102 dev br-lan FAILED
|
||||
"""
|
||||
|
||||
BRIDGE_FDB = """\
|
||||
@@ -98,7 +99,7 @@ config interface 'loopback'
|
||||
config interface 'lan'
|
||||
\toption device 'br-lan'
|
||||
\toption proto 'static'
|
||||
\toption ipaddr '192.168.1.1'
|
||||
\toption ipaddr '192.0.2.1'
|
||||
\toption netmask '255.255.255.0'
|
||||
"""
|
||||
|
||||
@@ -109,7 +110,7 @@ lldp.eth0.age=0 day, 01:23:45
|
||||
lldp.eth0.chassis.mac=00:aa:bb:cc:dd:ee
|
||||
lldp.eth0.chassis.name=core-router
|
||||
lldp.eth0.chassis.descr=RouterOS 7.x
|
||||
lldp.eth0.chassis.mgmt-ip=10.0.0.1
|
||||
lldp.eth0.chassis.mgmt-ip=203.0.113.10
|
||||
lldp.eth0.chassis.cap.available=Router, Bridge
|
||||
lldp.eth0.chassis.cap.enabled=Router
|
||||
lldp.eth0.port.ifname=ether1
|
||||
@@ -239,8 +240,8 @@ class TestGetInterfacesIP:
|
||||
driver._send_command = lambda cmd, **kw: IP_ADDR_SHOW
|
||||
result = driver.get_interfaces_ip()
|
||||
assert "br-lan" in result
|
||||
assert "192.168.1.1" in result["br-lan"]["ipv4"]
|
||||
assert result["br-lan"]["ipv4"]["192.168.1.1"]["prefix_length"] == 24
|
||||
assert "192.0.2.1" in result["br-lan"]["ipv4"]
|
||||
assert result["br-lan"]["ipv4"]["192.0.2.1"]["prefix_length"] == 24
|
||||
|
||||
def test_br_lan_ipv6(self, driver):
|
||||
driver._send_command = lambda cmd, **kw: IP_ADDR_SHOW
|
||||
@@ -271,8 +272,21 @@ class TestGetArpTable:
|
||||
driver._send_command = lambda cmd, **kw: IP_NEIGH_SHOW
|
||||
result = driver.get_arp_table()
|
||||
ips = {e["ip"] for e in result}
|
||||
assert "192.168.1.100" in ips
|
||||
assert "192.168.1.101" in ips
|
||||
assert "192.0.2.100" in ips
|
||||
assert "192.0.2.101" in ips
|
||||
|
||||
def test_ip_neigh_reports_no_age(self, driver):
|
||||
# REACHABLE or STALE, `ip neigh` says nothing about when the neighbour
|
||||
# was last confirmed; 0.0 would read as "just now" (NetOrk/netork#1327).
|
||||
driver._send_command = lambda cmd, **kw: IP_NEIGH_SHOW
|
||||
assert {e["age"] for e in driver.get_arp_table()} == {-1.0}
|
||||
|
||||
def test_proc_net_arp_reports_no_age(self, driver):
|
||||
driver._send_command = lambda cmd, **kw: (
|
||||
"IP address HW type Flags HW address Mask Device\n"
|
||||
"192.0.2.100 0x1 0x2 aa:bb:cc:dd:ee:ff * br-lan\n"
|
||||
)
|
||||
assert [e["age"] for e in driver.get_arp_table()] == [-1.0]
|
||||
|
||||
|
||||
class TestGetMacAddressTable:
|
||||
@@ -322,6 +336,201 @@ class TestGetLldpNeighbors:
|
||||
assert result["eth0"][0]["hostname"] == "core-router"
|
||||
assert result["eth0"][0]["port"] == "ether1"
|
||||
|
||||
def test_the_chassis_mac_is_reported(self, driver):
|
||||
# netOrk matches a neighbour by this MAC first (#31).
|
||||
driver._send_command = lambda cmd, **kw: LLDPCTL_KV
|
||||
|
||||
assert driver.get_lldp_neighbors()["eth0"][0]["mac"] == "00:aa:bb:cc:dd:ee"
|
||||
|
||||
def test_a_chassis_named_by_a_local_id_has_no_mac(self, driver):
|
||||
driver._send_command = lambda cmd, **kw: LLDPCTL_KV_DOTTED_AND_ID_TYPES
|
||||
|
||||
assert driver.get_lldp_neighbors()["eth1"] == [{"hostname": "access-sw", "port": "gi1/0/7"}]
|
||||
|
||||
|
||||
# Two neighbours on one port, laid out the way lldpd's keyvalue writer prints them
|
||||
# (src/client/display.c, kv_writer.c): every neighbour opens with an optional
|
||||
# ``alias`` and then ``via``, and the same key may repeat inside one neighbour
|
||||
# (one ``chassis.mgmt-ip`` per address). Not recorded from a device.
|
||||
LLDPCTL_KV_TWO_ON_ONE_PORT = """\
|
||||
lldp.lan1.via=LLDP
|
||||
lldp.lan1.rid=1
|
||||
lldp.lan1.age=0 day, 00:10:00
|
||||
lldp.lan1.chassis.mac=00:11:22:33:44:01
|
||||
lldp.lan1.chassis.name=desk-phone
|
||||
lldp.lan1.chassis.mgmt-ip=203.0.113.21
|
||||
lldp.lan1.chassis.mgmt-ip=fe80::211:22ff:fe33:4401
|
||||
lldp.lan1.port.ifname=lan
|
||||
lldp.lan1.port.descr=phone uplink
|
||||
lldp.lan1.alias=desk
|
||||
lldp.lan1.via=LLDP
|
||||
lldp.lan1.rid=2
|
||||
lldp.lan1.age=0 day, 00:09:00
|
||||
lldp.lan1.chassis.mac=00:11:22:33:44:02
|
||||
lldp.lan1.chassis.name=desk-pc
|
||||
lldp.lan1.port.ifname=eno1
|
||||
lldp.eth0.via=LLDP
|
||||
lldp.eth0.rid=3
|
||||
lldp.eth0.chassis.mac=00:aa:bb:cc:dd:ee
|
||||
lldp.eth0.chassis.name=core-router
|
||||
lldp.eth0.port.ifname=ether1
|
||||
"""
|
||||
|
||||
|
||||
class TestLldpGettersOnlyRead:
|
||||
"""Reading the neighbours neither starts lldpd nor rewrites its configuration (#8)."""
|
||||
|
||||
def _answer(self, driver) -> list:
|
||||
sent: list = []
|
||||
|
||||
def send(cmd, **kw):
|
||||
sent.append(cmd)
|
||||
# A default route on a VLAN of another bridge: the old code rewrote
|
||||
# lldpd's interface list for it and restarted the daemon.
|
||||
if "ip route" in cmd:
|
||||
return "br-ap"
|
||||
if "uci get lldpd" in cmd:
|
||||
return "br-lan"
|
||||
return LLDPCTL_KV
|
||||
|
||||
driver._send_command = send
|
||||
return sent
|
||||
|
||||
@pytest.mark.parametrize("getter", ["get_lldp_neighbors", "get_lldp_neighbors_detail"])
|
||||
def test_only_lldpctl_is_asked(self, driver, getter):
|
||||
sent = self._answer(driver)
|
||||
|
||||
getattr(driver, getter)()
|
||||
|
||||
assert sent == [LLDPCTL_KEYVALUE_COMMAND]
|
||||
|
||||
|
||||
class TestLldpSeveralNeighboursOnOnePort:
|
||||
"""Each neighbour on a port is its own entry; none is lost (#9)."""
|
||||
|
||||
def test_both_neighbours_on_the_port_are_reported(self, driver):
|
||||
driver._send_command = lambda cmd, **kw: LLDPCTL_KV_TWO_ON_ONE_PORT
|
||||
|
||||
result = driver.get_lldp_neighbors()
|
||||
|
||||
assert [(n["hostname"], n["port"]) for n in result["lan1"]] == [
|
||||
("desk-phone", "lan"),
|
||||
("desk-pc", "eno1"),
|
||||
]
|
||||
assert [(n["hostname"], n["port"]) for n in result["eth0"]] == [("core-router", "ether1")]
|
||||
|
||||
def test_a_neighbour_keeps_only_its_own_fields(self, driver):
|
||||
driver._send_command = lambda cmd, **kw: LLDPCTL_KV_TWO_ON_ONE_PORT
|
||||
|
||||
pc = driver.get_lldp_neighbors_detail("lan1")["lan1"][1]
|
||||
|
||||
assert pc["remote_chassis_id"] == "00:11:22:33:44:02"
|
||||
assert pc["remote_port_description"] == ""
|
||||
|
||||
def test_a_repeated_key_inside_one_neighbour_is_no_new_neighbour(self, driver):
|
||||
driver._send_command = lambda cmd, **kw: LLDPCTL_KV_TWO_ON_ONE_PORT
|
||||
|
||||
assert len(driver.get_lldp_neighbors_detail("lan1")["lan1"]) == 2
|
||||
|
||||
|
||||
class TestLldpFailedRead:
|
||||
"""A failed lldpctl raises; no neighbours only when it ran and listed none (#27)."""
|
||||
|
||||
@pytest.mark.parametrize("getter", ["get_lldp_neighbors", "get_lldp_neighbors_detail"])
|
||||
def test_a_missing_lldpctl_raises(self, driver, getter):
|
||||
driver._send_command = lambda cmd, **kw: "ash: lldpctl: not found\n__LLDPCTL_RC=127"
|
||||
|
||||
with pytest.raises(ValueError, match="lldpctl: not found"):
|
||||
getattr(driver, getter)()
|
||||
|
||||
def test_an_unreachable_lldpd_raises(self, driver):
|
||||
driver._send_command = lambda cmd, **kw: (
|
||||
"[WARN/control] unable to connect to socket /var/run/lldpd.socket: "
|
||||
"No such file or directory\n__LLDPCTL_RC=1"
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match="unable to connect"):
|
||||
driver.get_lldp_neighbors()
|
||||
|
||||
def test_lldpctl_without_neighbours_lists_none(self, driver):
|
||||
driver._send_command = lambda cmd, **kw: "__LLDPCTL_RC=0"
|
||||
|
||||
assert driver.get_lldp_neighbors() == {}
|
||||
assert driver.get_lldp_neighbors_detail() == {}
|
||||
|
||||
def test_the_exit_status_comes_back_with_the_output(self, driver):
|
||||
sent: list = []
|
||||
|
||||
def send(cmd, **kw):
|
||||
sent.append(cmd)
|
||||
return LLDPCTL_KV + "__LLDPCTL_RC=0"
|
||||
|
||||
driver._send_command = send
|
||||
|
||||
assert driver.get_lldp_neighbors()["eth0"][0]["hostname"] == "core-router"
|
||||
assert sent == [LLDPCTL_KEYVALUE_COMMAND]
|
||||
|
||||
|
||||
# A swconfig VLAN interface (``eth0.1``) with a neighbour that names its port by
|
||||
# MAC, and a switch on ``eth1`` that names itself and its port by local ids.
|
||||
# Laid out the way lldpd's keyvalue writer prints them (src/client/display.c):
|
||||
# an id is printed under its type, never as ``id.value``. Not recorded from a device.
|
||||
LLDPCTL_KV_DOTTED_AND_ID_TYPES = """\
|
||||
lldp.eth0.1.via=LLDP
|
||||
lldp.eth0.1.rid=1
|
||||
lldp.eth0.1.chassis.mac=00:11:22:33:44:01
|
||||
lldp.eth0.1.chassis.name=desk-phone
|
||||
lldp.eth0.1.chassis.descr=SIP phone
|
||||
lldp.eth0.1.chassis.Tel.enabled=on
|
||||
lldp.eth0.1.port.mac=00:11:22:33:44:01
|
||||
lldp.eth0.1.port.descr=WAN
|
||||
lldp.eth1.via=LLDP
|
||||
lldp.eth1.rid=2
|
||||
lldp.eth1.chassis.local=access-sw-01
|
||||
lldp.eth1.chassis.name=access-sw
|
||||
lldp.eth1.chassis.Bridge.enabled=on
|
||||
lldp.eth1.chassis.Router.enabled=off
|
||||
lldp.eth1.port.local=gi1/0/7
|
||||
"""
|
||||
|
||||
|
||||
class TestLldpDottedInterfaceAndPortIds:
|
||||
"""``eth0.1`` keeps its name, and a port id given as MAC or local id is read (#26)."""
|
||||
|
||||
def test_a_dotted_interface_keeps_its_name(self, driver):
|
||||
driver._send_command = lambda cmd, **kw: LLDPCTL_KV_DOTTED_AND_ID_TYPES
|
||||
|
||||
result = driver.get_lldp_neighbors()
|
||||
|
||||
assert sorted(result) == ["eth0.1", "eth1"]
|
||||
assert result["eth0.1"][0]["hostname"] == "desk-phone"
|
||||
|
||||
def test_a_port_given_by_mac_or_local_id_is_read(self, driver):
|
||||
driver._send_command = lambda cmd, **kw: LLDPCTL_KV_DOTTED_AND_ID_TYPES
|
||||
|
||||
result = driver.get_lldp_neighbors()
|
||||
|
||||
assert result["eth0.1"][0]["port"] == "00:11:22:33:44:01"
|
||||
assert result["eth1"][0]["port"] == "gi1/0/7"
|
||||
|
||||
def test_a_chassis_given_by_a_local_id_is_read(self, driver):
|
||||
driver._send_command = lambda cmd, **kw: LLDPCTL_KV_DOTTED_AND_ID_TYPES
|
||||
|
||||
switch = driver.get_lldp_neighbors_detail("eth1")["eth1"][0]
|
||||
|
||||
assert switch["remote_chassis_id"] == "access-sw-01"
|
||||
|
||||
def test_the_detail_carries_description_and_capabilities(self, driver):
|
||||
driver._send_command = lambda cmd, **kw: LLDPCTL_KV_DOTTED_AND_ID_TYPES
|
||||
|
||||
detail = driver.get_lldp_neighbors_detail()
|
||||
|
||||
phone = detail["eth0.1"][0]
|
||||
assert phone["remote_port_description"] == "WAN"
|
||||
assert phone["remote_system_description"] == "SIP phone"
|
||||
assert phone["remote_system_enable_capab"] == ["telephone"]
|
||||
assert detail["eth1"][0]["remote_system_capab"] == ["bridge", "router"]
|
||||
|
||||
|
||||
BRIDGE_VLAN_SHOW = """\
|
||||
port vlan-id
|
||||
@@ -603,8 +812,8 @@ system.ntp.enable_server='0'
|
||||
NTPQ_OUTPUT = """\
|
||||
remote refid st t when poll reach delay offset jitter
|
||||
==============================================================================
|
||||
*188.114.101.4 188.114.100.1 4 u 107 256 377 164.228 -13.866 2.695
|
||||
+37.187.56.220 192.53.103.108 2 u 22 64 377 30.112 5.123 1.100
|
||||
*203.0.113.104 203.0.113.100 4 u 107 256 377 164.228 -13.866 2.695
|
||||
+203.0.113.220 203.0.113.108 2 u 22 64 377 30.112 5.123 1.100
|
||||
"""
|
||||
|
||||
UCI_SNMPD = """\
|
||||
@@ -616,7 +825,7 @@ snmpd.@com2sec[0].source='default'
|
||||
snmpd.@com2sec[0].community='public'
|
||||
snmpd.@com2sec[1]=com2sec
|
||||
snmpd.@com2sec[1].secname='private'
|
||||
snmpd.@com2sec[1].source='10.0.0.0/8'
|
||||
snmpd.@com2sec[1].source='203.0.113.0/24'
|
||||
snmpd.@com2sec[1].community='private'
|
||||
snmpd.@system[0]=system
|
||||
snmpd.@system[0].sysContact='admin@example.com'
|
||||
@@ -625,18 +834,18 @@ snmpd.@system[0].sysName='MyRouter'
|
||||
"""
|
||||
|
||||
PING_SUCCESS = """\
|
||||
PING 8.8.8.8 (8.8.8.8): 56 data bytes
|
||||
64 bytes from 8.8.8.8: seq=0 ttl=120 time=7.123 ms
|
||||
64 bytes from 8.8.8.8: seq=1 ttl=120 time=6.987 ms
|
||||
64 bytes from 8.8.8.8: seq=2 ttl=120 time=7.234 ms
|
||||
--- 8.8.8.8 ping statistics ---
|
||||
PING 203.0.113.8 (203.0.113.8): 56 data bytes
|
||||
64 bytes from 203.0.113.8: seq=0 ttl=120 time=7.123 ms
|
||||
64 bytes from 203.0.113.8: seq=1 ttl=120 time=6.987 ms
|
||||
64 bytes from 203.0.113.8: seq=2 ttl=120 time=7.234 ms
|
||||
--- 203.0.113.8 ping statistics ---
|
||||
3 packets transmitted, 3 packets received, 0% packet loss
|
||||
round-trip min/avg/max = 6.987/7.115/7.234 ms
|
||||
"""
|
||||
|
||||
PING_LOSS = """\
|
||||
PING 10.0.0.99 (10.0.0.99): 56 data bytes
|
||||
--- 10.0.0.99 ping statistics ---
|
||||
PING 203.0.113.99 (203.0.113.99): 56 data bytes
|
||||
--- 203.0.113.99 ping statistics ---
|
||||
3 packets transmitted, 0 packets received, 100% packet loss
|
||||
"""
|
||||
|
||||
@@ -649,17 +858,17 @@ fe80::1 dev br-lan lladdr 11:22:33:44:55:66 STALE
|
||||
"""
|
||||
|
||||
IP_ROUTE_SHOW = """\
|
||||
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
|
||||
10.0.0.0/8 via 192.168.1.254 dev br-wan proto static metric 50
|
||||
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
|
||||
203.0.113.0/24 via 192.0.2.254 dev br-wan proto static metric 50
|
||||
"""
|
||||
|
||||
TRACEROUTE_OUTPUT = """\
|
||||
traceroute to 8.8.8.8 (8.8.8.8), 30 hops max, 38 byte packets
|
||||
1 192.168.1.1 (192.168.1.1) 1.123 ms 1.456 ms 1.789 ms
|
||||
2 10.0.0.1 (10.0.0.1) 5.123 ms 5.456 ms 5.789 ms
|
||||
traceroute to 203.0.113.8 (203.0.113.8), 30 hops max, 38 byte packets
|
||||
1 192.0.2.1 (192.0.2.1) 1.123 ms 1.456 ms 1.789 ms
|
||||
2 203.0.113.10 (203.0.113.10) 5.123 ms 5.456 ms 5.789 ms
|
||||
3 * * *
|
||||
4 8.8.8.8 (8.8.8.8) 7.001 ms 6.999 ms 7.100 ms
|
||||
4 203.0.113.8 (203.0.113.8) 7.001 ms 6.999 ms 7.100 ms
|
||||
"""
|
||||
|
||||
TRACEROUTE_ERROR = "traceroute: unknown host invalid.host"
|
||||
@@ -740,20 +949,26 @@ class TestGetUsers:
|
||||
|
||||
|
||||
class TestGetNtpServers:
|
||||
"""Read with get_time_sync's reading (test_time_sync.py), over an exec channel."""
|
||||
|
||||
@staticmethod
|
||||
def _uci(output):
|
||||
return lambda cmd, **kw: CommandResult(output, "", 0)
|
||||
|
||||
def test_returns_dict(self, driver):
|
||||
driver._send_command = lambda cmd, **kw: UCI_SYSTEM_NTP
|
||||
driver.run_command = self._uci(UCI_SYSTEM_NTP)
|
||||
result = driver.get_ntp_servers()
|
||||
assert isinstance(result, dict)
|
||||
|
||||
def test_servers_present(self, driver):
|
||||
driver._send_command = lambda cmd, **kw: UCI_SYSTEM_NTP
|
||||
driver.run_command = self._uci(UCI_SYSTEM_NTP)
|
||||
result = driver.get_ntp_servers()
|
||||
assert "0.openwrt.pool.ntp.org" in result
|
||||
assert "1.openwrt.pool.ntp.org" in result
|
||||
assert "2.openwrt.pool.ntp.org" in result
|
||||
|
||||
def test_empty_when_no_ntp(self, driver):
|
||||
driver._send_command = lambda cmd, **kw: ""
|
||||
driver.run_command = self._uci("")
|
||||
assert driver.get_ntp_servers() == {}
|
||||
|
||||
|
||||
@@ -768,7 +983,7 @@ class TestGetNtpStats:
|
||||
result = driver.get_ntp_stats()
|
||||
synced = [e for e in result if e["synchronized"]]
|
||||
assert len(synced) == 1
|
||||
assert synced[0]["remote"] == "188.114.101.4"
|
||||
assert synced[0]["remote"] == "203.0.113.104"
|
||||
|
||||
def test_required_keys(self, driver):
|
||||
driver._send_command = lambda cmd, **kw: NTPQ_OUTPUT
|
||||
@@ -827,14 +1042,14 @@ class TestGetSnmpInformation:
|
||||
class TestPing:
|
||||
def test_success_result(self, driver):
|
||||
driver._send_command = lambda cmd, **kw: PING_SUCCESS
|
||||
result = driver.ping("8.8.8.8")
|
||||
result = driver.ping("203.0.113.8")
|
||||
assert "success" in result
|
||||
assert result["success"]["probes_sent"] == 3
|
||||
assert result["success"]["packet_loss"] == 0
|
||||
|
||||
def test_rtt_values(self, driver):
|
||||
driver._send_command = lambda cmd, **kw: PING_SUCCESS
|
||||
result = driver.ping("8.8.8.8")
|
||||
result = driver.ping("203.0.113.8")
|
||||
s = result["success"]
|
||||
assert s["rtt_min"] == 6.987
|
||||
assert s["rtt_max"] == 7.234
|
||||
@@ -842,13 +1057,13 @@ class TestPing:
|
||||
|
||||
def test_probe_results(self, driver):
|
||||
driver._send_command = lambda cmd, **kw: PING_SUCCESS
|
||||
result = driver.ping("8.8.8.8")
|
||||
result = driver.ping("203.0.113.8")
|
||||
assert len(result["success"]["results"]) == 3
|
||||
assert result["success"]["results"][0]["ip_address"] == "8.8.8.8"
|
||||
assert result["success"]["results"][0]["ip_address"] == "203.0.113.8"
|
||||
|
||||
def test_100_percent_loss(self, driver):
|
||||
driver._send_command = lambda cmd, **kw: PING_LOSS
|
||||
result = driver.ping("10.0.0.99")
|
||||
result = driver.ping("203.0.113.99")
|
||||
assert "success" in result
|
||||
assert result["success"]["packet_loss"] == 3
|
||||
|
||||
@@ -894,20 +1109,20 @@ class TestGetRouteTo:
|
||||
driver._send_command = lambda cmd, **kw: IP_ROUTE_SHOW
|
||||
result = driver.get_route_to()
|
||||
default = result["0.0.0.0/0"][0]
|
||||
assert default["next_hop"] == "192.168.1.1"
|
||||
assert default["next_hop"] == "192.0.2.1"
|
||||
assert default["outgoing_interface"] == "br-wan"
|
||||
|
||||
def test_connected_route(self, driver):
|
||||
driver._send_command = lambda cmd, **kw: IP_ROUTE_SHOW
|
||||
result = driver.get_route_to()
|
||||
assert "192.168.1.0/24" in result
|
||||
assert result["192.168.1.0/24"][0]["protocol"] == "connected"
|
||||
assert "192.0.2.0/24" in result
|
||||
assert result["192.0.2.0/24"][0]["protocol"] == "connected"
|
||||
|
||||
def test_protocol_filter(self, driver):
|
||||
driver._send_command = lambda cmd, **kw: IP_ROUTE_SHOW
|
||||
result = driver.get_route_to(protocol="static")
|
||||
assert "10.0.0.0/8" in result
|
||||
assert "192.168.1.0/24" not in result
|
||||
assert "203.0.113.0/24" in result
|
||||
assert "192.0.2.0/24" not in result
|
||||
|
||||
def test_required_keys(self, driver):
|
||||
driver._send_command = lambda cmd, **kw: IP_ROUTE_SHOW
|
||||
@@ -926,24 +1141,24 @@ class TestGetRouteTo:
|
||||
class TestTraceroute:
|
||||
def test_success_result(self, driver):
|
||||
driver._send_command = lambda cmd, **kw: TRACEROUTE_OUTPUT
|
||||
result = driver.traceroute("8.8.8.8")
|
||||
result = driver.traceroute("203.0.113.8")
|
||||
assert "success" in result
|
||||
|
||||
def test_hop_count(self, driver):
|
||||
driver._send_command = lambda cmd, **kw: TRACEROUTE_OUTPUT
|
||||
result = driver.traceroute("8.8.8.8")
|
||||
result = driver.traceroute("203.0.113.8")
|
||||
assert len(result["success"]) == 4
|
||||
|
||||
def test_hop_1_rtt(self, driver):
|
||||
driver._send_command = lambda cmd, **kw: TRACEROUTE_OUTPUT
|
||||
result = driver.traceroute("8.8.8.8")
|
||||
result = driver.traceroute("203.0.113.8")
|
||||
hop1 = result["success"][1]["probes"][1]
|
||||
assert hop1["rtt"] == 1.123
|
||||
assert hop1["ip_address"] == "192.168.1.1"
|
||||
assert hop1["ip_address"] == "192.0.2.1"
|
||||
|
||||
def test_star_hop(self, driver):
|
||||
driver._send_command = lambda cmd, **kw: TRACEROUTE_OUTPUT
|
||||
result = driver.traceroute("8.8.8.8")
|
||||
result = driver.traceroute("203.0.113.8")
|
||||
hop3 = result["success"][3]["probes"][1]
|
||||
assert hop3["ip_address"] == "*"
|
||||
|
||||
@@ -1229,47 +1444,6 @@ BSS aa:bb:cc:dd:01:ff(on wlan0)
|
||||
assert entries[0]["frequency"] == 5975
|
||||
|
||||
|
||||
class TestPushRadioChannel:
|
||||
"""Tests for OpenWrtWirelessMixin.push_radio_channel()."""
|
||||
|
||||
def test_issues_uci_set(self, driver):
|
||||
"""Must call 'uci set wireless.radio0.channel=11'."""
|
||||
issued: list[str] = []
|
||||
driver._send_command = lambda cmd, **kw: issued.append(cmd) or ""
|
||||
driver.push_radio_channel("radio0", 11)
|
||||
assert any("uci set wireless.radio0.channel=11" in c for c in issued)
|
||||
|
||||
def test_issues_uci_commit(self, driver):
|
||||
issued: list[str] = []
|
||||
driver._send_command = lambda cmd, **kw: issued.append(cmd) or ""
|
||||
driver.push_radio_channel("radio0", 11)
|
||||
assert any("uci commit wireless" in c for c in issued)
|
||||
|
||||
def test_issues_wifi_restart(self, driver):
|
||||
"""Must call 'wifi' (full restart) — NOT just 'wifi reload'."""
|
||||
issued: list[str] = []
|
||||
driver._send_command = lambda cmd, **kw: issued.append(cmd) or ""
|
||||
driver.push_radio_channel("radio1", 36)
|
||||
# 'wifi' alone is a full restart; 'wifi reload' is insufficient for channel changes
|
||||
assert any(c.strip() == "wifi" for c in issued)
|
||||
|
||||
def test_auto_channel_zero(self, driver):
|
||||
"""channel=0 should set 'auto' in UCI."""
|
||||
issued: list[str] = []
|
||||
driver._send_command = lambda cmd, **kw: issued.append(cmd) or ""
|
||||
driver.push_radio_channel("radio0", 0)
|
||||
assert any("channel=auto" in c or "channel='auto'" in c for c in issued)
|
||||
|
||||
def test_commit_before_restart(self, driver):
|
||||
"""UCI commit must happen before wifi restart."""
|
||||
issued: list[str] = []
|
||||
driver._send_command = lambda cmd, **kw: issued.append(cmd) or ""
|
||||
driver.push_radio_channel("radio0", 6)
|
||||
commit_idx = next(i for i, c in enumerate(issued) if "commit" in c)
|
||||
wifi_idx = next(i for i, c in enumerate(issued) if c.strip() == "wifi")
|
||||
assert commit_idx < wifi_idx
|
||||
|
||||
|
||||
UCI_WIRELESS_ACL = """\
|
||||
wireless.radio0=wifi-device
|
||||
wireless.radio0.band='2g'
|
||||
@@ -1335,108 +1509,6 @@ class TestGetSsidsAcl:
|
||||
assert result["CorpWiFi"]["acl_mode"] == "blacklist"
|
||||
|
||||
|
||||
class TestPushMacAcl:
|
||||
"""Tests for OpenWrtWirelessMixin.push_mac_acl()."""
|
||||
|
||||
def _make_send(
|
||||
self, sections="wireless.@wifi-iface[0]\nwireless.@wifi-iface[1]", ssid_by_section=None
|
||||
):
|
||||
ssid_by_section = ssid_by_section or {
|
||||
"wireless.@wifi-iface[0]": "CorpWiFi",
|
||||
"wireless.@wifi-iface[1]": "GuestNet",
|
||||
}
|
||||
issued: list[str] = []
|
||||
|
||||
def _send(cmd, **kw):
|
||||
issued.append(cmd)
|
||||
if "grep -oE" in cmd and "sort -u" in cmd:
|
||||
return sections
|
||||
for sec, ssid in ssid_by_section.items():
|
||||
if f"uci -q get {sec}.ssid" in cmd:
|
||||
return ssid
|
||||
return ""
|
||||
|
||||
return _send, issued
|
||||
|
||||
def test_whitelist_sets_macfilter_allow(self, driver):
|
||||
send, issued = self._make_send()
|
||||
driver._send_command = send
|
||||
driver.push_mac_acl("CorpWiFi", "whitelist", ["AA:BB:CC:DD:EE:01"])
|
||||
assert any("wireless.@wifi-iface[0].macfilter='allow'" in c for c in issued)
|
||||
|
||||
def test_blacklist_sets_macfilter_deny(self, driver):
|
||||
send, issued = self._make_send()
|
||||
driver._send_command = send
|
||||
driver.push_mac_acl("CorpWiFi", "blacklist", ["AA:BB:CC:DD:EE:01"])
|
||||
assert any("wireless.@wifi-iface[0].macfilter='deny'" in c for c in issued)
|
||||
|
||||
def test_off_deletes_macfilter_option_instead_of_setting_disable(self, driver):
|
||||
"""OpenWrt's validator rejects macfilter='disable' outright (confirmed on
|
||||
real hardware — it puts netifd in a permanent restart crash loop with
|
||||
the radio stuck down). "off" must delete the option, never set it."""
|
||||
send, issued = self._make_send()
|
||||
driver._send_command = send
|
||||
driver.push_mac_acl("CorpWiFi", "off", [])
|
||||
assert not any("macfilter='disable'" in c for c in issued)
|
||||
assert any("delete wireless.@wifi-iface[0].macfilter" in c for c in issued)
|
||||
assert any("delete wireless.@wifi-iface[0].maclist" in c for c in issued)
|
||||
assert not any("add_list wireless.@wifi-iface[0].maclist" in c for c in issued)
|
||||
|
||||
def test_whitelist_with_zero_macs_treated_as_off(self, driver):
|
||||
"""An empty whitelist blocks every client outright — must not be pushed
|
||||
as macfilter='allow' with an empty list."""
|
||||
send, issued = self._make_send()
|
||||
driver._send_command = send
|
||||
driver.push_mac_acl("CorpWiFi", "whitelist", [])
|
||||
assert not any("macfilter='allow'" in c for c in issued)
|
||||
assert any("delete wireless.@wifi-iface[0].macfilter" in c for c in issued)
|
||||
|
||||
def test_blacklist_with_zero_macs_still_pushed(self, driver):
|
||||
"""An empty blacklist is safe (blocks nobody) — no guard needed."""
|
||||
send, issued = self._make_send()
|
||||
driver._send_command = send
|
||||
driver.push_mac_acl("CorpWiFi", "blacklist", [])
|
||||
assert any("macfilter='deny'" in c for c in issued)
|
||||
|
||||
def test_maclist_entries_added(self, driver):
|
||||
send, issued = self._make_send()
|
||||
driver._send_command = send
|
||||
driver.push_mac_acl("CorpWiFi", "whitelist", ["AA:BB:CC:DD:EE:01", "AA:BB:CC:DD:EE:02"])
|
||||
assert any(
|
||||
"add_list wireless.@wifi-iface[0].maclist='AA:BB:CC:DD:EE:01'" in c for c in issued
|
||||
)
|
||||
assert any(
|
||||
"add_list wireless.@wifi-iface[0].maclist='AA:BB:CC:DD:EE:02'" in c for c in issued
|
||||
)
|
||||
|
||||
def test_maclist_cleared_before_readd(self, driver):
|
||||
"""Full-rebuild: existing maclist must be deleted before new entries are added."""
|
||||
send, issued = self._make_send()
|
||||
driver._send_command = send
|
||||
driver.push_mac_acl("CorpWiFi", "whitelist", ["AA:BB:CC:DD:EE:01"])
|
||||
delete_idx = next(
|
||||
i for i, c in enumerate(issued) if "delete wireless.@wifi-iface[0].maclist" in c
|
||||
)
|
||||
add_idx = next(
|
||||
i for i, c in enumerate(issued) if "add_list wireless.@wifi-iface[0].maclist" in c
|
||||
)
|
||||
assert delete_idx < add_idx
|
||||
|
||||
def test_only_matching_ssid_sections_touched(self, driver):
|
||||
"""GuestNet section must not be modified when pushing CorpWiFi's ACL."""
|
||||
send, issued = self._make_send()
|
||||
driver._send_command = send
|
||||
driver.push_mac_acl("CorpWiFi", "whitelist", ["AA:BB:CC:DD:EE:01"])
|
||||
assert not any("wireless.@wifi-iface[1].macfilter" in c for c in issued)
|
||||
|
||||
def test_issues_uci_commit_and_wifi_reload(self, driver):
|
||||
send, issued = self._make_send()
|
||||
driver._send_command = send
|
||||
driver.push_mac_acl("CorpWiFi", "whitelist", ["AA:BB:CC:DD:EE:01"])
|
||||
assert any("uci commit wireless" in c for c in issued)
|
||||
assert any(c.strip() == "wifi reload" for c in issued)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# fix_snmp — firewall zone handling
|
||||
# ---------------------------------------------------------------------------
|
||||
@@ -1492,11 +1564,11 @@ network.loopback.device='lo'
|
||||
network.lan=interface
|
||||
network.lan.device='br-lan'
|
||||
network.lan.proto='static'
|
||||
network.lan.ipaddr='192.168.1.1'
|
||||
network.lan.ipaddr='192.0.2.1'
|
||||
network.mgmt=interface
|
||||
network.mgmt.device='br-lan.9'
|
||||
network.mgmt.proto='static'
|
||||
network.mgmt.ipaddr='10.10.0.5'
|
||||
network.mgmt.ipaddr='198.51.100.5'
|
||||
"""
|
||||
|
||||
UCI_NETWORK_DHCP = """\
|
||||
@@ -1507,7 +1579,7 @@ network.lan.proto='dhcp'
|
||||
|
||||
IP_ADDR_BRLAN = """\
|
||||
1: lo inet 127.0.0.1/8 scope host lo\\ valid_lft forever preferred_lft forever
|
||||
7: br-lan inet 10.10.0.5/24 brd 10.10.0.255 scope global br-lan\\ valid_lft forever
|
||||
7: br-lan inet 198.51.100.5/24 brd 198.51.100.255 scope global br-lan\\ valid_lft forever
|
||||
"""
|
||||
|
||||
|
||||
@@ -1569,11 +1641,11 @@ class TestFixSnmpZoneDetection:
|
||||
"""The firewall step must resolve the real zone that owns the mgmt address."""
|
||||
|
||||
def test_static_mgmt_address_selects_owning_zone(self, driver):
|
||||
"""10.10.0.5 lives on network 'mgmt' → zone 'mgmt', not the 'lan' fallback."""
|
||||
"""198.51.100.5 lives on network 'mgmt' → zone 'mgmt', not the 'lan' fallback."""
|
||||
shell = _FakeShell(
|
||||
firewall=UCI_FIREWALL_MGMT_ZONE,
|
||||
network=UCI_NETWORK_STATIC,
|
||||
ssh_connection="10.10.0.1 51234 10.10.0.5 22",
|
||||
ssh_connection="198.51.100.1 51234 198.51.100.5 22",
|
||||
)
|
||||
driver._send_command = shell
|
||||
result = driver.configure_snmp_agent(_SETTINGS)
|
||||
@@ -1585,7 +1657,7 @@ class TestFixSnmpZoneDetection:
|
||||
shell = _FakeShell(
|
||||
firewall=UCI_FIREWALL_HEALTHY,
|
||||
network=UCI_NETWORK_STATIC,
|
||||
ssh_connection="192.168.1.50 5000 192.168.1.1 22",
|
||||
ssh_connection="192.0.2.50 5000 192.0.2.1 22",
|
||||
)
|
||||
driver._send_command = shell
|
||||
result = driver.configure_snmp_agent(_SETTINGS)
|
||||
@@ -1597,7 +1669,7 @@ class TestFixSnmpZoneDetection:
|
||||
firewall=UCI_FIREWALL_HEALTHY,
|
||||
network=UCI_NETWORK_DHCP,
|
||||
ip_addr=IP_ADDR_BRLAN,
|
||||
ssh_connection="10.10.0.1 51234 10.10.0.5 22",
|
||||
ssh_connection="198.51.100.1 51234 198.51.100.5 22",
|
||||
)
|
||||
driver._send_command = shell
|
||||
result = driver.configure_snmp_agent(_SETTINGS)
|
||||
@@ -1608,7 +1680,7 @@ class TestFixSnmpZoneDetection:
|
||||
shell = _FakeShell(
|
||||
firewall=UCI_FIREWALL_NAMELESS_ZONE,
|
||||
network=UCI_NETWORK_STATIC,
|
||||
ssh_connection="192.168.1.50 5000 192.168.1.1 22",
|
||||
ssh_connection="192.0.2.50 5000 192.0.2.1 22",
|
||||
)
|
||||
driver._send_command = shell
|
||||
result = driver.configure_snmp_agent(_SETTINGS)
|
||||
@@ -1621,7 +1693,7 @@ class TestFixSnmpZoneDetection:
|
||||
shell = _FakeShell(
|
||||
firewall=UCI_FIREWALL_NAMELESS_ZONE,
|
||||
network=UCI_NETWORK_STATIC,
|
||||
ssh_connection="192.168.1.50 5000 192.168.1.1 22",
|
||||
ssh_connection="192.0.2.50 5000 192.0.2.1 22",
|
||||
)
|
||||
driver._send_command = shell
|
||||
driver.configure_snmp_agent(_SETTINGS)
|
||||
@@ -1641,7 +1713,7 @@ class TestFixSnmpRuleWriting:
|
||||
shell = _FakeShell(
|
||||
firewall=broken,
|
||||
network=UCI_NETWORK_STATIC,
|
||||
ssh_connection="192.168.1.50 5000 192.168.1.1 22",
|
||||
ssh_connection="192.0.2.50 5000 192.0.2.1 22",
|
||||
)
|
||||
driver._send_command = shell
|
||||
driver.configure_snmp_agent(_SETTINGS)
|
||||
@@ -1660,7 +1732,7 @@ class TestFixSnmpRuleWriting:
|
||||
shell = _FakeShell(
|
||||
firewall=stale,
|
||||
network=UCI_NETWORK_STATIC,
|
||||
ssh_connection="192.168.1.50 5000 192.168.1.1 22",
|
||||
ssh_connection="192.0.2.50 5000 192.0.2.1 22",
|
||||
)
|
||||
driver._send_command = shell
|
||||
driver.configure_snmp_agent(_SETTINGS)
|
||||
@@ -1678,7 +1750,7 @@ class TestFixSnmpRuleWriting:
|
||||
shell = _FakeShell(
|
||||
firewall=stale,
|
||||
network=UCI_NETWORK_STATIC,
|
||||
ssh_connection="192.168.1.50 5000 192.168.1.1 22",
|
||||
ssh_connection="192.0.2.50 5000 192.0.2.1 22",
|
||||
)
|
||||
driver._send_command = shell
|
||||
driver.configure_snmp_agent(_SETTINGS)
|
||||
@@ -1698,7 +1770,7 @@ class TestFixSnmpRuleWriting:
|
||||
shell = _FakeShell(
|
||||
firewall=stale,
|
||||
network=UCI_NETWORK_STATIC,
|
||||
ssh_connection="192.168.1.50 5000 192.168.1.1 22",
|
||||
ssh_connection="192.0.2.50 5000 192.0.2.1 22",
|
||||
)
|
||||
driver._send_command = shell
|
||||
driver.configure_snmp_agent(_SETTINGS)
|
||||
@@ -1719,7 +1791,7 @@ class TestFixSnmpReloadVerification:
|
||||
shell = _FakeShell(
|
||||
firewall=UCI_FIREWALL_HEALTHY,
|
||||
network=UCI_NETWORK_STATIC,
|
||||
ssh_connection="192.168.1.50 5000 192.168.1.1 22",
|
||||
ssh_connection="192.0.2.50 5000 192.0.2.1 22",
|
||||
reload_out=self.FW4_ZONE_ERROR,
|
||||
)
|
||||
driver._send_command = shell
|
||||
@@ -1731,7 +1803,7 @@ class TestFixSnmpReloadVerification:
|
||||
shell = _FakeShell(
|
||||
firewall=UCI_FIREWALL_HEALTHY,
|
||||
network=UCI_NETWORK_STATIC,
|
||||
ssh_connection="192.168.1.50 5000 192.168.1.1 22",
|
||||
ssh_connection="192.0.2.50 5000 192.0.2.1 22",
|
||||
reload_out=self.FW4_ZONE_ERROR,
|
||||
)
|
||||
driver._send_command = shell
|
||||
@@ -1743,7 +1815,7 @@ class TestFixSnmpReloadVerification:
|
||||
shell = _FakeShell(
|
||||
firewall=UCI_FIREWALL_HEALTHY,
|
||||
network=UCI_NETWORK_STATIC,
|
||||
ssh_connection="192.168.1.50 5000 192.168.1.1 22",
|
||||
ssh_connection="192.0.2.50 5000 192.0.2.1 22",
|
||||
nft_hits="0",
|
||||
)
|
||||
driver._send_command = shell
|
||||
@@ -1754,7 +1826,7 @@ class TestFixSnmpReloadVerification:
|
||||
shell = _FakeShell(
|
||||
firewall=UCI_FIREWALL_HEALTHY,
|
||||
network=UCI_NETWORK_STATIC,
|
||||
ssh_connection="192.168.1.50 5000 192.168.1.1 22",
|
||||
ssh_connection="192.0.2.50 5000 192.0.2.1 22",
|
||||
listen_hits="0",
|
||||
)
|
||||
driver._send_command = shell
|
||||
@@ -1765,7 +1837,7 @@ class TestFixSnmpReloadVerification:
|
||||
shell = _FakeShell(
|
||||
firewall=UCI_FIREWALL_HEALTHY,
|
||||
network=UCI_NETWORK_STATIC,
|
||||
ssh_connection="192.168.1.50 5000 192.168.1.1 22",
|
||||
ssh_connection="192.0.2.50 5000 192.0.2.1 22",
|
||||
)
|
||||
driver._send_command = shell
|
||||
result = driver.configure_snmp_agent(_SETTINGS)
|
||||
@@ -1802,11 +1874,11 @@ class TestUciSectionParser:
|
||||
|
||||
UCI_SYSTEM_WITH_SYSLOG = """\
|
||||
system.@system[0]=system
|
||||
system.@system[0].hostname='ap-eze-Garten'
|
||||
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='10.10.40.2'
|
||||
system.@system[0].log_ip='192.0.2.40'
|
||||
system.@system[0].log_port='5514'
|
||||
system.@system[0].log_proto='udp'
|
||||
system.ntp=timeserver
|
||||
@@ -1815,7 +1887,7 @@ system.ntp.server='0.openwrt.pool.ntp.org' '1.openwrt.pool.ntp.org'
|
||||
|
||||
UCI_SYSTEM_NO_SYSLOG = """\
|
||||
system.@system[0]=system
|
||||
system.@system[0].hostname='ap-eze-Parkplatz'
|
||||
system.@system[0].hostname='ap-02'
|
||||
system.@system[0].timezone='GMT0'
|
||||
system.@system[0].zonename='UTC'
|
||||
system.ntp=timeserver
|
||||
@@ -1867,7 +1939,7 @@ class TestGetSystemConfigSyslog:
|
||||
driver._send_command = _system_send()
|
||||
cfg = driver.get_system_config()
|
||||
assert cfg["syslog_remote"] is True
|
||||
assert cfg["syslog_ip"] == "10.10.40.2"
|
||||
assert cfg["syslog_ip"] == "192.0.2.40"
|
||||
assert cfg["syslog_port"] == 5514
|
||||
|
||||
def test_absent_syslog_reports_as_disabled(self, driver):
|
||||
@@ -1878,13 +1950,13 @@ class TestGetSystemConfigSyslog:
|
||||
|
||||
def test_log_ip_without_log_remote_is_not_active(self, driver):
|
||||
# OpenWrt only ships logs when log_remote is set, whatever log_ip says.
|
||||
out = UCI_SYSTEM_NO_SYSLOG + "system.@system[0].log_ip='10.10.40.2'\n"
|
||||
out = UCI_SYSTEM_NO_SYSLOG + "system.@system[0].log_ip='192.0.2.40'\n"
|
||||
driver._send_command = _system_send(out)
|
||||
assert driver.get_system_config()["syslog_remote"] is False
|
||||
|
||||
def test_port_falls_back_to_the_openwrt_default(self, driver):
|
||||
out = UCI_SYSTEM_NO_SYSLOG + (
|
||||
"system.@system[0].log_remote='1'\nsystem.@system[0].log_ip='10.10.40.2'\n"
|
||||
"system.@system[0].log_remote='1'\nsystem.@system[0].log_ip='192.0.2.40'\n"
|
||||
)
|
||||
driver._send_command = _system_send(out)
|
||||
assert driver.get_system_config()["syslog_port"] == 514
|
||||
@@ -1927,3 +1999,157 @@ class TestGetSystemConfigBridgeStp:
|
||||
# Nothing to have an opinion about — distinct from "STP is off".
|
||||
driver._send_command = _system_send(network_out="network.lan=interface\n")
|
||||
assert driver.get_system_config()["bridge_stp"] is None
|
||||
|
||||
|
||||
class TestOptionalArgs:
|
||||
def test_the_callers_optional_args_are_left_as_they_were(self):
|
||||
optional_args = {"port": 2222, "conn_timeout": 15}
|
||||
|
||||
drv = OpenWrtDriver("192.0.2.1", "root", "", optional_args=optional_args)
|
||||
|
||||
assert drv.port == 2222
|
||||
assert optional_args == {"port": 2222, "conn_timeout": 15}
|
||||
|
||||
|
||||
class TestManageService:
|
||||
"""Only the init script's exit status decides whether an action succeeded (#3)."""
|
||||
|
||||
def _answer(self, driver, reply: str) -> list:
|
||||
sent: list = []
|
||||
|
||||
def send(cmd, **kw):
|
||||
sent.append(cmd)
|
||||
return reply
|
||||
|
||||
driver._send_command = send
|
||||
return sent
|
||||
|
||||
def test_a_clean_exit_is_a_success(self, driver):
|
||||
sent = self._answer(driver, "__OWRT_RC=0\n")
|
||||
|
||||
assert driver.manage_service("dnsmasq", "restart") == {"success": True, "output": ""}
|
||||
assert sent[0].startswith("/etc/init.d/dnsmasq restart 2>&1")
|
||||
|
||||
def test_a_failed_action_is_no_success(self, driver):
|
||||
self._answer(driver, "Command failed: Not found\n__OWRT_RC=1\n")
|
||||
|
||||
result = driver.manage_service("dnsmasq", "start")
|
||||
|
||||
assert result == {"success": False, "output": "Command failed: Not found"}
|
||||
|
||||
def test_a_missing_init_script_is_no_success(self, driver):
|
||||
self._answer(driver, "ash: /etc/init.d/nope: not found\n__OWRT_RC=127\n")
|
||||
|
||||
result = driver.manage_service("nope", "start")
|
||||
|
||||
assert result["success"] is False
|
||||
assert "not found" in result["output"]
|
||||
|
||||
def test_a_silent_failure_names_the_status(self, driver):
|
||||
self._answer(driver, "__OWRT_RC=1\n")
|
||||
|
||||
result = driver.manage_service("lldpd", "enable")
|
||||
|
||||
assert result["success"] is False
|
||||
assert "status 1" in result["output"]
|
||||
|
||||
def test_output_without_a_status_is_no_success(self, driver):
|
||||
self._answer(driver, "")
|
||||
|
||||
assert driver.manage_service("dnsmasq", "stop")["success"] is False
|
||||
|
||||
def test_an_invalid_name_is_refused_before_anything_is_sent(self, driver):
|
||||
sent = self._answer(driver, "__OWRT_RC=0\n")
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
driver.manage_service("x; reboot", "start")
|
||||
assert sent == []
|
||||
|
||||
|
||||
# Busy 15 % on average since boot, 90 % in the second between the two reads.
|
||||
PROC_STAT_CPU_TWICE = """\
|
||||
cpu 1000 0 500 8500 0 0 0 0 0 0
|
||||
cpu 1090 0 500 8510 0 0 0 0 0 0
|
||||
"""
|
||||
|
||||
MEMINFO = """\
|
||||
MemTotal: 124608 kB
|
||||
MemFree: 43204 kB
|
||||
MemAvailable: 62000 kB
|
||||
"""
|
||||
|
||||
|
||||
class TestGetEnvironmentCpu:
|
||||
"""CPU usage is the second between two reads, not the average since boot (#10)."""
|
||||
|
||||
def _answer(self, driver, cpu: str) -> list:
|
||||
sent: list = []
|
||||
|
||||
def send(cmd, **kw):
|
||||
sent.append(cmd)
|
||||
return MEMINFO if "meminfo" in cmd else cpu
|
||||
|
||||
driver._send_command = send
|
||||
return sent
|
||||
|
||||
def test_usage_is_the_difference_of_two_reads(self, driver):
|
||||
self._answer(driver, PROC_STAT_CPU_TWICE)
|
||||
|
||||
assert driver.get_environment()["cpu"] == {0: {"%usage": 90.0}}
|
||||
|
||||
def test_the_two_reads_are_a_second_apart(self, driver):
|
||||
sent = self._answer(driver, PROC_STAT_CPU_TWICE)
|
||||
|
||||
driver.get_environment()
|
||||
|
||||
command = next(cmd for cmd in sent if "/proc/stat" in cmd)
|
||||
assert command.count("/proc/stat") == 2
|
||||
assert "sleep 1" in command
|
||||
|
||||
def test_counters_that_did_not_move_are_zero(self, driver):
|
||||
self._answer(driver, "cpu 1000 0 500 8500 0 0 0\ncpu 1000 0 500 8500 0 0 0\n")
|
||||
|
||||
assert driver.get_environment()["cpu"][0]["%usage"] == 0.0
|
||||
|
||||
def test_a_single_read_raises(self, driver):
|
||||
# Not taken for the usage (#10), and not reported as 0 % either (#27).
|
||||
self._answer(driver, "cpu 1000 0 500 8500 0 0 0\n")
|
||||
|
||||
with pytest.raises(ValueError, match="/proc/stat"):
|
||||
driver.get_environment()
|
||||
|
||||
def test_an_unreadable_proc_stat_raises(self, driver):
|
||||
self._answer(driver, "grep: /proc/stat: No such file or directory\n")
|
||||
|
||||
with pytest.raises(ValueError, match="/proc/stat"):
|
||||
driver.get_environment()
|
||||
|
||||
def test_a_garbled_cpu_line_raises(self, driver):
|
||||
self._answer(driver, "cpu 1000 0 500 x 0 0 0\ncpu 1090 0 500 8510 0 0 0\n")
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
driver.get_environment()
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"meminfo",
|
||||
[
|
||||
"cat: can't open '/proc/meminfo': No such file or directory",
|
||||
"MemTotal: 124608 kB\nMemFree: 43204 kB\n",
|
||||
"MemTotal: 124608 kB\nMemAvailable:\n",
|
||||
],
|
||||
)
|
||||
def test_an_unreadable_meminfo_raises(self, driver, meminfo):
|
||||
def send(cmd, **kw):
|
||||
return meminfo if "meminfo" in cmd else PROC_STAT_CPU_TWICE
|
||||
|
||||
driver._send_command = send
|
||||
|
||||
with pytest.raises(ValueError, match="/proc/meminfo"):
|
||||
driver.get_environment()
|
||||
|
||||
def test_memory_is_still_read(self, driver):
|
||||
self._answer(driver, PROC_STAT_CPU_TWICE)
|
||||
|
||||
memory = driver.get_environment()["memory"]
|
||||
|
||||
assert memory == {"available_ram": 62000 * 1024, "used_ram": (124608 - 62000) * 1024}
|
||||
@@ -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,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
|
||||
@@ -13,7 +13,7 @@ from tests.unit.test_driver import UCI_FIREWALL_HEALTHY, UCI_NETWORK_STATIC, _Fa
|
||||
|
||||
SETTINGS = {
|
||||
"community": "c0mm",
|
||||
"allowed_sources": ["10.7.224.20", "fd00::20"],
|
||||
"allowed_sources": ["198.51.100.20", "fd00::20"],
|
||||
"contact": "ops",
|
||||
"location": "rack 1",
|
||||
}
|
||||
@@ -24,7 +24,7 @@ def shell():
|
||||
return _FakeShell(
|
||||
firewall=UCI_FIREWALL_HEALTHY,
|
||||
network=UCI_NETWORK_STATIC,
|
||||
ssh_connection="10.7.224.20 51234 192.168.1.1 22",
|
||||
ssh_connection="198.51.100.20 51234 192.0.2.1 22",
|
||||
)
|
||||
|
||||
|
||||
@@ -50,7 +50,7 @@ def test_community_per_source_in_uci(owrt, shell):
|
||||
owrt.configure_snmp_agent(SETTINGS)
|
||||
|
||||
uci = _joined(shell)
|
||||
assert "uci set snmpd.public.source='10.7.224.20/32'" in uci
|
||||
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
|
||||
@@ -64,7 +64,7 @@ def test_without_sources_every_address_may_ask(owrt, shell):
|
||||
|
||||
|
||||
def test_ipv4_sources_only_keep_ipv6_to_localhost(owrt, shell):
|
||||
owrt.configure_snmp_agent({"community": "c0mm", "allowed_sources": ["10.7.224.20"]})
|
||||
owrt.configure_snmp_agent({"community": "c0mm", "allowed_sources": ["198.51.100.20"]})
|
||||
|
||||
assert "uci set snmpd.public6.source='::1/128'" in _joined(shell)
|
||||
|
||||
@@ -73,13 +73,13 @@ def test_the_firewall_rule_is_limited_to_the_sources_and_neutrally_named(owrt, s
|
||||
owrt.configure_snmp_agent(SETTINGS)
|
||||
|
||||
uci = _joined(shell)
|
||||
assert "uci add_list firewall.allow_snmp_from_lan.src_ip='10.7.224.20/32'" in uci
|
||||
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() == "10.7.224.20"
|
||||
assert owrt.get_management_peer() == "198.51.100.20"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("community", ["two words", "it's", ""])
|
||||
|
||||
@@ -34,7 +34,7 @@ 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("10.0.0.8", "admin", "s3cret", optional_args=args)
|
||||
return OpenWrtDriver("192.0.2.8", "admin", "s3cret", optional_args=args)
|
||||
|
||||
|
||||
def test_first_use_lets_netmiko_accept_and_reports_the_key():
|
||||
@@ -48,7 +48,7 @@ def test_first_use_lets_netmiko_accept_and_reports_the_key():
|
||||
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"]) == ("10.0.0.8", 2222)
|
||||
assert (seen[0]["host"], seen[0]["port"]) == ("192.0.2.8", 2222)
|
||||
|
||||
|
||||
def test_a_known_key_is_the_only_one_netmiko_accepts():
|
||||
@@ -59,7 +59,7 @@ def test_a_known_key_is_the_only_one_netmiko_accepts():
|
||||
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("10.0.0.8", 2222)
|
||||
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()
|
||||
|
||||
@@ -74,7 +74,7 @@ def test_a_changed_key_is_refused():
|
||||
|
||||
def refuse(**kwargs):
|
||||
try:
|
||||
raise paramiko.BadHostKeyException("10.0.0.8", SERVER_KEY, OTHER_KEY)
|
||||
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
|
||||
|
||||
|
||||
@@ -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