Python SDK 指南


Red Hat Virtualization 4.0

使用 Red Hat Virtualization Python SDK

摘要

本指南论述了如何安装和使用 Red Hat Virtualization Python 软件开发工具包的版本 3 和版本 4。

部分 I. Python Sofware Development Kit

第 1 章 概述

Python 软件开发工具包是一系列类,允许您在基于 Python 的项目中与 Red Hat Virtualization Manager 交互。通过下载这些类并将它们添加到项目中,您可以访问一系列功能的管理任务自动化。
Red Hat Virtualization 提供两个 Python 软件开发工具包版本:
版本 3
V3 Python 软件开发工具包提供了与 Python 软件开发工具包中提供的类和方法结构向后兼容,作为 Red Hat Enterprise Virtualization 3.6 的最新版本。使用来自 Red Hat Enterprise Virtualization 3.6 的 Python 软件开发工具包编写的应用程序可以在不修改的情况下用于此版本。
版本 4
V4 Python 软件开发工具包提供了一组更新的类和方法名称和签名。使用 Red Hat Enterprise Virtualization 3.6 中的 Python 软件开发工具包编写的应用程序必须更新它们,然后才能用于此版本。
安装相应的软件包并将所需的库添加到 Python 项目时,可以在 Red Hat Virtualization 环境中使用任一版本的 Python 软件开发工具包。

1.1. 前提条件

要安装 Python 软件开发工具包,您必须有:
  • A system where Red Hat Enterprise Linux 7 is installed.支持 Server 和 Workstation 变体。
  • Red Hat Virtualization 权利的订阅。
重要
软件开发套件是 Red Hat Virtualization REST API 的接口。因此,您必须使用与 Red Hat Virtualization 环境版本对应的软件开发工具包版本。例如,如果您使用 Red Hat Virtualization 4.0,则必须使用为 4.0 设计的软件开发工具包版本。

1.2. 安装 Python 软件开发套件

安装 Python 软件开发工具包。

过程 1.1. 安装 Python 软件开发套件

  1. 启用所需的频道:
    # subscription-manager repos --enable=rhel-7-server-rpms
    # subscription-manager repos --enable=rhel-7-server-rhv-4.0-rpms
    
    Copy to Clipboard Toggle word wrap
  2. 安装所需的软件包:
    • 对于 V3:
      # yum install ovirt-engine-sdk-python
      Copy to Clipboard Toggle word wrap
    • 对于 V4:
      # yum install python-ovirt-engine-sdk4
      Copy to Clipboard Toggle word wrap
Python 软件开发工具包和附带的文档下载到 /usr/lib/python2.7/site-packages/ovirtsdk/ 目录中,现在可以添加到 Python 项目中。

第 2 章 Python 快速入门示例

2.1. Python 快速入门介绍

本章提供了一系列示例演示了使用 Python SDK 在基本 Red Hat Virtualization 环境中创建虚拟机的步骤。
重要
本章中的示例设计为使用 Python SDK 的 V3。
这些示例使用 ovirt-engine-sdk-python 软件包提供的 ovirtsdk Python 库。这个软件包可供订阅在 Red Hat Subscription Manager 中的 Red Hat Virtualization 授权池的系统中。有关订阅您的系统以下载软件的更多信息,请参阅 第 1.2 节 “安装 Python 软件开发套件”
您还需要:
  • Red Hat Virtualization Manager 的联网安装。
  • 已联网和配置 Red Hat Virtualization 主机。
  • 包含用于在虚拟机上安装的操作系统的 ISO 镜像文件。
  • 了解组成 Red Hat Virtualization 环境的逻辑和物理对象。
  • 了解 Python 编程语言。
重要
所有 Python 示例都包括身份验证详细信息的占位符(用于用户名的USERPASS 用于密码)。确保通过 Python 执行的所有请求满足您的环境的身份验证要求。
注意
Red Hat Virtualization Manager 为每个资源的 id 属性生成全局唯一标识符(GUID)。这些示例中的标识符代码可能与 Red Hat Virtualization 环境中的标识符代码不同。
注意
这些 Python 示例仅包含基本异常和错误处理逻辑。有关特定于 SDK 的异常处理的更多信息,请参阅 ovirtsdk.infrastructure.errors 模块的 pydoc。
$ pydoc ovirtsdk.infrastructure.errors
Copy to Clipboard Toggle word wrap

2.2. 示例:使用 Python 访问 API 条目点

ovirtsdk Python 库提供 API 类,它充当 API 的入口点。

例 2.1. 使用 Python 访问 API 入口点

这个 Python 示例连接到 Red Hat Virtualization Manager 提供的 REST API 实例,地址为 rhevm.demo.redhat.com。若要连接示例,请创建一个 API 类实例,如果连接成功会输出信息。最后,调用 API 类的 disconnect () 方法来关闭连接。
本例中 API 类为构造器提供的参数有:
  • 要连接的 Manager 的 URL。
  • 要进行身份验证的 用户的用户名
  • 要进行身份验证的 用户的密码
  • ca_file,这是证书的路径。证书应该是管理器证书颁发机构的一个副本。它可以从 https://[engine-fqdn]ovirt-engine/services/pki-resource?resource=ca-certificate&format=X509-PEM-CA 中获取。
API 类的构造器支持其他参数。本例中只指定强制参数。
from ovirtsdk.api import API
from ovirtsdk.xml import params

try:
    api = API (url="https://HOST",
               username="USER@DOMAIN",
               password="PASS",
               ca_file="ca.crt")

    print "Connected to %s successfully!" % api.get_product_info().name

    api.disconnect()

except Exception as ex:
    print "Unexpected error: %s" % ex
Copy to Clipboard Toggle word wrap
如果连接尝试成功,示例会输出文本:
Connected to Red Hat Virtualization Manager successfully!
Copy to Clipboard Toggle word wrap

2.3. 示例:使用 Python 列出数据中心集合

API 类提供对数据中心集合的访问,名为 datacenter。此集合包含环境中的所有数据中心。

例 2.2. 使用 Python 列出数据中心集合

这个 Python 示例列出了 datacenters 集合中的数据中心。它还会输出集合中每个数据中心的一些基本信息。
from ovirtsdk.api import API
from ovirtsdk.xml import params

try:
    api = API (url="https://HOST",
               username="USER@DOMAIN",
               password="PASS",
               ca_file="ca.crt")

    dc_list = api.datacenters.list()

    for dc in dc_list:
        print "%s (%s)" % (dc.get_name(), dc.get_id())

    api.disconnect()

except Exception as ex:
    print "Unexpected error: %s" % ex
Copy to Clipboard Toggle word wrap
在只存在 Default 数据中心的环境中,且没有激活,示例输出:
Default (d8b74b20-c6e1-11e1-87a3-00163e77e2ed)
Copy to Clipboard Toggle word wrap

2.4. 示例:使用 Python 列出 Cluster Collection

API 类提供名为 clusters 的集群集合。此集合包含环境中的所有集群。

例 2.3. 使用 Python 列出集群集合

此 Python 示例列出了集群集合中 的集群。它还会输出集合中每个集群的一些基本信息。
from ovirtsdk.api import API
from ovirtsdk.xml import params

try:
    api = API (url="https://HOST",
               username="USER@DOMAIN",
               password="PASS",
               ca_file="ca.crt")
      
    c_list = api.clusters.list()       
    
    for c in c_list:
        print "%s (%s)" % (c.get_name(), c.get_id())

    api.disconnect()

except Exception as ex:
    print "Unexpected error: %s" % ex
Copy to Clipboard Toggle word wrap
在只存在 Default 集群的环境中,示例输出:
Default (99408929-82cf-4dc7-a532-9d998063fa95)
Copy to Clipboard Toggle word wrap

2.5. 示例:使用 Python 列出逻辑网络集合

API 类提供对逻辑网络集合(名为 network )的访问。此集合包含环境中的所有逻辑网络。

例 2.4. 使用 Python 列出逻辑网络集合

这个 Python 示例列出了网络集合中的 逻辑网络。它还会输出集合中每个网络的一些基本信息。
from ovirtsdk.api import API
from ovirtsdk.xml import params

try:
    api = API(url="https://HOST",
              username="USER@DOMAIN",
              password="PASS",
              ca_file="ca.crt")

    n_list = api.networks.list()

    for n in n_list:
        print "%s (%s)" % (n.get_name(), n.get_id())
    
    api.disconnect()
    
except Exception as ex:
    print "Unexpected error: %s" % ex
Copy to Clipboard Toggle word wrap
在只存在默认管理网络的环境中,示例输出:
ovirtmgmt (00000000-0000-0000-0000-000000000009)
Copy to Clipboard Toggle word wrap

2.6. 示例:使用 Python 列出主机集合

API 类提供对名为 hosts 的主机集合的访问。此集合包含环境中的所有主机。

例 2.5. 使用 Python 列出主机集合

此 Python 示例列出了主机集合中 的主机
from ovirtsdk.api import API
from ovirtsdk.xml import params

try:
    api = API(url="https://HOST",
              username="USER@DOMAIN",
              password="PASS",
              ca_file="ca.crt")

    h_list = api.hosts.list()

    for h in h_list:
        print "%s (%s)" % (h.get_name(), h.get_id())

    api.disconnect()

except Exception as ex:
    print "Unexpected error: %s" % ex
Copy to Clipboard Toggle word wrap
在一个只有一个主机的环境中,名为 Atlantic,并附加了示例输出:
Atlantic (5b333c18-f224-11e1-9bdd-00163e77e2ed)
Copy to Clipboard Toggle word wrap

2.7. 示例:列出 ISO 存储域中的 ISO 文件

API 类提供对存储域集合的访问,名为 storagedomains。这个集合包含描述存储域中 的文件 集合。

例 2.6. 列出 ISO 存储域中的 ISO 文件

这个 Python 示例输出 Red Hat Virtualization 环境中每个 ISO 存储域中的 ISO 文件列表:
from ovirtsdk.api import API
from ovirtsdk.xml import params

try:
    api = API (url="https://HOST",
               username="USER@DOMAIN",
               password="PASS",
               ca_file="ca.crt")

    storage_domains = api.storagedomains.list()

    for storage_domain in storage_domains:
        if(storage_domain.get_type() == "iso"):

            print(storage_domain.get_name() + ":\n")

            files = storage_domain.files.list()

            for file in files:
                print("     %s" % file.get_name())

            print()

    api.disconnect()

except Exception as ex:
    print "Unexpected error: %s" % ex
Copy to Clipboard Toggle word wrap

2.8. 示例:列出虚拟机的大小

API 类提供对名为 vms 的虚拟机集合的访问。这个集合包含 磁盘 集合,用于描述附加到虚拟机的每个磁盘的详情。

例 2.7. 列出虚拟机的大小

这个 Python 示例在 Red Hat Virtualization 环境中显示虚拟机列表及其总磁盘大小,以字节为单位:
from ovirtsdk.api import API
from ovirtsdk.xml import params

try:
    api = API (url="https://HOST",
               username="USER@DOMAIN",
               password="PASS",
               ca_file="ca.crt")

    virtual_machines = api.vms.list()

    if len(virtual_machines) > 0:

        print("%-30s  %s" % ("Name","Disk Size"))
        print("==================================================")

        for virtual_machine in virtual_machines:

            disks = virtual_machine.disks.list()

            disk_size = 0

            for disk in disks:
                disk_size += disk.get_size()

            print("%-30s: %d" % (virtual_machine.get_name(), disk_size))

    api.disconnect()

except Exception as ex:
    print "Unexpected error: %s" % ex
Copy to Clipboard Toggle word wrap

2.9. 示例:使用 Python 创建 NFS 数据存储

当首次创建 Red Hat Virtualization 环境时,需要至少定义数据存储域和 ISO 存储域。数据存储域将用于存储虚拟磁盘映像,而 ISO 存储域则用于存储客户机操作系统的安装介质。
API 类提供对名为 storagedomains 的存储域集合的访问。此集合包含环境中的所有存储域。storagedomains 集合也可用于添加和删除存储域。
注意
本例中提供的代码假定已预先配置了远程 NFS 共享以用于 Red Hat Virtualization。有关准备 NFS 共享以供使用的更多信息,请参阅 Red Hat Virtualization 管理指南

例 2.8. 使用 Python 创建 NFS 数据存储

这个 Python 示例在 storagedomains 集合中添加了一个 NFS 数据域。在 Python 中添加 NFS 存储域可分为几个步骤:
  1. 使用数据中心集合的 get 方法来识别必须附加存储 的数据中心
    dc = api.datacenters.get(name="Default")
    Copy to Clipboard Toggle word wrap
  2. 使用 get 方法识别必须用于附加存储 的主机
    h = api.hosts.get(name="Atlantic")
    Copy to Clipboard Toggle word wrap
  3. 定义 NFS 存储域的存储参数。在本例中,使用 NFS 位置 192.0.43.10/storage/data
    s = params.Storage(address="192.0.43.10", path="/storage/data", type_="nfs")
    Copy to Clipboard Toggle word wrap
  4. 使用 storagedomains 集合的 add 方法,请求创建存储域。除了 存储 参数外,还需要通过:
    • 存储域的名称。
    • 从数据中心集合中检索 的数据中心 对象。
    • 从主机集合检索 的主机 对象。
    • 正在添加的存储域类型(数据iso导出)。
    • 要使用的存储格式(v1、 v2v3)。
合并这些步骤后,完成的脚本为:
from ovirtsdk.api import API
from ovirtsdk.xml import params

try:
    api = API (url="https://HOST",
               username="USER@DOMAIN",
               password="PASS",
               ca_file="ca.crt")

    dc = api.datacenters.get(name="Default")
    h = api.hosts.get(name="Atlantic")

    s = params.Storage(address="192.0.43.10", path="/storage/data", type_="nfs")
    sd_params = params.StorageDomain(name="data1", data_center=dc, host=h, type_="data", storage_format="v3", storage=s)

    try:
        sd = api.storagedomains.add(sd_params)
        print "Storage Domain '%s' added (%s)." % (sd.get_name())
    except Exception as ex:
        print "Adding storage domain failed: %s" % ex

    api.disconnect()

except Exception as ex:
    print "Unexpected error: %s" % ex
Copy to Clipboard Toggle word wrap
如果 add 方法调用成功,则脚本将输出:
Storage Domain 'data1' added (bd954c03-d180-4d16-878c-2aedbdede566).
Copy to Clipboard Toggle word wrap

2.10. 示例:使用 Python 创建 NFS ISO 存储

要创建虚拟机,您必须能够为客户机操作系统提供安装介质。在 Red Hat Virtualization 环境中,将安装介质存储在 ISO 存储域中。
注意
本例中提供的代码假定已预先配置了远程 NFS 共享以用于 Red Hat Virtualization。有关准备 NFS 共享以供使用的更多信息,请参阅 Red Hat Virtualization 管理指南

例 2.9. 使用 Python 创建 NFS ISO 存储

这个 Python 示例在 storagedomains 集合中添加了一个 NFS ISO 域。在 Python 中添加 NFS 存储域可分为几个步骤:
  1. 使用数据中心集合的 get 方法来识别必须附加存储 的数据中心
    dc = api.datacenters.get( name="Default" )
    Copy to Clipboard Toggle word wrap
  2. 使用 get 方法识别必须用于附加存储 的主机
    h = api.hosts.get(name="Atlantic")
    Copy to Clipboard Toggle word wrap
  3. 定义 NFS 存储域的存储参数。在本例中,使用 NFS 位置 192.0.43.10/storage/iso
    s = params.Storage(address="192.0.43.10", path="/storage/iso", type_="nfs")
    Copy to Clipboard Toggle word wrap
  4. 使用 storagedomains 集合的 add 方法,请求创建存储域。除了 存储 参数外,还需要通过:
    • 存储域的名称。
    • 从数据中心集合中检索 的数据中心 对象。
    • 从主机集合检索 的主机 对象。
    • 正在添加的存储域类型(数据iso导出)。
    • 要使用的存储格式(v1、 v2v3)。
合并这些步骤后,完成的脚本为:
from ovirtsdk.api import API
from ovirtsdk.xml import params

try:
    api = API (url="https://HOST",
               username="USER@DOMAIN",
               password="PASS",
               ca_file="ca.crt")

    dc = api.datacenters.get(name="Default")
    h = api.hosts.get(name="Atlantic")

    s = params.Storage(address="192.0.43.10", path="/storage/iso", type_="nfs")
    sd_params = params.StorageDomain(name="iso1", data_center=dc, host=h, type_="iso", storage_format="v3", storage=s)

    try:
        sd = api.storagedomains.add(sd_params)
        print "Storage Domain '%s' added (%s)." % (sd.get_name())
    except Exception as ex:
        print "Adding storage domain failed: %s" % ex

    api.disconnect()

except Exception as ex:
    print "Unexpected error: %s" % ex
Copy to Clipboard Toggle word wrap
如果 add 方法调用成功,则脚本将输出:
Storage Domain 'iso1' added (789814a7-7b90-4a39-a1fd-f6a98cc915d8).
Copy to Clipboard Toggle word wrap
将存储域添加到 Red Hat Virtualization 后,您必须将其附加到数据中心,并在它们就绪可用前激活它们。

例 2.10. 使用 Python 将存储域附加到数据中心

这个 Python 示例将名为 data1 的数据存储域,以及名为 iso1ISO 存储域 附加到默认 数据中心。attach 操作由数据中心的 storagedomains 集合的 add 方法促进。
from ovirtsdk.api import API
from ovirtsdk.xml import params

try:
    api = API (url="https://HOST",
               username="USER@DOMAIN",
               password="PASS",
               ca_file="ca.crt")

    dc = api.datacenters.get(name="Default")

    sd_data = api.storagedomains.get(name="data1")
    sd_iso = api.storagedomains.get(name="iso1")

    try:
        dc_sd = dc.storagedomains.add(sd_data)
        print "Attached data storage domain '%s' to data center '%s' (Status: %s)." % 
		      (dc_sd.get_name(), dc.get_name, dc_sd.get_status().get_state())
    except Exception as ex:
        print "Attaching data storage domain to data center failed: %s." % ex

    try:
        dc_sd = dc.storagedomains.add(sd_iso)
        print "Attached ISO storage domain '%s' to data center '%s' (Status: %s)." % 
		      (dc_sd.get_name(), dc.get_name, dc_sd.get_status().get_state())
    except Exception as ex:
        print "Attaching ISO storage domain to data center failed: %s." % ex

    api.disconnect()
    
except Exception as ex:
    print "Unexpected error: %s" % ex
Copy to Clipboard Toggle word wrap
如果对 add 方法的调用成功,则脚本会输出:
Attached data storage domain 'data1' to data center 'Default' (Status: maintenance).
Attached ISO storage domain 'iso1' to data center 'Default' (Status: maintenance).
Copy to Clipboard Toggle word wrap
请注意,状态 反映了存储域仍然需要激活。

2.12. 示例:使用 Python 激活存储域

将存储域添加到 Red Hat Virtualization 并将其附加到数据中心后,您必须在它们就绪可用前激活它们。

例 2.11. 使用 Python 激活存储域

这个 Python 示例激活一个名为 data1 的数据存储域,以及名为 iso1ISO 存储域。两个存储域都附加到 Default 数据中心。激活操作由存储域的 激活 方法促进。
from ovirtsdk.api import API
from ovirtsdk.xml import params

try:
    api = API (url="https://HOST",
               username="USER@DOMAIN",
               password="PASS",
               ca_file="ca.crt")

    dc = api.datacenters.get(name="Default")

    sd_data = dc.storagedomains.get(name="data1")
    sd_iso = dc.storagedomains.get(name="iso1")

    try:
        sd_data.activate()
        print "Activated data storage domain '%s' in data center '%s' (Status: %s)." % 
		      (sd_data.get_name(), dc.get_name, sd_data.get_status().get_state())
    except Exception as ex:
        print "Activating data storage domain in data center failed: %s." % ex

    try:
        sd_iso.activate()
        print "Activated ISO storage domain '%s' in data center '%s' (Status: %s)." % 
		      (sd_iso.get_name(), dc.get_name, sd_iso.get_status().get_state())
    except Exception as ex:
        print "Activating ISO storage domain in data center failed: %s." % ex

    api.disconnect()

except Exception as ex:
    print "Unexpected error: %s" % ex
Copy to Clipboard Toggle word wrap
如果激活 请求成功,则脚本将输出:
Activated data storage domain 'data1' in data center 'Default' (Status: active).
Activated ISO storage domain 'iso1' in data center 'Default' (Status: active).
Copy to Clipboard Toggle word wrap
请注意,状态 反映了存储域已激活。

2.13. 示例:使用 Python 创建虚拟机

虚拟机创建以几个步骤执行。此处介绍的第一步是创建虚拟机对象本身。

例 2.12. 使用 Python 创建虚拟机

此 Python 示例创建一个名为 vm1 的虚拟机。本例中的虚拟机:
  • 必须有 512 MB 内存,以字节为单位表示。
    vm_memory = 512 * 1024 * 1024
    Copy to Clipboard Toggle word wrap
  • 必须附加到 Default 集群,因此 Default 数据中心。
    vm_cluster = api.clusters.get(name="Default")
    Copy to Clipboard Toggle word wrap
  • 必须基于默认的 空白模板
    vm_template = api.templates.get(name="Blank")
    Copy to Clipboard Toggle word wrap
  • 必须从虚拟硬盘引导。
    vm_os = params.OperatingSystem(boot=[params.Boot(dev="hd")])
    Copy to Clipboard Toggle word wrap
这些选项合并到虚拟机参数对象中,然后再使用 vms 集合的 add 方法创建虚拟机本身。
from ovirtsdk.api import API
from ovirtsdk.xml import params

try:
    api = API (url="https://HOST",
               username="USER@DOMAIN",
               password="PASS",
               ca_file="ca.crt")

    vm_name = "vm1"
    vm_memory = 512 * 1024 * 1024
    vm_cluster = api.clusters.get(name="Default")
    vm_template = api.templates.get(name="Blank")
    vm_os = params.OperatingSystem(boot=[params.Boot(dev="hd")])

    vm_params = params.VM(name=vm_name,
                         memory=vm_memory,
                         cluster=vm_cluster,
                         template=vm_template,
                         os=vm_os)

    try:
        api.vms.add(vm=vm_params)
        print "Virtual machine '%s' added." % vm_name
    except Exception as ex:
        print "Adding virtual machine '%s' failed: %s" % (vm_name, ex)

    api.disconnect()

except Exception as ex:
    print "Unexpected error: %s" % ex
Copy to Clipboard Toggle word wrap
如果 添加 请求成功,则脚本将输出:
Virtual machine 'vm1' added.
Copy to Clipboard Toggle word wrap

2.14. 示例:使用 Python 创建虚拟机 NIC

为确保新创建的虚拟机具有网络访问权限,您必须创建并附加虚拟 NIC。

例 2.13. 使用 Python 创建虚拟机 NIC

此 Python 示例创建一个名为 nic1 的 NIC,并将它附加到名为 vm1 的虚拟机。本例中的 NIC:
  • 必须是 virtio 网络设备。
    nic_interface = "virtio"
    Copy to Clipboard Toggle word wrap
  • 必须链接到 ovirtmgmt 管理网络。
    nic_network = api.networks.get(name="ovirtmgmt")
    Copy to Clipboard Toggle word wrap
在使用虚拟机的 nics 集合的 add 方法来创建 NIC 参数对象之前,这些选项会被合并到 NIC 中。
from ovirtsdk.api import API
from ovirtsdk.xml import params

try:
    api = API (url="https://HOST",
               username="USER@DOMAIN",
               password="PASS",
               ca_file="ca.crt")

    vm = api.vms.get(name="vm1")

    nic_name = "nic1"
    nic_interface = "virtio"
    nic_network = api.networks.get(name="ovirtmgmt")

    nic_params = params.NIC(name=nic_name, interface=nic_interface, network=nic_network)

    try:
        nic = vm.nics.add(nic_params)
        print "Network interface '%s' added to '%s'." % (nic.get_name(), vm.get_name())
    except Exception as ex:
        print "Adding network interface to '%s' failed: %s" % (vm.get_name(), ex)

    api.disconnect()
              
except Exception as ex:
    print "Unexpected error: %s" % ex
Copy to Clipboard Toggle word wrap
如果 添加 请求成功,则脚本将输出:
Network interface 'nic1' added to 'vm1'.
Copy to Clipboard Toggle word wrap

2.15. 示例:使用 Python 创建虚拟机存储磁盘

为确保新创建的虚拟机有权访问持久性存储,您必须创建并附加磁盘。

例 2.14. 使用 Python 创建虚拟机存储磁盘

这个 Python 示例创建了一个 8 GB virtio 磁盘驱动器,并将其附加到名为 vm1 的虚拟机。本例中的磁盘:
  • 必须存储在名为 data1 的存储域中,
    disk_storage_domain = params.StorageDomains(storage_domain=[api.storagedomains.get(name="data1")])
    Copy to Clipboard Toggle word wrap
  • 的大小必须为 8 GB,
    disk_size = 8*1024*1024
    Copy to Clipboard Toggle word wrap
  • 必须是 系统 类型磁盘(与 数据相反)
    disk_type = "system"
    Copy to Clipboard Toggle word wrap
  • 必须是 virtio 存储设备,
    disk_interface = "virtio"
    Copy to Clipboard Toggle word wrap
  • 必须以 cow 格式存储,
    disk_format = "cow"
    Copy to Clipboard Toggle word wrap
  • 必须标记为可用的引导设备。
    disk_bootable = True
    Copy to Clipboard Toggle word wrap
在使用 虚拟机磁盘集合的 add 方法来创建磁盘本身之前,这些选项将合并到磁盘 参数对象中。
from ovirtsdk.api import API
from ovirtsdk.xml import params

try:
    api = API (url="https://HOST",
               username="USER@DOMAIN",
               password="PASS",
               ca_file="ca.crt")

    vm = api.vms.get(name="vm1")

    sd = params.StorageDomains(storage_domain=[api.storagedomains.get(name="data1")])
    disk_size = 8*1024*1024
    disk_type = "system"
    disk_interface = "virtio"
    disk_format = "cow"
    disk_bootable = True

    disk_params = params.Disk(storage_domains=sd,
                              size=disk_size,
                              type_=disk_type,
                              interface=disk_interface,
                              format=disk_format,
                              bootable=disk_bootable)

    try:
        d = vm.disks.add(disk_params)
        print "Disk '%s' added to '%s'." % (d.get_name(), vm.get_name())
    except Exception as ex:
        print "Adding disk to '%s' failed: %s" % (vm.get_name(), ex)

    api.disconnect()

except Exception as ex:
    print "Unexpected error: %s" % ex
Copy to Clipboard Toggle word wrap
如果 添加 请求成功,则脚本将输出:
Disk 'vm1_Disk1' added to 'vm1'.
Copy to Clipboard Toggle word wrap
要在新创建的虚拟机上安装客户机操作系统,您必须附加包含操作系统安装介质的 ISO 文件。

例 2.15. 识别 ISO 镜像

ISO 镜像在附加到 ISO 存储域 的文件 集合中找到。这个示例列出了 ISO 存储域中 文件 集合的内容。
from ovirtsdk.api import API 
from ovirtsdk.xml import params

try:
    api = API(url="https://HOST",
              username="USER@DOMAIN",
              password="PASS",
              ca_file="ca.crt")

    sd = api.storagedomains.get(name="iso1")
    iso = sd.files.list()

    for i in iso:
        print "%s" % i.get_name()
		
except Exception as ex:
    print "Unexpected error: %s" % ex
Copy to Clipboard Toggle word wrap
如果成功,该脚本会 为文件 集合中找到的每个文件输出类似如下的条目:
RHEL6.3-Server-x86_64-DVD1.iso
Copy to Clipboard Toggle word wrap
请注意,由于 ISO 域中的文件必须唯一命名文件,所以必须共享文件的 idname 属性。

例 2.16. 使用 Python 将 ISO 镜像附加到虚拟机

此 Python 示例将 RHEL6.3-Server-x86_64-DVD1.iso ISO 镜像文件连接到 vm1 虚拟机。确定镜像文件后,使用虚拟机的 cdroms 集合的 add 方法附加镜像文件。
from ovirtsdk.api import API 
from ovirtsdk.xml import params

try:
    api = API(url="https://HOST",
              username="USER@DOMAIN",
              password="PASS,
              ca_file="ca.crt")

    sd = api.storagedomains.get(name="iso1")

    cd_iso = sd.files.get(name="RHEL6.3-Server-x86_64-DVD1.iso")
    cd_vm = api.vms.get(name="vm1")
    cd_params = params.CdRom(file=cd_iso)

    try:
        cd_vm.cdroms.add(cd_params)
        print "Attached CD to '%s'." % cd_vm.get_name()
    except Exception as ex:
        print "Failed to attach CD to '%s': %s" % (cd_vm.get_name(), ex)

    api.disconnect()

except Exception as ex:
    print "Unexpected error: %s" % ex
Copy to Clipboard Toggle word wrap
如果 添加 请求成功,则脚本将输出:
Attached CD to 'vm1'.
Copy to Clipboard Toggle word wrap
注意
这个过程是将 ISO 镜像附加到状态为 Down 的虚拟机。要将 ISO 附加到状态为 Up 的虚拟机,第二个 尝试 语句到以下内容:
try:
	cdrom=cd_vm.cdroms.get(id="00000000-0000-0000-0000-000000000000")
	cdrom.set_file(cd_iso)
	cdrom.update(current=True)
	print "Attached CD to '%s'." % cd_vm.get_name()
except:
	print "Failed to attach CD to '%s': %s" % (cd_vm.get_name(), ex)
Copy to Clipboard Toggle word wrap

例 2.17. 使用 Python 从虚拟机检索 cdrom

从虚拟机的 cdrom 集合中弹出 ISO。
from ovirtsdk.api import API 
from ovirtsdk.xml import params

try:
    api = API(url="https://HOST",
              username="USER@DOMAIN",
              password="PASS,
              ca_file="ca.crt")

    sd = api.storagedomains.get(name="iso1")
    vm = api.vms.get(name="vm1")

    try:
        vm.cdroms.get(id="00000000-0000-0000-0000-000000000000").delete()
        print "Removed CD from '%s'." % vm.get_name()
    except Exception as ex:
        print "Failed to remove CD from '%s': %s" % (vm.get_name(), ex)

    api.disconnect()

except Exception as ex:
    print "Unexpected error: %s" % ex
Copy to Clipboard Toggle word wrap

2.17. 示例:使用 Python 分离磁盘

您可以使用 Python 软件开发工具包从虚拟机中分离虚拟磁盘。

例 2.18. 使用 Python 分离磁盘

from ovirtsdk.api import API
from ovirtsdk.xml import params

try:
    api = API(url="https://HOST", 
              username="USER@DOMAIN", 
              password="PASS",
              ca_file="ca.crt")

    vm = api.vms.get(name="VM_NAME")
    disk = vm.disks.get(name="DISK_NAME")

    detach = params.Action(detach=True)
    disk.delete(action=detach)

    print "Detached disk %s successfully!" % disk

    api.disconnect()

except Exception as ex:
    print "Unexpected error: %s" % ex
Copy to Clipboard Toggle word wrap

2.18. 示例:使用 Python 启动虚拟机

启动虚拟机

例 2.19. 使用 Python 启动虚拟机

本例使用 start 方法启动虚拟机。
from ovirtsdk.api import API 
from ovirtsdk.xml import params

try:
    api = API (url="https://HOST",
               username="USER@DOMAIN",
               password="PASS",
               ca_file="ca.crt")

    vm = api.vms.get(name="vm1")

    try:
        vm.start()
        print "Started '%s'." % vm.get_name()
    except Exception as ex:
        print "Unable to start '%s': %s" % (vm.get_name(), ex)

    api.disconnect()

except Exception as ex:
    print "Unexpected error: %s" % ex
Copy to Clipboard Toggle word wrap
如果 启动 请求成功,则脚本将输出:
Started 'vm1'.
Copy to Clipboard Toggle word wrap
请注意,状态 反映了虚拟机已启动,现在为。
通过覆盖的参数启动虚拟机。

例 2.20. 使用 Python 通过覆盖的参数启动虚拟机

这个示例使用 Windows ISO 引导虚拟机,并附加 virtio-win_x86.vfd 软盘(包含 Windows 驱动程序)。此操作等同于在管理门户或用户访问中使用 Run Once 窗口启动虚拟机。
from ovirtsdk.api import API 
from ovirtsdk.xml import params

try:
    api = API (url="https://HOST",
               username="USER@DOMAIN",
               password="PASS",
               ca_file="ca.crt")
except Exception as ex:
    print "Failed to connect to API: %s" % ex


try:
    vm = api.vms.get(name="Win_machine")
except Exception as ex:
    print "Failed to retrieve VM: %s" % ex

cdrom = params.CdRom(file=params.File(id="windows_example.iso"))
floppy = params.Floppy(file=params.File(id="virtio-win_x86.vfd"))
try:
    vm.start(
      action=params.Action(
        vm=params.VM(
          os=params.OperatingSystem(
            boot=[params.Boot(dev="cdrom")]
          ),
          cdroms=params.CdRoms(cdrom=[cdrom]),
          floppies=params.Floppies(floppy=[floppy])
        )
      )
    )
except Exception as ex:
    print "Failed to start VM: %s" % ex
Copy to Clipboard Toggle word wrap
注意
CD 镜像和软盘文件必须已经在 ISO 域中可用。如果没有,使用 ISO uploader 工具上传文件。如需更多信息,请参阅 ISO 上传工具
使用 Python 启动使用 Cloud-Init 的虚拟机.

例 2.21. 使用 Python 启动使用 Cloud-Init 的虚拟机

本例演示了如何使用 Cloud-Init 工具启动虚拟机,来为 eth0 接口设置主机名和静态 IP。
from ovirtsdk.api import API
from ovirtsdk.xml import params

try:
    api = API (url="https://HOST",
               username="USER@DOMAIN",
               password="PASS",
               ca_file="ca.crt")
except Exception as ex:
    print "Failed to connect to API: %s" % ex


try:
    vm = api.vms.get(name="MyVM")
except Exception as ex:
    print "Failed to retrieve VM: %s" % ex

try:
    vm.start(
		use_cloud_init=True,
      action=params.Action(
        vm=params.VM(
          initialization=params.Initialization(
            cloud_init=params.CloudInit(
              host=params.Host(address="MyHost.example.com"),
          network_configuration=params.NetworkConfiguration(
            nics=params.Nics(
              nic=[params.NIC(
                name="eth0",
                boot_protocol="static",
                on_boot=True,
                network=params.Network(
                  ip=params.IP(
                    address="10.10.10.1",
                    netmask="255.255.255.0",
                    gateway="10.10.10.1"
                              )
                            )
                          )
                        ]
                       )
                     )
                    )
                  )
                 )
               )
              )
except Exception as ex:
    print "Failed to start VM: %s" % ex
Copy to Clipboard Toggle word wrap

2.21. 示例:使用 Python 检查系统事件

Red Hat Virtualization Manager 记录并记录很多系统事件。这些事件日志可以通过用户界面、系统日志文件和使用 API 访问。ovirtsdk 库使用事件集合公开 事件

例 2.22. 使用 Python 检查系统事件

本例中列出了 事件 集合。请注意:
  • list 方法的查询参数用于确保返回所有可用结果页面。默认情况下,list 方法仅返回结果的第一页,默认为最多 100 个记录长度。
  • 结果列表被撤销,以确保事件以它们发生的顺序包含在输出中。
from ovirtsdk.api import API
from ovirtsdk.xml import params

try:
    api = API (url="https://HOST",
               username="USER@DOMAIN",
               password="PASS",
               ca_file="ca.crt")

    event_list = []
    event_page_index = 1
    event_page_current = api.events.list(query="page %s" % event_page_index)

    while(len(event_page_current) != 0):
        event_list = event_list + event_page_current
        event_page_index = event_page_index + 1
		try:
            event_page_current = api.events.list(query="page %s" % event_page_index)
	    except Exception as ex:
		    print "Error retrieving page %s of list: %s" % (event_page_index, ex)

    event_list.reverse()

    for event in event_list:
        print "%s %s CODE %s - %s" % (event.get_time(),
                                      event.get_severity().upper(),
                                      event.get_code(),
                                      event.get_description())

except Exception as ex:
    print "Unexpected error: %s" % ex
Copy to Clipboard Toggle word wrap
这个脚本的输出将类似如下 - 根据环境状态的不同事件:
2012-09-25T18:40:10.065-04:00 NORMAL CODE 30 - User admin@internal logged in.
2012-09-25T18:40:10.368-04:00 NORMAL CODE 153 - VM vm1 was started by admin@internal (Host: Atlantic).
2012-09-25T18:40:10.470-04:00 NORMAL CODE 30 - User admin@internal logged in.
Copy to Clipboard Toggle word wrap

第 3 章 使用软件开发组件

3.1. 使用 Python 连接到 API

要使用 Python 连接到 REST API,您必须从 ovirtsdk.api 模块创建一个 API 类实例。要执行此操作,需要首先在脚本开始时导入类:
from ovirtsdk.api import API
Copy to Clipboard Toggle word wrap
API 类的结构采用多个参数。支持的参数有:
url
指定要连接的 Manager 的 URL,包括 /api 路径。这个参数是必需的。
用户名
以 User Principal Name (UPN)格式指定要连接的用户名。这个参数是必需的。
密码
指定 username 参数提供的用户名的密码。这个参数是必需的。
kerberos
使用有效的 Kerberos 票据来验证连接。有效值为 TrueFalse。这个参数是可选的。
key_file
指定包含与 cert_file 指定的证书关联的私钥的 PEM 格式密钥文件。这个参数是可选的。
cert_file
指定用于在服务器上建立客户端身份的 PEM 格式的客户端证书。这个参数是可选的。
ca_file
指定服务器的证书颁发机构的证书文件。这个参数是必需的,除非将 insecure 参数设置为 True
port
指定要使用的端口,其中尚未作为 url 参数的组件提供。这个参数是可选的。
timeout
指定在请求被视为超时前允许传递的时间(以秒为单位)。这个参数是可选的。
persistent_auth
指定是否为这个连接启用持久性身份验证。有效值为 TrueFalse。此参数是可选的,默认为 False
insecure
允许在没有证书颁发机构的情况下通过 SSL 连接。有效值为 TrueFalse。如果 insecure 参数设置为 False - 它是默认值 -,则必须提供 ca_file 来保护连接。
这个选项应该谨慎使用,因为它允许中间人(MITM)攻击者欺骗服务器的身份。
filter
指定基于用户权限的过滤器是 on 或 off。有效值为 TrueFalse。如果 filter 参数设置为 False - 这是默认值 -,提供的身份验证凭据必须是管理用户的。如果 filter 参数设置为 True,则可使用任何用户,管理器将根据其权限过滤用户可用的操作。
debug
指定是否为这个连接启用 debug 模式。有效值为 TrueFalse。这个参数是可选的。
您可以通过创建和操作 ovirtsdk.API Python 类的单独实例来与多个 Red Hat Virtualization Manager 通信。
本例脚本创建 API 类的实例,使用 test () 方法检查连接是否正常工作,并使用 disconnect () 方法断开连接。
from ovirtsdk.api import API    
    
api_instance = API ( url="https://rhevm31.demo.redhat.com", 
                     username="admin@internal", 
                     password="Password", 
                     ca_file="/etc/pki/ovirt-engine/ca.pem")

print "Connected successfully!"

api_instance.disconnect()
Copy to Clipboard Toggle word wrap
有关 API 类支持的方法的完整列表,请参阅 ovirtsdk.api 模块的 pydoc 输出。
$ pydoc ovirtsdk.api
Copy to Clipboard Toggle word wrap

3.2. 资源和集合

API 的 RESTful 性质对于理论上和实际原因,在整个 Python 绑定中都有明显。所有 RESTful API 都有两个主要概念,您需要了解:
集合
集合是一组相同类型的资源。API 提供顶层集合和子集合。顶级集合的示例是包含环境中所有虚拟化主机的 主机集合。子集合的示例是 host.nics 集合,其中包含附加到主机资源的所有网络接口卡的资源。
与集合交互的接口提供了添加资源(添加)、获取资源(获取)和列出资源(列表)的方法。
Resources
RESTful API 中的资源是具有固定接口的对象,还包含与所代表特定类型的资源类型相关的一组属性。用于与资源交互的接口提供了更新(更新 )和删除(删除 )资源的方法。另外,一些资源支持特定于资源类型的操作。示例是 Host 资源的 批准 方法。

3.3. 从集合检索资源

使用 getlist 方法从集合检索资源。
get
从集合检索单个资源。要检索的项目取决于作为参数提供的名称。get 方法采用这些参数:
  • name - 从集合检索的资源名称。
  • id - 从集合检索的资源的全局唯一标识符(GUID)。
list
从集合检索任意数量的资源。要检索的项目会根据提供的条件来决定。list 方法使用这些参数:
  • **kwargs - 允许基于关键字的过滤的额外参数的字典。
  • query - 使用与使用 Red Hat Virtualization 用户界面执行的相同格式的查询。
  • max - 要检索的最大资源数。
  • case_sensitive - 是否将搜索词视为区分大小写(TrueFalse,默认值为 True)。

3.4. 从集合检索特定资源

在这些示例中,使用 get 方法从集合中检索特定资源。

例 3.1. 根据名称检索特定资源

使用 get 方法的 name 参数从数据中心 集合中检索 Default 数据中心:
dc = api.datacenters.get("Default")
Copy to Clipboard Toggle word wrap
这个语法等同于:
dc = api.datacenters.get(name="Default")
Copy to Clipboard Toggle word wrap
可以使用 all_content 标头检索 获取 请求的其他信息。

例 3.2. 在特定资源上检索其他信息

vm = api.vms.get(name="VM01", all_content=True)
Copy to Clipboard Toggle word wrap

3.5. 从集合检索资源列表

在这些示例中,使用 list 方法从集合检索资源列表。

例 3.3. 检索集合中所有资源的列表

检索 数据中心 集合中所有资源的列表。list 方法的查询参数允许使用基于引擎的查询。这样,S SDK 支持以与管理和用户门户中执行的格式相同的格式使用查询。查询参数 也是在迭代集合期间提供分页参数的机制。
dc_list = []
dc_page_index = 1
dc_page_current = api.datacenters.list(query="page %s" % dc_page_index)
while(len(dc_page_current) != 0):
    dc_list = dc_list + dc_page_current
    dc_page_index = dc_page_index + 1
    dc_page_current = api.datacenters.list(query="page %s" % dc_page_index)
Copy to Clipboard Toggle word wrap
在本例中,datacenters 集合中包含的资源列表最终存储在本地定义的 dc_list 列表中。
警告
集合 的列表 方法仅限于返回由 SearchResultsLimit Red Hat Virtualization Manager 配置键允许的数量。
为确保返回列表中的所有记录,建议您按照本例所示分页结果。
或者,您可以选择将 list 方法的 max 参数设置为您要检索的最大记录数。

例 3.4. 在集合匹配基于关键字的过滤器中检索资源列表

检索 datacenter 集合中具有 nfs 类型的所有资源的列表。在本例中,提供了 查询参数**kwargs 参数。查询 用于分页的方式,其方式与上例中所示相同。**kwargs 参数用于根据数据中心的存储类型进行过滤。
dc_list = []
dc_page_index = 1
dc_page_current = api.datacenters.list(query="page %s" % dc_page_index, **{"storage_type": "nfs"})
while(len(dc_page_current) != 0):
    dc_list = dc_list + dc_page_current
    dc_page_index = dc_page_index + 1
    dc_page_current = api.datacenters.list(query="page %s" % dc_page_index, **{"storage_type": "nfs"})
Copy to Clipboard Toggle word wrap
在本例中,由 datacenters 集合中包含的资源列表,存储类型为 nfs,最终存储在本地定义的 dc_list 列表变量中。

3.6. 在集合中添加资源

集合的 add 方法会添加资源。要添加的资源会根据提供的参数创建。参数使用 ovirtsdk.xml.params 模块中的对象实例提供给 add 方法。需要使用模块的特定类因所创建的资源类型而异。

例 3.5. 在集合中添加资源

在本例中,创建虚拟机资源。
vm_params = params.VM(name="DemoVM",
                      cluster=api.clusters.get("Default"),
                      template=api.templates.get("Blank"),
                      memory=536870912)
vm = api.vms.add(vm_params)
Copy to Clipboard Toggle word wrap
虽然本例创建的虚拟机尚未准备好运行,但它演示了创建任何 Red Hat Virtualization 资源的过程:
  • 为正在创建的资源类型创建 parameter 对象的实例。
  • 确定将添加资源的集合。
  • 调用集合的 add 方法,将参数对象作为参数传递。
有些参数对象也具有自己的复杂参数。

例 3.6. 复杂的参数

在本例中,会创建一个以完整版本 4.0 兼容模式运行的 NFS 数据中心。要做到这一点,首先构建 ovirtsdk.xml.params.Version 对象。然后,在创建 ovirtsdk.xml.params.DataCenter 对象实例时用作参数,其中包含要创建的数据中心的参数。然后,使用 datacenters 集合的 add 方法来创建资源。
v_params = params.Version(major=4, minor=0)
dc_params = params.DataCenter(name="DemoDataCenter", storage_type="NFS", version=v_params)
dc = api.datacenters.add(dc_params)
Copy to Clipboard Toggle word wrap

3.7. 在集合中更新资源

要更新资源,您必须从它所在的集合中检索它,修改所需的参数,然后调用资源的 update 方法来保存更改。参数修改通过使用检索到的资源的 set_* 方法执行。

例 3.7. 更新资源

在本例中,名为 DemoDataCenter 的数据中心已更新其描述。
dc = api.datacenters.get("DemoDataCenter")
dc.set_description("This data center description provided using the Python SDK")
dc.update()
Copy to Clipboard Toggle word wrap

3.8. 从集合中删除资源

要删除资源,您必须从包含该资源的集合中检索它,并调用资源的 delete 方法。

例 3.8. 从集合中删除资源

vms 集合中删除名为 DemoVM 的虚拟机:
vm = api.vms.get("DemoVM")
vm.delete()
Copy to Clipboard Toggle word wrap

3.9. 处理错误

在遇到错误的情况下,软件开发套件使用例外来突出显示它们。除了 Python 解释器本身定义的例外类型外,软件开发套件还定义了异常类型。这些例外位于 ovirtsdk.infrastructure.errors 模块中:
ConnectionError
发生传输层错误时引发。
DisconnectedError
在明确断开连接后尝试使用 SDK 时引发。
ImmutableError
在启动 SDK 时引发,同时同一域下已存在 SDK 实例。适用于 SDK 版本 3.2 或更高版本。
NoCertificatesError
在不提供 CA 时引发,并且 --insecure 为 'False'。
RequestError
出现任何类型的 oVirt 服务器错误。
UnsecuredConnectionAttemptError
在服务器运行 HTTPS 时引发 HTTP 协议。
MissingParametersError
当您试图在不提供 id 或 name 的情况下使用 get ()方法时,会引发。
这些例外可能会捕获,并像任何其他 Python 异常一样处理:

例 3.9. 捕获 ConnectionError Exception

from ovirtsdk.api import API
from ovirtsdk.xml import params

try:
    api = API(url="https://HOST",
              user="USER,
              pass="PASS,
              ca_file="/etc/pki/ovirt-engine/ca.pem")
except ConnectionError, err:
    print "Connection failed: %s" % err
Copy to Clipboard Toggle word wrap

第 4 章 Python 参考文档

4.1. Python 参考文档

以下模块提供了使用 pydoc 生成的文档。文档由 ovirt-engine-sdk-python 软件包提供。
  • ovirtsdk.api
  • ovirtsdk.infrastructure.brokers
  • ovirtsdk.infrastructure.errors
在安装 Red Hat Virtualization Manager 的机器上运行以下命令查看以下文档的最新版本:
$ pydoc [MODULE]
Copy to Clipboard Toggle word wrap
返回顶部
Red Hat logoGithubredditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

通过我们的产品和服务,以及可以信赖的内容,帮助红帽用户创新并实现他们的目标。 了解我们当前的更新.

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

Theme

© 2026 Red Hat