Python libvirt API - create a Virtual Machine

柔情痞子 提交于 2019-11-30 10:37:44

I finally found and answer to my problems- so I'm posting the solution here in case anyone ever hits the same problem.

The libvirt connection object can work with storage pools.

From the libvirt.org: "A storage pool is a quantity of storage set aside by an administrator, often a dedicated storage administrator, for use by virtual machines. Storage pools are divided into storage volumes either by the storage administrator or the system administrator, and the volumes are assigned to VMs as block devices."

Basically a volume is what quemu-img create creates. Once you create a storage pool in the same directory where all the .img (created using qemu-img) files are; the files created with qemu-img are seen as volumes.

The following code will list all existing volumes, including the ones created with 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)

Creating a storage pool:

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

Creating a volume:

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!