Improved dockerized backend
This commit is contained in:
parent
cfe1c32d0c
commit
beea4ef609
7 changed files with 89 additions and 152 deletions
10
Dockerfile
Normal file
10
Dockerfile
Normal file
|
|
@ -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"]
|
||||
|
|
@ -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
|
||||
|
|
|
|||
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
|
||||
|
|
|
|||
28
start.sh
28
start.sh
|
|
@ -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
|
||||
Loading…
Reference in a new issue