| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263 |
- from fastapi import FastAPI
- import os
- import re
- import libvirt
- 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):
- 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()
- # Replace the name in XML
- xml = re.sub(r'<name>.*?</name>', f'<name>{name}</name>', xml)
- try:
- # Create VM from template
- domain = conn.defineXML(xml)
- domain.create()
- return {"message": f"VM {name} created from template {template}"}
- except Exception as e:
- return {"error": str(e)}
- #return {"message": f"VM created from template {template} (mock)"}
|