Skip to content

Commit 0149e52

Browse files
committed
python/knot_resolver: ruff linter fixes
1 parent 4d6aa76 commit 0149e52

33 files changed

+216
-254
lines changed

python/knot_resolver/client/command.py

+1-1
Original file line numberDiff line numberDiff line change
@@ -48,7 +48,7 @@ def get_socket_from_config(config: Path, optional_file: bool) -> Optional[Socket
4848
f'http+unix://{quote(management["unix-socket"], safe="")}/',
4949
f'Key "/management/unix-socket" in "{config}" file',
5050
)
51-
elif "interface" in management:
51+
if "interface" in management:
5252
ip = IPAddressPort(management["interface"], object_path=f"/{mkey}/interface")
5353
return SocketDesc(
5454
f"http://{ip.addr}:{ip.port}",

python/knot_resolver/client/commands/config.py

+13-13
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ class Operations(Enum):
1717
def operation_to_method(operation: Operations) -> Literal["PUT", "GET", "DELETE"]:
1818
if operation == Operations.SET:
1919
return "PUT"
20-
elif operation == Operations.DELETE:
20+
if operation == Operations.DELETE:
2121
return "DELETE"
2222
return "GET"
2323

@@ -91,25 +91,25 @@ def register_args_subparser(
9191
config_subparsers = config.add_subparsers(help="operation type")
9292

9393
# GET operation
94-
get = config_subparsers.add_parser("get", help="Get current configuration from the resolver.")
95-
get.set_defaults(operation=Operations.GET, format=DataFormat.YAML)
94+
get_op = config_subparsers.add_parser("get", help="Get current configuration from the resolver.")
95+
get_op.set_defaults(operation=Operations.GET, format=DataFormat.YAML)
9696

97-
get.add_argument(
97+
get_op.add_argument(
9898
"-p",
9999
"--path",
100100
help=path_help,
101101
action="store",
102102
type=str,
103103
default="",
104104
)
105-
get.add_argument(
105+
get_op.add_argument(
106106
"file",
107107
help="Optional, path to the file where to save exported configuration data. If not specified, data will be printed.",
108108
type=str,
109109
nargs="?",
110110
)
111111

112-
get_formats = get.add_mutually_exclusive_group()
112+
get_formats = get_op.add_mutually_exclusive_group()
113113
get_formats.add_argument(
114114
"--json",
115115
help="Get configuration data in JSON format.",
@@ -126,10 +126,10 @@ def register_args_subparser(
126126
)
127127

128128
# SET operation
129-
set = config_subparsers.add_parser("set", help="Set new configuration for the resolver.")
130-
set.set_defaults(operation=Operations.SET)
129+
set_op = config_subparsers.add_parser("set", help="Set new configuration for the resolver.")
130+
set_op.set_defaults(operation=Operations.SET)
131131

132-
set.add_argument(
132+
set_op.add_argument(
133133
"-p",
134134
"--path",
135135
help=path_help,
@@ -138,7 +138,7 @@ def register_args_subparser(
138138
default="",
139139
)
140140

141-
value_or_file = set.add_mutually_exclusive_group()
141+
value_or_file = set_op.add_mutually_exclusive_group()
142142
value_or_file.add_argument(
143143
"file",
144144
help="Optional, path to file with new configuraion.",
@@ -153,11 +153,11 @@ def register_args_subparser(
153153
)
154154

155155
# DELETE operation
156-
delete = config_subparsers.add_parser(
156+
delete_op = config_subparsers.add_parser(
157157
"delete", help="Delete given configuration property or list item at the given index."
158158
)
159-
delete.set_defaults(operation=Operations.DELETE)
160-
delete.add_argument(
159+
delete_op.set_defaults(operation=Operations.DELETE)
160+
delete_op.add_argument(
161161
"-p",
162162
"--path",
163163
help=path_help,

python/knot_resolver/controller/__init__.py

+1-2
Original file line numberDiff line numberDiff line change
@@ -86,8 +86,7 @@ async def get_controller_by_name(config: KresConfig, name: str) -> SubprocessCon
8686
if await controller.is_controller_available(config):
8787
logger.info("Selected controller '%s'", str(controller))
8888
return controller
89-
else:
90-
raise LookupError("The selected subprocess controller is not available for use on this system.")
89+
raise LookupError("The selected subprocess controller is not available for use on this system.")
9190

9291

9392
# run the imports on module load

python/knot_resolver/controller/exceptions.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,11 @@
33
from knot_resolver import KresBaseException
44

55

6-
class SubprocessControllerException(KresBaseException):
6+
class SubprocessControllerError(KresBaseException):
77
pass
88

99

10-
class SubprocessControllerExecException(Exception):
10+
class SubprocessControllerExecError(Exception):
1111
"""
1212
Exception that is used to deliberately terminate system startup
1313
and make exec() of something else. This is used by the subprocess controller

python/knot_resolver/controller/interface.py

+6-8
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
from typing import Dict, Iterable, Optional, Type, TypeVar
1111
from weakref import WeakValueDictionary
1212

13-
from knot_resolver.controller.exceptions import SubprocessControllerException
13+
from knot_resolver.controller.exceptions import SubprocessControllerError
1414
from knot_resolver.controller.registered_workers import register_worker, unregister_worker
1515
from knot_resolver.datamodel.config_schema import KresConfig
1616
from knot_resolver.manager.constants import kresd_config_file, policy_loader_config_file
@@ -47,8 +47,7 @@ def alloc(cls: Type[T], typ: SubprocessType) -> T:
4747
# find free ID closest to zero
4848
for i in itertools.count(start=0, step=1):
4949
if i not in cls._used[typ]:
50-
res = cls.new(typ, i)
51-
return res
50+
return cls.new(typ, i)
5251

5352
raise RuntimeError("Reached an end of an infinite loop. How?")
5453

@@ -59,10 +58,9 @@ def new(cls: "Type[T]", typ: SubprocessType, n: int) -> "T":
5958
# typed based on subclass. I am not even sure that it's different between subclasses,
6059
# it's probably still the same dict. But we don't really care about it
6160
return cls._used[typ][n] # type: ignore
62-
else:
63-
val = cls(typ, n, _i_know_what_i_am_doing=True)
64-
cls._used[typ][n] = val
65-
return val
61+
val = cls(typ, n, _i_know_what_i_am_doing=True)
62+
cls._used[typ][n] = val
63+
return val
6664

6765
def __init__(self, typ: SubprocessType, n: int, _i_know_what_i_am_doing: bool = False):
6866
if not _i_know_what_i_am_doing:
@@ -132,7 +130,7 @@ async def start(self, new_config: Optional[KresConfig] = None) -> None:
132130
if self.type is SubprocessType.KRESD:
133131
register_worker(self)
134132
self._registered_worker = True
135-
except SubprocessControllerException as e:
133+
except SubprocessControllerError as e:
136134
if config_file:
137135
config_file.unlink()
138136
raise e

python/knot_resolver/controller/registered_workers.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
import logging
33
from typing import TYPE_CHECKING, Dict, List, Tuple
44

5-
from .exceptions import SubprocessControllerException
5+
from .exceptions import SubprocessControllerError
66

77
if TYPE_CHECKING:
88
from knot_resolver.controller.interface import KresID, Subprocess
@@ -21,7 +21,7 @@ def get_registered_workers_kresids() -> "List[KresID]":
2121
async def command_single_registered_worker(cmd: str) -> "Tuple[KresID, object]":
2222
for sub in _REGISTERED_WORKERS.values():
2323
return sub.id, await sub.command(cmd)
24-
raise SubprocessControllerException(
24+
raise SubprocessControllerError(
2525
"Unable to execute the command. There is no kresd worker running to execute the command."
2626
"Try start/restart the resolver.",
2727
)

python/knot_resolver/controller/supervisord/__init__.py

+10-12
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,7 @@
66

77
import supervisor.xmlrpc # type: ignore[import]
88

9-
from knot_resolver.controller.exceptions import SubprocessControllerException, SubprocessControllerExecException
9+
from knot_resolver.controller.exceptions import SubprocessControllerError, SubprocessControllerExecError
1010
from knot_resolver.controller.interface import (
1111
KresID,
1212
Subprocess,
@@ -30,14 +30,14 @@ async def _start_supervisord(config: KresConfig) -> None:
3030
logger.debug("Starting supervisord")
3131
res = await call(["supervisord", "--configuration", str(supervisord_config_file(config).absolute())])
3232
if res != 0:
33-
raise SubprocessControllerException(f"Supervisord exited with exit code {res}")
33+
raise SubprocessControllerError(f"Supervisord exited with exit code {res}")
3434

3535

3636
async def _exec_supervisord(config: KresConfig) -> NoReturn:
3737
logger.debug("Writing supervisord config")
3838
await write_config_file(config)
3939
logger.debug("Execing supervisord")
40-
raise SubprocessControllerExecException(
40+
raise SubprocessControllerExecError(
4141
[
4242
str(which.which("supervisord")),
4343
"supervisord",
@@ -53,7 +53,7 @@ async def _reload_supervisord(config: KresConfig) -> None:
5353
supervisord = _create_supervisord_proxy(config)
5454
supervisord.reloadConfig()
5555
except Fault as e:
56-
raise SubprocessControllerException("supervisord reload failed") from e
56+
raise SubprocessControllerError("supervisord reload failed") from e
5757

5858

5959
@async_in_a_thread
@@ -113,11 +113,10 @@ async def _is_supervisord_running(config: KresConfig) -> bool:
113113
pid = await _get_supervisord_pid(config)
114114
if pid is None:
115115
return False
116-
elif not _is_process_runinng(pid):
116+
if not _is_process_runinng(pid):
117117
supervisord_pid_file(config).unlink()
118118
return False
119-
else:
120-
return True
119+
return True
121120

122121

123122
def _create_proxy(config: KresConfig) -> ServerProxy:
@@ -164,7 +163,7 @@ def _list_running_subprocesses(config: KresConfig) -> Dict[SupervisordKresID, Su
164163
supervisord = _create_supervisord_proxy(config)
165164
processes: Any = supervisord.getAllProcessInfo()
166165
except Fault as e:
167-
raise SubprocessControllerException(f"failed to get info from all running processes: {e}") from e
166+
raise SubprocessControllerError(f"failed to get info from all running processes: {e}") from e
168167

169168
# there will be a manager process as well, but we don't want to report anything on ourselves
170169
processes = [pr for pr in processes if pr["name"] != "manager"]
@@ -199,7 +198,7 @@ def status(self) -> SubprocessStatus:
199198
supervisord = _create_supervisord_proxy(self._config)
200199
status = supervisord.getProcessInfo(self.name)
201200
except Fault as e:
202-
raise SubprocessControllerException(f"failed to get status from '{self.id}' process: {e}") from e
201+
raise SubprocessControllerError(f"failed to get status from '{self.id}' process: {e}") from e
203202
return _convert_subprocess_status(status)
204203

205204
@async_in_a_thread
@@ -210,7 +209,7 @@ def _start(self) -> None:
210209
supervisord = _create_fast_proxy(self._config)
211210
supervisord.startProcess(self.name)
212211
except Fault as e:
213-
raise SubprocessControllerException(f"failed to start '{self.id}'") from e
212+
raise SubprocessControllerError(f"failed to start '{self.id}'") from e
214213

215214
@async_in_a_thread
216215
def _stop(self) -> None:
@@ -253,8 +252,7 @@ async def get_all_running_instances(self) -> Iterable[Subprocess]:
253252
for id_ in states
254253
if states[id_] == SubprocessStatus.RUNNING
255254
]
256-
else:
257-
return []
255+
return []
258256

259257
async def initialize_controller(self, config: KresConfig) -> None:
260258
self._controller_config = config

python/knot_resolver/controller/supervisord/config_file.py

+6-8
Original file line numberDiff line numberDiff line change
@@ -36,21 +36,19 @@ def from_string(val: str) -> "SupervisordKresID":
3636
# the double name is checked because thats how we read it from supervisord
3737
if val in ("cache-gc", "cache-gc:cache-gc"):
3838
return SupervisordKresID.new(SubprocessType.GC, 0)
39-
elif val in ("policy-loader", "policy-loader:policy-loader"):
39+
if val in ("policy-loader", "policy-loader:policy-loader"):
4040
return SupervisordKresID.new(SubprocessType.POLICY_LOADER, 0)
41-
else:
42-
val = val.replace("kresd:kresd", "")
43-
return SupervisordKresID.new(SubprocessType.KRESD, int(val))
41+
val = val.replace("kresd:kresd", "")
42+
return SupervisordKresID.new(SubprocessType.KRESD, int(val))
4443

4544
def __str__(self) -> str:
4645
if self.subprocess_type is SubprocessType.GC:
4746
return "cache-gc"
48-
elif self.subprocess_type is SubprocessType.POLICY_LOADER:
47+
if self.subprocess_type is SubprocessType.POLICY_LOADER:
4948
return "policy-loader"
50-
elif self.subprocess_type is SubprocessType.KRESD:
49+
if self.subprocess_type is SubprocessType.KRESD:
5150
return f"kresd:kresd{self._id}"
52-
else:
53-
raise RuntimeError(f"Unexpected subprocess type {self.subprocess_type}")
51+
raise RuntimeError(f"Unexpected subprocess type {self.subprocess_type}")
5452

5553

5654
def kres_cache_gc_args(config: KresConfig) -> str:

python/knot_resolver/controller/supervisord/plugin/fast_rpcinterface.py

+5-5
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ def _update(self, text):
7373

7474
# RPC API methods
7575

76-
def _getGroupAndProcess(self, name):
76+
def _getGroupAndProcess(self, name): # noqa: N802
7777
# get process to start from name
7878
group_name, process_name = split_namespec(name)
7979

@@ -90,7 +90,7 @@ def _getGroupAndProcess(self, name):
9090

9191
return group, process
9292

93-
def startProcess(self, name, wait=True):
93+
def startProcess(self, name, wait=True): # noqa: N802
9494
"""Start a process
9595
9696
@param string name Process name (or ``group:name``, or ``group:*``)
@@ -108,10 +108,10 @@ def startProcess(self, name, wait=True):
108108
# eventually fail
109109
try:
110110
filename, argv = process.get_execv_args()
111-
except NotFound as why:
112-
raise RPCError(Faults.NO_FILE, why.args[0])
111+
except NotFound as e:
112+
raise RPCError(Faults.NO_FILE, e.args[0]) from e
113113
except (BadCommand, NotExecutable, NoPermission) as why:
114-
raise RPCError(Faults.NOT_EXECUTABLE, why.args[0])
114+
raise RPCError(Faults.NOT_EXECUTABLE, why.args[0]) from why
115115

116116
if process.get_state() in RUNNING_STATES:
117117
raise RPCError(Faults.ALREADY_STARTED, name)

python/knot_resolver/controller/supervisord/plugin/manager_integration.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -51,7 +51,7 @@ def check_for_runnning_manager(event: ProcessStateRunningEvent) -> None:
5151
systemd_notify(READY="1", STATUS="Ready")
5252

5353

54-
def ServerOptions_get_signal(self):
54+
def get_server_options_signal(self):
5555
sig = self.signal_receiver.get_signal()
5656
if sig == signal.SIGHUP and superd is not None:
5757
superd.options.logger.info("received SIGHUP, forwarding to the process 'manager'")
@@ -77,7 +77,7 @@ def inject(supervisord: Supervisor, **_config: Any) -> Any: # pylint: disable=u
7777
subscribe(ProcessStateRunningEvent, check_for_runnning_manager)
7878

7979
# forward SIGHUP to manager
80-
ServerOptions.get_signal = ServerOptions_get_signal
80+
ServerOptions.get_signal = get_server_options_signal
8181

8282
# this method is called by supervisord when loading the plugin,
8383
# it should return XML-RPC object, which we don't care about

python/knot_resolver/controller/supervisord/plugin/patch_logger.py

+2-2
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ def empty_function(*args, **kwargs):
2020
FORWARD_MSG_FORMAT: str = "%(name)s[%(pid)d]%(stream)s: %(data)s"
2121

2222

23-
def POutputDispatcher_log(self: POutputDispatcher, data: bytearray):
23+
def p_output_dispatcher_log(self: POutputDispatcher, data: bytearray):
2424
if data:
2525
# parse the input
2626
if not isinstance(data, bytes):
@@ -75,7 +75,7 @@ def inject(supervisord: Supervisor, **config: Any) -> Any: # pylint: disable=us
7575
supervisord.options.logger.handlers = supervisord_handlers
7676

7777
# replace output handler for subprocesses
78-
POutputDispatcher._log = POutputDispatcher_log
78+
POutputDispatcher._log = p_output_dispatcher_log # noqa: SLF001
7979

8080
# we forward stdio in all cases, even when logging to syslog. This should prevent the unforturtunate
8181
# case of swallowing an error message leaving the users confused. To make the forwarded lines obvious

0 commit comments

Comments
 (0)