Improved dockerized backend
This commit is contained in:
parent
cfe1c32d0c
commit
beea4ef609
7 changed files with 89 additions and 152 deletions
100
src/__main__.py
100
src/__main__.py
|
|
@ -1,100 +0,0 @@
|
|||
"""
|
||||
Author: Jose Stovall
|
||||
Description: A Flask API service for the running Minecraft server statuses
|
||||
"""
|
||||
|
||||
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 list_servers
|
||||
import docker
|
||||
from docker import DockerClient
|
||||
|
||||
from threading import Thread
|
||||
import logging
|
||||
|
||||
|
||||
class RestServer:
|
||||
def __init__(self, docker_client: DockerClient):
|
||||
log = logging.getLogger("werkzeug")
|
||||
log.setLevel(logging.ERROR)
|
||||
|
||||
self._app = Flask("RestAPI")
|
||||
self._app.add_url_rule("/", view_func=self.index)
|
||||
self._client = docker_client
|
||||
CORS(self._app)
|
||||
|
||||
def index(self):
|
||||
try:
|
||||
data = list_servers(self._client, all=bool(request.args.get("all")))
|
||||
|
||||
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(list_servers(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(list_servers(self._client, all=True))
|
||||
|
||||
while new == self.cache:
|
||||
await asyncio.sleep(1)
|
||||
new = json.dumps(list_servers(self._client, all=True))
|
||||
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__":
|
||||
main()
|
||||
|
|
@ -3,24 +3,11 @@ Author: Jose Stovall
|
|||
Description: Common utilities used to fetch current server statuses
|
||||
"""
|
||||
|
||||
from typing import List
|
||||
from typing import List, Union
|
||||
|
||||
from docker import DockerClient
|
||||
|
||||
from server import Server
|
||||
from typing import Union
|
||||
|
||||
|
||||
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:
|
||||
(Server): The server parsed out from the container's attributes
|
||||
"""
|
||||
params = Server.params_from_attrs(attrs)
|
||||
return Server(params) if params else None
|
||||
|
||||
|
||||
def list_servers(client: DockerClient, all: bool = False) -> List[dict]:
|
||||
|
|
@ -31,6 +18,18 @@ def list_servers(client: DockerClient, all: bool = False) -> List[dict]:
|
|||
Returns:
|
||||
(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(
|
||||
filter(
|
||||
lambda x: "itzg/minecraft-server" in x.attrs["Config"]["Image"] and "net.forgeserv.hide" not in x.labels,
|
||||
|
|
@ -38,6 +37,6 @@ def list_servers(client: DockerClient, all: bool = False) -> List[dict]:
|
|||
)
|
||||
)
|
||||
|
||||
ret = [parse_server(c.attrs) for c in containers]
|
||||
ret = [__parse(c.attrs) for c in containers]
|
||||
ret = list(filter(lambda x: x is not None, ret))
|
||||
return [x.asdict() for x in ret] # type: ignore
|
||||
|
|
|
|||
32
src/main.py
Normal file
32
src/main.py
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
"""
|
||||
Author: Jose Stovall
|
||||
Description: A Flask API service for the running Minecraft server statuses
|
||||
Architecture:
|
||||
|
||||
Python App that loops infinitely, pushing the correct Pixlet state to the TidByt
|
||||
Changes come in via WebAPI so we can make a lightweight desktop client and leave the work to the RasPi
|
||||
Also allows the TidByt to still have forgeserv.net data without needing to be stood up
|
||||
"""
|
||||
|
||||
import logging
|
||||
|
||||
import docker
|
||||
from fastapi import FastAPI, Response, status
|
||||
|
||||
from common import list_servers
|
||||
|
||||
app: FastAPI = FastAPI()
|
||||
client = docker.from_env()
|
||||
|
||||
|
||||
@app.get("/")
|
||||
def index(response: Response, all: bool = False, sort: str = ""):
|
||||
try:
|
||||
data = list_servers(client, all=all)
|
||||
if sort:
|
||||
data = sorted(data, key=lambda x: x[sort])
|
||||
response.status_code = status.HTTP_200_OK
|
||||
return data
|
||||
except KeyError:
|
||||
response.status_code = status.HTTP_400_BAD_REQUEST
|
||||
return {"error": f"Failed to find key {sort}"}
|
||||
|
|
@ -2,7 +2,7 @@ import base64
|
|||
import re
|
||||
from dataclasses import dataclass
|
||||
from typing import List, Union
|
||||
|
||||
from os import getenv
|
||||
from ping import ServerPingResponse
|
||||
from ping import ping as ping_server
|
||||
|
||||
|
|
@ -77,7 +77,7 @@ class Server:
|
|||
# By default they'd otherwise all show up as 25565.. :/
|
||||
for binding in attrs["HostConfig"]["PortBindings"][key]:
|
||||
try:
|
||||
ping_resp = ping_server("localhost", port=int(binding["HostPort"]))
|
||||
ping_resp = ping_server(getenv("HOST_IP", "localhost"), port=int(binding["HostPort"]))
|
||||
return ping_resp
|
||||
except ValueError:
|
||||
continue
|
||||
|
|
|
|||
Loading…
Reference in a new issue