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

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:
Christian Manivong committed 2026-11-29 22:43:34 +01:00
1 parent f71c12dfb6
commit 9bac9bd1af
6 files changed
+350 -98

No files matched your search

+157 -60
View File
@@ -13,19 +13,27 @@
"""The access point's configuration applied as desired state (``ApConfigMixin``).
The caller names the parts that differ; :func:`build_script` turns the values
those parts need into one shell script of ``uci`` commands, the commits and the
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
on the AP.
The caller names the parts that differ; :func:`build_scripts` turns the values those
parts need into two shell scripts:
* **stage** -- the ``uci`` changes, staged but not committed, so the running device
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
import logging
import re
from dataclasses import dataclass
from typing import TYPE_CHECKING
from napalm.base.exceptions import CommandErrorException
from napalm_device_types import (
ApConfigDict,
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_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_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"
@@ -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:
if part.startswith("radio/"):
radio_part(part, config, radios, plan)
@@ -93,8 +150,9 @@ def build_commands(
) -> tuple[Plan, list[str], list[str]]:
"""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
``network/vlan/<vid>`` is written by it.
Each part's commands follow a ``_part=`` line naming it, so the stage script
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()
applied: list[str] = []
@@ -107,40 +165,47 @@ def build_commands(
if rebuilds_bridge and ap_config_vlan_part(part) is not None:
applied.append(part)
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)
(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
def build_script(
config: ApConfigDict, parts: list[str], radios: Radios
) -> tuple[str, list[str], list[str], bool]:
"""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]
def _apply_script(plan: Plan, restarts: bool) -> str:
"""The commits, then what is live, then the reloads -- or the restart, which applies it all."""
lines = ["#!/bin/sh"]
lines += [f"uci commit {config_name}" for config_name in sorted(plan.commits)]
lines += plan.actions
if restarts:
lines.append("reboot")
else:
for config_name, reloads in _RELOADS.items():
if config_name in plan.commits:
lines += reloads
return "\n".join(lines), applied, skipped, restarts
return "\n".join(lines)
def masked(script: str, config: ApConfigDict) -> str:
"""*script* with every passphrase of *config* as ``MASK``."""
def build_scripts(config: ApConfigDict, parts: list[str], radios: Radios) -> ApScripts:
"""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 []:
if key := ssid.get("key"):
script = script.replace(sq(key), MASK)
return script
text = text.replace(sq(key), MASK).replace(key, _MASK_WORD)
return text
class OpenWrtApConfigMixin(ApConfigMixin, UciStepsMixin):
@@ -159,60 +224,92 @@ class OpenWrtApConfigMixin(ApConfigMixin, UciStepsMixin):
) -> CommandResult: ...
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
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``.
:raises CommandErrorException: when the radios cannot be read.
:raises RuntimeError: when the script cannot be written to the AP.
:raises CommandErrorException: when the radios cannot be read, or 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)))
script, applied, skipped, restarts = build_script(config, list(parts), radios)
if not script:
return {"applied": [], "skipped": skipped, "restarts": False, "commands": "", "log": ""}
workdir = self._run_detached(script)
scripts = build_scripts(config, list(parts), radios)
if not scripts.stage:
empty: ApConfigResultDict = {
"applied": [],
"skipped": scripts.skipped,
"restarts": False,
"commands": "",
"log": "",
}
return empty
workdir = self._write_scripts(scripts)
self._stage(workdir, config)
self._start_apply(workdir)
return {
"applied": applied,
"skipped": skipped,
"restarts": restarts,
"commands": masked(script, config),
"applied": scripts.applied,
"skipped": scripts.skipped,
"restarts": scripts.restarts,
"commands": masked(f"{scripts.stage}\n{scripts.apply}", config),
"log": f"{workdir}/apply.log",
}
def _run_detached(self, script: str) -> str:
"""Write *script* to the AP from stdin and run it detached; returns its directory.
def _write_scripts(self, scripts: ApScripts) -> str:
"""Write both scripts to the AP from stdin; returns their directory.
Root writes the script, passphrases and all, into a directory of its own
(``mktemp -d``: mode 0700, a name nobody knows in advance), never to a fixed
/tmp name another account could have placed or could swap between the write
and the run. The script goes once it has run; the log stays.
Root writes them, passphrases and all, into a directory of its own (``mktemp
-d``: mode 0700, a name nobody knows in advance), never to a fixed /tmp name
another account could have placed or could swap between the write and the run.
"""
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,
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()
if not _WORKDIR_RE.fullmatch(workdir):
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(
f"( sh {workdir}/apply.sh > {workdir}/apply.log 2>&1 < /dev/null; "
f"rm -f {workdir}/apply.sh ) &",
privileged=True,
)
if started.exit_code:
raise RuntimeError(
f"{self.hostname}: could not start the configuration script: "
f"{started.stderr.strip() or started.stdout.strip()}"
)
logger.info(
"%s: configuration script started; its log is %s/apply.log", self.hostname, workdir
)
return workdir
self._check(started, "could not start the configuration script")
logger.info("%s: configuration applying; its log is %s/apply.log", self.hostname, workdir)
def _check(self, result: CommandResult, what: str) -> None:
if result.exit_code:
said = result.stderr.strip() or result.stdout.strip()
raise RuntimeError(f"{self.hostname}: {what}: {said}")