Skip to content

Commit

Permalink
refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
mdevaev committed Sep 18, 2024
1 parent 45270a0 commit 7a53f14
Show file tree
Hide file tree
Showing 83 changed files with 517 additions and 516 deletions.
12 changes: 6 additions & 6 deletions kvmd/aiogp.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,24 +83,24 @@ def __run(self) -> None:
self.__path,
consumer=self.__consumer,
config={tuple(pins): gpiod.LineSettings(edge_detection=gpiod.line.Edge.BOTH)},
) as line_request:
) as line_req:

line_request.wait_edge_events(0.1)
line_req.wait_edge_events(0.1)
self.__values = {
pin: _DebouncedValue(
initial=bool(value.value),
debounce=self.__pins[pin].debounce,
notifier=self.__notifier,
loop=self.__loop,
)
for (pin, value) in zip(pins, line_request.get_values(pins))
for (pin, value) in zip(pins, line_req.get_values(pins))
}
self.__loop.call_soon_threadsafe(self.__notifier.notify)

while not self.__stop_event.is_set():
if line_request.wait_edge_events(1):
if line_req.wait_edge_events(1):
new: dict[int, bool] = {}
for event in line_request.read_edge_events():
for event in line_req.read_edge_events():
(pin, value) = self.__parse_event(event)
new[pin] = value
for (pin, value) in new.items():
Expand All @@ -110,7 +110,7 @@ def __run(self) -> None:
# Размер буфера ядра - 16 эвентов на линии. При превышении этого числа,
# новые эвенты потеряются. Это не баг, это фича, как мне объяснили в LKML.
# Штош. Будем с этим жить и синхронизировать состояния при таймауте.
for (pin, value) in zip(pins, line_request.get_values(pins)):
for (pin, value) in zip(pins, line_req.get_values(pins)):
self.__values[pin].set(bool(value.value)) # type: ignore

def __parse_event(self, event: gpiod.EdgeEvent) -> tuple[int, bool]:
Expand Down
4 changes: 2 additions & 2 deletions kvmd/aiohelpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ async def remount(name: str, base_cmd: list[str], rw: bool) -> bool:
if proc.returncode != 0:
assert proc.returncode is not None
raise subprocess.CalledProcessError(proc.returncode, cmd)
except Exception as err:
logger.error("Can't remount %s storage: %s", name, tools.efmt(err))
except Exception as ex:
logger.error("Can't remount %s storage: %s", name, tools.efmt(ex))
return False
return True
6 changes: 3 additions & 3 deletions kvmd/aiotools.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,9 @@ def inner_done(_) -> None: # type: ignore
if inner.cancelled():
outer.forced_cancel()
else:
err = inner.exception()
if err is not None:
outer.set_exception(err)
ex = inner.exception()
if ex is not None:
outer.set_exception(ex)
else:
outer.set_result(inner.result())

Expand Down
8 changes: 4 additions & 4 deletions kvmd/apps/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -171,8 +171,8 @@ def _init_config(config_path: str, override_options: list[str], **load_flags: bo
config_path = os.path.expanduser(config_path)
try:
raw_config: dict = load_yaml_file(config_path)
except Exception as err:
raise SystemExit(f"ConfigError: Can't read config file {config_path!r}:\n{tools.efmt(err)}")
except Exception as ex:
raise SystemExit(f"ConfigError: Can't read config file {config_path!r}:\n{tools.efmt(ex)}")
if not isinstance(raw_config, dict):
raise SystemExit(f"ConfigError: Top-level of the file {config_path!r} must be a dictionary")

Expand All @@ -187,8 +187,8 @@ def _init_config(config_path: str, override_options: list[str], **load_flags: bo
config = make_config(raw_config, scheme)

return config
except (ConfigError, UnknownPluginError) as err:
raise SystemExit(f"ConfigError: {err}")
except (ConfigError, UnknownPluginError) as ex:
raise SystemExit(f"ConfigError: {ex}")


def _patch_raw(raw_config: dict) -> None: # pylint: disable=too-many-branches
Expand Down
4 changes: 2 additions & 2 deletions kvmd/apps/edidconf/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -402,5 +402,5 @@ def main(argv: (list[str] | None)=None) -> None: # pylint: disable=too-many-bra
f"--set-edid=file={orig_edid_path}",
"--info-edid",
], stdout=sys.stderr, check=True)
except subprocess.CalledProcessError as err:
raise SystemExit(str(err))
except subprocess.CalledProcessError as ex:
raise SystemExit(str(ex))
4 changes: 2 additions & 2 deletions kvmd/apps/htpasswd/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -155,5 +155,5 @@ def main(argv: (list[str] | None)=None) -> None:
options = parser.parse_args(argv[1:])
try:
options.cmd(config, options)
except ValidatorError as err:
raise SystemExit(str(err))
except ValidatorError as ex:
raise SystemExit(str(ex))
9 changes: 5 additions & 4 deletions kvmd/apps/ipmi/server.py
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ def run(self) -> None:
# =====

def handle_raw_request(self, request: dict, session: IpmiServerSession) -> None:
# Parameter 'request' has been renamed to 'req' in overriding method
handler = {
(6, 1): (lambda _, session: self.send_device_id(session)), # Get device ID
(6, 7): self.__get_power_state_handler, # Power state
Expand Down Expand Up @@ -145,13 +146,13 @@ def __get_chassis_status_handler(self, _: dict, session: IpmiServerSession) -> N
data = [int(result["leds"]["power"]), 0, 0]
session.send_ipmi_response(data=data)

def __chassis_control_handler(self, request: dict, session: IpmiServerSession) -> None:
def __chassis_control_handler(self, req: dict, session: IpmiServerSession) -> None:
action = {
0: "off_hard",
1: "on",
3: "reset_hard",
5: "off",
}.get(request["data"][0], "")
}.get(req["data"][0], "")
if action:
if not self.__make_request(session, f"atx.switch_power({action})", "atx.switch_power", action=action):
code = 0xC0 # Try again later
Expand All @@ -171,8 +172,8 @@ async def runner(): # type: ignore
async with self.__kvmd.make_session(credentials.kvmd_user, credentials.kvmd_passwd) as kvmd_session:
func = functools.reduce(getattr, func_path.split("."), kvmd_session)
return (await func(**kwargs))
except (aiohttp.ClientError, asyncio.TimeoutError) as err:
logger.error("[%s]: Can't perform request %s: %s", session.sockaddr[0], name, err)
except (aiohttp.ClientError, asyncio.TimeoutError) as ex:
logger.error("[%s]: Can't perform request %s: %s", session.sockaddr[0], name, ex)
raise

return aiotools.run_sync(runner())
Expand Down
4 changes: 2 additions & 2 deletions kvmd/apps/janus/runner.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,8 @@ def __get_default_ip(self) -> str:
for proto in [socket.AF_INET, socket.AF_INET6]:
if proto in addrs:
return addrs[proto][0]["addr"]
except Exception as err:
get_logger().error("Can't get default IP: %s", tools.efmt(err))
except Exception as ex:
get_logger().error("Can't get default IP: %s", tools.efmt(ex))
return ""

# =====
Expand Down
18 changes: 9 additions & 9 deletions kvmd/apps/janus/stun.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,8 @@ async def get_info(self, src_ip: str, src_port: int) -> StunInfo:
self.__sock.bind(src_addr)
(nat_type, resp) = await self.__get_nat_type(src_ip)
ext_ip = (resp.ext.ip if resp.ext is not None else "")
except Exception as err:
get_logger(0).error("Can't get STUN info: %s", tools.efmt(err))
except Exception as ex:
get_logger(0).error("Can't get STUN info: %s", tools.efmt(ex))
finally:
self.__sock = None

Expand Down Expand Up @@ -201,16 +201,16 @@ async def __inner_make_request(self, trans_id: bytes, req: bytes, addr: tuple[st

try:
await aiotools.run_async(self.__sock.sendto, req, addr)
except Exception as err:
return (b"", f"Send error: {tools.efmt(err)}")
except Exception as ex:
return (b"", f"Send error: {tools.efmt(ex)}")
try:
resp = (await aiotools.run_async(self.__sock.recvfrom, 2048))[0]
except Exception as err:
return (b"", f"Recv error: {tools.efmt(err)}")
except Exception as ex:
return (b"", f"Recv error: {tools.efmt(ex)}")

(response_type, payload_len) = struct.unpack(">HH", resp[:4])
if response_type != 0x0101:
return (b"", f"Invalid response type: {response_type:#06x}")
(resp_type, payload_len) = struct.unpack(">HH", resp[:4])
if resp_type != 0x0101:
return (b"", f"Invalid response type: {resp_type:#06x}")
if trans_id != resp[4:20]:
return (b"", "Transaction ID mismatch")

Expand Down
12 changes: 6 additions & 6 deletions kvmd/apps/kvmd/api/atx.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,9 @@ async def __state_handler(self, _: Request) -> Response:
return make_json_response(await self.__atx.get_state())

@exposed_http("POST", "/atx/power")
async def __power_handler(self, request: Request) -> Response:
action = valid_atx_power_action(request.query.get("action"))
wait = valid_bool(request.query.get("wait", False))
async def __power_handler(self, req: Request) -> Response:
action = valid_atx_power_action(req.query.get("action"))
wait = valid_bool(req.query.get("wait", False))
await ({
"on": self.__atx.power_on,
"off": self.__atx.power_off,
Expand All @@ -57,9 +57,9 @@ async def __power_handler(self, request: Request) -> Response:
return make_json_response()

@exposed_http("POST", "/atx/click")
async def __click_handler(self, request: Request) -> Response:
button = valid_atx_button(request.query.get("button"))
wait = valid_bool(request.query.get("wait", False))
async def __click_handler(self, req: Request) -> Response:
button = valid_atx_button(req.query.get("button"))
wait = valid_bool(req.query.get("wait", False))
await ({
"power": self.__atx.click_power,
"power_long": self.__atx.click_power_long,
Expand Down
26 changes: 13 additions & 13 deletions kvmd/apps/kvmd/api/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -43,34 +43,34 @@
_COOKIE_AUTH_TOKEN = "auth_token"


async def check_request_auth(auth_manager: AuthManager, exposed: HttpExposed, request: Request) -> None:
async def check_request_auth(auth_manager: AuthManager, exposed: HttpExposed, req: Request) -> None:
if auth_manager.is_auth_required(exposed):
user = request.headers.get("X-KVMD-User", "")
user = req.headers.get("X-KVMD-User", "")
if user:
user = valid_user(user)
passwd = request.headers.get("X-KVMD-Passwd", "")
set_request_auth_info(request, f"{user} (xhdr)")
passwd = req.headers.get("X-KVMD-Passwd", "")
set_request_auth_info(req, f"{user} (xhdr)")
if not (await auth_manager.authorize(user, valid_passwd(passwd))):
raise ForbiddenError()
return

token = request.cookies.get(_COOKIE_AUTH_TOKEN, "")
token = req.cookies.get(_COOKIE_AUTH_TOKEN, "")
if token:
user = auth_manager.check(valid_auth_token(token)) # type: ignore
if not user:
set_request_auth_info(request, "- (token)")
set_request_auth_info(req, "- (token)")
raise ForbiddenError()
set_request_auth_info(request, f"{user} (token)")
set_request_auth_info(req, f"{user} (token)")
return

basic_auth = request.headers.get("Authorization", "")
basic_auth = req.headers.get("Authorization", "")
if basic_auth and basic_auth[:6].lower() == "basic ":
try:
(user, passwd) = base64.b64decode(basic_auth[6:]).decode("utf-8").split(":")
except Exception:
raise UnauthorizedError()
user = valid_user(user)
set_request_auth_info(request, f"{user} (basic)")
set_request_auth_info(req, f"{user} (basic)")
if not (await auth_manager.authorize(user, valid_passwd(passwd))):
raise ForbiddenError()
return
Expand All @@ -85,9 +85,9 @@ def __init__(self, auth_manager: AuthManager) -> None:
# =====

@exposed_http("POST", "/auth/login", auth_required=False)
async def __login_handler(self, request: Request) -> Response:
async def __login_handler(self, req: Request) -> Response:
if self.__auth_manager.is_auth_enabled():
credentials = await request.post()
credentials = await req.post()
token = await self.__auth_manager.login(
user=valid_user(credentials.get("user", "")),
passwd=valid_passwd(credentials.get("passwd", "")),
Expand All @@ -98,9 +98,9 @@ async def __login_handler(self, request: Request) -> Response:
return make_json_response()

@exposed_http("POST", "/auth/logout")
async def __logout_handler(self, request: Request) -> Response:
async def __logout_handler(self, req: Request) -> Response:
if self.__auth_manager.is_auth_enabled():
token = valid_auth_token(request.cookies.get(_COOKIE_AUTH_TOKEN, ""))
token = valid_auth_token(req.cookies.get(_COOKIE_AUTH_TOKEN, ""))
self.__auth_manager.logout(token)
return make_json_response()

Expand Down
54 changes: 27 additions & 27 deletions kvmd/apps/kvmd/api/hid.py
Original file line number Diff line number Diff line change
Expand Up @@ -85,22 +85,22 @@ async def __state_handler(self, _: Request) -> Response:
return make_json_response(await self.__hid.get_state())

@exposed_http("POST", "/hid/set_params")
async def __set_params_handler(self, request: Request) -> Response:
async def __set_params_handler(self, req: Request) -> Response:
params = {
key: validator(request.query.get(key))
key: validator(req.query.get(key))
for (key, validator) in [
("keyboard_output", valid_hid_keyboard_output),
("mouse_output", valid_hid_mouse_output),
("jiggler", valid_bool),
]
if request.query.get(key) is not None
if req.query.get(key) is not None
}
self.__hid.set_params(**params) # type: ignore
return make_json_response()

@exposed_http("POST", "/hid/set_connected")
async def __set_connected_handler(self, request: Request) -> Response:
self.__hid.set_connected(valid_bool(request.query.get("connected")))
async def __set_connected_handler(self, req: Request) -> Response:
self.__hid.set_connected(valid_bool(req.query.get("connected")))
return make_json_response()

@exposed_http("POST", "/hid/reset")
Expand Down Expand Up @@ -128,12 +128,12 @@ async def __keymaps_handler(self, _: Request) -> Response:
return make_json_response(await self.get_keymaps())

@exposed_http("POST", "/hid/print")
async def __print_handler(self, request: Request) -> Response:
text = await request.text()
limit = int(valid_int_f0(request.query.get("limit", 1024)))
async def __print_handler(self, req: Request) -> Response:
text = await req.text()
limit = int(valid_int_f0(req.query.get("limit", 1024)))
if limit > 0:
text = text[:limit]
symmap = self.__ensure_symmap(request.query.get("keymap", self.__default_keymap_name))
symmap = self.__ensure_symmap(req.query.get("keymap", self.__default_keymap_name))
self.__hid.send_key_events(text_to_web_keys(text, symmap))
return make_json_response()

Expand Down Expand Up @@ -257,45 +257,45 @@ def __process_ws_delta_event(self, event: dict, handler: Callable[[int, int], No
# =====

@exposed_http("POST", "/hid/events/send_key")
async def __events_send_key_handler(self, request: Request) -> Response:
key = valid_hid_key(request.query.get("key"))
async def __events_send_key_handler(self, req: Request) -> Response:
key = valid_hid_key(req.query.get("key"))
if key not in self.__ignore_keys:
if "state" in request.query:
state = valid_bool(request.query["state"])
if "state" in req.query:
state = valid_bool(req.query["state"])
self.__hid.send_key_events([(key, state)])
else:
self.__hid.send_key_events([(key, True), (key, False)])
return make_json_response()

@exposed_http("POST", "/hid/events/send_mouse_button")
async def __events_send_mouse_button_handler(self, request: Request) -> Response:
button = valid_hid_mouse_button(request.query.get("button"))
if "state" in request.query:
state = valid_bool(request.query["state"])
async def __events_send_mouse_button_handler(self, req: Request) -> Response:
button = valid_hid_mouse_button(req.query.get("button"))
if "state" in req.query:
state = valid_bool(req.query["state"])
self.__hid.send_mouse_button_event(button, state)
else:
self.__hid.send_mouse_button_event(button, True)
self.__hid.send_mouse_button_event(button, False)
return make_json_response()

@exposed_http("POST", "/hid/events/send_mouse_move")
async def __events_send_mouse_move_handler(self, request: Request) -> Response:
to_x = valid_hid_mouse_move(request.query.get("to_x"))
to_y = valid_hid_mouse_move(request.query.get("to_y"))
async def __events_send_mouse_move_handler(self, req: Request) -> Response:
to_x = valid_hid_mouse_move(req.query.get("to_x"))
to_y = valid_hid_mouse_move(req.query.get("to_y"))
self.__send_mouse_move_event(to_x, to_y)
return make_json_response()

@exposed_http("POST", "/hid/events/send_mouse_relative")
async def __events_send_mouse_relative_handler(self, request: Request) -> Response:
return self.__process_http_delta_event(request, self.__hid.send_mouse_relative_event)
async def __events_send_mouse_relative_handler(self, req: Request) -> Response:
return self.__process_http_delta_event(req, self.__hid.send_mouse_relative_event)

@exposed_http("POST", "/hid/events/send_mouse_wheel")
async def __events_send_mouse_wheel_handler(self, request: Request) -> Response:
return self.__process_http_delta_event(request, self.__hid.send_mouse_wheel_event)
async def __events_send_mouse_wheel_handler(self, req: Request) -> Response:
return self.__process_http_delta_event(req, self.__hid.send_mouse_wheel_event)

def __process_http_delta_event(self, request: Request, handler: Callable[[int, int], None]) -> Response:
delta_x = valid_hid_mouse_delta(request.query.get("delta_x"))
delta_y = valid_hid_mouse_delta(request.query.get("delta_y"))
def __process_http_delta_event(self, req: Request, handler: Callable[[int, int], None]) -> Response:
delta_x = valid_hid_mouse_delta(req.query.get("delta_x"))
delta_y = valid_hid_mouse_delta(req.query.get("delta_y"))
handler(delta_x, delta_y)
return make_json_response()

Expand Down
Loading

0 comments on commit 7a53f14

Please sign in to comment.