Massive refactor, WSS and Rest on same eec
This commit is contained in:
parent
57f71eb0b9
commit
9863b0ead9
6 changed files with 276 additions and 242 deletions
41
src/__.py
41
src/__.py
|
|
@ -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())
|
||||
|
|
@ -3,30 +3,95 @@ Author: Jose Stovall
|
|||
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 websockets.asyncio.server import serve, ServerConnection
|
||||
|
||||
from common import get_server_info
|
||||
import docker
|
||||
from docker import DockerClient
|
||||
|
||||
app = Flask(__name__)
|
||||
CORS(app)
|
||||
from threading import Thread
|
||||
|
||||
|
||||
@app.route("/")
|
||||
def index():
|
||||
try:
|
||||
data = get_server_info(all=request.args.get("all"))
|
||||
class RestServer:
|
||||
def __init__(self, docker_client: DockerClient):
|
||||
self._app = Flask("RestAPI")
|
||||
self._app.add_url_rule("/", view_func=self.index)
|
||||
self._client = docker_client
|
||||
CORS(self._app)
|
||||
|
||||
if request.args.get("sort"):
|
||||
data = sorted(data, key=lambda x: x[request.args.get("sort")])
|
||||
def index(self):
|
||||
try:
|
||||
data = get_server_info(self._client, all=bool(request.args.get("all")))
|
||||
|
||||
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 request.args.get("sort"):
|
||||
data = sorted(data, key=lambda x: x[request.args.get("sort")])
|
||||
|
||||
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
|
||||
|
||||
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__":
|
||||
app.run(host="0.0.0.0")
|
||||
main()
|
||||
|
|
|
|||
147
src/common.py
147
src/common.py
|
|
@ -3,149 +3,27 @@ Author: Jose Stovall
|
|||
Description: Common utilities used to fetch current server statuses
|
||||
"""
|
||||
|
||||
import base64
|
||||
from typing import List
|
||||
|
||||
import docker
|
||||
import requests
|
||||
from docker import DockerClient
|
||||
|
||||
from ping import ping as ping_server
|
||||
|
||||
client = docker.from_env()
|
||||
from server import Server
|
||||
from typing import Union
|
||||
|
||||
|
||||
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:
|
||||
def parse_server(attrs: dict) -> Union[Server, None]:
|
||||
"""
|
||||
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
|
||||
(Server): The server parsed out from the container's attributes
|
||||
"""
|
||||
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
|
||||
params = Server.params_from_attrs(attrs)
|
||||
return Server(params) if params else None
|
||||
|
||||
|
||||
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
|
||||
Arguments:
|
||||
|
|
@ -155,12 +33,11 @@ def get_server_info(all: bool = False):
|
|||
"""
|
||||
containers = list(
|
||||
filter(
|
||||
lambda x: "itzg/minecraft-server" in x.attrs["Config"]["Image"]
|
||||
and "net.forgeserv.hide" not in x.labels,
|
||||
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 = [parse_server(c.attrs) for c in containers]
|
||||
ret = list(filter(lambda x: x is not None, ret))
|
||||
return ret
|
||||
return [x.asdict() for x in ret] # type: ignore
|
||||
|
|
|
|||
79
src/ping.py
79
src/ping.py
|
|
@ -4,35 +4,39 @@ import base64
|
|||
import json
|
||||
|
||||
|
||||
class Server:
|
||||
class ServerPingResponse:
|
||||
def __init__(self, data):
|
||||
self.description = data.get('description')
|
||||
self.description = data.get("description")
|
||||
if isinstance(self.description, dict):
|
||||
self.description = self.description['text']
|
||||
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']
|
||||
self.icon = base64.b64decode(data.get("favicon", "")[22:])
|
||||
self.players: ServerPingResponsePlayers = ServerPingResponsePlayers(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
|
||||
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):
|
||||
|
||||
class ServerPingResponsePlayers(list):
|
||||
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):
|
||||
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):
|
||||
self.id = data['id']
|
||||
self.name = data['name']
|
||||
self.id = data["id"]
|
||||
self.name = data["name"]
|
||||
|
||||
def __str__(self):
|
||||
return self.name
|
||||
|
|
@ -48,43 +52,44 @@ def ping(ip, port=25565):
|
|||
if not k:
|
||||
return 0
|
||||
k = k[0]
|
||||
i |= (k & 0x7f) << (j * 7)
|
||||
i |= (k & 0x7F) << (j * 7)
|
||||
j += 1
|
||||
if j > 5:
|
||||
raise ValueError('var_int too big')
|
||||
return -1
|
||||
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
|
||||
sock = socket.socket()
|
||||
sock.connect((ip, port))
|
||||
except ConnectionRefusedError:
|
||||
return None
|
||||
|
||||
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))
|
||||
return None
|
||||
|
||||
sock.recv(1) # packet type, 0 for pings
|
||||
length = read_var_int() # string length
|
||||
data = b''
|
||||
data = b""
|
||||
while len(data) != length:
|
||||
chunk = sock.recv(length - len(data))
|
||||
if not chunk:
|
||||
raise ValueError('connection abborted')
|
||||
return None
|
||||
|
||||
data += chunk
|
||||
try:
|
||||
return Server(json.loads(data))
|
||||
return ServerPingResponse(json.loads(data))
|
||||
except json.decoder.JSONDecodeError:
|
||||
return None
|
||||
finally:
|
||||
|
|
|
|||
148
src/server.py
148
src/server.py
|
|
@ -1,25 +1,153 @@
|
|||
import base64
|
||||
import json
|
||||
import re
|
||||
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
|
||||
class Player:
|
||||
pass
|
||||
name: str
|
||||
uuid: str
|
||||
|
||||
|
||||
@dataclass
|
||||
class Server:
|
||||
dynmap: Union[str, None]
|
||||
class ServerConstructorParams:
|
||||
health: str
|
||||
icon: str
|
||||
|
||||
status: str
|
||||
type: str
|
||||
version: str
|
||||
icon: Union[str, None]
|
||||
motd: str
|
||||
name: str
|
||||
|
||||
online: int
|
||||
max: int
|
||||
players: List[Player]
|
||||
|
||||
status: str
|
||||
type: str
|
||||
version: str
|
||||
|
||||
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.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
|
||||
|
|
|
|||
Loading…
Reference in a new issue