Massive refactor, WSS and Rest on same eec

This commit is contained in:
oitsjustjose 2025-06-13 23:12:18 -05:00
commit 9863b0ead9
6 changed files with 276 additions and 242 deletions

4
.vscode/launch.json vendored
View file

@ -5,8 +5,8 @@
"name": "Python:Flask", "name": "Python:Flask",
"type": "debugpy", "type": "debugpy",
"request": "launch", "request": "launch",
"module": "streamlit", "cwd": "src",
"args": ["run", "src/main.py", "--server.headless", "true"] "program": "${file}"
} }
] ]
} }

View file

@ -1,41 +0,0 @@
"""
Author: Jose Stovall
Description: A WebSocket service which only pushes messages to clients when
server details change
"""
import json
import asyncio
from os import environ as env
from websockets.server import serve
from common import get_server_info
def __get():
return json.dumps(get_server_info(all=True))
async def wait_for_change(ws):
global cache
data = __get()
while data == cache:
await asyncio.sleep(1)
data = __get()
cache = data
await ws.send(data)
async def run(websocket):
while True:
# raises ConnectionClosed ex which breaks out of the loop.
# https://websockets.readthedocs.io/en/stable/howto/patterns.html
await wait_for_change(websocket)
async def setup():
async with serve(run, "localhost", int(env["PORT"])):
await asyncio.Future()
if __name__ == "__main__":
# Used to store the last message and compare if there's any change
cache = __get()
asyncio.run(setup())

View file

@ -3,30 +3,95 @@ Author: Jose Stovall
Description: A Flask API service for the running Minecraft server statuses Description: A Flask API service for the running Minecraft server statuses
""" """
from flask import jsonify, request, Flask import json
from os import environ as env
from flask import Flask, jsonify, request
import asyncio
from flask_cors import CORS from flask_cors import CORS
from websockets.asyncio.server import serve, ServerConnection
from common import get_server_info from common import get_server_info
import docker
from docker import DockerClient
app = Flask(__name__) from threading import Thread
CORS(app)
@app.route("/") class RestServer:
def index(): def __init__(self, docker_client: DockerClient):
try: self._app = Flask("RestAPI")
data = get_server_info(all=request.args.get("all")) self._app.add_url_rule("/", view_func=self.index)
self._client = docker_client
CORS(self._app)
if request.args.get("sort"): def index(self):
data = sorted(data, key=lambda x: x[request.args.get("sort")]) try:
data = get_server_info(self._client, all=bool(request.args.get("all")))
resp = jsonify(data) if request.args.get("sort"):
resp.status_code = 200 data = sorted(data, key=lambda x: x[request.args.get("sort")])
return resp
except KeyError as e: resp = jsonify(data)
resp = jsonify({"error": f"Failed to find key {str(e)}"}) resp.status_code = 200
resp.status_code = 422 return resp
return resp except KeyError as e:
resp = jsonify({"error": f"Failed to find key {str(e)}"})
resp.status_code = 422
return resp
def run(self, **kwargs):
print(f"Rest Server is now running on {kwargs['host']}:{kwargs['port']}")
self._app.run(**kwargs)
class WebSocketServer:
def __init__(self, docker_client: DockerClient):
self._client = docker_client
self.cache = json.dumps(get_server_info(self._client, all=True))
async def __loop_infinitely(self, conn: ServerConnection):
while True:
# raises ConnectionClosed ex which breaks out of the loop.
# https://websockets.readthedocs.io/en/stable/howto/patterns.html
await self.__wait_for_change(conn)
async def __setup(self, host: str, port: int = 8008):
async with serve(self.__loop_infinitely, host, port):
await asyncio.Future()
async def __wait_for_change(self, conn: ServerConnection):
new = json.dumps(get_server_info(self._client, all=True))
while new == self.cache:
await asyncio.sleep(1)
new = json.dumps(get_server_info(self._client, all=True))
print(new)
self.cache = new
await conn.send(new)
def run(self, host: str, port: int):
print(f"WebSocket Server is now running on {host}:{port}")
asyncio.run(self.__setup(host, port))
def main() -> None:
client = docker.from_env()
wss = WebSocketServer(client)
wss_thread = Thread(
daemon=True,
target=wss.run,
kwargs={
"host": "0.0.0.0",
"port": int(env["WS_PORT"]) if "WS_PORT" in env else 8008,
},
)
wss_thread.start()
RestServer(client).run(host="0.0.0.0", port=int(env["REST_PORT"]) if "REST_PORT" in env else 9090)
wss_thread.join()
if __name__ == "__main__": if __name__ == "__main__":
app.run(host="0.0.0.0") main()

View file

@ -3,149 +3,27 @@ Author: Jose Stovall
Description: Common utilities used to fetch current server statuses Description: Common utilities used to fetch current server statuses
""" """
import base64 from typing import List
import docker from docker import DockerClient
import requests
from ping import ping as ping_server from server import Server
from typing import Union
client = docker.from_env()
def __parse_log(log: str) -> dict: def parse_server(attrs: dict) -> Union[Server, None]:
"""
Gets the Game Version, MOTD, Online and Max Count from the server's log string
Arguments:
log (str): the current log from this server
Returns:
Dict[str, str] with fields:
"version": str
"online": str
"max": str
"motd": str
"""
FORMAT_CODES = [
"§0",
"§1",
"§2",
"§3",
"§4",
"§5",
"§6",
"§7",
"§8",
"§9",
"§a",
"§b",
"§c",
"§d",
"§e",
"§f",
"§o",
"§l",
"§m",
"§n",
"§o",
"§r",
]
KEYS = ["version", "online", "max", "motd"]
log = log.replace("localhost:25565 : ", "")
for cd in FORMAT_CODES:
log = log.replace(cd, "")
ret = {}
for idx, key in enumerate(KEYS):
start = log.find(key) + len(key)
end = 0
try:
end = log.index(KEYS[idx + 1])
except IndexError:
end = len(log)
except ValueError:
ret[key] = ""
value = log[start:end].strip().replace("=", "").replace("'", "")
ret[key] = value
return ret
def __get_type(env: list) -> 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 env:
if e.startswith("TYPE="):
tmp = e.replace("TYPE=", "")
return tmp[0].upper() + tmp[1:].lower()
return "Vanilla"
def __extract_info(attrs: dict) -> dict:
""" """
Retrieves only valuable fields from the a Minecraft Server's container attributes Retrieves only valuable fields from the a Minecraft Server's container attributes
Arguments: Arguments:
attrs (Dict[str, any]): The container's attributes attrs (Dict[str, any]): The container's attributes
Returns: Returns:
(Dict[str, any]) with fields: (Server): The server parsed out from the container's attributes
"name": str
"type": str
"status": str
"health": str
"players": List[Dict[str, str]], (A mapping of username & UUID)
"icon": str (A base64 representation of the server's 'server-icon.png')
"dynmap": Union[str, None] (None if the server has no dynmap associated with it)
"version": str
"online": str
"max": str
"motd": str
""" """
players = [] params = Server.params_from_attrs(attrs)
icon = None return Server(params) if params else None
dynmap = None
# Try to ping server if it's running to get users online
if attrs["State"]["Status"] == "running":
for key in attrs["HostConfig"]["PortBindings"]:
for binding in attrs["HostConfig"]["PortBindings"][key]:
try:
data = ping_server("localhost", port=int(binding["HostPort"]))
if (
not data
): # Hmm, it's a minecraft container but not a minecraft server port? might be dynmap:
# dynmap = find_dynmap(int(binding["HostPort"]))
host_port = int(binding["HostPort"])
request = requests.get(f"http://172.16.1.4:7070/{host_port}")
if request.ok:
dynmap = request.text
continue
icon = data.icon
players += [{"name": x.name, "uuid": x.id} for x in data.players]
except Exception as e:
print(e)
pass
info = {
"name": attrs["Name"][1:],
"type": __get_type(attrs["Config"]["Env"]),
"status": attrs["State"]["Status"],
"health": attrs["State"]["Health"]["Status"],
"players": players,
"icon": str(base64.b64encode(icon).decode()) if icon else None,
"dynmap": dynmap,
}
info.update(__parse_log(attrs["State"]["Health"]["Log"][-1]["Output"]))
return info
def get_server_info(all: bool = False): def get_server_info(client: DockerClient, all: bool = False) -> List[dict]:
""" """
Distills the container data for all servers on the current host into a usable format Distills the container data for all servers on the current host into a usable format
Arguments: Arguments:
@ -155,12 +33,11 @@ def get_server_info(all: bool = False):
""" """
containers = list( containers = list(
filter( filter(
lambda x: "itzg/minecraft-server" in x.attrs["Config"]["Image"] lambda x: "itzg/minecraft-server" in x.attrs["Config"]["Image"] and "net.forgeserv.hide" not in x.labels,
and "net.forgeserv.hide" not in x.labels,
client.containers.list(all=all), client.containers.list(all=all),
) )
) )
ret = [__extract_info(c.attrs) for c in containers] ret = [parse_server(c.attrs) for c in containers]
ret = list(filter(lambda x: x is not None, ret)) ret = list(filter(lambda x: x is not None, ret))
return ret return [x.asdict() for x in ret] # type: ignore

View file

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

View file

@ -1,25 +1,153 @@
import base64
import json
import re
from dataclasses import dataclass from dataclasses import dataclass
from typing import Union, List from typing import List, Union
from ping import ServerPingResponse
from ping import ping as ping_server
SPECIAL_CHAR = "§"
@dataclass
class LogDerivedInfo:
version: str = ""
max: int = 0
motd: str = ""
@dataclass @dataclass
class Player: class Player:
pass name: str
uuid: str
@dataclass @dataclass
class Server: class ServerConstructorParams:
dynmap: Union[str, None]
health: str health: str
icon: str status: str
type: str
version: str
icon: Union[str, None]
motd: str motd: str
name: str name: str
online: int online: int
max: int max: int
players: List[Player] players: List[Player]
status: str
type: str class Server:
version: str 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.icon: Union[str, None] = params.icon
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
def asdict(self) -> dict:
d = self.__dict__
d["players"] = [x.__dict__ for x in self.players]
return d
@staticmethod
def params_from_attrs(attrs: dict) -> Union[ServerConstructorParams, None]:
"""Builds the class from the container attrs passed in
Args:
attrs (dict): The container attributes for the given MC container
"""
server_ping_info: Union[ServerPingResponse, None] = None
# Try to ping server if it's running to get users online
for binding in attrs["HostConfig"]["PortBindings"]:
port, protocol = binding.split("/")
# Realistically nothing we care about is on TCP...
if protocol != "tcp":
continue
server_ping_info = ping_server("localhost", port=int(port))
if server_ping_info is not None:
break
if server_ping_info is None:
return None
log_info = Server.parse_log_for_info(attrs["State"]["Health"]["Log"][-1]["Output"])
players = [Player(name=pl.name, uuid=pl.id) for pl in server_ping_info.players]
return ServerConstructorParams(
health=attrs["State"]["Health"]["Status"],
status=attrs["State"]["Status"],
type=Server.get_server_type(attrs["Config"]["Env"]),
version=log_info.version,
icon=str(base64.b64encode(server_ping_info.icon).decode()) if server_ping_info.icon else None,
motd=log_info.motd,
name=attrs["Name"][1:],
online=len(players),
max=log_info.max,
players=players,
)
@staticmethod
def get_server_type(docker_environment: list) -> 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()
return "Vanilla"
@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
Returns:
(LogDerivedInfo): Info derived from the log lines.
"""
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, ""))
# 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("\w+(?=\=)", logs)
ret = LogDerivedInfo()
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])
value = logs[start:end].strip()
try:
value = int(value)
except ValueError:
pass
ret.__dict__[key] = value
ret.motd = __cleanup_motd(ret.motd).replace('"', "").replace("'", "")
return ret