from fastapi import APIRouter, HTTPException, status, WebSocket import base64 import docker import aiodocker router = APIRouter() client = docker.from_env() docker = aiodocker.Docker() @router.post("/server/{server}/start") async def start(server): try: container = await getContainer(server) await container.start() except: raise HTTPException(status_code=500) return server @router.post("/server/{server}/stop") async def stop(server): try: container = await getContainer(server) await container.stop() except: raise HTTPException(status_code=500) return server @router.post("/server/{server}/command/{command}", description="Take server and base64 encoded command") async def commnd(server, command): try: container = client.containers.get(server) print(command) cmd = base64.urlsafe_b64decode(command).decode('utf_8') print(cmd) container.exec_run(cmd="/usr/local/bin/cmd " + str(cmd)) s= 200 running="Success" except: raise HTTPException(status_code=500) return f"{server} {base64.urlsafe_b64decode(command).decode('utf_8')}" @router.websocket("/server/{server}/logs") async def logs(websocket: WebSocket, server: str): await websocket.accept() container = await getContainer(server) async for line in container.log(stdout=True, follow=True, tail=5000): #print(line) await websocket.send_bytes(line) print("Closed") return server @router.get("/server/{server}/stats") async def stats(websocket: WebSocket, server: str): await websocket.accept() container = await getContainer(server) async for line in container.log(): await websocket.send_bytes(line) return server async def getContainer(server): return await docker.containers.get(server)