feat:
--ADDED CONTAINER API
This commit is contained in:
1 parent
c3ca0689f0
commit
0ab69e0995
1 file changed
+57
@@ -129,6 +129,63 @@ def get_containers():
|
||||
detail=f"Docker error: {str(e)}"
|
||||
)
|
||||
|
||||
# websocket for docker containers
|
||||
def get_container_status():
|
||||
|
||||
client = docker.from_env()
|
||||
|
||||
containers = client.containers.list(all=True)
|
||||
|
||||
result = []
|
||||
|
||||
for container in containers:
|
||||
|
||||
result.append({
|
||||
"id": container.short_id,
|
||||
"name": container.name,
|
||||
"status": container.status
|
||||
})
|
||||
|
||||
return result
|
||||
|
||||
@app.websocket("/ws/docker/containers")
|
||||
async def docker_container_status(websocket: WebSocket):
|
||||
|
||||
await websocket.accept()
|
||||
|
||||
try:
|
||||
|
||||
while True:
|
||||
|
||||
# Docker SDK is synchronous/blocking,
|
||||
# so run it in a worker thread.
|
||||
containers = await asyncio.to_thread(
|
||||
get_container_status
|
||||
)
|
||||
|
||||
await websocket.send_json({
|
||||
"containers": containers
|
||||
})
|
||||
|
||||
# Update every 2 seconds
|
||||
await asyncio.sleep(2)
|
||||
|
||||
except WebSocketDisconnect:
|
||||
|
||||
print("Docker WebSocket disconnected")
|
||||
|
||||
except Exception as e:
|
||||
|
||||
try:
|
||||
await websocket.send_json({
|
||||
"error": str(e)
|
||||
})
|
||||
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
import uvicorn
|
||||
|
||||
Reference in new issue
Block a user