| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273 |
- from fastapi import FastAPI
- import os
- import re
- import libvirt
- app = FastAPI(title="VirtManager API", description="API for managing virtual machines")
- # Connect to libvirt
- conn = libvirt.open('qemu:///system')
- @app.get("/")
- async def root():
- return {"message": "VirtManager API"}
- @app.get("/vms")
- async def list_vms():
- domains = conn.listAllDomains()
- vms = []
- for domain in domains:
- vms.append({
- "id": domain.ID(),
- "name": domain.name(),
- "state": domain.state()[0]
- })
- return {"vms": vms}
- @app.get("/vms/{vm_id}/start")
- async def start_vm(vm_id: int):
- # try:
- # domain = conn.lookupByID(vm_id)
- # domain.create()
- # return {"message": f"VM {vm_id} started"}
- # except Exception as e:
- # return {"error": str(e)}
- return {"message": f"VM {vm_id} started (mock)"}
- @app.get("/vms/{vm_id}/stop")
- async def stop_vm(vm_id: int):
- # try:
- # domain = conn.lookupByID(vm_id)
- # domain.destroy()
- # return {"message": f"VM {vm_id} stopped"}
- # except Exception as e:
- # return {"error": str(e)}
- return {"message": f"VM {vm_id} stopped (mock)"}
- @app.post("/vms")
- async def create_vm(name: str, template: str):
- xml_path = f"templates/{template}.xml"
- if not os.path.exists(xml_path):
- return {"error": f"Template {template} not found"}
- with open(xml_path, 'r') as f:
- xml = f.read()
- # Replace the name in XML
- xml = re.sub(r'<name>.*?</name>', f'<name>{name}</name>', xml)
- try:
- # Create VM from template
- domain = conn.defineXML(xml)
- domain.create()
- return {"message": f"VM {name} created from template {template}"}
- except Exception as e:
- return {"error": str(e)}
- @app.delete("/vms/{vm_name}")
- async def delete_vm(vm_name: str):
- try:
- domain = conn.lookupByName(vm_name)
- if domain.isActive():
- domain.destroy()
- domain.undefine()
- return {"message": f"VM {vm_name} deleted"}
- except Exception as e:
- return {"error": str(e)}
|