| 12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091 |
- from fastapi import FastAPI
- import os
- import re
- import libvirt
- import subprocess
- app = FastAPI(title="VirtManager API", description="API for managing virtual machines")
- # Connect to libvirt
- conn = libvirt.open('qemu:///system')
- @app.get("/")
- async def root():
- return {"message": "VirtManager API"}
- @app.get("/vms")
- async def list_vms():
- domains = conn.listAllDomains()
- vms = []
- for domain in domains:
- vms.append({
- "id": domain.ID(),
- "name": domain.name(),
- "state": domain.state()[0]
- })
- return {"vms": vms}
- @app.get("/vms/{vm_id}/start")
- async def start_vm(vm_id: int):
- # try:
- # domain = conn.lookupByID(vm_id)
- # domain.create()
- # return {"message": f"VM {vm_id} started"}
- # except Exception as e:
- # return {"error": str(e)}
- return {"message": f"VM {vm_id} started (mock)"}
- @app.get("/vms/{vm_id}/stop")
- async def stop_vm(vm_id: int):
- # try:
- # domain = conn.lookupByID(vm_id)
- # domain.destroy()
- # return {"message": f"VM {vm_id} stopped"}
- # except Exception as e:
- # return {"error": str(e)}
- return {"message": f"VM {vm_id} stopped (mock)"}
- @app.post("/vms")
- async def create_vm(name: str, template: str, disk: str):
- xml_path = f"templates/{template}.xml"
- if not os.path.exists(xml_path):
- return {"error": f"Template {template} not found"}
- with open(xml_path, 'r') as f:
- xml = f.read()
- # Get images path from env
- images_path = os.environ.get('LIBVIRT_IMAGES_PATH', '/var/lib/libvirt/images')
- # Replace the name in XML
- xml = re.sub(r'<name>.*?</name>', f'<name>{name}</name>', xml)
- # Replace the disk file name
- xml = re.sub(r'file=\'/var/lib/libvirt/images/.*?\.qcow2\'', f"file='{images_path}/{disk}.qcow2'", xml)
- try:
- # Create VM from template
- domain = conn.defineXML(xml)
- domain.create()
- return {"message": f"VM {name} created from template {template} with disk {disk}.qcow2"}
- except Exception as e:
- return {"error": str(e)}
- @app.delete("/vms/{vm_name}")
- async def delete_vm(vm_name: str):
- try:
- domain = conn.lookupByName(vm_name)
- if domain.isActive():
- domain.destroy()
- domain.undefine()
- return {"message": f"VM {vm_name} deleted"}
- except Exception as e:
- return {"error": str(e)}
- @app.post("/disks")
- async def create_disk(name: str, size: int):
- images_path = os.environ.get('LIBVIRT_IMAGES_PATH', '/var/lib/libvirt/images')
- disk_path = f"{images_path}/{name}.qcow2"
- try:
- result = subprocess.run(['qemu-img', 'create', '-f', 'qcow2', disk_path, f'{size}G'], capture_output=True, text=True)
- if result.returncode == 0:
- return {"message": f"Disk {name}.qcow2 created with size {size}G"}
- else:
- return {"error": result.stderr}
- except Exception as e:
- return {"error": str(e)}
|