Asyncify more things, cache

This commit is contained in:
oitsjustjose 2026-08-29 22:41:57 -05:00
commit 57ed96ae42

View file

@ -1,5 +1,6 @@
from asyncio import Semaphore
from dataclasses import dataclass from dataclasses import dataclass
from enum import Enum from datetime import datetime, timedelta, timezone
from os import getenv from os import getenv
from typing import Any from typing import Any
@ -8,9 +9,11 @@ from docker.models.containers import Container
from mcstatus import JavaServer from mcstatus import JavaServer
from mcstatus.responses import JavaStatusPlayer from mcstatus.responses import JavaStatusPlayer
CACHE_MAX_AGE = timedelta(seconds=10)
@dataclass @dataclass
class DerivedInfo: class IntermittentData:
motd: str = "" motd: str = ""
icon: str = "" icon: str = ""
max_players: int = 0 max_players: int = 0
@ -20,11 +23,10 @@ class DerivedInfo:
dynmap: str | None = None dynmap: str | None = None
class DerivedInfoLabelKeys(Enum): @dataclass
DISPLAY_NAME = "net.forgeserv.display_name" class CachedData:
GAME_VERSION = "net.forgeserv.game_version" last_update: datetime
PACK_VERSION = "net.forgeserv.pack_version" data: IntermittentData
DYNMAP = "net.forgeserv.dynmap"
@dataclass @dataclass
@ -44,6 +46,11 @@ class ServerConstructorParams:
players: list[JavaStatusPlayer] players: list[JavaStatusPlayer]
sem = Semaphore()
# Maps a container ID to the intermittently-updating data
cached_info: dict[str, CachedData] = {}
class Server: class Server:
def __init__(self, params: ServerConstructorParams): def __init__(self, params: ServerConstructorParams):
self.health: str = params.health self.health: str = params.health
@ -87,7 +94,7 @@ class Server:
return subitem return subitem
@staticmethod @staticmethod
def get_players(container: Container) -> list[JavaStatusPlayer]: async def get_players(container: Container) -> list[JavaStatusPlayer]:
"""Iterates through all Container:Host port binding pairs and attempts to ping the server """Iterates through all Container:Host port binding pairs and attempts to ping the server
Args: Args:
@ -107,7 +114,7 @@ class Server:
for pair in pairs or []: # Really not necessary but pleases the linter for pair in pairs or []: # Really not necessary but pleases the linter
try: try:
server = JavaServer(getenv("HOST_IP", "localhost"), port=int(pair["HostPort"])) server = JavaServer(getenv("HOST_IP", "localhost"), port=int(pair["HostPort"]))
status = server.status() status = await server.async_status()
return status.players.sample or [] return status.players.sample or []
except Exception: # noqa: BLE001, S112 except Exception: # noqa: BLE001, S112
continue continue
@ -125,8 +132,11 @@ class Server:
Union[Server,None]: A server if parsing params was successful, None otherwise Union[Server,None]: A server if parsing params was successful, None otherwise
""" """
derived = Server.get_server_derived_info(container) if not container.id:
player_list = Server.get_players(container) raise Exception(f"This container doesn't have an ID! Name={container.name} (Probably Empty)") # noqa: TRY002
derived = await Server.get_intermittent_data(container)
player_list = await Server.get_players(container)
return Server( return Server(
ServerConstructorParams( ServerConstructorParams(
@ -173,7 +183,7 @@ class Server:
return default return default
@staticmethod @staticmethod
def get_server_derived_info(container: Container) -> DerivedInfo: async def get_intermittent_data(container: Container) -> IntermittentData:
"""Fetches any hard-coded information provided by labels and """Fetches any hard-coded information provided by labels and
other container-specific sources. It's expected to be used primarily, other container-specific sources. It's expected to be used primarily,
and will fall back to the log to derive this info (such as MOTD and will fall back to the log to derive this info (such as MOTD
@ -186,9 +196,6 @@ class Server:
LabelDerivedInfo: The derived info we were able to get from the server's labels. LabelDerivedInfo: The derived info we were able to get from the server's labels.
""" """
def __get_from_label(key: DerivedInfoLabelKeys) -> str | None:
return str(container.labels[key.value]) if key.value in container.labels else None
def __get_from_exec(cmd: str) -> str: def __get_from_exec(cmd: str) -> str:
"""_Somewhat_ sketchy, but lets us run native commands """_Somewhat_ sketchy, but lets us run native commands
(itzg/minecraft-server is based off ubuntu). `container.exec_run` (itzg/minecraft-server is based off ubuntu). `container.exec_run`
@ -206,22 +213,20 @@ class Server:
exit_code, output = container.exec_run(cmd) exit_code, output = container.exec_run(cmd)
if exit_code != 0: if exit_code != 0:
print(output.decode()) # type: ignore print(output.decode()) # type: ignore
return "⚠️ Error - Check Logs! ⚠️" raise Exception(f"Got a non-zero exit code running container.exec_run('{cmd}')") # noqa: TRY002
return output.decode() # type: ignore return output.decode() # type: ignore
except docker.errors.APIError: # Thrown when the server is down. Return an empty string - not really an error. except docker.errors.APIError: # Thrown when the server is down. Return an empty string - not really an error.
return "" return ""
def __parse_server_properties(props: str) -> dict[str, str | None]: def __parse_server_properties() -> dict[str, str | None]:
"""Parses the server.properties contents into a useable dict """Parses the server.properties contents into a useable dict
Smartly attempts to `json.loads` all values from the properties Smartly attempts to `json.loads` all values from the properties
so the resulting Dict has actually usable information! so the resulting Dict has actually usable information!
Args:
props (str): The contents of server.properties
Returns: Returns:
dict[str, Any]: The propertly parsed result dict[str, Any]: The propertly parsed result
""" """
props = __get_from_exec("cat server.properties")
lines = props.split("\n") lines = props.split("\n")
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] = {}
@ -234,21 +239,47 @@ class Server:
continue continue
return ret return ret
ret = DerivedInfo() def __get_cached() -> IntermittentData | None:
# Literally get the contents of server.properties """Attempts to get the cached data for this server. If the data is outdated or doesn't
server_props = __get_from_exec("cat server.properties") exist, then None is returned; otherwise, the cached data gets returned to avoid
thrashing or other I/O bound issues in the future.
Returns:
IntermittentData | None: The data, if valid, else None
"""
if not container.id or container.id not in cached_info:
return None
cached = cached_info[container.id]
if datetime.now(tz=timezone.utc) - cached.last_update > CACHE_MAX_AGE:
return None
return cached.data
cached = __get_cached()
if cached:
return cached
uncached = IntermittentData()
# 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()
ret.motd = server_props.get("motd", "") or "" uncached.motd = server_props.get("motd", "") or ""
ret.max_players = int(server_props.get("max-players", "0") or "0") uncached.max_players = int(server_props.get("max-players", "0") or "0")
# These are custom fields, but much more modular than labels.
uncached.display_name = server_props.get("server-name", container.name) or ""
uncached.pack_version = server_props.get("modpack-version")
uncached.dynmap = server_props.get("dynamp")
# 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") uncached.icon = __get_from_exec("base64 -i server-icon.png")
# Lastly we can get the game version just from the Environment
uncached.game_version = Server.get_from_env(container, "VERSION")
# The rest we'll get from labels if we can # Finally, let's get the semaphore and update the shared cache info
ret.display_name = __get_from_label(DerivedInfoLabelKeys.DISPLAY_NAME) or container.name or "" async with sem:
ret.game_version = __get_from_label(DerivedInfoLabelKeys.GAME_VERSION) or Server.get_from_env(container, "VERSION") cached_info[container.id] = CachedData( # type: ignore -- we already do a check for container.id in Server.from_container
ret.pack_version = __get_from_label(DerivedInfoLabelKeys.PACK_VERSION) last_update=datetime.now(tz=timezone.utc),
ret.dynmap = __get_from_label(DerivedInfoLabelKeys.DYNMAP) data=uncached,
)
return ret return uncached