File size: 4,865 Bytes
ae15fcc fd08784 ae15fcc fd08784 ae15fcc fd08784 08d28d4 fd08784 ae15fcc fd08784 ae15fcc fd08784 ae15fcc fd08784 08d28d4 ae15fcc fd08784 daabb36 fd08784 daabb36 fd08784 daabb36 fd08784 daabb36 fd08784 08d28d4 fd08784 ae15fcc fd08784 08d28d4 fd08784 08d28d4 fd08784 ae15fcc fd08784 08d28d4 fd08784 08d28d4 fd08784 ae15fcc fd08784 08d28d4 fd08784 08d28d4 ae15fcc fd08784 ae15fcc 08d28d4 |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 |
"""
Web Interface for QEMU VM
Provides browser-based access to VM display
"""
from fastapi import FastAPI, WebSocket, WebSocketDisconnect
from fastapi.staticfiles import StaticFiles
from fastapi.responses import HTMLResponse
import asyncio
import logging
from pathlib import Path
from typing import Optional, Dict
import json
import os
import sys
import subprocess
# Add parent directory to path for imports
current_dir = Path(__file__).parent
root_dir = current_dir.parent
if str(root_dir) not in sys.path:
sys.path.insert(0, str(root_dir))
from qemu_manager import QEMUManager
# Configure logging
logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger(__name__)
app = FastAPI()
# Mount static files
static_path = Path(__file__).parent / "static"
app.mount("/static", StaticFiles(directory=str(static_path)), name="static")
# Global QEMU manager instance
qemu: Optional[QEMUManager] = None
websockify_process: Optional[subprocess.Popen] = None
class VMConnection:
def __init__(self):
self.active_connections: Dict[int, WebSocket] = {}
async def connect(self, websocket: WebSocket):
await websocket.accept()
client_id = id(websocket)
self.active_connections[client_id] = websocket
return client_id
def disconnect(self, client_id: int):
self.active_connections.pop(client_id, None)
async def broadcast(self, message: str):
for ws in self.active_connections.values():
try:
await ws.send_text(message)
except:
continue
vm_connection = VMConnection()
def start_websockify(vnc_port: int, websocket_port: int = 6080):
"""Start websockify proxy for VNC"""
global websockify_process
if websockify_process:
websockify_process.terminate()
websockify_process.wait()
cmd = [
"websockify",
f"{websocket_port}",
f"localhost:{vnc_port}"
]
websockify_process = subprocess.Popen(cmd)
logger.info(f"Started websockify proxy on port {websocket_port} for VNC port {vnc_port}")
return websocket_port
@app.get("/")
async def get_index():
"""Serve main HTML interface"""
html_path = static_path / "index.html"
return HTMLResponse(content=html_path.read_text())
@app.websocket("/ws/vm")
async def vm_websocket(websocket: WebSocket):
"""Handle VM display and control WebSocket"""
client_id = await vm_connection.connect(websocket)
try:
while True:
message = await websocket.receive_json()
if message["type"] == "install":
# Start fresh OS installation
if qemu:
vnc_port = await qemu.install_os(message["iso_url"])
websocket_port = start_websockify(vnc_port)
await websocket.send_json({
"type": "vnc_info",
"port": websocket_port
})
elif message["type"] == "boot":
# Boot existing OS
if qemu:
try:
vnc_port = await qemu.boot_os()
websocket_port = start_websockify(vnc_port)
await websocket.send_json({
"type": "vnc_info",
"port": websocket_port
})
except FileNotFoundError:
await websocket.send_json({
"type": "error",
"message": "No OS installation found"
})
elif message["type"] == "shutdown":
# Shutdown VM
if qemu:
await qemu.shutdown()
await websocket.send_json({
"type": "status",
"message": "VM shut down"
})
except WebSocketDisconnect:
vm_connection.disconnect(client_id)
@app.on_event("startup")
async def startup_event():
"""Initialize QEMU manager on startup"""
global qemu
qemu = QEMUManager()
logger.info("QEMU manager initialized")
@app.on_event("shutdown")
async def shutdown_event():
"""Cleanup on shutdown"""
global websockify_process
if qemu:
await qemu.shutdown()
logger.info("QEMU manager shut down")
if websockify_process:
websockify_process.terminate()
websockify_process.wait()
logger.info("Websockify proxy shut down")
def main():
"""Entry point for the FServe application"""
import uvicorn
uvicorn.run(app, host="0.0.0.0", port=8080)
if __name__ == "__main__":
main()
|