main.py 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  1. from fastapi import FastAPI, UploadFile, File
  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. if not iso:
  76. return {"error": "ISO path is required"}
  77. images_path = os.environ.get('LIBVIRT_IMAGES_PATH', '/mnt/vms/images')
  78. disk_path = f"{images_path}/{name}.qcow2"
  79. iso_path = iso # iso ya es la ruta completa desde el select
  80. print(f"Using ISO path: {iso_path}")
  81. # Create disk
  82. try:
  83. result = subprocess.run(['qemu-img', 'create', '-f', 'qcow2', disk_path, f'{disk_size}G'], capture_output=True, text=True)
  84. if result.returncode != 0:
  85. return {"error": f"Failed to create disk: {result.stderr}"}
  86. except Exception as e:
  87. return {"error": f"Error creating disk: {str(e)}"}
  88. # Generate unique MAC
  89. mac = f"52:54:00:{random.randint(0, 255):02x}:{random.randint(0, 255):02x}:{random.randint(0, 255):02x}"
  90. # Basic XML template
  91. xml_template = f"""<domain type='kvm'>
  92. <name>{name}</name>
  93. <memory unit='MiB'>{memory}</memory>
  94. <currentMemory unit='MiB'>{memory}</currentMemory>
  95. <vcpu placement='static'>1</vcpu>
  96. <os>
  97. <type arch='x86_64' machine='pc-i440fx-6.2'>hvm</type>
  98. <boot dev='cdrom'/>
  99. </os>
  100. <features>
  101. <acpi/>
  102. <apic/>
  103. </features>
  104. <cpu mode='host-model' check='partial'/>
  105. <clock offset='utc'>
  106. <timer name='rtc' tickpolicy='catchup'/>
  107. <timer name='pit' tickpolicy='delay'/>
  108. <timer name='hpet' present='no'/>
  109. </clock>
  110. <on_poweroff>destroy</on_poweroff>
  111. <on_reboot>restart</on_reboot>
  112. <on_crash>destroy</on_crash>
  113. <pm>
  114. <suspend-to-mem enabled='no'/>
  115. <suspend-to-disk enabled='no'/>
  116. </pm>
  117. <devices>
  118. <emulator>/usr/bin/kvm</emulator>
  119. <disk type='file' device='disk'>
  120. <driver name='qemu' type='qcow2'/>
  121. <source file='{disk_path}'/>
  122. <target dev='vda' bus='virtio'/>
  123. </disk>
  124. <disk type='file' device='cdrom'>
  125. <driver name='qemu' type='raw'/>
  126. <source file='{iso_path}'/>
  127. <target dev='hda' bus='ide'/>
  128. <readonly/>
  129. </disk>
  130. <interface type='network'>
  131. <mac address='{mac}'/>
  132. <source network='default'/>
  133. <model type='virtio'/>
  134. </interface>
  135. <console type='pty'>
  136. <target type='serial' port='0'/>
  137. </console>
  138. <input type='tablet' bus='usb'>
  139. <address type='usb' bus='0' port='1'/>
  140. </input>
  141. <input type='mouse' bus='ps2'/>
  142. <input type='keyboard' bus='ps2'/>
  143. <graphics type='vnc' port='-1' autoport='yes'/>
  144. <video>
  145. <model type='cirrus' vram='16384' heads='1' primary='yes'/>
  146. </video>
  147. <memballoon model='virtio'>
  148. <address type='pci' domain='0x0000' bus='0x00' slot='0x04' function='0x0'/>
  149. </memballoon>
  150. </devices>
  151. </domain>"""
  152. try:
  153. domain = conn.defineXML(xml_template)
  154. domain.create()
  155. return {"message": f"VM {name} created with {memory} MiB memory, {disk_size}G disk, booting from {iso}"}
  156. except Exception as e:
  157. return {"error": str(e)}
  158. @app.get("/console/{vm_name}")
  159. async def get_console(vm_name: str):
  160. try:
  161. domain = conn.lookupByName(vm_name)
  162. xml_desc = domain.XMLDesc()
  163. root = ET.fromstring(xml_desc)
  164. graphics = root.find(".//graphics[@type='vnc']")
  165. if graphics is None:
  166. return {"error": "No VNC graphics found"}
  167. vnc_port = graphics.get('port')
  168. if not vnc_port or vnc_port == '-1':
  169. return {"error": "VNC port not assigned"}
  170. vnc_port = int(vnc_port)
  171. if vm_name not in ws_processes:
  172. ws_port = get_free_port()
  173. proc = subprocess.Popen(['websockify', str(ws_port), f'localhost:{vnc_port}'])
  174. ws_processes[vm_name] = (proc, ws_port)
  175. _, ws_port = ws_processes[vm_name]
  176. return {"url": f"/static/novnc/vnc.html?host={socket.gethostname()}&port={ws_port}"}
  177. except Exception as e:
  178. return {"error": str(e)}
  179. @app.delete("/vms/{vm_name}")
  180. async def delete_vm(vm_name: str):
  181. try:
  182. domain = conn.lookupByName(vm_name)
  183. if domain.isActive():
  184. domain.destroy()
  185. domain.undefine()
  186. # Kill websockify process if exists
  187. if vm_name in ws_processes:
  188. proc, _ = ws_processes[vm_name]
  189. proc.terminate()
  190. proc.wait()
  191. del ws_processes[vm_name]
  192. return {"message": f"VM {vm_name} deleted"}
  193. except Exception as e:
  194. return {"error": str(e)}
  195. @app.put("/vms/{vm_name}/boot-order")
  196. async def set_boot_order(vm_name: str, boot_order: BootOrder):
  197. try:
  198. domain = conn.lookupByName(vm_name)
  199. if domain.isActive():
  200. return {"error": "VM must be shut off to change boot order"}
  201. xml_desc = domain.XMLDesc()
  202. root = ET.fromstring(xml_desc)
  203. os_section = root.find("os")
  204. # Remove existing boot elements
  205. for boot in os_section.findall("boot"):
  206. os_section.remove(boot)
  207. # Add new boot elements
  208. for dev in boot_order.order:
  209. ET.SubElement(os_section, "boot", {"dev": dev})
  210. new_xml = ET.tostring(root, encoding='unicode')
  211. # Undefine and redefine
  212. domain.undefine()
  213. new_domain = conn.defineXML(new_xml)
  214. return {"message": f"Boot order for {vm_name} updated to {boot_order.order}"}
  215. except Exception as e:
  216. return {"error": str(e)}
  217. @app.get("/isos")
  218. async def list_isos():
  219. images_path = os.environ.get('LIBVIRT_IMAGES_PATH', '/mnt/vms/images')
  220. iso_dir = f"{images_path}/isos"
  221. if os.path.exists(iso_dir):
  222. isos = [{"name": f, "path": os.path.join(iso_dir, f)} for f in os.listdir(iso_dir) if f.endswith('.iso')]
  223. return {"isos": isos}
  224. return {"isos": []}
  225. @app.post("/upload-iso")
  226. async def upload_iso(file: UploadFile = File(...)):
  227. images_path = os.environ.get('LIBVIRT_IMAGES_PATH', '/mnt/vms/images')
  228. iso_dir = f"{images_path}/isos"
  229. os.makedirs(iso_dir, exist_ok=True)
  230. file_path = os.path.join(iso_dir, file.filename)
  231. with open(file_path, "wb") as f:
  232. while chunk := await file.read(1024 * 1024): # Read in 1MB chunks
  233. f.write(chunk)
  234. return {"message": f"ISO {file.filename} uploaded successfully", "path": file_path}
  235. @app.delete("/isos/{iso_name}")
  236. async def delete_iso(iso_name: str):
  237. images_path = os.environ.get('LIBVIRT_IMAGES_PATH', '/mnt/vms/images')
  238. iso_dir = f"{images_path}/isos"
  239. file_path = os.path.join(iso_dir, iso_name)
  240. if os.path.exists(file_path) and iso_name.endswith('.iso'):
  241. os.remove(file_path)
  242. return {"message": f"ISO {iso_name} deleted successfully"}
  243. else:
  244. return {"error": "ISO not found or invalid"}
  245. @app.post("/disks")
  246. async def create_disk(name: str, size: int):
  247. images_path = os.environ.get('LIBVIRT_IMAGES_PATH', '/var/lib/libvirt/images')
  248. disk_path = f"{images_path}/{name}.qcow2"
  249. try:
  250. result = subprocess.run(['qemu-img', 'create', '-f', 'qcow2', disk_path, f'{size}G'], capture_output=True, text=True)
  251. if result.returncode == 0:
  252. return {"message": f"Disk {name}.qcow2 created with size {size}G"}
  253. else:
  254. return {"error": result.stderr}
  255. except Exception as e:
  256. return {"error": str(e)}