More robust error handling

This commit is contained in:
oitsjustjose 2026-08-29 11:21:26 -05:00
commit 60c733ca80
2 changed files with 23 additions and 17 deletions

View file

@ -36,12 +36,11 @@ async def list_servers(client: DockerClient, all: bool = False) -> list[dict]:
(List[Dict[str, any]]) A list of results from __extract_info (List[Dict[str, any]]) A list of results from __extract_info
""" """
containers: list[Container] = list( def __container_filter(container: Container) -> bool:
filter( image = container.attrs.get("Config", {}).get("Image", "")
lambda x: "itzg/minecraft-server" in x.attrs["Config"]["Image"] and "net.forgeserv.hidden" not in x.labels, return image == "itzg/minecraft-server" and "net.forgeserv.hidden" not in container.labels
client.containers.list(all=all),
) containers: list[Container] = list(filter(__container_filter, client.containers.list(all=all)))
)
ret = await asyncio.gather(*(Server.from_container(c) for c in containers)) ret = await asyncio.gather(*(Server.from_container(c) for c in containers))
ret = await asyncio.gather(*(x.asdict() for x in ret)) ret = await asyncio.gather(*(x.asdict() for x in ret))

View file

@ -3,6 +3,7 @@ from enum import Enum
from os import getenv from os import getenv
from typing import Any from typing import Any
import docker.errors
from docker.models.containers import Container from docker.models.containers import Container
from mcstatus import JavaServer from mcstatus import JavaServer
from mcstatus.responses import JavaStatusPlayer from mcstatus.responses import JavaStatusPlayer
@ -108,7 +109,7 @@ class Server:
server = JavaServer(getenv("HOST_IP", "localhost"), port=int(pair["HostPort"])) server = JavaServer(getenv("HOST_IP", "localhost"), port=int(pair["HostPort"]))
status = server.status() status = server.status()
return status.players.sample or [] return status.players.sample or []
except ConnectionRefusedError: # Thrown if the port isn't actually a server port except Exception: # noqa: BLE001, S112
continue continue
return [] return []
@ -201,11 +202,14 @@ class Server:
str: The resulting stdout value, or an error string to point str: The resulting stdout value, or an error string to point
you (me) to the logs. you (me) to the logs.
""" """
exit_code, output = container.exec_run(cmd) try:
if exit_code != 0: exit_code, output = container.exec_run(cmd)
print(output.decode()) # type: ignore if exit_code != 0:
return "⚠️ Error - Check Logs! ⚠️" print(output.decode()) # type: ignore
return output.decode() # type: ignore return "⚠️ Error - Check Logs! ⚠️"
return output.decode() # type: ignore
except docker.errors.APIError: # Thrown when the server is down. Return an empty string - not really an error.
return ""
def __parse_server_properties(props: str) -> dict[str, str | None]: def __parse_server_properties(props: str) -> dict[str, str | None]:
"""Parses the server.properties contents into a useable dict """Parses the server.properties contents into a useable dict
@ -222,9 +226,12 @@ class Server:
lines = list(filter(lambda x: not x.startswith("#") and len(x), lines)) lines = list(filter(lambda x: not x.startswith("#") and len(x), lines))
ret: dict[str, str | None] = {} ret: dict[str, str | None] = {}
for line in lines: for line in lines:
key, val = line.split("=") try:
val = str(val) if val else None key, val = line.split("=")
ret[key] = val val = str(val) if val else None
ret[key] = val
except ValueError: # Sometimes line.split() only returns one object instead of two?
continue
return ret return ret
ret = DerivedInfo() ret = DerivedInfo()
@ -232,8 +239,8 @@ class Server:
server_props = __get_from_exec("cat server.properties") server_props = __get_from_exec("cat server.properties")
# Then parse it into a useable format # Then parse it into a useable format
server_props = __parse_server_properties(server_props) server_props = __parse_server_properties(server_props)
ret.motd = server_props["motd"] or "" ret.motd = server_props.get("motd", "") or ""
ret.max_players = int(server_props["max-players"] or "0") ret.max_players = int(server_props.get("max-players", "0") or "0")
# We'll do something similar for the icon # We'll do something similar for the icon
ret.icon = __get_from_exec("base64 -i server-icon.png") ret.icon = __get_from_exec("base64 -i server-icon.png")