From beea4ef609276779e4a2080079ff39c6b9b306b0 Mon Sep 17 00:00:00 2001 From: oitsjustjose Date: Tue, 17 Jun 2025 12:31:12 -0500 Subject: [PATCH] Improved dockerized backend --- Dockerfile | 10 +++++ requirements.txt | 38 ++++++++++++++---- src/__main__.py | 100 ----------------------------------------------- src/common.py | 29 +++++++------- src/main.py | 32 +++++++++++++++ src/server.py | 4 +- start.sh | 28 ------------- 7 files changed, 89 insertions(+), 152 deletions(-) create mode 100644 Dockerfile delete mode 100644 src/__main__.py create mode 100644 src/main.py delete mode 100755 start.sh diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000..54ed5ba --- /dev/null +++ b/Dockerfile @@ -0,0 +1,10 @@ +FROM python:3.10-slim-bookworm + +RUN apt-get update && apt-get upgrade -y + +COPY . . +RUN pip install -r requirements.txt + +WORKDIR /src +EXPOSE 8000 +CMD ["fastapi", "run", "main.py"] \ No newline at end of file diff --git a/requirements.txt b/requirements.txt index 387f4c3..fdbbf06 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,16 +1,40 @@ -asyncio==3.4.3 -blinker==1.9.0 -certifi==2025.4.26 +annotated-types==0.7.0 +anyio==4.9.0 +certifi==2025.6.15 charset-normalizer==3.4.2 click==8.2.1 +dnspython==2.7.0 docker==7.1.0 -Flask==3.1.1 -flask-cors==6.0.1 +email_validator==2.2.0 +exceptiongroup==1.3.0 +fastapi==0.115.13 +fastapi-cli==0.0.7 +h11==0.16.0 +httpcore==1.0.9 +httptools==0.6.4 +httpx==0.28.1 idna==3.10 -itsdangerous==2.2.0 Jinja2==3.1.6 +markdown-it-py==3.0.0 MarkupSafe==3.0.2 +mdurl==0.1.2 +pydantic==2.11.7 +pydantic_core==2.33.2 +Pygments==2.19.1 +python-dotenv==1.1.0 +python-multipart==0.0.20 +PyYAML==6.0.2 requests==2.32.4 +rich==14.0.0 +rich-toolkit==0.14.7 +shellingham==1.5.4 +sniffio==1.3.1 +starlette==0.46.2 +typer==0.16.0 +typing-inspection==0.4.1 +typing_extensions==4.14.0 urllib3==2.4.0 +uvicorn==0.34.3 +uvloop==0.21.0 +watchfiles==1.1.0 websockets==15.0.1 -Werkzeug==3.1.3 diff --git a/src/__main__.py b/src/__main__.py deleted file mode 100644 index 23b6c73..0000000 --- a/src/__main__.py +++ /dev/null @@ -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() diff --git a/src/common.py b/src/common.py index 28f1236..6a029ad 100644 --- a/src/common.py +++ b/src/common.py @@ -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 diff --git a/src/main.py b/src/main.py new file mode 100644 index 0000000..63085ab --- /dev/null +++ b/src/main.py @@ -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}"} diff --git a/src/server.py b/src/server.py index bb92d06..00dd586 100644 --- a/src/server.py +++ b/src/server.py @@ -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 diff --git a/start.sh b/start.sh deleted file mode 100755 index ef73190..0000000 --- a/start.sh +++ /dev/null @@ -1,28 +0,0 @@ -#!/bin/bash - -# Get an absolute path to the script -basedir=$(dirname $0) -absdir=$(realpath -s "${PWD}/${basedir}") - -if [ -d "${absdir}/.venv" ]; then - echo "${absdir}/.venv exists - removing and resetting" - rm -rf "${absdir}/.venv" -fi - -pythoncmd=python3 # TODO: this might need to be changed? - -$pythoncmd -m venv "${absdir}/.venv" -echo "Made venv successfully" - -source "${absdir}/.venv/bin/activate" -echo "Activated venv successfully" - -# Re-assess the python command now that we're in the venv -pythoncmd=$(command -v python) || $(command -v python3) - -$pythoncmd -m pip install -r "${absdir}/requirements.txt" >/dev/null 2>&1 -echo "Installed Python requirements successfully" - -cd "${absdir}/src" -echo "Starting up.." -$pythoncmd __main__.py