feat(firmware): offer the newest release of the line and install it with owut (NetOrk/netork#2615) #49
No files matched your search
+13
-1
@@ -7,8 +7,10 @@ recorded here; their history is the git log.
|
||||
|
||||
## [Unreleased]
|
||||
|
||||
## [0.8.0] - 2026-11-17
|
||||
|
||||
### Changed
|
||||
- Needs napalm-device-types 4.40.0 or later (`ZabbixAgentMixin`).
|
||||
- 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
|
||||
@@ -19,6 +21,16 @@ recorded here; their history is the git log.
|
||||
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
|
||||
|
||||
@@ -71,6 +71,7 @@ device.close()
|
||||
| `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
|
||||
|
||||
@@ -127,6 +128,28 @@ start it), opens tcp/`listen_port` for the allowed sources in the zone that owns
|
||||
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
|
||||
|
||||
@@ -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}
|
||||
@@ -43,6 +43,7 @@ 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
|
||||
@@ -83,6 +84,7 @@ class OpenWrtDriver(
|
||||
OpenWrtPackageMixin,
|
||||
OpenWrtRoutingMixin,
|
||||
OpenWrtScheduledJobsMixin,
|
||||
OpenWrtFirmwareMixin,
|
||||
ListeningSocketsMixin,
|
||||
HostStatusMixin,
|
||||
SnmpAgentMixin,
|
||||
|
||||
+2
-2
@@ -4,7 +4,7 @@ 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"
|
||||
@@ -21,7 +21,7 @@ classifiers = [
|
||||
]
|
||||
dependencies = [
|
||||
"napalm>=5.1", # older releases import pkg_resources, which a 3.12 venv lacks
|
||||
"napalm_device_types>=4.40.0", # ZabbixAgentMixin
|
||||
"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)
|
||||
|
||||
@@ -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"
|
||||
Reference in new issue
Block a user