fix(access-point): a change the AP refuses in apply_ap_config is raised, and nothing applied (#54)
driver / standard (pull_request) Successful in 16s
driver / lint (pull_request) Successful in 11s
driver / lowest (pull_request) Successful in 28s
driver / types (pull_request) Successful in 1m4s
driver / test (3.13) (pull_request) Successful in 54s
driver / test (3.12) (pull_request) Successful in 1m8s
driver / build (pull_request) Successful in 28s
driver / security (pull_request) Successful in 59s
CI / driver (pull_request) Successful in 2m8s
driver / publish (pull_request) Skipped
driver / standard (pull_request) Successful in 16s
driver / lint (pull_request) Successful in 11s
driver / lowest (pull_request) Successful in 28s
driver / types (pull_request) Successful in 1m4s
driver / test (3.13) (pull_request) Successful in 54s
driver / test (3.12) (pull_request) Successful in 1m8s
driver / build (pull_request) Successful in 28s
driver / security (pull_request) Successful in 59s
CI / driver (pull_request) Successful in 2m8s
driver / publish (pull_request) Skipped
The configuration ran as one detached script, so a refused uci step only reached its log while the call reported the part as applied. The changes are now staged by a script the call waits for: a uci wrapper records each refused set, add, add_list or delete with its part, and at the end every config is reverted and the script exits 3, which raises CommandErrorException naming each part, passphrases masked. Quiet -q calls stay tests. The commits, LuCI's service, the reloads and the restart run detached afterwards, as before. Closes #54
This commit is contained in:
1 parent
f71c12dfb6
commit
9bac9bd1af
6 files changed
+350
-98
No files matched your search
+5
-2
@@ -25,8 +25,11 @@ recorded here; their history is the git log.
|
|||||||
SSID's VLAN, bands, presence, encryption, key, flags, limits, MAC filter and 802.11r.
|
SSID's VLAN, bands, presence, encryption, key, flags, limits, MAC filter and 802.11r.
|
||||||
It answers which parts it wrote, which it could not (`skipped`: unknown, or a keyed
|
It answers which parts it wrote, which it could not (`skipped`: unknown, or a keyed
|
||||||
mode without its key), whether the AP restarts (a new bridge), and the script with
|
mode without its key), whether the AP restarts (a new bridge), and the script with
|
||||||
every passphrase masked. `wireless/<ssid>/passphrase` now writes the key, where
|
every passphrase masked. The changes are staged by a script the call waits for: a
|
||||||
netOrk's own builder wrote nothing for it.
|
change the AP refuses raises `CommandErrorException` naming its part, and nothing of
|
||||||
|
the configuration is applied (#54); the commits, reloads and the restart run detached
|
||||||
|
afterwards. `wireless/<ssid>/passphrase` now writes the key, where netOrk's own
|
||||||
|
builder wrote nothing for it.
|
||||||
- `get_dhcp_leases()` (`DhcpLeasesMixin`): dnsmasq's DHCPv4 leases from its lease file;
|
- `get_dhcp_leases()` (`DhcpLeasesMixin`): dnsmasq's DHCPv4 leases from its lease file;
|
||||||
`[]` where dnsmasq never ran, a raise where the file cannot be read.
|
`[]` where dnsmasq never ran, a raise where the file cannot be read.
|
||||||
|
|
||||||
|
|||||||
@@ -176,7 +176,7 @@ reverted, and nothing is committed or restarted.
|
|||||||
## AP configuration
|
## AP configuration
|
||||||
|
|
||||||
`apply_ap_config(config, parts)` (napalm-device-types `ApConfigMixin`) writes the parts of
|
`apply_ap_config(config, parts)` (napalm-device-types `ApConfigMixin`) writes the parts of
|
||||||
an `ApConfigDict` the caller names as one shell script: the radios (country, 5 and 2.4
|
an `ApConfigDict` the caller names as UCI changes: the radios (country, 5 and 2.4
|
||||||
GHz `htmode`), remote syslog, LuCI (`uhttpd` enabled or stopped), dropbear's port and
|
GHz `htmode`), remote syslog, LuCI (`uhttpd` enabled or stopped), dropbear's port and
|
||||||
password logins, the `br-ap` bridge with VLAN filtering on `eth0` (every VLAN tagged, the
|
password logins, the `br-ap` bridge with VLAN filtering on `eth0` (every VLAN tagged, the
|
||||||
management VLAN untagged where asked), one VLAN of it, its spanning tree, and per SSID its
|
management VLAN untagged where asked), one VLAN of it, its spanning tree, and per SSID its
|
||||||
@@ -185,12 +185,21 @@ VLAN (`ap_vlan<vid>`), bands, presence, encryption and key, flags, limits, MAC f
|
|||||||
written without its key, a whitelist without MACs is written as no filter, and a part the
|
written without its key, a whitelist without MACs is written as no filter, and a part the
|
||||||
driver does not know or whose values are missing comes back in `skipped`.
|
driver does not know or whose values are missing comes back in `skipped`.
|
||||||
|
|
||||||
The script is written as root from stdin into a fresh `mktemp -d` directory
|
Two scripts are written as root from stdin into a fresh `mktemp -d` directory
|
||||||
(`/tmp/openwrt-apply.XXXXXX`) and run detached, since it may cut the session; its output
|
(`/tmp/openwrt-apply.XXXXXX`):
|
||||||
stays in `apply.log` there. Rebuilding the bridge restarts the AP (`restarts`); otherwise
|
|
||||||
the configs are committed and network, wifi, system, dropbear and the firewall reloaded as
|
- `stage.sh` stages the changes without committing them, so the running AP is untouched,
|
||||||
needed. The result carries the script with every passphrase masked. A step that fails
|
and the call waits for it. A change `uci` refuses (`set`, `add`, `add_list`, `delete`,
|
||||||
inside the script is in the log, not raised: the script has left the session by then.
|
...) is recorded with its part; at the end every config is reverted and the call raises
|
||||||
|
`CommandErrorException` naming each refused part and what `uci` said, passphrases
|
||||||
|
masked. Nothing of the configuration is applied then (NAPALM/napalm-openwrt#54). A quiet
|
||||||
|
`uci -q` call, such as deleting an option that may be missing, is no refusal. The script
|
||||||
|
removes itself as it starts, since it holds the passphrases.
|
||||||
|
- `apply.sh` commits, enables or stops LuCI, and reloads network, wifi, system, dropbear and
|
||||||
|
the firewall as needed, or restarts the AP when the bridge was rebuilt (`restarts`). It
|
||||||
|
runs detached, since it may cut the session; its output stays in `apply.log` there.
|
||||||
|
|
||||||
|
The result carries both scripts with every passphrase masked.
|
||||||
|
|
||||||
## Time sync
|
## Time sync
|
||||||
|
|
||||||
|
|||||||
@@ -13,19 +13,27 @@
|
|||||||
|
|
||||||
"""The access point's configuration applied as desired state (``ApConfigMixin``).
|
"""The access point's configuration applied as desired state (``ApConfigMixin``).
|
||||||
|
|
||||||
The caller names the parts that differ; :func:`build_script` turns the values
|
The caller names the parts that differ; :func:`build_scripts` turns the values those
|
||||||
those parts need into one shell script of ``uci`` commands, the commits and the
|
parts need into two shell scripts:
|
||||||
reloads that apply them. The script reconfigures the AP and may cut the session --
|
|
||||||
rebuilding the bridge restarts the AP -- so it runs detached, its output in a log
|
* **stage** -- the ``uci`` changes, staged but not committed, so the running device
|
||||||
on the AP.
|
is untouched. The call waits for it. A change ``uci`` refuses is recorded with its
|
||||||
|
part; at the end every config is reverted and the script exits 3 with the
|
||||||
|
refusals, so nothing of the configuration applies and the call raises (#54).
|
||||||
|
* **apply** -- the commits, what changes the running device (LuCI's service), and the
|
||||||
|
reloads or the restart. It reconfigures the AP and may cut the session --
|
||||||
|
rebuilding the bridge restarts the AP -- so it runs detached, its output in a log
|
||||||
|
on the AP.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import logging
|
import logging
|
||||||
import re
|
import re
|
||||||
|
from dataclasses import dataclass
|
||||||
from typing import TYPE_CHECKING
|
from typing import TYPE_CHECKING
|
||||||
|
|
||||||
|
from napalm.base.exceptions import CommandErrorException
|
||||||
from napalm_device_types import (
|
from napalm_device_types import (
|
||||||
ApConfigDict,
|
ApConfigDict,
|
||||||
ApConfigMixin,
|
ApConfigMixin,
|
||||||
@@ -53,8 +61,31 @@ RESTARTING_PARTS = frozenset({"network/bridge"})
|
|||||||
WORKDIR_TEMPLATE = "/tmp/openwrt-apply.XXXXXX" # nosec B108 - on the AP, root's own 0700 dir
|
WORKDIR_TEMPLATE = "/tmp/openwrt-apply.XXXXXX" # nosec B108 - on the AP, root's own 0700 dir
|
||||||
_WORKDIR_RE = re.compile(r"/tmp/openwrt-apply\.[A-Za-z0-9]{6}") # nosec B108
|
_WORKDIR_RE = re.compile(r"/tmp/openwrt-apply\.[A-Za-z0-9]{6}") # nosec B108
|
||||||
|
|
||||||
#: What a passphrase shows as in the script the result carries.
|
#: What a passphrase shows as in the script the result carries, quoted and as a word.
|
||||||
MASK = "'********'"
|
MASK = "'********'"
|
||||||
|
_MASK_WORD = "********"
|
||||||
|
#: Seconds the stage script may take: a few hundred ``uci`` calls.
|
||||||
|
STAGE_TIMEOUT = 120
|
||||||
|
#: The stage script's exit status when ``uci`` refused a change.
|
||||||
|
REFUSED = 3
|
||||||
|
|
||||||
|
#: The ``uci`` verbs that change a config; a refusal of any is a refused part. A read
|
||||||
|
#: (``get``, ``show``) or a quiet ``-q`` call may fail on purpose, as a test.
|
||||||
|
_STAGE_PRELUDE = """#!/bin/sh
|
||||||
|
rm -f "$0"
|
||||||
|
_refused="${0%/*}/refused"
|
||||||
|
: > "$_refused"
|
||||||
|
_part=''
|
||||||
|
uci() {
|
||||||
|
case "$1" in
|
||||||
|
set|add|add_list|del_list|delete|rename|reorder) ;;
|
||||||
|
*) command uci "$@"; return ;;
|
||||||
|
esac
|
||||||
|
_out=$(command uci "$@" 2>&1) && { [ -z "$_out" ] || echo "$_out"; return 0; }
|
||||||
|
_rc=$?
|
||||||
|
echo "$_part: uci $*: $_out" >> "$_refused"
|
||||||
|
return $_rc
|
||||||
|
}"""
|
||||||
|
|
||||||
_SHOW_WIRELESS = "uci -q show wireless"
|
_SHOW_WIRELESS = "uci -q show wireless"
|
||||||
|
|
||||||
@@ -73,6 +104,32 @@ _RELOADS = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _stage_epilogue(configs: set[str]) -> str:
|
||||||
|
"""Revert every config and exit ``REFUSED`` with the refusals, if there were any."""
|
||||||
|
reverts = " ".join(sorted(configs)) or "wireless"
|
||||||
|
return "\n".join(
|
||||||
|
[
|
||||||
|
'if [ -s "$_refused" ]; then',
|
||||||
|
f' for _c in {reverts}; do command uci revert "$_c"; done',
|
||||||
|
' cat "$_refused" >&2',
|
||||||
|
f" exit {REFUSED}",
|
||||||
|
"fi",
|
||||||
|
'rm -f "$_refused"',
|
||||||
|
]
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@dataclass(frozen=True)
|
||||||
|
class ApScripts:
|
||||||
|
"""The stage and apply scripts of a configuration; both "" when it writes nothing."""
|
||||||
|
|
||||||
|
stage: str
|
||||||
|
apply: str
|
||||||
|
applied: list[str]
|
||||||
|
skipped: list[str]
|
||||||
|
restarts: bool
|
||||||
|
|
||||||
|
|
||||||
def _build_part(part: str, config: ApConfigDict, radios: Radios, plan: Plan) -> None:
|
def _build_part(part: str, config: ApConfigDict, radios: Radios, plan: Plan) -> None:
|
||||||
if part.startswith("radio/"):
|
if part.startswith("radio/"):
|
||||||
radio_part(part, config, radios, plan)
|
radio_part(part, config, radios, plan)
|
||||||
@@ -93,8 +150,9 @@ def build_commands(
|
|||||||
) -> tuple[Plan, list[str], list[str]]:
|
) -> tuple[Plan, list[str], list[str]]:
|
||||||
"""The commands for *parts*, and which parts they write and which they cannot.
|
"""The commands for *parts*, and which parts they write and which they cannot.
|
||||||
|
|
||||||
A VLAN is part of the bridge: with ``network/bridge`` among the parts, a
|
Each part's commands follow a ``_part=`` line naming it, so the stage script
|
||||||
``network/vlan/<vid>`` is written by it.
|
can say which part a refused change belongs to. A VLAN is part of the bridge:
|
||||||
|
with ``network/bridge`` among the parts, a ``network/vlan/<vid>`` is written by it.
|
||||||
"""
|
"""
|
||||||
plan = Plan()
|
plan = Plan()
|
||||||
applied: list[str] = []
|
applied: list[str] = []
|
||||||
@@ -107,40 +165,47 @@ def build_commands(
|
|||||||
if rebuilds_bridge and ap_config_vlan_part(part) is not None:
|
if rebuilds_bridge and ap_config_vlan_part(part) is not None:
|
||||||
applied.append(part)
|
applied.append(part)
|
||||||
continue
|
continue
|
||||||
before = len(plan.commands)
|
before = len(plan.commands) + len(plan.actions)
|
||||||
|
plan.commands.append(f"_part={sq(part)}")
|
||||||
_build_part(part, config, radios, plan)
|
_build_part(part, config, radios, plan)
|
||||||
(applied if len(plan.commands) > before else skipped).append(part)
|
if len(plan.commands) + len(plan.actions) > before + 1:
|
||||||
|
applied.append(part)
|
||||||
|
else:
|
||||||
|
plan.commands.pop()
|
||||||
|
skipped.append(part)
|
||||||
return plan, applied, skipped
|
return plan, applied, skipped
|
||||||
|
|
||||||
|
|
||||||
def build_script(
|
def _apply_script(plan: Plan, restarts: bool) -> str:
|
||||||
config: ApConfigDict, parts: list[str], radios: Radios
|
"""The commits, then what is live, then the reloads -- or the restart, which applies it all."""
|
||||||
) -> tuple[str, list[str], list[str], bool]:
|
lines = ["#!/bin/sh"]
|
||||||
"""The script for *parts*: ``(script, applied, skipped, restarts)``; "" when it writes nothing.
|
|
||||||
|
|
||||||
A script that restarts the AP reloads nothing first: the restart applies it all.
|
|
||||||
"""
|
|
||||||
plan, applied, skipped = build_commands(config, parts, radios)
|
|
||||||
if not plan.commands:
|
|
||||||
return "", applied, skipped, False
|
|
||||||
restarts = bool(RESTARTING_PARTS & set(applied))
|
|
||||||
lines = ["#!/bin/sh", *plan.commands]
|
|
||||||
lines += [f"uci commit {config_name}" for config_name in sorted(plan.commits)]
|
lines += [f"uci commit {config_name}" for config_name in sorted(plan.commits)]
|
||||||
|
lines += plan.actions
|
||||||
if restarts:
|
if restarts:
|
||||||
lines.append("reboot")
|
lines.append("reboot")
|
||||||
else:
|
else:
|
||||||
for config_name, reloads in _RELOADS.items():
|
for config_name, reloads in _RELOADS.items():
|
||||||
if config_name in plan.commits:
|
if config_name in plan.commits:
|
||||||
lines += reloads
|
lines += reloads
|
||||||
return "\n".join(lines), applied, skipped, restarts
|
return "\n".join(lines)
|
||||||
|
|
||||||
|
|
||||||
def masked(script: str, config: ApConfigDict) -> str:
|
def build_scripts(config: ApConfigDict, parts: list[str], radios: Radios) -> ApScripts:
|
||||||
"""*script* with every passphrase of *config* as ``MASK``."""
|
"""The stage and apply scripts for *parts*; see the module."""
|
||||||
|
plan, applied, skipped = build_commands(config, parts, radios)
|
||||||
|
if not applied:
|
||||||
|
return ApScripts("", "", applied, skipped, False)
|
||||||
|
restarts = bool(RESTARTING_PARTS & set(applied))
|
||||||
|
stage = "\n".join([_STAGE_PRELUDE, *plan.commands, _stage_epilogue(plan.commits)])
|
||||||
|
return ApScripts(stage, _apply_script(plan, restarts), applied, skipped, restarts)
|
||||||
|
|
||||||
|
|
||||||
|
def masked(text: str, config: ApConfigDict) -> str:
|
||||||
|
"""*text* with every passphrase of *config* masked: quoted as ``MASK``, bare as a word."""
|
||||||
for ssid in config.get("ssids") or []:
|
for ssid in config.get("ssids") or []:
|
||||||
if key := ssid.get("key"):
|
if key := ssid.get("key"):
|
||||||
script = script.replace(sq(key), MASK)
|
text = text.replace(sq(key), MASK).replace(key, _MASK_WORD)
|
||||||
return script
|
return text
|
||||||
|
|
||||||
|
|
||||||
class OpenWrtApConfigMixin(ApConfigMixin, UciStepsMixin):
|
class OpenWrtApConfigMixin(ApConfigMixin, UciStepsMixin):
|
||||||
@@ -159,60 +224,92 @@ class OpenWrtApConfigMixin(ApConfigMixin, UciStepsMixin):
|
|||||||
) -> CommandResult: ...
|
) -> CommandResult: ...
|
||||||
|
|
||||||
def apply_ap_config(self, config: ApConfigDict, parts: list[str]) -> ApConfigResultDict:
|
def apply_ap_config(self, config: ApConfigDict, parts: list[str]) -> ApConfigResultDict:
|
||||||
"""Write the *parts* of *config* (``ApConfigMixin``) with one detached script.
|
"""Write the *parts* of *config* (``ApConfigMixin``): staged, then applied detached.
|
||||||
|
|
||||||
The radios are read first (``uci show wireless``): the 5 GHz and 2.4 GHz
|
The radios are read first (``uci show wireless``): the 5 GHz and 2.4 GHz
|
||||||
ones by their ``band``. A part whose values *config* lacks, or that this
|
ones by their ``band``. A part whose values *config* lacks, or that this
|
||||||
driver does not know, is written not at all and comes back in ``skipped``.
|
driver does not know, is written not at all and comes back in ``skipped``.
|
||||||
|
|
||||||
:raises CommandErrorException: when the radios cannot be read.
|
:raises CommandErrorException: when the radios cannot be read, or the AP
|
||||||
:raises RuntimeError: when the script cannot be written to the AP.
|
refused a change; then nothing of the configuration is applied, and the
|
||||||
|
message names each refused part with what ``uci`` said (passphrases masked).
|
||||||
|
:raises RuntimeError: when the scripts cannot be written to the AP.
|
||||||
"""
|
"""
|
||||||
radios = radios_of(parse_uci_show(self._uci_step(_SHOW_WIRELESS)))
|
radios = radios_of(parse_uci_show(self._uci_step(_SHOW_WIRELESS)))
|
||||||
script, applied, skipped, restarts = build_script(config, list(parts), radios)
|
scripts = build_scripts(config, list(parts), radios)
|
||||||
if not script:
|
if not scripts.stage:
|
||||||
return {"applied": [], "skipped": skipped, "restarts": False, "commands": "", "log": ""}
|
empty: ApConfigResultDict = {
|
||||||
workdir = self._run_detached(script)
|
"applied": [],
|
||||||
|
"skipped": scripts.skipped,
|
||||||
|
"restarts": False,
|
||||||
|
"commands": "",
|
||||||
|
"log": "",
|
||||||
|
}
|
||||||
|
return empty
|
||||||
|
workdir = self._write_scripts(scripts)
|
||||||
|
self._stage(workdir, config)
|
||||||
|
self._start_apply(workdir)
|
||||||
return {
|
return {
|
||||||
"applied": applied,
|
"applied": scripts.applied,
|
||||||
"skipped": skipped,
|
"skipped": scripts.skipped,
|
||||||
"restarts": restarts,
|
"restarts": scripts.restarts,
|
||||||
"commands": masked(script, config),
|
"commands": masked(f"{scripts.stage}\n{scripts.apply}", config),
|
||||||
"log": f"{workdir}/apply.log",
|
"log": f"{workdir}/apply.log",
|
||||||
}
|
}
|
||||||
|
|
||||||
def _run_detached(self, script: str) -> str:
|
def _write_scripts(self, scripts: ApScripts) -> str:
|
||||||
"""Write *script* to the AP from stdin and run it detached; returns its directory.
|
"""Write both scripts to the AP from stdin; returns their directory.
|
||||||
|
|
||||||
Root writes the script, passphrases and all, into a directory of its own
|
Root writes them, passphrases and all, into a directory of its own (``mktemp
|
||||||
(``mktemp -d``: mode 0700, a name nobody knows in advance), never to a fixed
|
-d``: mode 0700, a name nobody knows in advance), never to a fixed /tmp name
|
||||||
/tmp name another account could have placed or could swap between the write
|
another account could have placed or could swap between the write and the run.
|
||||||
and the run. The script goes once it has run; the log stays.
|
|
||||||
"""
|
"""
|
||||||
written = self.run_command(
|
written = self.run_command(
|
||||||
f'umask 077 && d=$(mktemp -d {WORKDIR_TEMPLATE}) && cat > "$d/apply.sh" && echo "$d"',
|
f'umask 077 && d=$(mktemp -d {WORKDIR_TEMPLATE}) && cat > "$d/stage.sh" && echo "$d"',
|
||||||
privileged=True,
|
privileged=True,
|
||||||
stdin=script.encode(),
|
stdin=scripts.stage.encode(),
|
||||||
)
|
|
||||||
if written.exit_code:
|
|
||||||
raise RuntimeError(
|
|
||||||
f"{self.hostname}: could not write the configuration script: "
|
|
||||||
f"{written.stderr.strip() or written.stdout.strip()}"
|
|
||||||
)
|
)
|
||||||
|
self._check(written, "could not write the configuration script")
|
||||||
workdir = written.stdout.strip()
|
workdir = written.stdout.strip()
|
||||||
if not _WORKDIR_RE.fullmatch(workdir):
|
if not _WORKDIR_RE.fullmatch(workdir):
|
||||||
raise RuntimeError(f"{self.hostname}: the AP named no work directory: {workdir!r}")
|
raise RuntimeError(f"{self.hostname}: the AP named no work directory: {workdir!r}")
|
||||||
|
self._check(
|
||||||
|
self.run_command(
|
||||||
|
f"umask 077 && cat > {workdir}/apply.sh",
|
||||||
|
privileged=True,
|
||||||
|
stdin=scripts.apply.encode(),
|
||||||
|
),
|
||||||
|
"could not write the configuration script",
|
||||||
|
)
|
||||||
|
return workdir
|
||||||
|
|
||||||
|
def _stage(self, workdir: str, config: ApConfigDict) -> None:
|
||||||
|
"""Run the stage script and wait for it; a refusal raises, nothing applied."""
|
||||||
|
staged = self.run_command(f"sh {workdir}/stage.sh", privileged=True, timeout=STAGE_TIMEOUT)
|
||||||
|
if staged.exit_code == 0:
|
||||||
|
return
|
||||||
|
self.run_command(f"rm -rf {workdir}", privileged=True)
|
||||||
|
said = staged.stderr.strip() or staged.stdout.strip() or f"exit status {staged.exit_code}"
|
||||||
|
raise CommandErrorException(
|
||||||
|
masked(
|
||||||
|
f"{self.hostname}: the AP refused the configuration, nothing of it is applied: "
|
||||||
|
f"{said}",
|
||||||
|
config,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
def _start_apply(self, workdir: str) -> None:
|
||||||
|
"""Run the apply script detached: it may cut the session. The script goes once
|
||||||
|
it has run; the log stays."""
|
||||||
started = self.run_command(
|
started = self.run_command(
|
||||||
f"( sh {workdir}/apply.sh > {workdir}/apply.log 2>&1 < /dev/null; "
|
f"( sh {workdir}/apply.sh > {workdir}/apply.log 2>&1 < /dev/null; "
|
||||||
f"rm -f {workdir}/apply.sh ) &",
|
f"rm -f {workdir}/apply.sh ) &",
|
||||||
privileged=True,
|
privileged=True,
|
||||||
)
|
)
|
||||||
if started.exit_code:
|
self._check(started, "could not start the configuration script")
|
||||||
raise RuntimeError(
|
logger.info("%s: configuration applying; its log is %s/apply.log", self.hostname, workdir)
|
||||||
f"{self.hostname}: could not start the configuration script: "
|
|
||||||
f"{started.stderr.strip() or started.stdout.strip()}"
|
def _check(self, result: CommandResult, what: str) -> None:
|
||||||
)
|
if result.exit_code:
|
||||||
logger.info(
|
said = result.stderr.strip() or result.stdout.strip()
|
||||||
"%s: configuration script started; its log is %s/apply.log", self.hostname, workdir
|
raise RuntimeError(f"{self.hostname}: {what}: {said}")
|
||||||
)
|
|
||||||
return workdir
|
|
||||||
@@ -47,10 +47,15 @@ def sq(value: object) -> str:
|
|||||||
|
|
||||||
@dataclass
|
@dataclass
|
||||||
class Plan:
|
class Plan:
|
||||||
"""The commands built so far, and the configs they stage for a commit."""
|
"""The commands built so far, the configs they stage for a commit, and what runs live.
|
||||||
|
|
||||||
|
``commands`` only stage UCI changes, which the device does not run until they are
|
||||||
|
committed; ``actions`` change the running device and come after the commits.
|
||||||
|
"""
|
||||||
|
|
||||||
commands: list[str] = field(default_factory=list)
|
commands: list[str] = field(default_factory=list)
|
||||||
commits: set[str] = field(default_factory=set)
|
commits: set[str] = field(default_factory=set)
|
||||||
|
actions: list[str] = field(default_factory=list)
|
||||||
|
|
||||||
|
|
||||||
@dataclass(frozen=True)
|
@dataclass(frozen=True)
|
||||||
|
|||||||
@@ -70,9 +70,9 @@ def _web_ui(config: ApConfigDict, plan: Plan) -> None:
|
|||||||
if "web_ui" not in config:
|
if "web_ui" not in config:
|
||||||
return
|
return
|
||||||
if config["web_ui"]:
|
if config["web_ui"]:
|
||||||
plan.commands.append("/etc/init.d/uhttpd enable && /etc/init.d/uhttpd start")
|
plan.actions.append("/etc/init.d/uhttpd enable && /etc/init.d/uhttpd start")
|
||||||
else:
|
else:
|
||||||
plan.commands.append("/etc/init.d/uhttpd stop; /etc/init.d/uhttpd disable")
|
plan.actions.append("/etc/init.d/uhttpd stop; /etc/init.d/uhttpd disable")
|
||||||
|
|
||||||
|
|
||||||
def _ssh_port(config: ApConfigDict, plan: Plan) -> None:
|
def _ssh_port(config: ApConfigDict, plan: Plan) -> None:
|
||||||
|
|||||||
+164
-26
@@ -1,9 +1,13 @@
|
|||||||
"""``apply_ap_config``: an access point's desired configuration as one UCI script (NetOrk/netork#695).
|
"""``apply_ap_config``: an access point's desired configuration as UCI scripts (NetOrk/netork#695).
|
||||||
|
|
||||||
netOrk built this script itself, from its AP profile, and uploaded it through the
|
netOrk built this script itself, from its AP profile, and uploaded it through the
|
||||||
driver's ``run_command``. The builders moved here unchanged in what they write; what
|
driver's ``run_command``. The builders moved here unchanged in what they write; what
|
||||||
comes in is napalm-device-types' ``ApConfigDict`` and the parts the caller found
|
comes in is napalm-device-types' ``ApConfigDict`` and the parts the caller found
|
||||||
different. ``uci -q show wireless`` is the shape of ``test_wireless_writes``.
|
different. ``uci -q show wireless`` is the shape of ``test_wireless_writes``.
|
||||||
|
|
||||||
|
The changes are staged by a script the call waits for, so a step the AP refuses is
|
||||||
|
raised and nothing of it applied (#54); the commits, reloads and the restart run
|
||||||
|
detached afterwards, since they may cut the session.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
@@ -11,9 +15,10 @@ from __future__ import annotations
|
|||||||
import subprocess
|
import subprocess
|
||||||
|
|
||||||
import pytest
|
import pytest
|
||||||
|
from napalm.base.exceptions import CommandErrorException
|
||||||
from napalm_device_types import ApConfigDict, ApSsidConfigDict, CommandResult
|
from napalm_device_types import ApConfigDict, ApSsidConfigDict, CommandResult
|
||||||
|
|
||||||
from napalm_openwrt.ap_config import MASK, build_script, masked
|
from napalm_openwrt.ap_config import MASK, build_commands, build_scripts, masked
|
||||||
from napalm_openwrt.ap_config._common import Radios, radios_of
|
from napalm_openwrt.ap_config._common import Radios, radios_of
|
||||||
from napalm_openwrt.uci_steps import parse_uci_show
|
from napalm_openwrt.uci_steps import parse_uci_show
|
||||||
from tests.unit.test_wireless_writes import SHOW, WIRELESS, _driver
|
from tests.unit.test_wireless_writes import SHOW, WIRELESS, _driver
|
||||||
@@ -65,8 +70,10 @@ def _config(**fields: object) -> ApConfigDict:
|
|||||||
|
|
||||||
|
|
||||||
def _build(parts: list[str], config: ApConfigDict | None = None, radios: Radios = RADIOS):
|
def _build(parts: list[str], config: ApConfigDict | None = None, radios: Radios = RADIOS):
|
||||||
script, applied, skipped, restarts = build_script(config or _config(), parts, radios)
|
"""``(stage + apply, applied, skipped, restarts)``; "" when nothing is written."""
|
||||||
return script, applied, skipped, restarts
|
scripts = build_scripts(config or _config(), parts, radios)
|
||||||
|
script = f"{scripts.stage}\n{scripts.apply}" if scripts.stage else ""
|
||||||
|
return script, scripts.applied, scripts.skipped, scripts.restarts
|
||||||
|
|
||||||
|
|
||||||
def _script(parts: list[str], config: ApConfigDict | None = None, radios: Radios = RADIOS) -> str:
|
def _script(parts: list[str], config: ApConfigDict | None = None, radios: Radios = RADIOS) -> str:
|
||||||
@@ -432,17 +439,16 @@ def _run(command: str, ssid: str, tmp_path) -> list[str]:
|
|||||||
return log.read_text().splitlines()
|
return log.read_text().splitlines()
|
||||||
|
|
||||||
|
|
||||||
def _loop(script: str) -> str:
|
def _loop(parts: list[str], config: ApConfigDict) -> str:
|
||||||
"""The ssid loop of a one-part script: between the shebang and the commits."""
|
"""The commands of the parts, without the stage script's own lines around them."""
|
||||||
lines = script.split("\n")
|
plan = build_commands(config, parts, RADIOS)[0]
|
||||||
end = next(i for i, c in enumerate(lines) if c.startswith("uci commit"))
|
return "\n".join(c for c in plan.commands if not c.startswith("_part="))
|
||||||
return "\n".join(lines[1:end])
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("value", NASTY)
|
@pytest.mark.parametrize("value", NASTY)
|
||||||
def test_a_passphrase_arrives_as_it_is(value, tmp_path):
|
def test_a_passphrase_arrives_as_it_is(value, tmp_path):
|
||||||
script = _script(["wireless/Home/encryption"], _config(ssids=[_ssid(name="Home", key=value)]))
|
config = _config(ssids=[_ssid(name="Home", key=value)])
|
||||||
assert _run(_loop(script), "Home", tmp_path) == [
|
assert _run(_loop(["wireless/Home/encryption"], config), "Home", tmp_path) == [
|
||||||
"wireless.default_radio0.encryption=psk2",
|
"wireless.default_radio0.encryption=psk2",
|
||||||
f"wireless.default_radio0.key={value}",
|
f"wireless.default_radio0.key={value}",
|
||||||
]
|
]
|
||||||
@@ -451,28 +457,136 @@ def test_a_passphrase_arrives_as_it_is(value, tmp_path):
|
|||||||
|
|
||||||
@pytest.mark.parametrize("value", NASTY)
|
@pytest.mark.parametrize("value", NASTY)
|
||||||
def test_an_ssid_name_is_matched_as_it_is(value, tmp_path):
|
def test_an_ssid_name_is_matched_as_it_is(value, tmp_path):
|
||||||
script = _script([f"wireless/{value}/hidden"], _config(ssids=[_ssid(name=value, hidden=True)]))
|
config = _config(ssids=[_ssid(name=value, hidden=True)])
|
||||||
assert _run(_loop(script), value, tmp_path) == ["wireless.default_radio0.hidden=1"]
|
loop = _loop([f"wireless/{value}/hidden"], config)
|
||||||
|
assert _run(loop, value, tmp_path) == ["wireless.default_radio0.hidden=1"]
|
||||||
|
|
||||||
|
|
||||||
def test_a_mac_arrives_as_it_is(tmp_path):
|
def test_a_mac_arrives_as_it_is(tmp_path):
|
||||||
mac = "AA:BB:CC:DD:EE:01'; touch pwned; echo '"
|
mac = "AA:BB:CC:DD:EE:01'; touch pwned; echo '"
|
||||||
config = _config(ssids=[_ssid(name="Home", acl_mode="whitelist", acl_macs=[mac])])
|
config = _config(ssids=[_ssid(name="Home", acl_mode="whitelist", acl_macs=[mac])])
|
||||||
script = _script(["wireless/Home/acl"], config)
|
loop = _loop(["wireless/Home/acl"], config)
|
||||||
assert _run(_loop(script), "Home", tmp_path)[-1] == f"wireless.default_radio0.maclist={mac}"
|
assert _run(loop, "Home", tmp_path)[-1] == f"wireless.default_radio0.maclist={mac}"
|
||||||
assert not (tmp_path / "pwned").exists()
|
assert not (tmp_path / "pwned").exists()
|
||||||
|
|
||||||
|
|
||||||
|
# -- the stage script: a refused step is reported, and nothing applied (#54) -----------------
|
||||||
|
|
||||||
|
#: A ``uci`` on PATH that knows one interface serving Corp, logs every call, and
|
||||||
|
#: refuses those whose words hold $REFUSE.
|
||||||
|
_FAKE_UCI_BIN = """#!/bin/sh
|
||||||
|
echo "$*" >> "$LOG"
|
||||||
|
if [ -n "$REFUSE" ] && echo "$*" | grep -qF -- "$REFUSE"; then
|
||||||
|
echo "uci: Invalid argument" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
case "$1" in
|
||||||
|
show) echo "wireless.default_radio0.ssid='Corp'" ;;
|
||||||
|
-q) [ "$2" = get ] || exit 0
|
||||||
|
[ "$3" = wireless.default_radio0.ssid ] && { echo Corp; exit 0; }
|
||||||
|
exit 1 ;;
|
||||||
|
esac
|
||||||
|
exit 0
|
||||||
|
"""
|
||||||
|
|
||||||
|
|
||||||
|
def _stage(tmp_path, parts: list[str], refuse: str = "", config: ApConfigDict | None = None):
|
||||||
|
"""Run the stage script of *parts* through /bin/sh against the fake ``uci``."""
|
||||||
|
bin_dir = tmp_path / "bin"
|
||||||
|
bin_dir.mkdir(exist_ok=True)
|
||||||
|
fake = bin_dir / "uci"
|
||||||
|
fake.write_text(_FAKE_UCI_BIN)
|
||||||
|
fake.chmod(0o755)
|
||||||
|
log = tmp_path / "uci.log"
|
||||||
|
log.touch()
|
||||||
|
script = tmp_path / "stage.sh"
|
||||||
|
script.write_text(build_scripts(config or _config(), parts, RADIOS).stage)
|
||||||
|
done = subprocess.run( # nosec B603 - a fixed /bin/sh on the test's own script
|
||||||
|
["/bin/sh", str(script)],
|
||||||
|
env={"LOG": str(log), "REFUSE": refuse, "PATH": f"{bin_dir}:/usr/bin:/bin"},
|
||||||
|
capture_output=True,
|
||||||
|
text=True,
|
||||||
|
cwd=tmp_path,
|
||||||
|
)
|
||||||
|
return done, log.read_text().splitlines()
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_stage_that_goes_through_commits_nothing(tmp_path):
|
||||||
|
"""The commits are the detached script's; staging leaves the device running as it is."""
|
||||||
|
done, calls = _stage(tmp_path, ["system/ssh_port", "wireless/Corp/hidden"])
|
||||||
|
|
||||||
|
assert done.returncode == 0, done.stderr
|
||||||
|
assert "set dropbear.@dropbear[0].Port=22" in calls
|
||||||
|
assert not any(c.startswith(("commit", "revert")) for c in calls)
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_refused_step_reverts_every_config_and_names_its_part(tmp_path):
|
||||||
|
done, calls = _stage(
|
||||||
|
tmp_path, ["system/ssh_port", "radio/country"], refuse="dropbear.@dropbear[0].Port"
|
||||||
|
)
|
||||||
|
|
||||||
|
assert done.returncode == 3
|
||||||
|
assert "system/ssh_port: uci set dropbear.@dropbear[0].Port=22" in done.stderr
|
||||||
|
assert "uci: Invalid argument" in done.stderr
|
||||||
|
assert "radio/country" not in done.stderr
|
||||||
|
assert {"revert dropbear", "revert wireless"} <= set(calls)
|
||||||
|
assert not any(c.startswith("commit") for c in calls)
|
||||||
|
|
||||||
|
|
||||||
|
def test_every_refused_part_is_named(tmp_path):
|
||||||
|
done, _ = _stage(tmp_path, ["radio/country", "radio/5g_htmode"], refuse="radio1")
|
||||||
|
|
||||||
|
assert "radio/country: uci set wireless.radio1.country=DE" in done.stderr
|
||||||
|
assert "radio/5g_htmode: uci set wireless.radio1.htmode=VHT80" in done.stderr
|
||||||
|
|
||||||
|
|
||||||
|
def test_a_quiet_delete_of_a_missing_option_is_no_refusal(tmp_path):
|
||||||
|
"""``uci -q delete`` of an option the section lacks exits 1; the builders count on it."""
|
||||||
|
config = _config(ssids=[_ssid(acl_mode="off")])
|
||||||
|
done, calls = _stage(tmp_path, ["wireless/Corp/acl"], refuse="-q delete", config=config)
|
||||||
|
|
||||||
|
assert done.returncode == 0, done.stderr
|
||||||
|
assert "-q delete wireless.default_radio0.macfilter" in calls
|
||||||
|
assert not any(c.startswith("revert") for c in calls)
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_stage_script_removes_itself(tmp_path):
|
||||||
|
"""It holds the passphrases; the AP keeps it no longer than it runs."""
|
||||||
|
_stage(tmp_path, ["wireless/Corp/encryption"])
|
||||||
|
|
||||||
|
assert not (tmp_path / "stage.sh").exists()
|
||||||
|
|
||||||
|
|
||||||
|
def test_the_detached_script_commits_reloads_and_starts_what_is_live():
|
||||||
|
scripts = build_scripts(
|
||||||
|
_config(web_ui=False), ["system/web_ui", "wireless/Corp/hidden"], RADIOS
|
||||||
|
)
|
||||||
|
|
||||||
|
assert "uhttpd" not in scripts.stage
|
||||||
|
assert scripts.apply.split("\n") == [
|
||||||
|
"#!/bin/sh",
|
||||||
|
"uci commit wireless",
|
||||||
|
"/etc/init.d/uhttpd stop; /etc/init.d/uhttpd disable",
|
||||||
|
"wifi reload 2>&1; true",
|
||||||
|
]
|
||||||
|
|
||||||
|
|
||||||
# -- apply_ap_config ---------------------------------------------------------------------------
|
# -- apply_ap_config ---------------------------------------------------------------------------
|
||||||
|
|
||||||
WORKDIR = "/tmp/openwrt-apply.Ab12Cd"
|
WORKDIR = "/tmp/openwrt-apply.Ab12Cd"
|
||||||
|
STAGE = f"sh {WORKDIR}/stage.sh"
|
||||||
|
|
||||||
|
|
||||||
class _ApplyAp:
|
class _ApplyAp:
|
||||||
"""``run_command`` of an AP that answers the read and makes the work directory."""
|
"""``run_command`` of an AP: answers the read, makes the work directory, stages."""
|
||||||
|
|
||||||
def __init__(self, made: str = WORKDIR, write: CommandResult | None = None) -> None:
|
def __init__(
|
||||||
self.made, self.write = made, write
|
self,
|
||||||
|
made: str = WORKDIR,
|
||||||
|
write: CommandResult | None = None,
|
||||||
|
stage: CommandResult | None = None,
|
||||||
|
) -> None:
|
||||||
|
self.made, self.write, self.stage = made, write, stage
|
||||||
self.calls: list[tuple[str, bytes | None]] = []
|
self.calls: list[tuple[str, bytes | None]] = []
|
||||||
|
|
||||||
def __call__(
|
def __call__(
|
||||||
@@ -488,18 +602,27 @@ class _ApplyAp:
|
|||||||
return CommandResult(WIRELESS, "", 0)
|
return CommandResult(WIRELESS, "", 0)
|
||||||
if "mktemp -d" in command:
|
if "mktemp -d" in command:
|
||||||
return self.write or CommandResult(self.made + "\n", "", 0)
|
return self.write or CommandResult(self.made + "\n", "", 0)
|
||||||
|
if command == STAGE:
|
||||||
|
return self.stage or CommandResult("", "", 0)
|
||||||
return CommandResult("", "", 0)
|
return CommandResult("", "", 0)
|
||||||
|
|
||||||
|
@property
|
||||||
|
def commands(self) -> list[str]:
|
||||||
|
return [c for c, _ in self.calls]
|
||||||
|
|
||||||
def test_the_script_is_written_from_stdin_into_a_fresh_directory_then_run_detached():
|
|
||||||
|
def test_the_changes_are_staged_and_waited_for_then_applied_detached():
|
||||||
ap = _ApplyAp()
|
ap = _ApplyAp()
|
||||||
result = _driver(ap).apply_ap_config(_config(), ["radio/country", "wireless/Corp/encryption"])
|
result = _driver(ap).apply_ap_config(_config(), ["radio/country", "wireless/Corp/encryption"])
|
||||||
|
|
||||||
(read, _), (write, script), (run, _) = ap.calls
|
(read, _), (write, stage), (write_apply, apply), (run, _), (start, _) = ap.calls
|
||||||
assert read == SHOW
|
assert read == SHOW
|
||||||
assert write.startswith("umask 077 && d=$(mktemp -d /tmp/openwrt-apply.XXXXXX)")
|
assert write.startswith("umask 077 && d=$(mktemp -d /tmp/openwrt-apply.XXXXXX)")
|
||||||
assert script is not None and f"key='{PSK}'".encode() in script
|
assert stage is not None and f"key='{PSK}'".encode() in stage
|
||||||
assert run == (
|
assert write_apply == f"umask 077 && cat > {WORKDIR}/apply.sh"
|
||||||
|
assert apply is not None and b"uci commit wireless" in apply and PSK.encode() not in apply
|
||||||
|
assert run == STAGE
|
||||||
|
assert start == (
|
||||||
f"( sh {WORKDIR}/apply.sh > {WORKDIR}/apply.log 2>&1 < /dev/null; "
|
f"( sh {WORKDIR}/apply.sh > {WORKDIR}/apply.log 2>&1 < /dev/null; "
|
||||||
f"rm -f {WORKDIR}/apply.sh ) &"
|
f"rm -f {WORKDIR}/apply.sh ) &"
|
||||||
)
|
)
|
||||||
@@ -507,17 +630,32 @@ def test_the_script_is_written_from_stdin_into_a_fresh_directory_then_run_detach
|
|||||||
assert result["skipped"] == []
|
assert result["skipped"] == []
|
||||||
assert result["restarts"] is False
|
assert result["restarts"] is False
|
||||||
assert result["log"] == f"{WORKDIR}/apply.log"
|
assert result["log"] == f"{WORKDIR}/apply.log"
|
||||||
assert (
|
assert PSK not in result["commands"]
|
||||||
PSK not in result["commands"]
|
assert "uci set wireless.radio1.country='DE'" in result["commands"]
|
||||||
and "uci set wireless.radio1.country='DE'" in result["commands"]
|
|
||||||
|
|
||||||
|
def test_a_refused_step_raises_names_it_and_applies_nothing():
|
||||||
|
said = (
|
||||||
|
f"wireless/Corp/encryption: uci set wireless.default_radio0.key={PSK}: "
|
||||||
|
"uci: Invalid argument\n"
|
||||||
)
|
)
|
||||||
|
ap = _ApplyAp(stage=CommandResult("", said, 3))
|
||||||
|
with pytest.raises(CommandErrorException) as caught:
|
||||||
|
_driver(ap).apply_ap_config(_config(), ["radio/country", "wireless/Corp/encryption"])
|
||||||
|
|
||||||
|
message = str(caught.value)
|
||||||
|
assert "wireless/Corp/encryption" in message and "Invalid argument" in message
|
||||||
|
assert "nothing of it is applied" in message
|
||||||
|
assert PSK not in message
|
||||||
|
assert not any("apply.sh >" in c for c in ap.commands)
|
||||||
|
assert ap.commands[-1] == f"rm -rf {WORKDIR}"
|
||||||
|
|
||||||
|
|
||||||
def test_nothing_to_write_sends_only_the_read():
|
def test_nothing_to_write_sends_only_the_read():
|
||||||
ap = _ApplyAp()
|
ap = _ApplyAp()
|
||||||
result = _driver(ap).apply_ap_config(_config(), ["system/luci"])
|
result = _driver(ap).apply_ap_config(_config(), ["system/luci"])
|
||||||
|
|
||||||
assert [c for c, _ in ap.calls] == [SHOW]
|
assert ap.commands == [SHOW]
|
||||||
assert result == {
|
assert result == {
|
||||||
"applied": [],
|
"applied": [],
|
||||||
"skipped": ["system/luci"],
|
"skipped": ["system/luci"],
|
||||||
|
|||||||
Reference in new issue
Block a user