main.py 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. from fastapi import FastAPI
  2. import os
  3. import re
  4. import libvirt
  5. app = FastAPI(title="VirtManager API", description="API for managing virtual machines")
  6. # Connect to libvirt
  7. conn = libvirt.open('qemu:///system')
  8. @app.get("/")
  9. async def root():
  10. return {"message": "VirtManager API"}
  11. @app.get("/vms")
  12. async def list_vms():
  13. domains = conn.listAllDomains()
  14. vms = []
  15. for domain in domains:
  16. vms.append({
  17. "id": domain.ID(),
  18. "name": domain.name(),
  19. "state": domain.state()[0]
  20. })
  21. return {"vms": vms}
  22. @app.get("/vms/{vm_id}/start")
  23. async def start_vm(vm_id: int):
  24. # try:
  25. # domain = conn.lookupByID(vm_id)
  26. # domain.create()
  27. # return {"message": f"VM {vm_id} started"}
  28. # except Exception as e:
  29. # return {"error": str(e)}
  30. return {"message": f"VM {vm_id} started (mock)"}
  31. @app.get("/vms/{vm_id}/stop")
  32. async def stop_vm(vm_id: int):
  33. # try:
  34. # domain = conn.lookupByID(vm_id)
  35. # domain.destroy()
  36. # return {"message": f"VM {vm_id} stopped"}
  37. # except Exception as e:
  38. # return {"error": str(e)}
  39. return {"message": f"VM {vm_id} stopped (mock)"}
  40. @app.post("/vms")
  41. async def create_vm(name: str, template: str):
  42. xml_path = f"templates/{template}.xml"
  43. if not os.path.exists(xml_path):
  44. return {"error": f"Template {template} not found"}
  45. with open(xml_path, 'r') as f:
  46. xml = f.read()
  47. # Replace the name in XML
  48. xml = re.sub(r'<name>.*?</name>', f'<name>{name}</name>', xml)
  49. try:
  50. # Create VM from template
  51. domain = conn.defineXML(xml)
  52. domain.create()
  53. return {"message": f"VM {name} created from template {template}"}
  54. except Exception as e:
  55. return {"error": str(e)}
  56. #return {"message": f"VM created from template {template} (mock)"}