Files
napalm-openwrt/napalm_openwrt/uci_steps.py
T
Christian Manivong 0552663d53
driver / standard (pull_request) Successful in 24s
driver / lint (pull_request) Successful in 24s
driver / types (pull_request) Successful in 1m28s
driver / test (3.13) (pull_request) Successful in 1m12s
driver / test (3.12) (pull_request) Successful in 1m21s
driver / lowest (pull_request) Successful in 29s
driver / build (pull_request) Successful in 30s
driver / security (pull_request) Successful in 1m0s
CI / driver (pull_request) Successful in 2m38s
driver / publish (pull_request) Skipped
fix(wireless): raise when a uci step of an ACL or channel push is refused
push_mac_acl and push_radio_channel sent each step through the
interactive shell and never looked at the result: a refused uci set,
add_list, commit or wifi reload passed silently, an SSID no wifi-iface
carried did nothing, and wifi was restarted after a refused channel.

Each step now runs on an SSH exec channel of its own, as root, with its
exit status checked (uci_steps.UciStepsMixin). A refused step raises
CommandErrorException naming the command and what the router said; a
refusal before the commit reverts what was staged, so a later commit
does not apply half of it, and wifi is not restarted. push_mac_acl
reads the sections once, raises when none carries the SSID, and deletes
macfilter/maclist only where a section has them instead of hiding each
delete's status behind `|| true`.

Closes #35
2026-11-12 19:01:07 +01:00

148 lines
5.3 KiB
Python

# 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)