diff --git a/.vscode/launch.json b/.vscode/launch.json index d6802be..2c5d13c 100644 --- a/.vscode/launch.json +++ b/.vscode/launch.json @@ -5,7 +5,6 @@ "name": "Python:Flask", "type": "debugpy", "request": "launch", - "cwd": "src", "program": "${file}" } ] diff --git a/Dockerfile b/Dockerfile index c2b74b6..e74e3e7 100644 --- a/Dockerfile +++ b/Dockerfile @@ -1,6 +1,10 @@ -FROM python:3.10-buster +FROM python:3.10.16-slim RUN apt-get update && apt-get upgrade -y +# Required for the Docker Client to work within our app inside of another Docker Container +RUN apt-get -y install apt-transport-https ca-certificates curl gnupg2 software-properties-common +RUN curl -fsSL https://download.docker.com/linux/debian/gpg | apt-key add - +RUN add-apt-repository "deb [arch=amd64] https://download.docker.com/linux/debian $(lsb_release -cs) stable" COPY . . @@ -8,4 +12,4 @@ RUN pip install -r requirements.txt WORKDIR /src -CMD ["python", "src/__main__.py"] \ No newline at end of file +CMD ["python", "__main__.py"] \ No newline at end of file diff --git a/src/__main__.bak.py b/src/__main__.bak.py new file mode 100644 index 0000000..90bc2ea --- /dev/null +++ b/src/__main__.bak.py @@ -0,0 +1,24 @@ +""" +Author: Jose Stovall +Description: A Flask API service for the running Minecraft server statuses +""" + +from os import environ as env + + +def main() -> None: + host_method = env["METHOD"].lower() + if host_method == "rest": + from runtimes import rest + + rest.run() + elif host_method == "websocket": + from runtimes import websocket + + websocket.run() + else: + raise Exception(f"Unsupported 'METHOD' environment variable Currently set to {host_method}. Must be either 'rest' or 'websocket', and CANNOT be empty!") + + +if __name__ == "__main__": + main() diff --git a/src/__main__.py b/src/__main__.py index 42a7d74..a024ef4 100644 --- a/src/__main__.py +++ b/src/__main__.py @@ -89,7 +89,7 @@ def main() -> None: 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() + # wss_thread.join() if __name__ == "__main__": diff --git a/src/runtimes/rest.py b/src/runtimes/rest.py new file mode 100644 index 0000000..7db14be --- /dev/null +++ b/src/runtimes/rest.py @@ -0,0 +1,42 @@ +""" +@author: Jose Stovall | oitsjustjose +A dedicated REST API server for manually fetching the current status + of the running servers +""" + +from os import environ as env + +import docker +from flask import Flask, jsonify, request +from flask_cors import CORS + +from common import get_server_info + +client = docker.from_env() +app = Flask(__name__) +CORS(app) + + +@app.route("/") +def index(): + try: + data = get_server_info(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(): + host = "0.0.0.0" + port = int(env["PORT"]) if "PORT" in env else 9090 + + print(f"RestAPI Server is now running on {host}:{port}") + app.run(host=host, port=port, threaded=True) diff --git a/src/runtimes/websocket.py b/src/runtimes/websocket.py new file mode 100644 index 0000000..771f3e0 --- /dev/null +++ b/src/runtimes/websocket.py @@ -0,0 +1,55 @@ +""" +@author: Jose Stovall | oitsjustjose +A dedicated websocket server for updating connected clients with + the latest set of changes to the server list +""" + +import asyncio +import json +from os import environ as env + +import docker +from docker import DockerClient +from websockets.asyncio.server import ServerConnection, serve + +from common import get_server_info + + +def __fetch(client: DockerClient): + return json.dumps(get_server_info(client, all=True)) + + +CLIENT = docker.from_env() +CACHE = __fetch(CLIENT) + + +async def __loop_infinitely(conn: ServerConnection): + while True: + # raises ConnectionClosed ex which breaks out of the loop. + # https://websockets.readthedocs.io/en/stable/howto/patterns.html + await __wait_for_change(conn) + + +async def __setup(host: str, port: int = 8008): + async with serve(__loop_infinitely, host, port): + await asyncio.Future() + + +async def __wait_for_change(conn: ServerConnection): + global CACHE + + new = json.dumps(get_server_info(CLIENT, all=True)) + + while new == CACHE: + await asyncio.sleep(1) + new = json.dumps(get_server_info(CLIENT, all=True)) + CACHE = new + await conn.send(new) + + +def run(): + host = "0.0.0.0" + port = int(env["PORT"]) if "PORT" in env else 8008 + + print(f"WebSocket Server is now running on {host}:{port}") + asyncio.run(__setup(host, port)) diff --git a/start.sh b/start.sh new file mode 100755 index 0000000..245773c --- /dev/null +++ b/start.sh @@ -0,0 +1,28 @@ +#!/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=$(command -v python) || $(command -v python3) + +$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