From e4b353ec9f6964bbeef6432ade8e1cc80ae242b3 Mon Sep 17 00:00:00 2001 From: WasinUddy Date: Fri, 5 Apr 2024 13:09:34 +0700 Subject: [PATCH] Implement Kubernetes health probe --- web/backend/main.py | 17 +++++++++++++++++ web/backend/server.py | 28 ++++++++++++++++++++++++++-- 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/web/backend/main.py b/web/backend/main.py index 8f4cb0f..a539cfa 100644 --- a/web/backend/main.py +++ b/web/backend/main.py @@ -77,6 +77,23 @@ def get_log(): except Exception as e: raise HTTPException(status_code=500, detail=str(e)) + +# Kubernetes health checks +@app.get("/health/readiness") +def readiness(): + # Ready when FastAPI server is running (ready to accept requests) + return {"message": "ready"} + +@app.get("/health/liveness") +def liveness(): + # Server is not in Illegal State + if minecraft_server.live_probe(): + return {"message": "live"} + else: + raise HTTPException(status_code=500, detail="Server is in Illegal State") + + + if __name__ == "__main__": # edit index.html for correct subdirectory subpath = os.environ.get("SUBPATH", "") diff --git a/web/backend/server.py b/web/backend/server.py index 559512a..cf543e2 100644 --- a/web/backend/server.py +++ b/web/backend/server.py @@ -11,6 +11,7 @@ def __init__(self, cwd: str): self.cwd = cwd self.server = None self.config_files = ("server.properties", "allowlist.json", "permissions.json") + self.running = False def start(self, x86: bool = True): """ @@ -34,6 +35,7 @@ def start(self, x86: bool = True): # Open the log file in read and write mode. self.server_log = open("server.log", "r+") + # Start the server process, redirecting stdout and stderr to the log file. if x86: self.server = subprocess.Popen( @@ -46,6 +48,8 @@ def start(self, x86: bool = True): bufsize=1, universal_newlines=True ) + + # Work in progress else: self.server = subprocess.Popen( ["qemu-x86_64", "./bedrock_server"], @@ -57,8 +61,10 @@ def start(self, x86: bool = True): bufsize=1, universal_newlines=True ) - + # Set the running flag to True. + self.running = True + def stop(self, force: bool = False): """ Stops the server process. @@ -76,6 +82,10 @@ def stop(self, force: bool = False): self.server.kill() self.server = None + # Set the running flag to False. + self.running = False + + def command(self, cmd: str): """ Sends a command to the server process. @@ -88,4 +98,18 @@ def command(self, cmd: str): self.server.stdin.write(f"{cmd}\n") self.server.stdin.flush() else: - raise Exception("Server is not running") \ No newline at end of file + raise Exception("Server is not running") + + def live_probe(self): + """ + Check if the server is not in illegal state. to be used with Kubernetes liveness probe + if the process died while flag is still True then the Server is in illegal state + """ + + # self.server.poll() is None if the process is still running + if self.running!=(self.server.poll() is None): + return False # Illegal state + else: + return True + + \ No newline at end of file