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
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
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
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.",
)
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,
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",
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
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"]
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
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:
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]]
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
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
# 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.")
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():
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.")
)
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)
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
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
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)
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.")
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.")
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
# 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.")
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
# 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
# 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
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
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)
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)
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)