main.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  1. from fastapi import FastAPI
  2. from fastapi.staticfiles import StaticFiles
  3. from fastapi.responses import FileResponse
  4. import os
  5. import libvirt
  6. import subprocess
  7. import random
  8. import xml.etree.ElementTree as ET
  9. import socket
  10. from pydantic import BaseModel
  11. app = FastAPI(title="VirtManager API", description="API for managing virtual machines")
  12. app.mount("/static", StaticFiles(directory="static"), name="static")
  13. ws_processes = {}
  14. def get_free_port():
  15. with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:
  16. s.bind(('', 0))
  17. return s.getsockname()[1]
  18. def get_state_string(state_code):
  19. states = {
  20. 0: "no state",
  21. 1: "running",
  22. 2: "blocked",
  23. 3: "paused",
  24. 4: "shutdown",
  25. 5: "shut off",
  26. 6: "crashed",
  27. 7: "pm suspended"
  28. }
  29. return states.get(state_code, "unknown")
  30. class BootOrder(BaseModel):
  31. order: list[str]
  32. # Connect to libvirt
  33. conn = libvirt.open('qemu:///system')
  34. @app.get("/")
  35. async def root():
  36. return FileResponse("static/index.html")
  37. @app.get("/vms")
  38. async def list_vms():
  39. domains = conn.listAllDomains()
  40. vms = []
  41. for domain in domains:
  42. xml_desc = domain.XMLDesc()
  43. root = ET.fromstring(xml_desc)
  44. graphics = root.find(".//graphics[@type='vnc']")
  45. vnc_port = None
  46. if graphics is not None:
  47. port_str = graphics.get('port')
  48. if port_str and port_str != '-1':
  49. vnc_port = int(port_str)
  50. vms.append({
  51. "id": domain.ID(),
  52. "name": domain.name(),
  53. "state": get_state_string(domain.state()[0]),
  54. "vnc_port": vnc_port
  55. })
  56. return {"vms": vms}
  57. @app.get("/vms/{vm_name}/start")
  58. async def start_vm(vm_name: str):
  59. try:
  60. domain = conn.lookupByName(vm_name)
  61. domain.create()
  62. return {"message": f"VM {vm_name} started"}
  63. except Exception as e:
  64. return {"error": str(e)}
  65. @app.get("/vms/{vm_name}/stop")
  66. async def stop_vm(vm_name: str):
  67. try:
  68. domain = conn.lookupByName(vm_name)
  69. domain.destroy()
  70. return {"message": f"VM {vm_name} stopped"}
  71. except Exception as e:
  72. return {"error": str(e)}
  73. @app.post("/vms")
  74. async def create_vm(name: str, memory: int, disk_size: int, iso: str):
  75. images_path = os.environ.get('LIBVIRT_IMAGES_PATH', '/var/lib/libvirt/images')
  76. disk_path = f"{images_path}/{name}.qcow2"
  77. iso_path = f"{images_path}/{iso}"
  78. print(f"Using ISO path: {iso_path}")
  79. # Create disk
  80. try:
  81. result = subprocess.run(['qemu-img', 'create', '-f', 'qcow2', disk_path, f'{disk_size}G'], capture_output=True, text=True)
  82. if result.returncode != 0:
  83. return {"error": f"Failed to create disk: {result.stderr}"}
  84. except Exception as e:
  85. return {"error": f"Error creating disk: {str(e)}"}
  86. # Generate unique MAC
  87. mac = f"52:54:00:{random.randint(0, 255):02x}:{random.randint(0, 255):02x}:{random.randint(0, 255):02x}"
  88. # Basic XML template
  89. xml_template = f"""<domain type='kvm'>
  90. <name>{name}</name>
  91. <memory unit='MiB'>{memory}</memory>
  92. <currentMemory unit='MiB'>{memory}</currentMemory>
  93. <vcpu placement='static'>1</vcpu>
  94. <os>
  95. <type arch='x86_64' machine='pc-i440fx-6.2'>hvm</type>
  96. <boot dev='cdrom'/>
  97. </os>
  98. <features>
  99. <acpi/>
  100. <apic/>
  101. </features>
  102. <cpu mode='host-model' check='partial'/>
  103. <clock offset='utc'>
  104. <timer name='rtc' tickpolicy='catchup'/>
  105. <timer name='pit' tickpolicy='delay'/>
  106. <timer name='hpet' present='no'/>
  107. </clock>
  108. <on_poweroff>destroy</on_poweroff>
  109. <on_reboot>restart</on_reboot>
  110. <on_crash>destroy</on_crash>
  111. <pm>
  112. <suspend-to-mem enabled='no'/>
  113. <suspend-to-disk enabled='no'/>
  114. </pm>
  115. <devices>
  116. <emulator>/usr/bin/kvm</emulator>
  117. <disk type='file' device='disk'>
  118. <driver name='qemu' type='qcow2'/>
  119. <source file='{disk_path}'/>
  120. <target dev='vda' bus='virtio'/>
  121. </disk>
  122. <disk type='file' device='cdrom'>
  123. <driver name='qemu' type='raw'/>
  124. <source file='{iso_path}'/>
  125. <target dev='hda' bus='ide'/>
  126. <readonly/>
  127. </disk>
  128. <interface type='network'>
  129. <mac address='{mac}'/>
  130. <source network='default'/>
  131. <model type='virtio'/>
  132. </interface>
  133. <console type='pty'>
  134. <target type='serial' port='0'/>
  135. </console>
  136. <input type='tablet' bus='usb'>
  137. <address type='usb' bus='0' port='1'/>
  138. </input>
  139. <input type='mouse' bus='ps2'/>
  140. <input type='keyboard' bus='ps2'/>
  141. <graphics type='vnc' port='-1' autoport='yes'/>
  142. <video>
  143. <model type='cirrus' vram='16384' heads='1' primary='yes'/>
  144. </video>
  145. <memballoon model='virtio'>
  146. <address type='pci' domain='0x0000' bus='0x00' slot='0x04' function='0x0'/>
  147. </memballoon>
  148. </devices>
  149. </domain>"""
  150. try:
  151. domain = conn.defineXML(xml_template)
  152. domain.create()
  153. return {"message": f"VM {name} created with {memory} MiB memory, {disk_size}G disk, booting from {iso}"}
  154. except Exception as e:
  155. return {"error": str(e)}
  156. @app.get("/console/{vm_name}")
  157. async def get_console(vm_name: str):
  158. try:
  159. domain = conn.lookupByName(vm_name)
  160. xml_desc = domain.XMLDesc()
  161. root = ET.fromstring(xml_desc)
  162. graphics = root.find(".//graphics[@type='vnc']")
  163. if graphics is None:
  164. return {"error": "No VNC graphics found"}
  165. vnc_port = graphics.get('port')
  166. if not vnc_port or vnc_port == '-1':
  167. return {"error": "VNC port not assigned"}
  168. vnc_port = int(vnc_port)
  169. if vm_name not in ws_processes:
  170. ws_port = get_free_port()
  171. proc = subprocess.Popen(['websockify', str(ws_port), f'localhost:{vnc_port}'])
  172. ws_processes[vm_name] = (proc, ws_port)
  173. _, ws_port = ws_processes[vm_name]
  174. return {"url": f"/static/novnc/vnc.html?host={socket.gethostname()}&port={ws_port}"}
  175. except Exception as e:
  176. return {"error": str(e)}
  177. @app.delete("/vms/{vm_name}")
  178. async def delete_vm(vm_name: str):
  179. try:
  180. domain = conn.lookupByName(vm_name)
  181. if domain.isActive():
  182. domain.destroy()
  183. domain.undefine()
  184. # Kill websockify process if exists
  185. if vm_name in ws_processes:
  186. proc, _ = ws_processes[vm_name]
  187. proc.terminate()
  188. proc.wait()
  189. del ws_processes[vm_name]
  190. return {"message": f"VM {vm_name} deleted"}
  191. except Exception as e:
  192. return {"error": str(e)}
  193. @app.put("/vms/{vm_name}/boot-order")
  194. async def set_boot_order(vm_name: str, boot_order: BootOrder):
  195. try:
  196. domain = conn.lookupByName(vm_name)
  197. if domain.isActive():
  198. return {"error": "VM must be shut off to change boot order"}
  199. xml_desc = domain.XMLDesc()
  200. root = ET.fromstring(xml_desc)
  201. os_section = root.find("os")
  202. # Remove existing boot elements
  203. for boot in os_section.findall("boot"):
  204. os_section.remove(boot)
  205. # Add new boot elements
  206. for dev in boot_order.order:
  207. ET.SubElement(os_section, "boot", {"dev": dev})
  208. new_xml = ET.tostring(root, encoding='unicode')
  209. # Undefine and redefine
  210. domain.undefine()
  211. new_domain = conn.defineXML(new_xml)
  212. return {"message": f"Boot order for {vm_name} updated to {boot_order.order}"}
  213. except Exception as e:
  214. return {"error": str(e)}
  215. @app.post("/disks")
  216. async def create_disk(name: str, size: int):
  217. images_path = os.environ.get('LIBVIRT_IMAGES_PATH', '/var/lib/libvirt/images')
  218. disk_path = f"{images_path}/{name}.qcow2"
  219. try:
  220. result = subprocess.run(['qemu-img', 'create', '-f', 'qcow2', disk_path, f'{size}G'], capture_output=True, text=True)
  221. if result.returncode == 0:
  222. return {"message": f"Disk {name}.qcow2 created with size {size}G"}
  223. else:
  224. return {"error": result.stderr}
  225. except Exception as e:
  226. return {"error": str(e)}