Browse Source

Crea máquina virtual sin plantilla

Celestino Rey 7 months ago
parent
commit
d77665758e
3 changed files with 87 additions and 4 deletions
  1. 3 2
      README.md
  2. 83 0
      app/main.py
  3. 1 2
      requirements.txt

+ 3 - 2
README.md

@@ -15,9 +15,9 @@ API for managing virtual machines on Ubuntu using FastAPI and libvirt.
    pip install -r requirements.txt
    ```
 
-3. Ensure libvirt is installed on the system:
+3. Ensure libvirt and Python bindings are installed on the system:
    ```bash
-   sudo apt install libvirt-daemon-system libvirt-dev pkg-config
+   sudo apt install libvirt-daemon-system libvirt-dev pkg-config python3-libvirt python3-gi
    ```
 
 ## Running the API
@@ -38,6 +38,7 @@ Access the interactive documentation at http://0.0.0.0:8000/docs
 
 - GET / : Root message
 - GET /vms : List all VMs
+- POST /vms?name={name}&memory={memory}&disk_size={disk_size}&iso={iso} : Create a new VM with specified memory (MiB), disk size (GB), and ISO for installation
 - GET /vms/{vm_id}/start : Start a VM by ID
 - GET /vms/{vm_id}/stop : Stop a VM by ID
 - DELETE /vms/{vm_name} : Delete a VM by name

+ 83 - 0
app/main.py

@@ -44,6 +44,89 @@ async def stop_vm(vm_id: int):
     #     return {"error": str(e)}
     return {"message": f"VM {vm_id} stopped (mock)"}
 
+@app.post("/vms")
+async def create_vm(name: str, memory: int, disk_size: int, iso: str):
+    images_path = os.environ.get('LIBVIRT_IMAGES_PATH', '/var/lib/libvirt/images')
+    disk_path = f"{images_path}/{name}.qcow2"
+    
+    # Create disk
+    try:
+        result = subprocess.run(['qemu-img', 'create', '-f', 'qcow2', disk_path, f'{disk_size}G'], capture_output=True, text=True)
+        if result.returncode != 0:
+            return {"error": f"Failed to create disk: {result.stderr}"}
+    except Exception as e:
+        return {"error": f"Error creating disk: {str(e)}"}
+    
+    # Basic XML template
+    xml_template = f"""<domain type='kvm'>
+  <name>{name}</name>
+  <memory unit='MiB'>{memory}</memory>
+  <currentMemory unit='MiB'>{memory}</currentMemory>
+  <vcpu placement='static'>1</vcpu>
+  <os>
+    <type arch='x86_64' machine='pc-i440fx-6.2'>hvm</type>
+    <boot dev='cdrom'/>
+  </os>
+  <features>
+    <acpi/>
+    <apic/>
+  </features>
+  <cpu mode='host-model' check='partial'/>
+  <clock offset='utc'>
+    <timer name='rtc' tickpolicy='catchup'/>
+    <timer name='pit' tickpolicy='delay'/>
+    <timer name='hpet' present='no'/>
+  </clock>
+  <on_poweroff>destroy</on_poweroff>
+  <on_reboot>restart</on_reboot>
+  <on_crash>destroy</on_crash>
+  <pm>
+    <suspend-to-mem enabled='no'/>
+    <suspend-to-disk enabled='no'/>
+  </pm>
+  <devices>
+    <emulator>/usr/bin/kvm</emulator>
+    <disk type='file' device='disk'>
+      <driver name='qemu' type='qcow2'/>
+      <source file='{disk_path}'/>
+      <target dev='vda' bus='virtio'/>
+    </disk>
+    <disk type='file' device='cdrom'>
+      <driver name='qemu' type='raw'/>
+      <source file='{images_path}/{iso}'/>
+      <target dev='hda' bus='ide'/>
+      <readonly/>
+    </disk>
+    <interface type='network'>
+      <mac address='52:54:00:00:00:01'/>
+      <source network='default'/>
+      <model type='virtio'/>
+    </interface>
+    <console type='pty'>
+      <target type='serial' port='0'/>
+    </console>
+    <input type='tablet' bus='usb'>
+      <address type='usb' bus='0' port='1'/>
+    </input>
+    <input type='mouse' bus='ps2'/>
+    <input type='keyboard' bus='ps2'/>
+    <graphics type='vnc' port='-1' autoport='yes'/>
+    <video>
+      <model type='cirrus' vram='16384' heads='1' primary='yes'/>
+    </video>
+    <memballoon model='virtio'>
+      <address type='pci' domain='0x0000' bus='0x00' slot='0x04' function='0x0'/>
+    </memballoon>
+  </devices>
+</domain>"""
+    
+    try:
+        domain = conn.defineXML(xml_template)
+        domain.create()
+        return {"message": f"VM {name} created with {memory} MiB memory, {disk_size}G disk, booting from {iso}"}
+    except Exception as e:
+        return {"error": str(e)}
+
 @app.delete("/vms/{vm_name}")
 async def delete_vm(vm_name: str):
     try:

+ 1 - 2
requirements.txt

@@ -1,3 +1,2 @@
 fastapi
-uvicorn[standard]
-libvirt-python
+uvicorn[standard]