Files
napalm-openwrt/napalm_openwrt/config_mixin.py
T
Christian Manivong 248c87009f
driver / standard (pull_request) Successful in 18s
driver / lint (pull_request) Successful in 19s
driver / types (pull_request) Successful in 57s
driver / test (3.12) (pull_request) Successful in 1m0s
driver / test (3.13) (pull_request) Successful in 51s
driver / lowest (pull_request) Successful in 29s
driver / build (pull_request) Successful in 36s
driver / security (pull_request) Successful in 1m13s
CI / driver (pull_request) Successful in 2m50s
driver / publish (pull_request) Skipped
fix(config): import replace and rollback configs through a private temporary file (#45)
A replace commit_config() and rollback() 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 imported
and committed (NetOrk/netork#2446).

Each import is now one command: a mktemp file made under umask 077, the
config written to it, `uci import < "$f" && uci commit`, then the file
removed.
2026-11-12 22:32:46 +01:00

116 lines
4.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# 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.
from __future__ import annotations
import shlex
from napalm.base.exceptions import (
CommandErrorException,
MergeConfigException,
ReplaceConfigException,
)
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.
Reuses the standard lifecycle (load/compare/discard) from
:class:`ConfigLifecycleMixin` and adds OpenWrt-specific
``commit_config`` and ``rollback``.
"""
_comment_chars = ("#",)
def _get_running_config(self) -> str:
return self._send_command("uci export")
def commit_config(self, message: str = "", revert_in: int | None = None) -> None:
"""Apply the staged candidate configuration and commit it.
**Merge mode**: each UCI command line is sent to the device shell, then
``uci commit`` is called to persist the changes.
**Replace mode**: the candidate is piped through ``uci import`` and
then ``uci commit`` is called for every affected package.
:raises MergeConfigException: if no candidate is staged or if
commands are rejected.
:raises ReplaceConfigException: same, for replace candidates.
"""
if self._candidate_config is None:
raise MergeConfigException("No candidate configuration is staged.")
ex_cls = (
ReplaceConfigException if self._candidate_mode == "replace" else MergeConfigException
)
self._backup_config = self._send_command("uci export")
errors: list[str] = []
try:
if self._candidate_mode == "merge":
for line in self._candidate_config.splitlines():
stripped = line.strip()
if not stripped or stripped.startswith("#"):
continue
out = self._send_command(stripped)
if out and ("uci: " in out.lower() or "error" in out.lower()):
errors.append(f" {stripped!r}: {out}")
self._send_command("uci commit")
else:
out = self._send_command(_uci_import_command(self._candidate_config))
if out and "error" in out.lower():
errors.append(out)
except Exception as exc:
raise ex_cls(str(exc)) from exc
if errors:
raise ex_cls("The following commands were rejected:\n" + "\n".join(errors))
self._candidate_config = None
self._candidate_mode = None
def rollback(self) -> None:
"""Restore the UCI configuration to the state before the last :meth:`commit_config`.
Pipes the saved backup through ``uci import`` and then commits.
:raises CommandErrorException: if no backup is available.
"""
if self._backup_config is None:
raise CommandErrorException(
"No backup configuration available – "
"commit_config has not been called in this session."
)
self._send_command(_uci_import_command(self._backup_config))
self._backup_config = None