Update backend API infra
This commit is contained in:
parent
e4a3a0e46b
commit
e6db3abad6
3 changed files with 369 additions and 56 deletions
|
|
@ -3,9 +3,10 @@ Author: Jose Stovall
|
|||
Description: Common utilities used to fetch current server statuses
|
||||
"""
|
||||
|
||||
from typing import List, Union
|
||||
from typing import List
|
||||
|
||||
from docker import DockerClient
|
||||
from docker.models.containers import Container
|
||||
|
||||
from server import Server
|
||||
|
||||
|
|
@ -19,24 +20,13 @@ def list_servers(client: DockerClient, all: bool = False) -> List[dict]:
|
|||
(List[Dict[str, any]]) A list of results from __extract_info
|
||||
"""
|
||||
|
||||
def __parse(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:
|
||||
(Server): The server parsed out from the container's attributes
|
||||
"""
|
||||
params = Server.params_from_attrs(attrs)
|
||||
return Server(params) if params else None
|
||||
|
||||
containers = list(
|
||||
containers: List[Container] = 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 = [__parse(c.attrs) for c in containers]
|
||||
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
|
||||
|
|
|
|||
116
src/server.py
116
src/server.py
|
|
@ -1,12 +1,16 @@
|
|||
import base64
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import List, Union
|
||||
from os import getenv
|
||||
from typing import Any, List, Union
|
||||
|
||||
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"
|
||||
|
||||
|
||||
@dataclass
|
||||
|
|
@ -34,6 +38,50 @@ class ServerConstructorParams:
|
|||
online: int
|
||||
max: int
|
||||
players: List[Player]
|
||||
dynmap: Union[str, None]
|
||||
|
||||
|
||||
def ping_container_server(container: Container) -> Union[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:
|
||||
|
|
@ -48,6 +96,7 @@ class Server:
|
|||
self.online: int = params.online
|
||||
self.max: int = params.max
|
||||
self.players: List[Player] = params.players
|
||||
self.dynmap: Union[str, None] = params.dynmap
|
||||
|
||||
def asdict(self) -> dict:
|
||||
d = self.__dict__
|
||||
|
|
@ -55,53 +104,38 @@ class Server:
|
|||
return d
|
||||
|
||||
@staticmethod
|
||||
def params_from_attrs(attrs: dict) -> Union[ServerConstructorParams, None]:
|
||||
"""Builds the class from the container attrs passed in
|
||||
def from_container(container: Container):
|
||||
"""Attempts to build out a server instance from a given container
|
||||
|
||||
Args:
|
||||
attrs (dict): The container attributes for the given MC container
|
||||
container (Container): The container whose props should be analyzed
|
||||
|
||||
Returns:
|
||||
Union[Server,None]: A server if parsing params was successful, None otherwise
|
||||
"""
|
||||
|
||||
def __ping_server(attrs: dict) -> Union[ServerPingResponse, None]:
|
||||
"""Iterates through all Container:Host port binding pairs and attempts to ping the server
|
||||
|
||||
Args:
|
||||
attrs (dict): The container's attributes
|
||||
|
||||
Returns:
|
||||
Union[ServerPingResponse, None]: The info derived from the Ping, if available, otherwise None (failure case)
|
||||
"""
|
||||
|
||||
for key in attrs["HostConfig"]["PortBindings"]:
|
||||
# We have to do this nested for loop to get each Container->Host binding to get the actual port of the server
|
||||
# By default they'd otherwise all show up as 25565.. :/
|
||||
for binding in attrs["HostConfig"]["PortBindings"][key]:
|
||||
try:
|
||||
ping_resp = ping_server(getenv("HOST_IP", "localhost"), port=int(binding["HostPort"]))
|
||||
return ping_resp
|
||||
except ValueError:
|
||||
continue
|
||||
|
||||
ping_data = ping_container_server(container)
|
||||
if not ping_data:
|
||||
return None
|
||||
|
||||
ping_resp = __ping_server(attrs)
|
||||
if not ping_resp:
|
||||
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
|
||||
|
||||
log_info = Server.parse_log_for_info(attrs["State"]["Health"]["Log"][-1]["Output"])
|
||||
players = [Player(name=pl.name, uuid=pl.id) for pl in ping_resp.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(ping_resp.icon).decode()) if ping_resp.icon else None,
|
||||
motd=log_info.motd,
|
||||
name=attrs["Name"][1:],
|
||||
online=len(players),
|
||||
max=log_info.max,
|
||||
players=players,
|
||||
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,
|
||||
)
|
||||
)
|
||||
|
||||
@staticmethod
|
||||
|
|
|
|||
Loading…
Reference in a new issue