main.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684
  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}/info")
  58. async def get_vm_info(vm_name: str):
  59. try:
  60. domain = conn.lookupByName(vm_name)
  61. xml_desc = domain.XMLDesc()
  62. root = ET.fromstring(xml_desc)
  63. # Get basic info
  64. memory = root.find("memory").text if root.find("memory") is not None else "Unknown"
  65. cpus = root.find("vcpu").text if root.find("vcpu") is not None else "Unknown"
  66. # Get VNC port
  67. graphics = root.find(".//graphics[@type='vnc']")
  68. vnc_port = None
  69. if graphics is not None:
  70. port_str = graphics.get('port')
  71. if port_str and port_str != '-1':
  72. vnc_port = int(port_str)
  73. # Get disks
  74. disks = []
  75. for disk in root.findall(".//disk"):
  76. device = disk.get('device')
  77. driver = disk.find("driver")
  78. source = disk.find("source")
  79. target = disk.find("target")
  80. disks.append({
  81. "type": device,
  82. "driver": driver.get('type') if driver is not None else "unknown",
  83. "source": source.get('file') if source is not None else "unknown",
  84. "target": target.get('dev') if target is not None else "unknown"
  85. })
  86. # Get network interfaces
  87. interfaces = []
  88. for iface in root.findall(".//interface"):
  89. mac = iface.find("mac")
  90. source = iface.find("source")
  91. model = iface.find("model")
  92. interfaces.append({
  93. "mac": mac.get('address') if mac is not None else "unknown",
  94. "network": source.get('network') if source is not None else "unknown",
  95. "model": model.get('type') if model is not None else "unknown"
  96. })
  97. return {
  98. "id": domain.ID(),
  99. "name": domain.name(),
  100. "state": get_state_string(domain.state()[0]),
  101. "memory": int(memory),
  102. "cpus": int(cpus),
  103. "vnc_port": vnc_port,
  104. "disks": disks,
  105. "interfaces": interfaces
  106. }
  107. except Exception as e:
  108. return {"error": str(e)}, 500
  109. @app.get("/vms/{vm_name}/stats")
  110. async def get_vm_stats(vm_name: str):
  111. """Get CPU and memory usage statistics for a VM"""
  112. try:
  113. domain = conn.lookupByName(vm_name)
  114. # Check if VM is running
  115. if not domain.isActive():
  116. return {
  117. "name": vm_name,
  118. "state": "shut off",
  119. "cpu_percent": 0,
  120. "memory_used": 0,
  121. "memory_total": 0,
  122. "memory_percent": 0
  123. }
  124. # Get CPU stats
  125. try:
  126. cpu_stats = domain.getCPUStats(True)
  127. if cpu_stats:
  128. # CPU time in nanoseconds
  129. cpu_time = cpu_stats[0].get('cpu_time', 0)
  130. cpu_percent = cpu_time / 1e9 # Convert to percentage approximation
  131. cpu_percent = min(100, cpu_percent % 100) # Keep between 0-100
  132. else:
  133. cpu_percent = 0
  134. except:
  135. cpu_percent = 0
  136. # Get memory stats
  137. try:
  138. memory_stats = domain.memoryStats()
  139. # Memory stats returns values in KB
  140. memory_used = memory_stats.get('actual', 0) // 1024 # Convert to MiB
  141. memory_total = memory_stats.get('swap_in', 0) # Total memory in MiB
  142. # Get from domain info as fallback
  143. if memory_total == 0:
  144. info = domain.info()
  145. memory_total = info[1] # Memory in MiB
  146. memory_percent = (memory_used / memory_total * 100) if memory_total > 0 else 0
  147. except:
  148. memory_used = 0
  149. memory_total = 0
  150. memory_percent = 0
  151. # Get domain memory from config
  152. try:
  153. xml_desc = domain.XMLDesc()
  154. root = ET.fromstring(xml_desc)
  155. memory_elem = root.find("memory")
  156. if memory_elem is not None:
  157. memory_total = int(memory_elem.text) // 1024 # Convert from KB to MiB
  158. except:
  159. pass
  160. return {
  161. "name": vm_name,
  162. "state": "running",
  163. "cpu_percent": round(cpu_percent, 2),
  164. "memory_used": memory_used,
  165. "memory_total": memory_total,
  166. "memory_percent": round(memory_percent, 2)
  167. }
  168. except Exception as e:
  169. return {"error": str(e), "state": "error"}
  170. @app.get("/vms/{vm_name}/start")
  171. async def start_vm(vm_name: str):
  172. try:
  173. domain = conn.lookupByName(vm_name)
  174. domain.create()
  175. return {"message": f"VM {vm_name} started"}
  176. except Exception as e:
  177. return {"error": str(e)}
  178. @app.get("/vms/{vm_name}/stop")
  179. async def stop_vm(vm_name: str):
  180. try:
  181. domain = conn.lookupByName(vm_name)
  182. domain.destroy()
  183. return {"message": f"VM {vm_name} stopped"}
  184. except Exception as e:
  185. return {"error": str(e)}
  186. @app.post("/vms")
  187. async def create_vm(name: str, memory: int, disk_size: int, cpus: int = 1, iso: str = ""):
  188. if not iso:
  189. return {"error": "ISO path is required"}
  190. images_path = os.environ.get('LIBVIRT_IMAGES_PATH', '/var/lib/libvirt/images')
  191. disk_path = f"{images_path}/{name}.qcow2"
  192. iso_path = iso
  193. print(f"[CREATE_VM] Starting VM creation: name={name}, memory={memory}, disk_size={disk_size}, cpus={cpus}")
  194. print(f"[CREATE_VM] Using ISO path: {iso_path}")
  195. # Create disk using sudo script for proper permissions
  196. try:
  197. # Get absolute path to the script (up one level from app directory)
  198. app_dir = os.path.dirname(os.path.abspath(__file__))
  199. project_root = os.path.dirname(app_dir)
  200. script_path = os.path.join(project_root, 'create_disk.sh')
  201. print(f"[CREATE_VM] Script path: {script_path}")
  202. result = subprocess.run(['sudo', script_path, disk_path, f'{disk_size}G'], capture_output=True, text=True, timeout=60)
  203. print(f"[CREATE_VM] Disk creation return code: {result.returncode}")
  204. if result.returncode != 0:
  205. error_msg = result.stderr if result.stderr else result.stdout
  206. print(f"[CREATE_VM] ERROR creating disk: {error_msg}")
  207. return {"error": f"Failed to create disk: {error_msg}"}
  208. print(f"[CREATE_VM] Disk created successfully: {disk_path}")
  209. except subprocess.TimeoutExpired:
  210. return {"error": "Disk creation timed out"}
  211. except Exception as e:
  212. print(f"[CREATE_VM] Exception creating disk: {str(e)}")
  213. return {"error": f"Error creating disk: {str(e)}"}
  214. # Verify disk exists
  215. if not os.path.exists(disk_path):
  216. print(f"[CREATE_VM] ERROR: Disk file not found after creation: {disk_path}")
  217. return {"error": f"Disk file not created at {disk_path}"}
  218. # Generate unique MAC
  219. mac = f"52:54:00:{random.randint(0, 255):02x}:{random.randint(0, 255):02x}:{random.randint(0, 255):02x}"
  220. print(f"[CREATE_VM] Generated MAC: {mac}")
  221. # Basic XML template
  222. xml_template = f"""<domain type='kvm'>
  223. <name>{name}</name>
  224. <memory unit='MiB'>{memory}</memory>
  225. <currentMemory unit='MiB'>{memory}</currentMemory>
  226. <vcpu placement='static'>{cpus}</vcpu>
  227. <os>
  228. <type arch='x86_64' machine='pc-i440fx-6.2'>hvm</type>
  229. <boot dev='cdrom'/>
  230. </os>
  231. <features>
  232. <acpi/>
  233. <apic/>
  234. </features>
  235. <cpu mode='host-model' check='partial'/>
  236. <clock offset='utc'>
  237. <timer name='rtc' tickpolicy='catchup'/>
  238. <timer name='pit' tickpolicy='delay'/>
  239. <timer name='hpet' present='no'/>
  240. </clock>
  241. <on_poweroff>destroy</on_poweroff>
  242. <on_reboot>restart</on_reboot>
  243. <on_crash>destroy</on_crash>
  244. <pm>
  245. <suspend-to-mem enabled='no'/>
  246. <suspend-to-disk enabled='no'/>
  247. </pm>
  248. <devices>
  249. <emulator>/usr/bin/kvm</emulator>
  250. <disk type='file' device='disk'>
  251. <driver name='qemu' type='qcow2'/>
  252. <source file='{disk_path}'/>
  253. <target dev='vda' bus='virtio'/>
  254. </disk>
  255. <disk type='file' device='cdrom'>
  256. <driver name='qemu' type='raw'/>
  257. <source file='{iso_path}'/>
  258. <target dev='hda' bus='ide'/>
  259. <readonly/>
  260. </disk>
  261. <interface type='network'>
  262. <mac address='{mac}'/>
  263. <source network='default'/>
  264. <model type='virtio'/>
  265. </interface>
  266. <console type='pty'>
  267. <target type='serial' port='0'/>
  268. </console>
  269. <input type='tablet' bus='usb'>
  270. <address type='usb' bus='0' port='1'/>
  271. </input>
  272. <input type='mouse' bus='ps2'/>
  273. <input type='keyboard' bus='ps2'/>
  274. <graphics type='vnc' port='-1' autoport='yes'/>
  275. <video>
  276. <model type='cirrus' vram='16384' heads='1' primary='yes'/>
  277. </video>
  278. <memballoon model='virtio'>
  279. <address type='pci' domain='0x0000' bus='0x00' slot='0x04' function='0x0'/>
  280. </memballoon>
  281. </devices>
  282. </domain>"""
  283. print(f"[CREATE_VM] XML template prepared for VM definition")
  284. try:
  285. print(f"[CREATE_VM] Defining VM with libvirt...")
  286. domain = conn.defineXML(xml_template)
  287. print(f"[CREATE_VM] VM defined successfully. Starting VM...")
  288. domain.create()
  289. print(f"[CREATE_VM] VM started successfully!")
  290. return {"message": f"VM {name} created with {cpus} CPUs, {memory} MiB memory, {disk_size}G disk, booting from {iso}"}
  291. except libvirt.libvirtError as e:
  292. print(f"[CREATE_VM] Libvirt error: {str(e)}")
  293. # Try to clean up the disk if VM definition failed
  294. try:
  295. os.remove(disk_path)
  296. print(f"[CREATE_VM] Cleaned up disk file after error")
  297. except:
  298. pass
  299. return {"error": f"Libvirt error: {str(e)}"}
  300. except Exception as e:
  301. print(f"[CREATE_VM] Unexpected error: {str(e)}")
  302. # Try to clean up the disk if VM definition failed
  303. try:
  304. os.remove(disk_path)
  305. print(f"[CREATE_VM] Cleaned up disk file after error")
  306. except:
  307. pass
  308. return {"error": f"Error: {str(e)}"}
  309. @app.get("/console/{vm_name}")
  310. async def get_console(vm_name: str):
  311. try:
  312. console_conn = libvirt.open('qemu:///system')
  313. domain = console_conn.lookupByName(vm_name)
  314. xml_desc = domain.XMLDesc()
  315. root = ET.fromstring(xml_desc)
  316. graphics = root.find(".//graphics[@type='vnc']")
  317. console_conn.close()
  318. if graphics is None:
  319. return {"error": "No VNC graphics found"}
  320. vnc_port = graphics.get('port')
  321. if not vnc_port or vnc_port == '-1':
  322. return {"error": "VNC port not assigned"}
  323. vnc_port = int(vnc_port)
  324. if vm_name not in ws_processes:
  325. ws_port = get_free_port()
  326. try:
  327. proc = subprocess.Popen(['websockify', str(ws_port), f'localhost:{vnc_port}'],
  328. stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  329. ws_processes[vm_name] = (proc, ws_port)
  330. except FileNotFoundError:
  331. return {"error": "websockify not found. Please install it: apt-get install websockify"}
  332. _, ws_port = ws_processes[vm_name]
  333. return {"url": f"/static/novnc/vnc.html?host={socket.gethostname()}&port={ws_port}"}
  334. except Exception as e:
  335. import traceback
  336. error_msg = f"Error: {str(e)}\n{traceback.format_exc()}"
  337. print(error_msg)
  338. return {"error": str(e)}
  339. @app.delete("/vms/{vm_name}")
  340. async def delete_vm(vm_name: str):
  341. try:
  342. domain = conn.lookupByName(vm_name)
  343. if domain.isActive():
  344. domain.destroy()
  345. domain.undefine()
  346. # Kill websockify process if exists
  347. if vm_name in ws_processes:
  348. proc, _ = ws_processes[vm_name]
  349. proc.terminate()
  350. proc.wait()
  351. del ws_processes[vm_name]
  352. return {"message": f"VM {vm_name} deleted"}
  353. except Exception as e:
  354. return {"error": str(e)}
  355. @app.put("/vms/{vm_name}/boot-order")
  356. async def set_boot_order(vm_name: str, boot_order: BootOrder):
  357. try:
  358. domain = conn.lookupByName(vm_name)
  359. if domain.isActive():
  360. return {"error": "VM must be shut off to change boot order"}
  361. xml_desc = domain.XMLDesc()
  362. root = ET.fromstring(xml_desc)
  363. os_section = root.find("os")
  364. # Remove existing boot elements
  365. for boot in os_section.findall("boot"):
  366. os_section.remove(boot)
  367. # Add new boot elements
  368. for dev in boot_order.order:
  369. ET.SubElement(os_section, "boot", {"dev": dev})
  370. new_xml = ET.tostring(root, encoding='unicode')
  371. # Undefine and redefine
  372. domain.undefine()
  373. new_domain = conn.defineXML(new_xml)
  374. return {"message": f"Boot order for {vm_name} updated to {boot_order.order}"}
  375. except Exception as e:
  376. return {"error": str(e)}
  377. @app.get("/isos")
  378. async def list_isos():
  379. images_path = os.environ.get('LIBVIRT_IMAGES_PATH', '/var/lib/libvirt/images')
  380. iso_dir = f"{images_path}/isos"
  381. if os.path.exists(iso_dir):
  382. isos = [{"name": f, "path": os.path.join(iso_dir, f)} for f in os.listdir(iso_dir) if f.endswith('.iso')]
  383. return {"isos": isos}
  384. return {"isos": []}
  385. @app.post("/upload-iso")
  386. async def upload_iso(file: UploadFile = File(...)):
  387. images_path = os.environ.get('LIBVIRT_IMAGES_PATH', '/var/lib/libvirt/images')
  388. iso_dir = f"{images_path}/isos"
  389. os.makedirs(iso_dir, exist_ok=True)
  390. file_path = os.path.join(iso_dir, file.filename)
  391. with open(file_path, "wb") as f:
  392. while chunk := await file.read(1024 * 1024): # Read in 1MB chunks
  393. f.write(chunk)
  394. return {"message": f"ISO {file.filename} uploaded successfully", "path": file_path}
  395. @app.delete("/isos/{iso_name}")
  396. async def delete_iso(iso_name: str):
  397. images_path = os.environ.get('LIBVIRT_IMAGES_PATH', '/var/lib/libvirt/images')
  398. iso_dir = f"{images_path}/isos"
  399. file_path = os.path.join(iso_dir, iso_name)
  400. if os.path.exists(file_path) and iso_name.endswith('.iso'):
  401. os.remove(file_path)
  402. return {"message": f"ISO {iso_name} deleted successfully"}
  403. else:
  404. return {"error": "ISO not found or invalid"}
  405. @app.post("/vms/{vm_name}/add-disk")
  406. async def add_disk_to_vm(vm_name: str, disk_name: str, disk_size: int):
  407. images_path = os.environ.get('LIBVIRT_IMAGES_PATH', '/var/lib/libvirt/images')
  408. disk_path = f"{images_path}/{disk_name}.qcow2"
  409. print(f"[ADD_DISK] Starting disk addition: vm={vm_name}, disk_name={disk_name}, disk_size={disk_size}")
  410. try:
  411. # Get the VM first to check its state
  412. print(f"[ADD_DISK] Looking up VM: {vm_name}")
  413. domain = conn.lookupByName(vm_name)
  414. # Check if VM is running BEFORE creating disk
  415. print(f"[ADD_DISK] Checking VM state...")
  416. if domain.isActive():
  417. print(f"[ADD_DISK] ERROR: VM is running, must be shut off to add disk")
  418. return {"error": "Error: La máquina virtual debe estar PARADA (shut off) para agregar un disco"}
  419. print(f"[ADD_DISK] VM state OK (shut off)")
  420. # Check if disk already exists
  421. print(f"[ADD_DISK] Checking if disk exists: {disk_path}")
  422. if os.path.exists(disk_path):
  423. print(f"[ADD_DISK] ERROR: Disk already exists")
  424. return {"error": f"Error: El disco {disk_name}.qcow2 ya existe. Usa un nombre de disco diferente"}
  425. print(f"[ADD_DISK] Disk does not exist (OK)")
  426. # Create the disk using sudo script for proper permissions
  427. print(f"[ADD_DISK] Creating disk...")
  428. app_dir = os.path.dirname(os.path.abspath(__file__))
  429. project_root = os.path.dirname(app_dir)
  430. script_path = os.path.join(project_root, 'create_disk.sh')
  431. result = subprocess.run(['sudo', script_path, disk_path, f'{disk_size}G'],
  432. capture_output=True, text=True, timeout=60)
  433. if result.returncode != 0:
  434. error_msg = result.stderr if result.stderr else result.stdout
  435. print(f"[ADD_DISK] ERROR creating disk: {error_msg}")
  436. return {"error": f"Error al crear disco: {error_msg}"}
  437. print(f"[ADD_DISK] Disk created successfully")
  438. # Get the XML and add the disk
  439. print(f"[ADD_DISK] Getting VM XML...")
  440. xml_desc = domain.XMLDesc()
  441. root = ET.fromstring(xml_desc)
  442. # Find the devices section
  443. devices = root.find("devices")
  444. if devices is None:
  445. print(f"[ADD_DISK] ERROR: No devices section in XML")
  446. return {"error": "Error: No se encontró sección devices en la configuración de la VM"}
  447. # Find the next available disk target (vda, vdb, vdc, etc.)
  448. print(f"[ADD_DISK] Finding next available disk target...")
  449. existing_targets = set()
  450. for disk in root.findall(".//disk/target"):
  451. existing_targets.add(disk.get('dev'))
  452. print(f"[ADD_DISK] Existing targets: {existing_targets}")
  453. # Generate next available target
  454. target_letters = "abcdefghijklmnopqrstuvwxyz"
  455. next_target = None
  456. for i, letter in enumerate(target_letters):
  457. target = f"vd{letter}"
  458. if target not in existing_targets:
  459. next_target = target
  460. break
  461. if next_target is None:
  462. print(f"[ADD_DISK] ERROR: No available disk targets")
  463. return {"error": "Error: No hay dispositivos de disco disponibles"}
  464. print(f"[ADD_DISK] Next target: {next_target}")
  465. # Create the new disk element
  466. print(f"[ADD_DISK] Creating disk XML element...")
  467. new_disk = ET.Element("disk", {"type": "file", "device": "disk"})
  468. ET.SubElement(new_disk, "driver", {"name": "qemu", "type": "qcow2"})
  469. ET.SubElement(new_disk, "source", {"file": disk_path})
  470. ET.SubElement(new_disk, "target", {"dev": next_target, "bus": "virtio"})
  471. # Add the disk to devices
  472. devices.append(new_disk)
  473. # Convert back to string and redefine the VM
  474. print(f"[ADD_DISK] Redefining VM with new disk...")
  475. new_xml = ET.tostring(root, encoding='unicode')
  476. domain.undefine()
  477. conn.defineXML(new_xml)
  478. print(f"[ADD_DISK] VM redefined successfully")
  479. print(f"[ADD_DISK] SUCCESS: Disk added")
  480. return {"message": f"Disco {disk_name}.qcow2 ({disk_size}G) agregado a {vm_name} como {next_target}"}
  481. except libvirt.libvirtError as e:
  482. print(f"[ADD_DISK] Libvirt error: {str(e)}")
  483. return {"error": f"Error de libvirt: {str(e)}"}
  484. except Exception as e:
  485. print(f"[ADD_DISK] Unexpected error: {str(e)}")
  486. return {"error": f"Error: {str(e)}"}
  487. @app.post("/disks")
  488. async def create_disk(name: str, size: int):
  489. images_path = os.environ.get('LIBVIRT_IMAGES_PATH', '/var/lib/libvirt/images')
  490. disk_path = f"{images_path}/{name}.qcow2"
  491. try:
  492. result = subprocess.run(['qemu-img', 'create', '-f', 'qcow2', disk_path, f'{size}G'], capture_output=True, text=True)
  493. if result.returncode == 0:
  494. return {"message": f"Disk {name}.qcow2 created with size {size}G"}
  495. else:
  496. return {"error": result.stderr}
  497. except Exception as e:
  498. return {"error": str(e)}
  499. @app.get("/vms/{vm_name}/config")
  500. async def get_vm_config(vm_name: str):
  501. """Get VM configuration in XML format"""
  502. try:
  503. conn = libvirt.open(None)
  504. domain = conn.lookupByName(vm_name)
  505. xml_desc = domain.XMLDesc()
  506. conn.close()
  507. return {
  508. "name": vm_name,
  509. "xml": xml_desc
  510. }
  511. except libvirt.libvirtError as e:
  512. return {"error": f"Error de libvirt: {str(e)}"}
  513. @app.post("/vms/{vm_name}/snapshot")
  514. async def create_snapshot(vm_name: str, snapshot_name: str, description: str = ""):
  515. """Create a snapshot of a VM"""
  516. try:
  517. conn = libvirt.open(None)
  518. domain = conn.lookupByName(vm_name)
  519. # Create snapshot XML
  520. snapshot_xml = f"""<domainsnapshot>
  521. <name>{snapshot_name}</name>
  522. <description>{description}</description>
  523. </domainsnapshot>"""
  524. print(f"[SNAPSHOT] Creating snapshot '{snapshot_name}' for VM '{vm_name}'")
  525. domain.snapshotCreateXML(snapshot_xml, 0)
  526. conn.close()
  527. print(f"[SNAPSHOT] Snapshot '{snapshot_name}' created successfully")
  528. return {"message": f"Snapshot '{snapshot_name}' creado exitosamente"}
  529. except libvirt.libvirtError as e:
  530. error_msg = str(e)
  531. print(f"[SNAPSHOT] Error creating snapshot: {error_msg}")
  532. return {"error": f"Error al crear snapshot: {error_msg}"}
  533. except Exception as e:
  534. error_msg = str(e)
  535. print(f"[SNAPSHOT] Unexpected error: {error_msg}")
  536. return {"error": f"Error: {error_msg}"}
  537. @app.get("/vms/{vm_name}/snapshots")
  538. async def list_snapshots(vm_name: str):
  539. """List all snapshots of a VM"""
  540. try:
  541. conn = libvirt.open(None)
  542. domain = conn.lookupByName(vm_name)
  543. snapshots = []
  544. try:
  545. # Get all snapshots
  546. snapshot_list = domain.listAllSnapshots()
  547. for snapshot in snapshot_list:
  548. snap_name = snapshot.getName()
  549. # Get snapshot info using available methods
  550. try:
  551. # Try to get current status
  552. is_current = snapshot.isCurrent()
  553. state = "current" if is_current else "available"
  554. except:
  555. state = "available"
  556. # Try to get creation time from snapshot info
  557. created_time = 0
  558. try:
  559. # Get snapshot XML description using getXMLDesc()
  560. snap_xml = snapshot.getXMLDesc()
  561. # Parse XML to get creationTime
  562. root = ET.fromstring(snap_xml)
  563. creation_elem = root.find('.//creationTime')
  564. if creation_elem is not None and creation_elem.text:
  565. created_time = int(creation_elem.text)
  566. except Exception as e:
  567. print(f"[SNAPSHOT] Error obteniendo creationTime: {str(e)}")
  568. created_time = 0
  569. snapshots.append({
  570. "name": snap_name,
  571. "created": created_time,
  572. "description": "",
  573. "state": state
  574. })
  575. except libvirt.libvirtError as e:
  576. # No snapshots available
  577. print(f"[SNAPSHOT] No snapshots found: {str(e)}")
  578. pass
  579. conn.close()
  580. return {
  581. "vm_name": vm_name,
  582. "snapshots": snapshots
  583. }
  584. except libvirt.libvirtError as e:
  585. error_msg = str(e)
  586. print(f"[SNAPSHOT] Error listing snapshots: {error_msg}")
  587. return {"error": f"Error al listar snapshots: {error_msg}"}
  588. @app.delete("/vms/{vm_name}/snapshots/{snapshot_name}")
  589. async def delete_snapshot(vm_name: str, snapshot_name: str):
  590. """Delete a snapshot of a VM"""
  591. try:
  592. conn = libvirt.open(None)
  593. domain = conn.lookupByName(vm_name)
  594. print(f"[SNAPSHOT] Deleting snapshot '{snapshot_name}' from VM '{vm_name}'")
  595. snapshot = domain.snapshotLookupByName(snapshot_name)
  596. snapshot.delete(0)
  597. conn.close()
  598. print(f"[SNAPSHOT] Snapshot '{snapshot_name}' deleted successfully")
  599. return {"message": f"Snapshot '{snapshot_name}' eliminado exitosamente"}
  600. except libvirt.libvirtError as e:
  601. error_msg = str(e)
  602. print(f"[SNAPSHOT] Error deleting snapshot: {error_msg}")
  603. return {"error": f"Error al eliminar snapshot: {error_msg}"}
  604. except Exception as e:
  605. error_msg = str(e)
  606. print(f"[SNAPSHOT] Unexpected error: {error_msg}")