main.py 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. from fastapi import FastAPI
  2. import os
  3. import re
  4. import libvirt
  5. import subprocess
  6. app = FastAPI(title="VirtManager API", description="API for managing virtual machines")
  7. # Connect to libvirt
  8. conn = libvirt.open('qemu:///system')
  9. @app.get("/")
  10. async def root():
  11. return {"message": "VirtManager API"}
  12. @app.get("/vms")
  13. async def list_vms():
  14. domains = conn.listAllDomains()
  15. vms = []
  16. for domain in domains:
  17. vms.append({
  18. "id": domain.ID(),
  19. "name": domain.name(),
  20. "state": domain.state()[0]
  21. })
  22. return {"vms": vms}
  23. @app.get("/vms/{vm_id}/start")
  24. async def start_vm(vm_id: int):
  25. # try:
  26. # domain = conn.lookupByID(vm_id)
  27. # domain.create()
  28. # return {"message": f"VM {vm_id} started"}
  29. # except Exception as e:
  30. # return {"error": str(e)}
  31. return {"message": f"VM {vm_id} started (mock)"}
  32. @app.get("/vms/{vm_id}/stop")
  33. async def stop_vm(vm_id: int):
  34. # try:
  35. # domain = conn.lookupByID(vm_id)
  36. # domain.destroy()
  37. # return {"message": f"VM {vm_id} stopped"}
  38. # except Exception as e:
  39. # return {"error": str(e)}
  40. return {"message": f"VM {vm_id} stopped (mock)"}
  41. @app.post("/vms")
  42. async def create_vm(name: str, template: str, disk: str):
  43. xml_path = f"templates/{template}.xml"
  44. if not os.path.exists(xml_path):
  45. return {"error": f"Template {template} not found"}
  46. with open(xml_path, 'r') as f:
  47. xml = f.read()
  48. # Get images path from env
  49. images_path = os.environ.get('LIBVIRT_IMAGES_PATH', '/var/lib/libvirt/images')
  50. # Replace the name in XML
  51. xml = re.sub(r'<name>.*?</name>', f'<name>{name}</name>', xml)
  52. # Replace the disk file name
  53. xml = re.sub(r'file=\'/var/lib/libvirt/images/.*?\.qcow2\'', f"file='{images_path}/{disk}.qcow2'", xml)
  54. try:
  55. # Create VM from template
  56. domain = conn.defineXML(xml)
  57. domain.create()
  58. return {"message": f"VM {name} created from template {template} with disk {disk}.qcow2"}
  59. except Exception as e:
  60. return {"error": str(e)}
  61. @app.delete("/vms/{vm_name}")
  62. async def delete_vm(vm_name: str):
  63. try:
  64. domain = conn.lookupByName(vm_name)
  65. if domain.isActive():
  66. domain.destroy()
  67. domain.undefine()
  68. return {"message": f"VM {vm_name} deleted"}
  69. except Exception as e:
  70. return {"error": str(e)}
  71. @app.post("/disks")
  72. async def create_disk(name: str, size: int):
  73. images_path = os.environ.get('LIBVIRT_IMAGES_PATH', '/var/lib/libvirt/images')
  74. disk_path = f"{images_path}/{name}.qcow2"
  75. try:
  76. result = subprocess.run(['qemu-img', 'create', '-f', 'qcow2', disk_path, f'{size}G'], capture_output=True, text=True)
  77. if result.returncode == 0:
  78. return {"message": f"Disk {name}.qcow2 created with size {size}G"}
  79. else:
  80. return {"error": result.stderr}
  81. except Exception as e:
  82. return {"error": str(e)}