API/app/server.py

68 lines
2.0 KiB
Python

from fastapi import APIRouter, HTTPException, status, WebSocket, Request
from sse_starlette.sse import EventSourceResponse
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.get("/server/{server}/logs")
async def logs(server: str, request: Request):
container = await getContainer(server)
#event_generator = logGenerator(request, server)
return EventSourceResponse(container.log(stdout=True, follow=True, tail=5000))
async def logGenerator(request, server):
container = await getContainer(server)
for line in container.log(stdout=True, follow=True, tail=5000):
if await request.is_disconnected():
print("client disconnected!!!")
break
yield line
# @router.get("/server/{server}/stats")
# async def stats(server: str):
# container = await getContainer(server)
# return EventSourceResponse(container.stats(stream=True))
async def getContainer(server):
return await docker.containers.get(server)