main.py 23 KB

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