diff --git a/api.py b/api.py new file mode 100644 index 0000000..edfb609 --- /dev/null +++ b/api.py @@ -0,0 +1,30 @@ +""" +Author: Jose Stovall +Description: A Flask API service for the running Minecraft server statuses +""" + +from flask import jsonify, request, Flask +from flask_cors import CORS +from common import get_server_info + +app = Flask(__name__) +CORS(app) + +@app.route("/") +def index(): + try: + data = get_server_info(all=request.args.get('all')) + + if request.args.get('sortedOnKey'): + data = sorted(data, key=lambda x: x[request.args.get('sortedOnKey')]) + + resp = jsonify(data) + resp.status_code = 200 + return resp + except KeyError as e: + resp = jsonify({ "error": f"Failed to find key {str(e)}" }) + resp.status_code = 422 + return resp + +if __name__ == "__main__": + app.run(host='0.0.0.0') diff --git a/common.py b/common.py new file mode 100644 index 0000000..51e3ed1 --- /dev/null +++ b/common.py @@ -0,0 +1,136 @@ +""" +Author: Jose Stovall +Description: Common utilities used to fetch current server statuses +""" + +import docker +import base64 +import json +import requests +from ping import ping as ping_server + +client = docker.from_env() + +def __parse_log(log: str) -> dict: + """ + 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 + Arguments: + attrs (Dict[str, any]): The container's attributes + Returns: + (Dict[str, any]) with fields: + "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 = [] + icon = 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): + """ + 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( + filter( + lambda x: "itzg/minecraft-server" in x.attrs['Config']['Image'] and "net.forgeserv.hide" not in x.labels, + client.containers.list(all=all) + ) + ) + + ret = [__extract_info(c.attrs) for c in containers] + ret = list(filter(lambda x: x is not None, ret)) + return ret diff --git a/ping.py b/ping.py new file mode 100644 index 0000000..43606f8 --- /dev/null +++ b/ping.py @@ -0,0 +1,92 @@ +import struct +import socket +import base64 +import json +import sys + + +class Server: + 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 'Server(description={!r}, icon={!r}, version={!r}, '\ + 'protocol={!r}, players={})'.format( + self.description, bool(self.icon), self.version, + self.protocol, 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('invalid response %s' % sock.read(length)) + + 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 abborted') + + data += chunk + try: + return Server(json.loads(data)) + except json.decoder.JSONDecodeError: + return None + finally: + sock.close() diff --git a/ws.py b/ws.py new file mode 100644 index 0000000..3501338 --- /dev/null +++ b/ws.py @@ -0,0 +1,41 @@ +""" +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())