]> git.ipfire.org Git - thirdparty/knot-resolver.git/commitdiff
python: fixed renamed exceptions/errors
authorAleš Mrázek <ales.mrazek@nic.cz>
Sat, 10 Jan 2026 17:45:35 +0000 (18:45 +0100)
committerAleš Mrázek <ales.mrazek@nic.cz>
Mon, 12 Jan 2026 13:47:51 +0000 (14:47 +0100)
python/knot_resolver/controller/interface.py
python/knot_resolver/controller/registered_workers.py
python/knot_resolver/controller/supervisord/__init__.py
python/knot_resolver/manager/config_store.py
python/knot_resolver/manager/manager.py
python/knot_resolver/manager/server.py
tests/manager/datamodel/types/test_base_types.py

index d760c235869c5502b01a31ddb33233baecbe2dd7..98f876e11076982648fd931a7ef5cca4e66613bc 100644 (file)
@@ -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
 
index abc1f1a2530641b8f4f089f312e5cff6c9ca6364..85240c465c872cd7752c94ac56fafa4fde01c221 100644 (file)
@@ -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.",
     )
index 429745916015011d2bd510814845df1819801432..c418ba73872e673830263c71da792bcb97a21687 100644 (file)
@@ -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:
index f7a60cc1b6f5960dd12c59efb583591a22c83dec..2a3650e551d43063b0e87643c6739978f6c6fa83 100644 (file)
@@ -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
index d3805e72e696fa2c6fa48b257382462a18282507..7686ad179f72b4464ebc6ebd3fce46205acf26c1 100644 (file)
@@ -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)
index 07e086b5e6ed81cdd0995bba30aa5e1df7c28dec..37ec4cd4abb3ef3d73d4d4ee665ea5492dfbaa47 100644 (file)
@@ -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
index 4bb27a958f7669eaed014b8dee1b9c8079894e05..df122ae00e1c9e6ae6250b640182475f857bc9ad 100644 (file)
@@ -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)