try{300,301,400}: fix

This commit is contained in:
Jörg Thalheim
2025-08-26 15:14:23 +02:00
parent 0a1802c341
commit cb9c8e5b5a
9 changed files with 30 additions and 33 deletions

View File

@@ -148,8 +148,8 @@ class HttpBridge(ApiBridge, BaseHTTPRequestHandler):
self.send_header("Content-Type", content_type) self.send_header("Content-Type", content_type)
self.end_headers() self.end_headers()
self.wfile.write(file_data) self.wfile.write(file_data)
except (OSError, json.JSONDecodeError, UnicodeDecodeError) as e: except (OSError, json.JSONDecodeError, UnicodeDecodeError):
log.error(f"Error reading Swagger file: {e!s}") log.exception("Error reading Swagger file")
self.send_error(500, "Internal Server Error") self.send_error(500, "Internal Server Error")
def _get_swagger_file_path(self, rel_path: str) -> Path: def _get_swagger_file_path(self, rel_path: str) -> Path:
@@ -264,10 +264,10 @@ class HttpBridge(ApiBridge, BaseHTTPRequestHandler):
"""Read and parse the request body. Returns None if there was an error.""" """Read and parse the request body. Returns None if there was an error."""
try: try:
content_length = int(self.headers.get("Content-Length", 0)) content_length = int(self.headers.get("Content-Length", 0))
if content_length > 0: if content_length == 0:
body = self.rfile.read(content_length) return {}
return json.loads(body.decode("utf-8")) body = self.rfile.read(content_length)
return {} return json.loads(body.decode("utf-8"))
except json.JSONDecodeError: except json.JSONDecodeError:
self.send_api_error_response( self.send_api_error_response(
"post", "post",

View File

@@ -539,11 +539,11 @@ def main() -> None:
try: try:
args.func(args) args.func(args)
except ClanError as e: except ClanError:
if debug: if debug:
log.exception("Exited with error") log.exception("Exited with error")
else: else:
log.error("%s", e) log.exception("Exited with error")
sys.exit(1) sys.exit(1)
except KeyboardInterrupt as ex: except KeyboardInterrupt as ex:
log.warning("Interrupted by user", exc_info=ex) log.warning("Interrupted by user", exc_info=ex)

View File

@@ -71,7 +71,7 @@ def create_clan(opts: CreateOptions) -> None:
try: try:
nix_metadata(str(opts.src_flake)) nix_metadata(str(opts.src_flake))
except ClanError: except ClanError:
log.error( log.exception(
f"Found a repository, but it is not a valid flake: {opts.src_flake}", f"Found a repository, but it is not a valid flake: {opts.src_flake}",
) )
log.warning("Setting src_flake to None") log.warning("Setting src_flake to None")

View File

@@ -45,7 +45,6 @@ def check_machine_ssh_login(
["true"], ["true"],
RunOpts(timeout=opts.timeout, needs_user_terminal=True), RunOpts(timeout=opts.timeout, needs_user_terminal=True),
) )
return
except ClanCmdTimeoutError as e: except ClanCmdTimeoutError as e:
msg = f"SSH login timeout after {opts.timeout}s" msg = f"SSH login timeout after {opts.timeout}s"
raise ClanError(msg) from e raise ClanError(msg) from e
@@ -54,6 +53,8 @@ def check_machine_ssh_login(
raise ClanError(e.cmd.stderr.strip()) from e raise ClanError(e.cmd.stderr.strip()) from e
msg = f"SSH login failed: {e}" msg = f"SSH login failed: {e}"
raise ClanError(msg) from e raise ClanError(msg) from e
else:
return
@API.register @API.register

View File

@@ -158,15 +158,15 @@ def read_qr_image(image_path: Path) -> dict[str, Any]:
try: try:
res = run(cmd) res = run(cmd)
data = res.stdout.strip() data = res.stdout.strip()
if not data:
msg = f"No QR code found in image: {image_path}"
raise ClanError(msg)
return json.loads(data)
except json.JSONDecodeError as e: except json.JSONDecodeError as e:
msg = f"Invalid JSON in QR code: {e}" msg = f"Invalid JSON in QR code: {e}"
raise ClanError(msg) from e raise ClanError(msg) from e
except Exception as e: except OSError as e:
msg = f"Failed to read QR code from {image_path}: {e}" msg = f"Failed to read QR code from {image_path}: {e}"
raise ClanError(msg) from e raise ClanError(msg) from e
if not data:
msg = f"No QR code found in image: {image_path}"
raise ClanError(msg)
return json.loads(data)

View File

@@ -82,14 +82,14 @@ class SudoAskpassProxy:
prompt = stripped_line[len("PASSWORD_REQUESTED:") :].strip() prompt = stripped_line[len("PASSWORD_REQUESTED:") :].strip()
password = self.handle_password_request(prompt) password = self.handle_password_request(prompt)
if ssh_process.stdin is None: if ssh_process.stdin is None:
msg = "SSH process stdin is None" logger.error("SSH process stdin is None")
raise ClanError(msg) return
print(password, file=ssh_process.stdin) print(password, file=ssh_process.stdin)
ssh_process.stdin.flush() ssh_process.stdin.flush()
else: else:
print(stripped_line) print(stripped_line)
except (OSError, ClanError) as e: except (OSError, ClanError):
logger.error(f"Error processing passwords requests output: {e}") logger.exception("Error processing passwords requests output")
def run(self) -> str: def run(self) -> str:
"""Run the SSH command with password proxying. Returns the askpass script path.""" """Run the SSH command with password proxying. Returns the askpass script path."""

View File

@@ -89,8 +89,8 @@ def machine_template(
try: try:
yield dst_machine_dir yield dst_machine_dir
except Exception as e: except Exception:
log.error(f"An error occurred inside the 'machine_template' context: {e}") log.exception("An error occurred inside the 'machine_template' context")
# Ensure that the directory is removed to avoid half-created machines # Ensure that the directory is removed to avoid half-created machines
# Everything in the with block is considered part of the context # Everything in the with block is considered part of the context
@@ -182,7 +182,7 @@ def clan_template(
try: try:
post_process(dst_dir) post_process(dst_dir)
except Exception as e: except Exception as e:
log.error(f"Error during post-processing of clan template: {e}") log.exception("Error during post-processing of clan template")
log.info(f"Removing left-over directory: {dst_dir}") log.info(f"Removing left-over directory: {dst_dir}")
shutil.rmtree(dst_dir, ignore_errors=True) shutil.rmtree(dst_dir, ignore_errors=True)
msg = ( msg = (
@@ -191,8 +191,8 @@ def clan_template(
raise ClanError(msg) from e raise ClanError(msg) from e
try: try:
yield dst_dir yield dst_dir
except Exception as e: except Exception:
log.error(f"An error occurred inside the 'clan_template' context: {e}") log.exception("An error occurred inside the 'clan_template' context")
log.info(f"Removing left-over directory: {dst_dir}") log.info(f"Removing left-over directory: {dst_dir}")
shutil.rmtree(dst_dir, ignore_errors=True) shutil.rmtree(dst_dir, ignore_errors=True)
raise raise

View File

@@ -340,11 +340,9 @@ class VMObject(GObject.Object):
# Try to shutdown the VM gracefully using QMP # Try to shutdown the VM gracefully using QMP
try: try:
if self.qmp_wrap is None: if self.qmp_wrap is not None:
msg = "QMP wrapper is not available" with self.qmp_wrap.qmp_ctx() as qmp:
raise ClanError(msg) qmp.command("system_powerdown")
with self.qmp_wrap.qmp_ctx() as qmp:
qmp.command("system_powerdown")
except (ClanError, OSError, ConnectionError) as ex: except (ClanError, OSError, ConnectionError) as ex:
log.debug(f"QMP command 'system_powerdown' ignored. Error: {ex}") log.debug(f"QMP command 'system_powerdown' ignored. Error: {ex}")

View File

@@ -62,8 +62,6 @@ lint.ignore = [
"PLR0912", "PLR0912",
"PLR0913", "PLR0913",
"PLR0915", "PLR0915",
"TRY300",
"TRY301",
"FBT003", "FBT003",
"INP001", "INP001",
] ]