From: Aleš Mrázek Date: Sat, 10 Jan 2026 17:45:35 +0000 (+0100) Subject: python: fixed renamed exceptions/errors X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=5856a791caa338f166caecc8db2f08fab7e97c6e;p=thirdparty%2Fknot-resolver.git python: fixed renamed exceptions/errors --- diff --git a/python/knot_resolver/controller/interface.py b/python/knot_resolver/controller/interface.py index d760c2358..98f876e11 100644 --- a/python/knot_resolver/controller/interface.py +++ b/python/knot_resolver/controller/interface.py @@ -10,7 +10,7 @@ from pathlib import Path from typing import Dict, Iterable, Optional, Type, TypeVar from weakref import WeakValueDictionary -from knot_resolver.controller.exceptions import SubprocessControllerError +from knot_resolver.controller.exceptions import KresSubprocessControllerError from knot_resolver.controller.registered_workers import register_worker, unregister_worker from knot_resolver.datamodel.config_schema import KresConfig from knot_resolver.manager.constants import kresd_config_file, policy_loader_config_file @@ -144,7 +144,7 @@ class Subprocess(ABC): if self.type is SubprocessType.KRESD: register_worker(self) self._registered_worker = True - except SubprocessControllerError as e: + except KresSubprocessControllerError as e: self._unlink_config() raise e diff --git a/python/knot_resolver/controller/registered_workers.py b/python/knot_resolver/controller/registered_workers.py index abc1f1a25..85240c465 100644 --- a/python/knot_resolver/controller/registered_workers.py +++ b/python/knot_resolver/controller/registered_workers.py @@ -2,7 +2,7 @@ import asyncio import logging from typing import TYPE_CHECKING, Dict, List, Tuple -from .exceptions import SubprocessControllerError +from .exceptions import KresSubprocessControllerError if TYPE_CHECKING: from knot_resolver.controller.interface import KresID, Subprocess @@ -21,7 +21,7 @@ def get_registered_workers_kresids() -> "List[KresID]": async def command_single_registered_worker(cmd: str) -> "Tuple[KresID, object]": for sub in _REGISTERED_WORKERS.values(): return sub.id, await sub.command(cmd) - raise SubprocessControllerError( + raise KresSubprocessControllerError( "Unable to execute the command. There is no kresd worker running to execute the command." "Try start/restart the resolver.", ) diff --git a/python/knot_resolver/controller/supervisord/__init__.py b/python/knot_resolver/controller/supervisord/__init__.py index 429745916..c418ba738 100644 --- a/python/knot_resolver/controller/supervisord/__init__.py +++ b/python/knot_resolver/controller/supervisord/__init__.py @@ -6,7 +6,7 @@ from xmlrpc.client import Fault, ServerProxy import supervisor.xmlrpc # type: ignore[import] -from knot_resolver.controller.exceptions import SubprocessControllerError, SubprocessControllerExecError +from knot_resolver.controller.exceptions import KresSubprocessControllerError, KresSubprocessControllerExec from knot_resolver.controller.interface import ( KresID, Subprocess, @@ -30,14 +30,14 @@ async def _start_supervisord(config: KresConfig) -> None: logger.debug("Starting supervisord") res = await call(["supervisord", "--configuration", str(supervisord_config_file(config).absolute())]) if res != 0: - raise SubprocessControllerError(f"Supervisord exited with exit code {res}") + raise KresSubprocessControllerError(f"Supervisord exited with exit code {res}") async def _exec_supervisord(config: KresConfig) -> NoReturn: logger.debug("Writing supervisord config") await write_config_file(config) logger.debug("Execing supervisord") - raise SubprocessControllerExecError( + raise KresSubprocessControllerExec( [ str(which.which("supervisord")), "supervisord", @@ -53,7 +53,7 @@ async def _reload_supervisord(config: KresConfig) -> None: supervisord = _create_supervisord_proxy(config) supervisord.reloadConfig() except Fault as e: - raise SubprocessControllerError(f"supervisord reload failed: {e}") from e + raise KresSubprocessControllerError(f"supervisord reload failed: {e}") from e @async_in_a_thread @@ -162,7 +162,7 @@ def _list_running_subprocesses(config: KresConfig) -> Dict[SupervisordKresID, Su supervisord = _create_supervisord_proxy(config) processes: Any = supervisord.getAllProcessInfo() except Fault as e: - raise SubprocessControllerError(f"failed to get info from all running processes: {e}") from e + raise KresSubprocessControllerError(f"failed to get info from all running processes: {e}") from e # there will be a manager process as well, but we don't want to report anything on ourselves processes = [pr for pr in processes if pr["name"] != "manager"] @@ -197,7 +197,7 @@ class SupervisordSubprocess(Subprocess): supervisord = _create_supervisord_proxy(self._config) status = supervisord.getProcessInfo(self.name) except Fault as e: - raise SubprocessControllerError(f"failed to get status from '{self.id}' process: {e}") from e + raise KresSubprocessControllerError(f"failed to get status from '{self.id}' process: {e}") from e return _convert_subprocess_status(status) @async_in_a_thread @@ -208,7 +208,7 @@ class SupervisordSubprocess(Subprocess): supervisord = _create_fast_proxy(self._config) supervisord.startProcess(self.name) except Fault as e: - raise SubprocessControllerError(f"failed to start '{self.id}'") from e + raise KresSubprocessControllerError(f"failed to start '{self.id}'") from e @async_in_a_thread def _stop(self) -> None: diff --git a/python/knot_resolver/manager/config_store.py b/python/knot_resolver/manager/config_store.py index f7a60cc1b..2a3650e55 100644 --- a/python/knot_resolver/manager/config_store.py +++ b/python/knot_resolver/manager/config_store.py @@ -7,7 +7,7 @@ from knot_resolver.utils.functional import Result from knot_resolver.utils.modeling.exceptions import DataParsingError from knot_resolver.utils.modeling.types import NoneType -from .exceptions import KresManagerException +from .exceptions import KresManagerBaseError VerifyCallback = Callable[[KresConfig, KresConfig, bool], Awaitable[Result[None, str]]] UpdateCallback = Callable[[KresConfig, bool], Awaitable[None]] @@ -28,7 +28,7 @@ class ConfigStore: err_res = filter(lambda r: r.is_err(), results) errs = list(map(lambda r: r.unwrap_err(), err_res)) if len(errs) > 0: - raise KresManagerException("Configuration validation failed. The reasons are:\n - " + "\n - ".join(errs)) + raise KresManagerBaseError("Configuration validation failed. The reasons are:\n - " + "\n - ".join(errs)) async with self._update_lock: # update the stored config with the new version diff --git a/python/knot_resolver/manager/manager.py b/python/knot_resolver/manager/manager.py index d3805e72e..7686ad179 100644 --- a/python/knot_resolver/manager/manager.py +++ b/python/knot_resolver/manager/manager.py @@ -7,7 +7,7 @@ from secrets import token_hex from subprocess import SubprocessError from typing import Any, Callable, List, Optional -from knot_resolver.controller.exceptions import SubprocessControllerError +from knot_resolver.controller.exceptions import KresSubprocessControllerError from knot_resolver.controller.interface import Subprocess, SubprocessController, SubprocessStatus, SubprocessType from knot_resolver.controller.registered_workers import command_registered_workers, get_registered_workers_kresids from knot_resolver.datamodel import KresConfig @@ -243,7 +243,7 @@ class KresManager: # pylint: disable=too-many-instance-attributes # if it keeps running, the config is valid and others will soon join as well # if it crashes and the startup fails, then well, it's not running anymore... :) await self._spawn_new_worker(new) - except (SubprocessError, SubprocessControllerError): + except (SubprocessError, KresSubprocessControllerError): logger.error("Kresd with the new config failed to start, rejecting config") return Result.err("canary kresd process failed to start. Config might be invalid.") @@ -310,7 +310,7 @@ class KresManager: # pylint: disable=too-many-instance-attributes else: logger.debug("Stopping cache GC") await self._stop_gc() - except SubprocessControllerError as e: + except KresSubprocessControllerError as e: if _noretry: raise if self._fix_counter.is_too_high(): @@ -353,7 +353,7 @@ class KresManager: # pylint: disable=too-many-instance-attributes if self._policy_loader: await self._policy_loader.cleanup() - except (SubprocessError, SubprocessControllerError) as e: + except (SubprocessError, KresSubprocessControllerError) as e: logger.error(f"Failed to load policy rules: {e}") return Result.err("kresd 'policy-loader' process failed to start. Config might be invalid.") @@ -449,7 +449,7 @@ class KresManager: # pylint: disable=too-many-instance-attributes ) invoke_callback = True - except SubprocessControllerError as e: + except KresSubprocessControllerError as e: # wait few seconds and see if 'processes_watchdog' task is cancelled (during shutdown) # otherwise it is an error await asyncio.sleep(3) diff --git a/python/knot_resolver/manager/server.py b/python/knot_resolver/manager/server.py index 07e086b5e..37ec4cd4a 100644 --- a/python/knot_resolver/manager/server.py +++ b/python/knot_resolver/manager/server.py @@ -20,7 +20,7 @@ from aiohttp.web_runner import AppRunner, TCPSite, UnixSite from knot_resolver.constants import USER from knot_resolver.controller import get_best_controller_implementation -from knot_resolver.controller.exceptions import SubprocessControllerError, SubprocessControllerExecError +from knot_resolver.controller.exceptions import KresSubprocessControllerError, KresSubprocessControllerExec from knot_resolver.controller.interface import SubprocessType from knot_resolver.controller.registered_workers import command_single_registered_worker from knot_resolver.datamodel import kres_config_json_schema @@ -43,7 +43,7 @@ from knot_resolver.utils.systemd_notify import systemd_notify from .config_store import ConfigStore from .constants import PID_FILE_NAME, init_user_constants -from .exceptions import KresManagerException +from .exceptions import KresManagerBaseError from .logger import logger_init from .manager import KresManager @@ -65,7 +65,7 @@ async def error_handler(request: web.Request, handler: Any) -> web.Response: return web.Response(text=str(e), status=HTTPStatus.BAD_REQUEST) except DataParsingError as e: return web.Response(text=f"request processing error:\n{e}", status=HTTPStatus.BAD_REQUEST) - except KresManagerException as e: + except KresManagerBaseError as e: return web.Response(text=f"request processing failed:\n{e}", status=HTTPStatus.INTERNAL_SERVER_ERROR) @@ -150,7 +150,7 @@ class Server: except (DataParsingError, DataValidationError) as e: logger.error(f"Failed to parse the updated configuration file: {e}") logger.error("Configuration has NOT been changed.") - except KresManagerException as e: + except KresManagerBaseError as e: logger.error(f"Reloading of the configuration file failed: {e}") logger.error("Configuration has NOT been changed.") @@ -158,7 +158,7 @@ class Server: try: await self.config_store.renew(force) logger.info("Configuration successfully renewed") - except KresManagerException as e: + except KresManagerBaseError as e: logger.error(f"Renewing the configuration failed: {e}") logger.error("Configuration has NOT been renewed.") @@ -423,7 +423,7 @@ class Server: nsite = web.TCPSite(self.runner, str(mgn.interface.addr), int(mgn.interface.port)) logger.info(f"Starting API HTTP server on http://{mgn.interface.addr}:{mgn.interface.port}") else: - raise KresManagerException("Requested API on unsupported configuration format.") + raise KresManagerBaseError("Requested API on unsupported configuration format.") await nsite.start() # stop the old listen @@ -454,7 +454,7 @@ async def _load_raw_config(config: Union[Path, Dict[str, Any]]) -> Dict[str, Any # Initial configuration of the manager if isinstance(config, Path): if not config.exists(): - raise KresManagerException( + raise KresManagerBaseError( f"Manager is configured to load config file at {config} on startup, but the file does not exist." ) logger.info(f"Loading configuration from '{config}' file.") @@ -525,11 +525,11 @@ def _lock_working_directory(attempt: int = 0) -> None: os.unlink(PID_FILE_NAME) _lock_working_directory(attempt=attempt + 1) return - raise KresManagerException( + raise KresManagerBaseError( "Another manager is running in the same working directory." f" PID file is located at {os.getcwd()}/{PID_FILE_NAME}" ) from e - raise KresManagerException( + raise KresManagerBaseError( "Another manager is running in the same working directory." f" PID file is located at {os.getcwd()}/{PID_FILE_NAME}" ) from e @@ -650,7 +650,7 @@ async def start_server(config: List[str]) -> int: # noqa: PLR0915 # add Server's shutdown trigger to the manager manager.add_shutdown_trigger(server.trigger_shutdown) - except SubprocessControllerExecError as e: + except KresSubprocessControllerExec as e: # if we caught this exception, some component wants to perform a reexec during startup. Most likely, it would # be a subprocess manager like supervisord, which wants to make sure the manager runs under supervisord in # the process tree. So now we stop everything, and exec what we are told to. We are assuming, that the thing @@ -666,11 +666,11 @@ async def start_server(config: List[str]) -> int: # noqa: PLR0915 # and finally exec what we were told to exec os.execl(*e.exec_args) - except SubprocessControllerError as e: + except KresSubprocessControllerError as e: logger.error(f"Server initialization failed: {e}") return 1 - except KresManagerException as e: + except KresManagerBaseError as e: # We caught an error with a pretty error message. Just print it and exit. logger.error(e) return 1 diff --git a/tests/manager/datamodel/types/test_base_types.py b/tests/manager/datamodel/types/test_base_types.py index 4bb27a958..df122ae00 100644 --- a/tests/manager/datamodel/types/test_base_types.py +++ b/tests/manager/datamodel/types/test_base_types.py @@ -5,7 +5,7 @@ from typing import List, Optional import pytest from pytest import raises -from knot_resolver import KresBaseException +from knot_resolver import KresBaseError from knot_resolver.datamodel.types.base_types import FloatRangeBase, IntRangeBase, StringLengthBase @@ -34,7 +34,7 @@ def test_int_range_base(min: Optional[int], max: Optional[int]): invals.extend([random.randint(-sys.maxsize - 1, rmin - 1) for _ in range(n % 2)] if max else []) for inval in invals: - with raises(KresBaseException): + with raises(KresBaseError): Test(inval) @@ -63,7 +63,7 @@ def test_float_range_base(min: Optional[float], max: Optional[float]): invals.extend([random.uniform(sys.float_info.min - 1.0, rmin - 1.0) for _ in range(n % 2)] if max else []) for inval in invals: - with raises(KresBaseException): + with raises(KresBaseError): Test(inval) @@ -91,5 +91,5 @@ def test_str_bytes_length_base(min: Optional[int], max: Optional[int]): invals.extend(["x" * random.randint(1, rmin - 1) for _ in range(n % 2)] if max else []) for inval in invals: - with raises(KresBaseException): + with raises(KresBaseError): Test(inval)