Python libvirt API - 创建一个虚拟机

Pan*_*rei 5 python kvm libvirt hypervisor

我正在尝试创建一个python脚本来处理基本的VM操作,例如:创建VM,删除VM,启动,停止等.

目前我很"坚持" create

从命令行,您将执行以下操作:

qemu-img create -f qcow2 vdisk.img <size>
virt-install --virt-type kvm --name testVM --ram 1024
 --cdrom=ubuntu.iso  --disk /path/to/virtual/drive,size=10,format=qcow2
 --network network=default --graphics vnc,listen=0.0.0.0 --noautoconsole
 --os-type=linux
Run Code Online (Sandbox Code Playgroud)

这将创建一个新的VM,testVM并在之前定义的上安装它vdisk.img

但我想在python中完成所有这些; 我知道如何处理第二部分:

  1. 从VM的XML模板开始
  2. 打开libvirt连接并使用连接处理程序创建VM

    但我想知道第一部分,你必须创建虚拟磁盘.

有没有libvirt API calls可以使用的?

或者,你必须在系统调用qemu-img create来创建虚拟磁盘?

Pan*_*rei 7

我终于找到并回答了我的问题 - 所以我在这里发布解决方案以防万一有人遇到同样的问题.

libvirt连接对象可以与存储池一起使用.

来自libvirt.org:" 存储池是由管理员(通常是专用存储管理员)留出的一定数量的存储,供虚拟机使用.存储池由存储管理员或系统管理员分为存储卷,并将卷作为块设备分配给VM. "

基本上卷是quemu-img create创造的.在所有.img(使用创建的qemu-img)文件所在的同一目录中创建存储池后; 创建的文件qemu-img被视为卷.

以下代码将列出所有现有卷,包括使用创建的卷 qemu-img

conn = libvirt.open()

pools = conn.listAllStoragePools(0)

for pool in pools:              

    #check if pool is active
    if pool.isActive() == 0:
        #activate pool
        pool.create()

    stgvols = pool.listVolumes()
    print('Storage pool: '+pool.name())
    for stgvol in stgvols :
        print('  Storage vol: '+stgvol)
Run Code Online (Sandbox Code Playgroud)

创建存储池:

def createStoragePool(conn):        
        xmlDesc = """
        <pool type='dir'>
          <name>guest_images_storage_pool</name>
          <uuid>8c79f996-cb2a-d24d-9822-ac7547ab2d01</uuid>
          <capacity unit='bytes'>4306780815</capacity>
          <allocation unit='bytes'>237457858</allocation>
          <available unit='bytes'>4069322956</available>
          <source>
          </source>
          <target>
            <path>/path/to/guest_images</path>
            <permissions>
              <mode>0755</mode>
              <owner>-1</owner>
              <group>-1</group>
            </permissions>
          </target>
        </pool>"""


        pool = conn.storagePoolDefineXML(xmlDesc, 0)

        #set storage pool autostart     
        pool.setAutostart(1)
        return pool
Run Code Online (Sandbox Code Playgroud)

创建卷:

def createStoragePoolVolume(pool, name):    
        stpVolXml = """
        <volume>
          <name>"""+name+""".img</name>
          <allocation>0</allocation>
          <capacity unit="G">10</capacity>
          <target>
            <path>/path/to/guest_images/"""+name+""".img</path>
            <permissions>
              <owner>107</owner>
              <group>107</group>
              <mode>0744</mode>
              <label>virt_image_t</label>
            </permissions>
          </target>
        </volume>"""

        stpVol = pool.createXML(stpVolXml, 0)   
        return stpVol
Run Code Online (Sandbox Code Playgroud)