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 enum import Enum
from datetime import datetime, timedelta, timezone
from os import getenv
from typing import Any
@ -8,9 +9,11 @@ from docker.models.containers import Container
from mcstatus import JavaServer
from mcstatus.responses import JavaStatusPlayer
CACHE_MAX_AGE = timedelta(seconds=10)
@dataclass
class DerivedInfo:
class IntermittentData:
motd: str = ""
icon: str = ""
max_players: int = 0
@ -20,11 +23,10 @@ class DerivedInfo:
dynmap: str | None = None
class DerivedInfoLabelKeys(Enum):
DISPLAY_NAME = "net.forgeserv.display_name"
GAME_VERSION = "net.forgeserv.game_version"
PACK_VERSION = "net.forgeserv.pack_version"
DYNMAP = "net.forgeserv.dynmap"
@dataclass
class CachedData:
last_update: datetime
data: IntermittentData
@dataclass
@ -44,6 +46,11 @@ class ServerConstructorParams:
players: list[JavaStatusPlayer]
sem = Semaphore()
# Maps a container ID to the intermittently-updating data
cached_info: dict[str, CachedData] = {}
class Server:
def __init__(self, params: ServerConstructorParams):
self.health: str = params.health
@ -87,7 +94,7 @@ class Server:
return subitem
@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
Args:
@ -107,7 +114,7 @@ class Server:
for pair in pairs or []: # Really not necessary but pleases the linter
try:
server = JavaServer(getenv("HOST_IP", "localhost"), port=int(pair["HostPort"]))
status = server.status()
status = await server.async_status()
return status.players.sample or []
except Exception: # noqa: BLE001, S112
continue
@ -125,8 +132,11 @@ class Server:
Union[Server,None]: A server if parsing params was successful, None otherwise
"""
derived = Server.get_server_derived_info(container)
player_list = Server.get_players(container)
if not container.id:
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(
ServerConstructorParams(
@ -173,7 +183,7 @@ class Server:
return default
@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
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
@ -186,9 +196,6 @@ class Server:
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:
"""_Somewhat_ sketchy, but lets us run native commands
(itzg/minecraft-server is based off ubuntu). `container.exec_run`
@ -206,22 +213,20 @@ class Server:
exit_code, output = container.exec_run(cmd)
if exit_code != 0:
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
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() -> dict[str, str | None]:
"""Parses the server.properties contents into a useable dict
Smartly attempts to `json.loads` all values from the properties
so the resulting Dict has actually usable information!
Args:
props (str): The contents of server.properties
Returns:
dict[str, Any]: The propertly parsed result
"""
props = __get_from_exec("cat server.properties")
lines = props.split("\n")
lines = list(filter(lambda x: not x.startswith("#") and len(x), lines))
ret: dict[str, str | None] = {}
@ -234,21 +239,47 @@ class Server:
continue
return ret
ret = DerivedInfo()
# Literally get the contents of server.properties
server_props = __get_from_exec("cat server.properties")
def __get_cached() -> IntermittentData | None:
"""Attempts to get the cached data for this server. If the data is outdated or doesn't
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
server_props = __parse_server_properties(server_props)
ret.motd = server_props.get("motd", "") or ""
ret.max_players = int(server_props.get("max-players", "0") or "0")
server_props = __parse_server_properties()
uncached.motd = server_props.get("motd", "") or ""
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
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
ret.display_name = __get_from_label(DerivedInfoLabelKeys.DISPLAY_NAME) or container.name or ""
ret.game_version = __get_from_label(DerivedInfoLabelKeys.GAME_VERSION) or Server.get_from_env(container, "VERSION")
ret.pack_version = __get_from_label(DerivedInfoLabelKeys.PACK_VERSION)
ret.dynmap = __get_from_label(DerivedInfoLabelKeys.DYNMAP)
# Finally, let's get the semaphore and update the shared cache info
async with sem:
cached_info[container.id] = CachedData( # type: ignore -- we already do a check for container.id in Server.from_container
last_update=datetime.now(tz=timezone.utc),
data=uncached,
)
return ret
return uncached