|
| 1 | +from enum import Enum |
| 2 | +import os |
| 3 | +import subprocess |
| 4 | +from subprocess import PIPE |
| 5 | +from datetime import datetime |
| 6 | +from typing import Optional |
| 7 | + |
| 8 | +import requests |
| 9 | +from flask import Flask |
| 10 | + |
| 11 | +DEBUG = bool(os.environ.get("DEBUG", False)) |
| 12 | +CONFIG_URL = os.environ.get( |
| 13 | + "CONFIG_URL", |
| 14 | + "https://raw.githubusercontent.com/xonotic/xonotic/master/server/server.cfg", |
| 15 | +) |
| 16 | + |
| 17 | +HOST = os.environ.get("HOST", "0.0.0.0") |
| 18 | + |
| 19 | +DEFAULT_PORT = 5001 |
| 20 | +PORT = int(os.environ.get("PORT", DEFAULT_PORT)) |
| 21 | + |
| 22 | +app = Flask(__name__) |
| 23 | +process = None |
| 24 | + |
| 25 | + |
| 26 | +def log(message): |
| 27 | + print(f"SIDECAR: {message}") |
| 28 | + |
| 29 | + |
| 30 | +def get_game_pid() -> Optional[int]: |
| 31 | + try: |
| 32 | + int(subprocess.check_output(["pidof", "./xonotic-linux64-dedicated"])) |
| 33 | + except: |
| 34 | + log("Failed to get game pid, assuming not currently running") |
| 35 | + return None |
| 36 | + |
| 37 | + |
| 38 | +def write_config(): |
| 39 | + with open("/opt/server/server.cfg", "wb") as f: |
| 40 | + f.write(requests.get(CONFIG_URL).content) |
| 41 | + |
| 42 | + |
| 43 | +class Response(Enum): |
| 44 | + STARTED = "started" |
| 45 | + RESTARTED = "restarted" |
| 46 | + |
| 47 | + |
| 48 | +def start_or_restart_game() -> Response: |
| 49 | + global process |
| 50 | + |
| 51 | + def fresh(): |
| 52 | + return subprocess.Popen(["./xonotic-linux64-dedicated"], stdin=PIPE) |
| 53 | + |
| 54 | + if process is None: |
| 55 | + log("No process, starting initial process") |
| 56 | + process = fresh() |
| 57 | + return Response.STARTED |
| 58 | + else: |
| 59 | + log("Process already running, shutting down") |
| 60 | + process.stdin.write(str.encode("exit\n")) |
| 61 | + process.stdin.flush() |
| 62 | + process.wait(15) |
| 63 | + log("Process shutdown, starting fresh process") |
| 64 | + process = fresh() |
| 65 | + log("Fresh process started") |
| 66 | + return Response.RESTARTED |
| 67 | + |
| 68 | + |
| 69 | +@app.route("/") |
| 70 | +def home(): |
| 71 | + global process |
| 72 | + return {"pid": process.pid, "timestamp": datetime.now().isoformat()} |
| 73 | + |
| 74 | + |
| 75 | +@app.route("/restart") |
| 76 | +def restart(): |
| 77 | + global process |
| 78 | + response = start_or_restart_game() |
| 79 | + return {"pid": process.pid, "status": response.value} |
| 80 | + |
| 81 | + |
| 82 | +if __name__ == "__main__": |
| 83 | + write_config() |
| 84 | + start_or_restart_game() |
| 85 | + |
| 86 | + log(f"Starting sidecar-service on {HOST}:{PORT}") |
| 87 | + app.run(debug=DEBUG, host=HOST, port=PORT) |
0 commit comments