Enormous refactor

This commit is contained in:
oitsjustjose 2026-08-28 21:52:17 -05:00
commit 50b60c40d5
5 changed files with 215 additions and 253 deletions

View file

@ -1,5 +1,6 @@
annotated-types==0.7.0
anyio==4.9.0
asyncio-dgram==3.0.0
certifi==2025.6.15
charset-normalizer==3.4.2
click==8.2.1
@ -15,19 +16,28 @@ httptools==0.6.4
httpx==0.28.1
idna==3.10
Jinja2==3.1.6
lance-namespace==0.8.6
lance-namespace-urllib3-client==0.8.6
markdown-it-py==3.0.0
MarkupSafe==3.0.2
mcstatus==14.1.0
mdurl==0.1.2
numpy==2.2.6
pyarrow==25.0.1
pydantic==2.11.7
pydantic_core==2.33.2
Pygments==2.19.1
pylance==10.0.0
python-dateutil==2.9.0.post0
python-dotenv==1.1.0
python-multipart==0.0.20
PyYAML==6.0.2
requests==2.32.4
rich==14.0.0
rich-toolkit==0.14.7
ruff==0.16.5
shellingham==1.5.4
six==1.17.0
sniffio==1.3.1
starlette==0.46.2
typer==0.16.0

View file

@ -1,31 +0,0 @@
"""
Author: Jose Stovall
Description: Common utilities used to fetch current server statuses
"""
from docker import DockerClient
from docker.models.containers import Container
from server import Server
def list_servers(client: DockerClient, all: bool = False) -> list[dict]:
"""
Distills the container data for all servers on the current host into a usable format
Arguments:
all (bool): whether to return *all* servers, or just the running one
Returns:
(List[Dict[str, any]]) A list of results from __extract_info
"""
containers: list[Container] = list(
filter(
lambda x: "itzg/minecraft-server" in x.attrs["Config"]["Image"] and "net.forgeserv.hidden" not in x.labels,
client.containers.list(all=all),
)
)
ret = [Server.from_container(c) for c in containers]
ret = list(filter(lambda x: x is not None, ret))
return [x.asdict() for x in ret] # type: ignore

View file

@ -6,10 +6,12 @@ Run via Docker with either network mode = HOST, **OR** set the environment varia
"""
import docker
from docker import DockerClient
from docker.models.containers import Container
from fastapi import FastAPI, Response, status
from fastapi.middleware.cors import CORSMiddleware
from common import list_servers
from server import Server
app: FastAPI = FastAPI()
app.add_middleware(
@ -23,6 +25,27 @@ app.add_middleware(
client = docker.from_env()
def list_servers(client: DockerClient, all: bool = False) -> list[dict]:
"""
Distills the container data for all servers on the current host into a usable format
Arguments:
all (bool): whether to return *all* servers, or just the running one
Returns:
(List[Dict[str, any]]) A list of results from __extract_info
"""
containers: list[Container] = list(
filter(
lambda x: "itzg/minecraft-server" in x.attrs["Config"]["Image"] and "net.forgeserv.hidden" not in x.labels,
client.containers.list(all=all),
)
)
ret = [Server.from_container(c) for c in containers]
ret = list(filter(lambda x: x is not None, ret))
return [x.asdict() for x in ret]
@app.get("/")
def index(response: Response, all: bool = False, sort: str = ""):
try:

View file

@ -1,91 +0,0 @@
import base64
import json
import socket
import struct
class ServerPingResponse:
def __init__(self, data):
self.description = data.get("description")
if isinstance(self.description, dict):
self.description = self.description["text"]
self.icon = base64.b64decode(data.get("favicon", "")[22:])
self.players = Players(data["players"])
self.version = data["version"]["name"]
self.protocol = data["version"]["protocol"]
def __str__(self):
return f"Server(description={self.description!r}, icon={bool(self.icon)!r}, version={self.version!r}, protocol={self.protocol!r}, players={self.players})"
class Players(list):
def __init__(self, data):
super().__init__(Player(x) for x in data.get("sample", []))
def __str__(self):
return "[{}]".format(", ".join(str(x) for x in self))
class Player:
def __init__(self, data):
self.id = data["id"]
self.name = data["name"]
def __str__(self):
return self.name
# For the rest of requests see wiki.vg/Protocol
def ping(ip, port=25565):
def read_var_int():
i = 0
j = 0
while True:
k = sock.recv(1)
if not k:
return 0
k = k[0]
i |= (k & 0x7F) << (j * 7)
j += 1
if j > 5:
raise ValueError("var_int too big")
if not (k & 0x80):
return i
sock = socket.socket()
sock.connect((ip, port))
try:
host = ip.encode("utf-8")
data = b"" # wiki.vg/Server_List_Ping
data += b"\x00" # packet ID
data += b"\x04" # protocol variant
data += struct.pack(">b", len(host)) + host
data += struct.pack(">H", port)
data += b"\x01" # next state
data = struct.pack(">b", len(data)) + data
sock.sendall(data + b"\x01\x00") # handshake + status ping
length = read_var_int() # full packet length
if length < 10:
if length < 0:
raise ValueError("negative length read")
else:
raise ValueError(f"invalid response {sock.read(length)}") # type: ignore
sock.recv(1) # packet type, 0 for pings
length = read_var_int() # string length
data = b""
while len(data) != length:
chunk = sock.recv(length - len(data))
if not chunk:
raise ValueError("connection aborted")
data += chunk
try:
return ServerPingResponse(json.loads(data))
except json.decoder.JSONDecodeError:
return None
except:
return None
finally:
sock.close()

View file

@ -1,29 +1,29 @@
import base64
import re
from dataclasses import dataclass
from enum import Enum
from os import getenv
from typing import Any
from docker.models.containers import Container
from ping import ServerPingResponse
from ping import ping as ping_server
SPECIAL_CHAR = "§"
DYNMAP_LABEL_KEY = "net.forgeserv.dynmap"
from mcstatus import JavaServer
from mcstatus.responses import JavaStatusPlayer
@dataclass
class LogDerivedInfo:
version: str = ""
max: int = 0
class DerivedInfo:
motd: str = ""
icon: str = ""
max_players: int = 0
display_name: str = ""
game_version: str = ""
pack_version: str | None = ""
dynmap: str | None = None
@dataclass
class Player:
name: str
uuid: str
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
@ -31,71 +31,32 @@ class ServerConstructorParams:
health: str
status: str
type: str
version: str
game_version: str
icon: str | None
display_name: str
internal_name: str
motd: str
name: str
online: int
max: int
players: list[Player]
online_players: int
max_players: int
players: list[JavaStatusPlayer]
pack_version: str | None
dynmap: str | None
def ping_container_server(container: Container) -> ServerPingResponse | None:
"""Iterates through all Container:Host port binding pairs and attempts to ping the server
Args:
container (Container): The container whose port bindings to try to ping
Returns:
Union[ServerPingResponse, None]: The info derived from the Ping, if available, otherwise None (failure case)
"""
# container.ports looks like {'25565/tcp': [{'HostIp': '0.0.0.0', 'HostPort': '25567'}, {'HostIp': '::', 'HostPort': '25567'}] }
# we only want the host host IP and host port, so we can skip that and just look at the values and ignore the
# "{port}/{tcp|udp}" part
for ip_port_pairs in container.ports.values():
for ip_port_pair in ip_port_pairs:
try:
port = int(ip_port_pair["HostPort"])
return ping_server(getenv("HOST_IP", "localhost"), port=port)
except ValueError:
return None
def safe_get(d_in: dict, key: str) -> Any:
"""Attempts to get a heavily nested object in a k:v pair, safely and quickly
Nested keys are to be split using a slash (/), so dict["State"]["Health"]["Status"]
would mean that the key passed in would be "State/Health/Status"
Args:
d_in (dict): The dictionary to scan through
key (str): The key formatted as documented above
Returns:
object: The dict value (can be anything) or None if we failed to find it
"""
keys = key.split("/")
subitem = d_in
for k in keys:
if k not in subitem:
return None
subitem = subitem[k]
return subitem
class Server:
def __init__(self, params: ServerConstructorParams):
self.health: str = params.health
self.status: str = params.status
self.type: str = params.type
self.version: str = params.version
self.game_version: str = params.game_version
self.icon: str | None = params.icon
self.display_name: str = params.display_name
self.internal_name: str = params.internal_name
self.motd: str = params.motd
self.name: str = params.name
self.online: int = params.online
self.max: int = params.max
self.players: list[Player] = params.players
self.online_players: int = params.online_players
self.max_players: int = params.max_players
self.players: list[JavaStatusPlayer] = params.players
self.pack_version: str | None = params.pack_version
self.dynmap: str | None = params.dynmap
def asdict(self) -> dict:
@ -103,6 +64,55 @@ class Server:
d["players"] = [x.__dict__ for x in self.players]
return d
@staticmethod
def safe_get(d_in: dict, key: str) -> Any:
"""Attempts to get a heavily nested object in a k:v pair, safely and quickly
Nested keys are to be split using a slash (/), so dict["State"]["Health"]["Status"]
would mean that the key passed in would be "State/Health/Status"
Args:
d_in (dict): The dictionary to scan through
key (str): The key formatted as documented above
Returns:
object: The dict value (can be anything) or None if we failed to find it
"""
keys = key.split("/")
subitem = d_in
for k in keys:
if k not in subitem:
return None
subitem = subitem[k]
return subitem
@staticmethod
def get_players(container: Container) -> list[JavaStatusPlayer]:
"""Iterates through all Container:Host port binding pairs and attempts to ping the server
Args:
container (Container): The container whose port bindings to try to ping
Returns:
(ServerPingResponse): The info derived from the Ping, if available, otherwise a stub
"""
# container.ports looks like {'25565/tcp': [{'HostIp': '0.0.0.0', 'HostPort': '25567'}, {'HostIp': '::', 'HostPort': '25567'}] }
# we only want the host host IP and host port, so we can skip that and just look at the values and ignore the
# "{port}/{tcp|udp}" part
if not container.ports:
return []
for pairs in container.ports.values():
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()
return status.players.sample or []
except ConnectionRefusedError: # Thrown if the port isn't actually a server port
continue
return []
@staticmethod
def from_container(container: Container):
"""Attempts to build out a server instance from a given container
@ -114,83 +124,124 @@ class Server:
Union[Server,None]: A server if parsing params was successful, None otherwise
"""
ping_data = ping_container_server(container)
if not ping_data:
return None
log_info = Server.parse_log_for_info(container.attrs["State"]["Health"]["Log"][-1]["Output"])
players = [Player(name=pl.name, uuid=pl.id) for pl in ping_data.players]
dynmap = container.labels[DYNMAP_LABEL_KEY] if DYNMAP_LABEL_KEY in container.labels else None
derived = Server.get_server_derived_info(container)
player_list = Server.get_players(container)
return Server(
ServerConstructorParams(
health=str(safe_get(container.attrs, "State/Health/Status")),
status=str(safe_get(container.attrs, "State/Status")),
type=Server.get_server_type(list(safe_get(container.attrs, "Config/Env"))),
version=log_info.version,
icon=str(base64.b64encode(ping_data.icon).decode()) if ping_data.icon else None,
motd=log_info.motd,
name=container.name or container.id or "",
online=len(players),
max=log_info.max,
players=players,
dynmap=dynmap,
health=str(Server.safe_get(container.attrs, "State/Health/Status")),
status=str(Server.safe_get(container.attrs, "State/Status")),
type=Server.get_from_env(container, "TYPE", default="Vanilla"),
internal_name=container.name or "",
motd=derived.motd,
icon=derived.icon,
max_players=derived.max_players,
display_name=derived.display_name,
game_version=derived.game_version,
pack_version=derived.pack_version,
dynmap=derived.dynmap,
online_players=len(player_list),
players=player_list,
)
)
@staticmethod
def get_server_type(docker_environment: list) -> str:
def get_from_env(container: Container, env_key: str, default: str = "") -> str:
"""
Gets the type of MC Server currently hosted based on the Environment variables
Arguments:
env: List[str]
Returns:
(str) The type of server, or "Vanilla" if none can be detected.
"""
for e in docker_environment:
if e.startswith("TYPE="):
tmp = e.replace("TYPE=", "")
return tmp[0].upper() + tmp[1:].lower()
Gets a value from the Docker Container's Environment based on the provided key
return "Vanilla"
Arguments:
container: (Container) the container to inspect
env_key: (str) The key to look up
default: (str) The fallback if the key isn't found
Returns:
(str) The type of server, or `default` if the key isn't found in
the container's environment variables
"""
env: list[str] = Server.safe_get(container.attrs, "Config/Env")
if not env:
return default
normd_key = env_key if env_key.endswith("=") else f"{env_key}="
for e in env:
if e.startswith(normd_key):
return e.replace(normd_key, "")
return default
@staticmethod
def parse_log_for_info(logs: str) -> LogDerivedInfo:
"""
Gets the Game Version, MOTD, Online and Max Count from the server's log string
Arguments:
log (str): the current log from this server
def get_server_derived_info(container: Container) -> DerivedInfo:
"""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
for Display Name)
Args:
container (Container): The Docker Container for the given server
Returns:
(LogDerivedInfo): Info derived from the log lines.
LabelDerivedInfo: The derived info we were able to get from the server's labels.
"""
def __cleanup_motd(motd: str) -> str:
"""Removes any color / format coding from a given MOTD"""
if SPECIAL_CHAR not in motd:
return motd
start = motd.index(SPECIAL_CHAR)
repl = motd[start : start + 2]
return __cleanup_motd(motd.replace(repl, ""))
def __get_from_label(key: DerivedInfoLabelKeys) -> str | None:
return str(container.labels[key.value]) if key.value in container.labels else None
# We only care about the right half of the data after the :
_, logs = logs.split(" : ")
# Find all keys for the log line (universally)
keys: list[str] = re.findall(r"\w+(?=\=)", logs)
ret = LogDerivedInfo()
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`
takes any bash command and returns the exit_code and stdout
results. This allows us to validate and error out
for idx, key in enumerate(keys):
start = logs.index(key) + len(f"{key}=")
end = len(logs) - 1
if key != keys[-1]: # If we're NOT on the last key in the array, bump up
end = logs.index(keys[idx + 1])
Args:
cmd (str): The image-compatible command (test before using of course)
value = logs[start:end].strip()
try:
value = int(value)
except ValueError:
pass
Returns:
str: The resulting stdout value, or an error string to point
you (me) to the logs.
"""
exit_code, output = container.exec_run(cmd)
if exit_code != 0:
print(output.decode()) # type: ignore
return "⚠️ Error - Check Logs! ⚠️"
return output.decode() # type: ignore
ret.__dict__[key] = value
def __parse_server_properties(props: str) -> 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
"""
lines = props.split("\n")
lines = list(filter(lambda x: not x.startswith("#") and len(x), lines))
ret: dict[str, str | None] = {}
for line in lines:
key, val = line.split("=")
val = str(val) if val else None
ret[key] = val
return ret
ret = DerivedInfo()
# Literally get the contents of server.properties
server_props = __get_from_exec("cat server.properties")
# Then parse it into a useable format
server_props = __parse_server_properties(server_props)
ret.motd = server_props["motd"] or ""
ret.max_players = int(server_props["max-players"] or "0")
# We'll do something similar for the icon
ret.icon = __get_from_exec("base64 -i server-icon.png")
# The rest we'll get from labels if we can
ret.display_name = __get_from_label(DerivedInfoLabelKeys.DISPLAY_NAME) or ret.motd
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)
ret.motd = __cleanup_motd(ret.motd).replace('"', "").replace("'", "")
return ret