此内容没有您所选择的语言版本。
Python SDK Guide
Using the Red Hat Virtualization Python SDK
Abstract
Chapter 1. Overview 复制链接链接已复制到粘贴板!
The Python software development kit is a collection of classes that allows you to interact with the Red Hat Virtualization Manager in Python-based projects. By downloading these classes and adding them to your project, you can access a range of functionality for high-level automation of administrative tasks.
Red Hat Virtualization provides two versions of the Python software development kit:
- Version 3
The V3 Python software development kit provides backwards compatibility with the class and method structure provided in the Python software development kit as of the latest release of Red Hat Enterprise Virtualization 3.6. Applications written using using the Python software development kit from Red Hat Enterprise Virtualization 3.6 can be used with this version without modification.
WarningVersion 3 is no longer supported. The information and examples specific to version 3 are provided as a reference only. Migrate to version 4 for continued support.
- Version 4
- The V4 Python software development kit provides an updated set of class and method names and signatures. Applications written using the Python software development kit from Red Hat Enterprise Virtualization 3.6 must be updated before they can be used with this version.
Either version of the Python software development kit can be used in a Red Hat Virtualization environment as required by installing the corresponding package and adding the required libraries to your Python project.
Python 3.7 and async
In Python 3.7 and later versions, async is a reserved keyword. You cannot use the async parameter in methods of services that previously supported it, as in the following example, because async=True will cause an error:
The solution is to add an underscore to the parameter (async_):
This limitation applies only to Python 3.7 and later. Earlier versions of Python do not require this modification.
1.1. Prerequisites 复制链接链接已复制到粘贴板!
To install the Python software development kit, you must have:
- A system where Red Hat Enterprise Linux 7 is installed. Both the Server and Workstation variants are supported.
- A subscription to Red Hat Virtualization entitlements.
The software development kit is an interface for the Red Hat Virtualization REST API. As such, you must use the version of the software development kit that corresponds to the version of your environment. For example, if you are using RHV 4.2, you must use the version of the software development kit designed for 4.2.
1.2. Installing the Python Software Development Kit 复制链接链接已复制到粘贴板!
To install the Python software development kit:
Enable the repositories:
subscription-manager repos \ --enable=rhel-7-server-rpms \ --enable=rhel-7-server-rhv-4.3-manager-rpms# subscription-manager repos \ --enable=rhel-7-server-rpms \ --enable=rhel-7-server-rhv-4.3-manager-rpmsCopy to Clipboard Copied! Toggle word wrap Toggle overflow Install the required packages:
For V3:
yum install ovirt-engine-sdk-python
# yum install ovirt-engine-sdk-pythonCopy to Clipboard Copied! Toggle word wrap Toggle overflow For V4:
yum install python-ovirt-engine-sdk4
# yum install python-ovirt-engine-sdk4Copy to Clipboard Copied! Toggle word wrap Toggle overflow
The Python software development kit and accompanying documentation are downloaded to the /usr/lib/python2.7/site-packages/ovirtsdk/ directory and can be added to Python projects.
Chapter 2. Using the Software Development Kit 复制链接链接已复制到粘贴板!
This section describes how to use the software development kit for Version 4.
2.1. Packages 复制链接链接已复制到粘贴板!
The following modules are most frequently used by the Python SDK:
- ovirtsdk4
This is the top level module. It most important element is the
Connectionclass, which is the mechanism to connect to the server and to obtain the reference to the root of the services tree.The
Errorclass is the base exception class that the SDK will raise when it needs to report an error.For certain kinds of errors, there are specific error classes, which extend the base error class:
-
AuthError- Raised when authentication or authorization fails. -
ConnectionError- Raised when the name of the server cannot be resolved or the server is unreachable. -
NotFoundError- Raised when the requested object does not exist. -
TimeoutError- Raised when an operation times out.
-
- ovirtsdk4.types
This module contains the classes that implement the types used in the API. For example, the
ovirtsdk4.types.Vmclass is the implementation of the virtual machine type. These classes are data containers and do not contain any logic.Instances of these classes are used as parameters and return values of service methods. The conversion to or from the underlying representation is handled transparently by the SDK.
- ovirtsdk4.services
This module contains the classes that implement the services supported by the API. For example, the
ovirtsdk4.services.VmsServiceclass is the implementation of the service that manages the collection of virtual machines of the system.Instances of these classes are automatically created by the SDK when a service is located. For example, a new instance of the
VmsServiceclass is automatically created by the SDK when doing the following:vms_service = connection.system_service().vms_service()
vms_service = connection.system_service().vms_service()Copy to Clipboard Copied! Toggle word wrap Toggle overflow It is best to avoid creating instances of these classes manually, as the parameters of the constructors and, in general, all the methods except the service locators and service methods, may change in the future.
There are other modules, like
ovirtsdk4.http,ovirtsdk4.readers, andovirtsdk4.writers. These are used to implement the HTTP communication and for XML parsing and rendering. Avoid using them, because they are internal implementation details that may change in the future; backwards compatibility is not guaranteed.
2.2. Connecting to the Server 复制链接链接已复制到粘贴板!
To connect to the server, import the ovirtsdk4 module, which contains the Connection class. This is the entry point of the SDK, and provides access to the root of the tree of services of the API:
The connection holds critical resources, including a pool of HTTP connections to the server and an authentication token. It is very important to free these resources when they are no longer in use:
connection.close()
connection.close()
Once a connection is closed, it cannot be reused.
The ca.pem file is required when connecting to a server protected with TLS. In a normal installation, it is located in /etc/pki/ovirt-engine/ on the Manager machine. If you do not specify the ca_file, the system-wide CA certificate store will be used. For more information on obtaining the ca.pem file, see the REST API Guide.
If the connection is not successful, the SDK will raise an ovirtsdk4.Error exception containing the details.
2.3. Using Types 复制链接链接已复制到粘贴板!
The classes in the ovirtsdk4.types module are pure data containers. They do not have any logic or operations. Instances of types can be created and modified at will.
Creating or modifying an instance does not affect the server side, unless the change is explicitly passed with a call to one of the service methods described below. Changes on the server side are not automatically reflected in the instances that already exist in memory.
The constructors of these classes have multiple optional arguments, one for each attribute of the type. This is intended to simplify creation of objects using nested calls to multiple constructors. This example creates an instance of a virtual machine, specifying its cluster name, template, and memory, in bytes:
Using the constructors in this way is recommended, but not mandatory. You can also create the instance with no arguments in the call to the constructor and populate the object step by step, using the setters, or by using a mix of both approaches:
vm = types.Vm() vm.name = 'vm1' vm.cluster = types.Cluster(name='Default') vm.template = types.Template(name='mytemplate') vm.memory=1073741824
vm = types.Vm()
vm.name = 'vm1'
vm.cluster = types.Cluster(name='Default')
vm.template = types.Template(name='mytemplate')
vm.memory=1073741824
Attributes that are defined as lists of objects in the specification of the API are implemented as Python lists. For example, the custom_properties attributes of the Vm type are defined as a list of objects of type CustomProperty. When the attributes are used in the SDK, they are a Python list:
Attributes that are defined as enumerated values in API are implemented as enum in Python, using the native support for enums in Python 3 and the enum34 package in Python 2.7. In this example, the status attribute of the Vm type is defined using the VmStatus enum:
if vm.status == types.VmStatus.DOWN:
...
elif vm.status == types.VmStatus.IMAGE_LOCKED:
....
if vm.status == types.VmStatus.DOWN:
...
elif vm.status == types.VmStatus.IMAGE_LOCKED:
....
In the API specification, the values of enum types appear in lower case, because that is what is used for XML and JSON. The Python convention, however, is to capitalize enum values.
Reading the attributes of instances of types is done using the corresponding properties:
print("vm.name: %s" % vm.name)
print("vm.memory: %s" % vm.memory)
for custom_property in vm.custom_properties:
...
print("vm.name: %s" % vm.name)
print("vm.memory: %s" % vm.memory)
for custom_property in vm.custom_properties:
...
2.4. Using Links 复制链接链接已复制到粘贴板!
Some attributes of types are defined by the API as links. This convention indicates that the values are not normally populated when retrieving the representation of that object. Rather, a link is returned instead. For example, when retrieving a virtual machine, the XML response from the server includes the <link> attribute:
<vm id="123" href="/ovirt-engine/api/vms/123">
<name>vm1</name>
<link rel="diskattachments" href="/ovirt-engine/api/vms/123/diskattachments/>
...
</vm>
<vm id="123" href="/ovirt-engine/api/vms/123">
<name>vm1</name>
<link rel="diskattachments" href="/ovirt-engine/api/vms/123/diskattachments/>
...
</vm>
The link to vm.diskattachments does not contain the actual disk attachments. To obtain the data, the Connection class provides a follow_link method that uses the value of the href XML attribute to retrieve the actual data. For example, to retrieve the details of the disks of the virtual machine, you follow the link to the disk attachments, and then to each of the disks:
2.5. Locating Services 复制链接链接已复制到粘贴板!
The API provides a set of services, each associated with a path within the URL space of the server. For example, the service that manages the collection of virtual machines of the system is located in /vms, and the service that manages the virtual machine with identifier 123 is located in /vms/123.
In the SDK, the root of that tree of services is implemented by the system service. It is obtained calling the system_service method of the connection:
system_service = connection.system_service()
system_service = connection.system_service()
When you have the reference to this system service, you can use it to obtain references to other services, calling the *_service methods, called service locators, of the previous service. For example, to obtain a reference to the service that manages the collection of virtual machines of the system, you use the vms_service service locator:
vms_service = system_service.vms_service()
vms_service = system_service.vms_service()
To obtain a reference to the service that manages the virtual machine with identifier 123, you use the vm_service service locator of the service that manages the collection of virtual machines. It uses the identifier of the virtual machine as a parameter:
vm_service = vms_service.vm_service('123')
vm_service = vms_service.vm_service('123')
Calling service locators does not send a request to the server. The Python objects that they return are pure services, which do not contain any data. For example, the vm_service Python object called in this example is not the representation of a virtual machine. It is the service that is used to retrieve, update, delete, start and stop that virtual machine.
2.6. Using Services 复制链接链接已复制到粘贴板!
After you have located a service, you can call its service methods, which send requests to the server and do the real work.
Services that manage a single object usually support the get, update, and remove methods.
Services that manage collections of objects usually support the list and add methods.
Both kinds of services, especially services that manage a single object, can support additional action methods.
2.6.1. Using get Methods 复制链接链接已复制到粘贴板!
These service methods are used to retrieve the representation of a single object. The following example retrieves the representation of the virtual machine with identifier 123:
The response is an instance of the corresponding type, in this case an instance of the Python class ovirtsdk4.types.Vm.
The get methods of some services support additional parameters that control how to retrieve the representation of the object or what representation to retrieve if there is more than one. For example, you may want to retrieve either the current state of a virtual machine or its state the next time it is started, as they may be different. The get method of the service that manages a virtual machine supports a next_run Boolean parameter:
Retrieve the representation of the virtual machine, not the current one, but the one that will be used after the next boot:
# Retrieve the representation of the virtual machine, not the
# current one, but the one that will be used after the next
# boot:
vm = vm_service.get(next_run=True)
See the reference documentation of the SDK for details.
If the object cannot be retrieved for any reason, the SDK raises an ovirtsdk4.Error exception, with details of the failure. This includes the situation when the object does not actually exist. Note that the exception is raised when calling the get service method. The call to the service locator method never fails, even if the object does not exist, because that call does not send a request to the server. For example:
2.6.2. Using list Methods 复制链接链接已复制到粘贴板!
These service methods retrieve the representations of the objects of a collection. This example retrieves the complete collection of virtual machines of the system:
The result will be a Python list containing the instances of corresponding types. For example, in this case, the result will be a list of instances of the class ovirtsdk4.types.Vm.
The list methods of some services support additional parameters. For example, almost all top-level collections support a search parameter to filter the results or a max parameter to limit the number of results returned by the server. This example retrieves the names of virtual machines starting with my, with an upper limit of 10 results:
vms = vms_service.list(search='name=my*', max=10)
vms = vms_service.list(search='name=my*', max=10)
Not all list methods support these parameters. Some list methods support other parameters. See the reference documentation of the SDK for details.
If a list of returned results is empty for any reason, the returned value will be an empty list. It will never be None.
If there is an error while trying to retrieve the result, the SDK will raise an ovirtsdk4.Error exception containing the details of the failure.
2.6.3. Using add Methods 复制链接链接已复制到粘贴板!
These service methods add new elements to a collection. They receive an instance of the relevant type describing the object to add, send the request to add it, and return an instance of the type describing the added object.
This example adds a new virtual machine called vm1:
If the object cannot be created for any reason, the SDK will raise an ovirtsdk4.Error exception containing the details of the failure. It will never return None.
The Python object returned by this add method is an instance of the relevant type. It is not a service but a container of data. In this particular example, the returned object is an instance of the ovirtsdk4.types.Vm class. If, after creating the virtual machine, you need to perform an operation such as retrieving or starting it, you will first need to find the service that manages it, and call the corresponding service locator:
Objects are created asynchronously. When you create a new virtual machine, the add method will return a response before the virtual machine is completely created and ready to be used. It is good practice to poll the status of the object to ensure that it is completely created. For a virtual machine, you should check until its status is DOWN:
Using a loop to retrieve the object status, with the get method, ensures that the status attribute is updated.
2.6.4. Using update Methods 复制链接链接已复制到粘贴板!
These service methods update existing objects. They receive an instance of the relevant type describing the update to perform, send the request to update it, and return an instance of the type describing the updated object.
This example updates the name of a virtual machine from vm1 to newvm:
When performing updates, avoid sending the complete representation of the object. Send only the attributes that you want to update. Do not do this:
Sending the complete representation causes two problems:
- You are sending much more information than the server needs, thus wasting resources.
- The server will try to update all the attributes of the object, even those that you did not intend to change. This may cause bugs on the server side.
The update methods of some services support additional parameters that control how or what to update. For example, you may want to update either the current state of a virtual machine or the state that will be used the next time the virtual machine is started. The update method of the service that manages a virtual machine supports a next_run Boolean parameter:
If the update cannot be performed for any reason, the SDK will raise an ovirtsdk4.Error exception containing the details of the failure. It will never return None.
The Python object returned by this update method is an instance of the relevant type. It is not a service, but a container for data. In this particular example, the returned object will be an instance of the ovirtsdk4.types.Vm class.
2.6.5. Using remove Methods 复制链接链接已复制到粘贴板!
These service methods remove existing objects. They usually do not take parameters, because they are methods of services that manage single objects. Therefore, the service already knows what object to remove.
This example removes the virtual machine with identifier 123:
The remove methods of some services support additional parameters that control how or what to remove. For example, it is possible to remove a virtual machine while preserving its disks, using the detach_only Boolean parameter:
Remove the virtual machine while preserving the disks:
# Remove the virtual machine while preserving the disks:
vm_service.remove(detach_only=True)
The remove method returns None if the object is removed successfully. It does not return the removed object. If the object cannot be removed for any reason, the SDK raises an ovirtsdk4.Error exception containing the details of the failure.
2.6.6. Using Other Action Methods 复制链接链接已复制到粘贴板!
There are other service methods that perform miscellaneous operations, such as stopping and starting a virtual machine:
Start the virtual machine:
# Start the virtual machine:
vm_service.start()
Many of these methods include parameters that modify the operation. For example, the method that starts a virtual machine supports a use_cloud_init parameter, if you want to start it using cloud-init:
Start the virtual machine:
# Start the virtual machine:
vm_service.start(cloud_init=True)
Most action methods return None when they succeed and raise an ovirtsdk4.Error when they fail. A few action methods return values. For example, the service that manages a storage domain has an is_attached action method that checks whether the storage domain is already attached to a data center and returns a Boolean value:
Check if the storage domain is attached to a data center:
# Check if the storage domain is attached to a data center:
sds_service = system_service.storage_domains_service()
sd_service = sds_service.storage_domain_service('123')
if sd_service.is_attached():
...
Check the reference documentation of the SDK to see the action methods supported by each service, the parameters that they take, and the values that they return.
2.7. Additional Resources 复制链接链接已复制到粘贴板!
For detailed information and examples, see the following resources:
Generating Modules
You can generate documentation using pydoc for the following modules:
- ovirtsdk.api
- ovirtsdk.infrastructure.brokers
- ovirtsdk.infrastructure.errors
The documentation is provided by the ovirt-engine-sdk-python package. Run the following command on the Manager machine to view the latest version of these documents:
pydoc [MODULE]
$ pydoc [MODULE]
Chapter 3. Python Examples 复制链接链接已复制到粘贴板!
3.1. Overview 复制链接链接已复制到粘贴板!
This section provides examples demonstrating the steps to create a virtual machine within a basic Red Hat Virtualization environment, using the Python SDK.
These examples use the ovirtsdk Python library provided by the ovirt-engine-sdk-python package. This package is available to systems attached to a Red Hat Virtualization subscription pool in Red Hat Subscription Manager. See Section 1.2, “Installing the Python Software Development Kit” for more information on subscribing your system(s) to download the software.
You will also need:
- A networked installation of Red Hat Virtualization Manager.
- A networked and configured Red Hat Virtualization Host.
- An ISO image file containing an operating system for installation on a virtual machine.
- A working understanding of both the logical and physical objects that make up a Red Hat Virtualization environment.
- A working understanding of the Python programming language.
The examples include placeholders for authentication details (admin@internal for user name, and password for password). Replace the placeholders with the authentication requirements of your environment.
Red Hat Virtualization Manager generates a globally unique identifier (GUID) for the id attribute for each resource. Identifier codes in these examples differ from the identifier codes in your Red Hat Virtualization environment.
The examples contain only basic exception and error handling logic. For more information on the exception handling specific to the SDK, see the pydoc for the ovirtsdk.infrastructure.errors module:
pydoc ovirtsdk.infrastructure.errors
$ pydoc ovirtsdk.infrastructure.errors
3.2. Connecting to the Red Hat Virtualization Manager 复制链接链接已复制到粘贴板!
To connect to the Red Hat Virtualization Manager, you must create an instance of the API class from the ovirtsdk.api module by importing the class at the start of the script:
from ovirtsdk.api import API
from ovirtsdk.api import API
The constructor of the API class takes a number of arguments. Supported arguments are:
url-
Specifies the URL of the Manager to connect to, including the
/apipath. This parameter is mandatory. username- Specifies the user name to connect. This parameter is mandatory.
password-
Specifies the password for the user name provided by the
usernameparameter. This parameter is mandatory. kerberos-
Uses a valid Kerberos ticket to authenticate the connection. Valid values are
TrueandFalse. This parameter is optional. key_file-
Specifies a PEM formatted key file containing the private key associated with the certificate specified by
cert_file. This parameter is optional. cert_file- Specifies a PEM formatted client certificate to be used for establishing the identity of the client on the server. This parameter is optional.
ca_file-
Specifies the certificate file of the certificate authority for the server. This parameter is mandatory unless the
insecureparameter is set toTrue. The certificate is expected to be a copy of the one for the Manager’s Certificate Authority. For more information on obtaining the certificate, see the REST API Guide. port-
Specifies the port to connect using, where it has not been provided as component of the
urlparameter. This parameter is optional. timeout- Specifies the amount of time in seconds that is allowed to pass before a request is to be considered as having timed out. This parameter is optional.
persistent_auth-
Specifies whether persistent authentication is enabled for this connection. Valid values are
TrueandFalse. This parameter is optional and defaults toFalse. insecureAllows a connection via SSL without certificate authority. Valid values are
TrueandFalse. If theinsecureparameter is set toFalse, which is the default, theca_filemust be supplied to secure the connection.This option should be used with caution, as it may allow man-in-the-middle attackers to spoof the identity of the server.
filter-
Specifies whether or not user permission based filter is on or off. Valid values are
TrueandFalse. If thefilterparameter is set toFalse- which is the default - then the authentication credentials provided must be those of an administrative user. If thefilterparameter is set toTruethen any user can be used and the Manager will filter the actions available to the user based on their permissions. debugSpecifies whether debug mode is enabled for this connection. Valid values are
TrueandFalse. This parameter is optional.NoteUser names and passwords are written to the debug log, so handle it with care.
You can communicate with multiple Red Hat Virtualization Managers by creating and manipulating separate instances of the ovirtsdk.API Python class.
This example script creates an instance of the API class, checks that the connection is working using the test() method, and disconnects using the disconnect() method.
For a full list of supported methods, you can generate the documentation for the ovirtsdk.api module on the Manager machine:
pydoc ovirtsdk.api
$ pydoc ovirtsdk.api
To connect to the Red Hat Virtualization Manager, you must create an instance of the Connection class from the ovirtsdk4.sdk module by importing the class at the start of the script:
import ovirtsdk4 as sdk
import ovirtsdk4 as sdk
The constructor of the Connection class takes a number of arguments. Supported arguments are:
url-
A string containing the base URL of the Manager, such as
https://server.example.com/ovirt-engine/api. username-
Specifies the user name to connect, such as
admin@internal. This parameter is mandatory. password-
Specifies the password for the user name provided by the
usernameparameter. This parameter is mandatory. token-
An optional token to access the API, instead of a user name and password. If the
tokenparameter is not specified, the SDK will create one automatically. insecure- A Boolean flag that indicates whether the server’s TLS certificate and host name should be checked.
ca_file-
A PEM file containing the trusted CA certificates. The certificate presented by the server will be verified using these CA certificates. If
ca_fileparameter is not set, the system-wide CA certificate store is used. debugA Boolean flag indicating whether debug output should be generated. If the value is
Trueand thelogparameter is notNone, the data sent to and received from the server will be written to the log.NoteUser names and passwords are written to the debug log, so handle it with care.
Compression is disabled in debug mode, which means that debug messages are sent as plain text.
log- The logger where the log messages will be written.
kerberos- A Boolean flag indicating whether Kerberos authentication should be used instead of the default basic authentication.
timeout-
The maximum total time to wait for the response, in seconds. A value of
0(default) means to wait forever. If the timeout expires before the response is received, an exception is raised. compress-
A Boolean flag indicating whether the SDK should ask the server to send compressed responses. The default is
True. This is a hint for the server, which may return uncompressed data even when this parameter is set toTrue. Compression is disabled in debug mode, which means that debug messages are sent as plain text. sso_url-
A string containing the base SSO URL of the server. The default SSO URL is computed from the
urlif nosso_urlis provided. sso_revoke_url-
A string containing the base URL of the SSO revoke service. This needs to be specified only when using an external authentication service. By default, this URL is automatically calculated from the value of the
urlparameter, so that SSO token revoke will be performed using the SSO service, which is part of the Manager. sso_token_name-
The token name in the JSON SSO response returned from the SSO server. Default value is
access_token. headers- A dictionary with headers, which should be sent with every request.
connections-
The maximum number of connections to open to the host. If the value is
0(default), the number of connections is unlimited. pipeline-
The maximum number of requests to put in an HTTP pipeline without waiting for the response. If the value is
0(default), pipelining is disabled.
For a full list of supported methods, you can generate the documentation for the ovirtsdk.api module on the Manager machine:
pydoc ovirtsdk.api
$ pydoc ovirtsdk.api
3.3. Listing Data Centers 复制链接链接已复制到粘贴板!
The datacenters collection contains all the data centers in the environment.
Example 3.1. Listing data centers
These examples list the data centers in the datacenters collection and output some basic information about each data center in the collection.
V3
V4
In an environment where only the Default data center exists, and it is not activated, the examples output the text:
Default (00000000-0000-0000-0000-000000000000)
Default (00000000-0000-0000-0000-000000000000)
3.4. Listing Clusters 复制链接链接已复制到粘贴板!
The clusters collection contains all clusters in the environment.
Example 3.2. Listing clusters
These examples list the clusters in the clusters collection and output some basic information about each cluster in the collection.
V3
V4
In an environment where only the Default cluster exists, the examples output the text:
Default (00000000-0000-0000-0000-000000000000)
Default (00000000-0000-0000-0000-000000000000)
3.5. Listing Hosts 复制链接链接已复制到粘贴板!
The hosts collection contains all hosts in the environment.
Example 3.3. Listing hosts
These examples list the hosts in the hosts collection and their IDs.
V3
V4
In an environment where only one host, MyHost, has been attached, the examples output the text:
MyHost (00000000-0000-0000-0000-000000000000)
MyHost (00000000-0000-0000-0000-000000000000)
3.6. Listing Logical Networks 复制链接链接已复制到粘贴板!
The networks collection contains all logical networks in the environment.
Example 3.4. Listing logical networks
These examples list the logical networks in the networks collection and outputs some basic information about each network in the collection.
V3
V4
In an environment where only the default management network exists, the examples output the text:
ovirtmgmt (00000000-0000-0000-0000-000000000000)
ovirtmgmt (00000000-0000-0000-0000-000000000000)
3.7. Listing Virtual Machines and Total Disk Size 复制链接链接已复制到粘贴板!
The vms collection contains a disks collection that describes the details of each disk attached to a virtual machine.
Example 3.5. Listing virtual machines and total disk size
These examples print a list of virtual machines and their total disk size in bytes:
V3
V4
The examples output the virtual machine names and their disk sizes:
Name Disk Size ================================================== vm1 50000000000
Name Disk Size
==================================================
vm1 50000000000
3.8. Creating NFS Data Storage 复制链接链接已复制到粘贴板!
When a Red Hat Virtualization environment is first created, it is necessary to define at least a data storage domain and an ISO storage domain. The data storage domain stores virtual disks while the ISO storage domain stores the installation media for guest operating systems.
The storagedomains collection contains all the storage domains in the environment and can be used to add and remove storage domains.
The code provided in this example assumes that the remote NFS share has been pre-configured for use with Red Hat Virtualization. See the Administration Guide for more information on preparing NFS shares.
Example 3.6. Creating NFS data storage
These examples add an NFS data domain to the storagedomains collection. For V3, adding an NFS storage domain can be broken down into several steps:
Identify the data center to which the storage must be attached, using the
getmethod of thedatacenterscollection.dc = api.datacenters.get(name="Default")
dc = api.datacenters.get(name="Default")Copy to Clipboard Copied! Toggle word wrap Toggle overflow Identify the host that must be used to attach the storage, using the
getmethod of thehostscollection.h = api.hosts.get(name="myhost")
h = api.hosts.get(name="myhost")Copy to Clipboard Copied! Toggle word wrap Toggle overflow Define the
Storageparameters for the NFS storage domain. In this example the NFS location192.0.43.10/storage/datais being used.s = params.Storage(address="_IP_address_", path="/storage/data", type_="nfs")
s = params.Storage(address="_IP_address_", path="/storage/data", type_="nfs")Copy to Clipboard Copied! Toggle word wrap Toggle overflow Request creation of the storage domain, using the
addmethod of thestoragedomainscollection. In addition to theStorageparameters it is necessary to pass:- A name for the storage domain.
-
The data center object that was retrieved from the
datacenterscollection. -
The host object that was retrieved from the
hostscollection. -
The type of storage domain being added (
data,iso, orexport). -
The storage format to use (
v1,v2, orv3).
Once these steps are combined, the completed script is:
V3
V4
For V4, the add method is used to add the new storage domain and the types class is used to pass the parameters.
If the add method call is successful, the examples output the text:
Storage Domain 'mydata' added (00000000-0000-0000-0000-000000000000).
Storage Domain 'mydata' added (00000000-0000-0000-0000-000000000000).
3.9. Creating NFS ISO Storage 复制链接链接已复制到粘贴板!
To create a virtual machine, you need installation media for the guest operating system. The installation media are stored in an ISO storage domain.
The code provided in this example assumes that the remote NFS share has been pre-configured for use with Red Hat Virtualization. See the Administration Guide for more information on preparing NFS shares.
Example 3.7. Creating NFS ISO storage
These examples add an NFS ISO domain to the storagedomains collection. For V3, adding an NFS storage domain can be broken down into several steps:
Identify the data center to which the storage must be attached, using the
getmethod of thedatacenterscollection.dc = api.datacenters.get( name="Default" )
dc = api.datacenters.get( name="Default" )Copy to Clipboard Copied! Toggle word wrap Toggle overflow Identify the host that must be used to attach the storage, using the
getmethod of thehostscollection.h = api.hosts.get(name="myhost")
h = api.hosts.get(name="myhost")Copy to Clipboard Copied! Toggle word wrap Toggle overflow Define the
Storageparameters for the NFS storage domain. In this example the NFS locationFQDN/storage/isois being used.s = params.Storage(address="_IP_address_", path="/storage/iso", type_="nfs")
s = params.Storage(address="_IP_address_", path="/storage/iso", type_="nfs")Copy to Clipboard Copied! Toggle word wrap Toggle overflow Request creation of the storage domain, using the
addmethod of thestoragedomainscollection. In addition to theStorageparameters it is necessary to pass:- A name for the storage domain.
-
The data center object that was retrieved from the
datacenterscollection. -
The host object that was retrieved from the
hostscollection. -
The type of storage domain being added (
data,iso, orexport). -
The storage format to use (
v1,v2, orv3).
V3
V4
For V4, the add method is used to add the new storage domain and the types class is used to pass the parameters.
If the add method call is successful, the examples output the text:
Storage Domain 'myiso' added (00000000-0000-0000-0000-000000000000).
Storage Domain 'myiso' added (00000000-0000-0000-0000-000000000000).
3.10. Attaching a Storage Domain to a Data Center 复制链接链接已复制到粘贴板!
Once you have added a storage domain to Red Hat Virtualization, you must attach it to a data center and activate it before it will be ready for use.
Example 3.8. Attaching a storage domain to a data center
These examples attach an existing NFS storage domain, mydata, to the an existing data center, Default. The attach action is facilitated by the add method of the data center’s storagedomains collection. These examples may be used to attach both data and ISO storage domains.
V3
V4
If the calls to the add methods are successful, the examples output the following text:
Attached data storage domain 'data1' to data center 'Default' (Status: maintenance).
Attached data storage domain 'data1' to data center 'Default' (Status: maintenance).
Status: maintenance indicates that the storage domains still need to be activated.
3.11. Activating a Storage Domain 复制链接链接已复制到粘贴板!
Once you have added a storage domain to Red Hat Virtualization and attached it to a data center, you must activate it before it will be ready for use.
Example 3.9. Activating a storage domain
These examples activate an NFS storage domain, mydata, attached to the data center, Default. The activate action is facilitated by the activate method of the storage domain.
V3
V4
If the activate requests are successful, the examples output the text:
Activated storage domain 'mydata' in data center 'Default' (Status: active).
Activated storage domain 'mydata' in data center 'Default' (Status: active).
Status: active indicates that the storage domains have been activated.
3.12. Listing Files in an ISO Storage Domain 复制链接链接已复制到粘贴板!
The storagedomains collection contains a files collection that describes the files in a storage domain.
Example 3.10. Listing Files in an ISO Storage Domain
These examples print a list of the ISO files in each ISO storage domain:
V3
V4
The examples output the text:
ISO_storage_domain: file1 file2
ISO_storage_domain:
file1
file2
3.13. Creating a Virtual Machine 复制链接链接已复制到粘贴板!
Virtual machine creation is performed in several steps. The first step, covered here, is to create the virtual machine object itself.
Example 3.11. Creating a virtual machine
These examples create a virtual machine, vm1, with the following requirements:
- 512 MB of memory, expressed in bytes.
-
Attached to the
Defaultcluster, and therefore theDefaultdata center. -
Based on the default
Blanktemplate. - Boots from the virtual hard disk drive.
V3
In V3, the virtual machine options are combined into a virtual machine parameter object, before using the add method of the vms collection to create the virtual machine itself.
V4
In V4, the options are added as types, using the add method.
If the add request is successful, the examples output the text:
Virtual machine 'vm1' added.
Virtual machine 'vm1' added.
3.14. Creating a Virtual NIC 复制链接链接已复制到粘贴板!
To ensure that a newly created virtual machine has network access, you must create and attach a virtual NIC.
Example 3.12. Creating a virtual NIC
These examples create a NIC, nic1, and attach it to a virtual machine, vm1. The NIC in this example is a virtio network device and attached to the ovirtmgmt management network.
V3
In V3, these options are combined into an NIC parameter object, before using the add method of the virtual machine’s nics collection to create the NIC.
V4
If the add request is successful, the examples output the text:
Network interface 'nic1' added to 'vm1'.
Network interface 'nic1' added to 'vm1'.
3.15. Creating a Virtual Machine Disk 复制链接链接已复制到粘贴板!
To ensure that a newly created virtual machine has access to persistent storage, you must create and attach a disk.
Example 3.13. Creating a virtual machine disk
These examples create an 8 GB virtio disk and attach it to a virtual machine, vm1. The disk has the following requirements:
-
Stored on the storage domain named
data1. - 8 GB in size.
-
systemtype disk (as opposed todata). -
virtiostorage device. -
COWformat. - Marked as a usable boot device.
V3
In V3, the options are combined into a disk parameter object, before using the add method of the virtual machine’s disks collection to create the disk itself.
V4
If the add request is successful, the examples output the text:
Disk 'vm1_Disk1' added to 'vm1'.
Disk 'vm1_Disk1' added to 'vm1'.
3.16. Attaching an ISO Image to a Virtual Machine 复制链接链接已复制到粘贴板!
To install a guest operating system on a newly created virtual machine, you must attach an ISO file containing the operating system installation media. To locate the ISO file, see Section 3.12, “Listing Files in an ISO Storage Domain”.
Example 3.14. Attaching an ISO image to a virtual machine
These examples attach my_iso_file.iso to the vm1 virtual machine, using the add method of the virtual machine’s cdroms collection.
V3
V4
If the add request is successful, the examples output the text:
Attached CD to 'vm1'.
Attached CD to 'vm1'.
Example 3.15. Ejecting a cdrom from a virtual machine
These examples eject an ISO image from a virtual machine’s cdrom collection.
V3
V4
If the delete or remove request is successful, the examples output the text:
Removed CD from 'vm1'.
Removed CD from 'vm1'.
3.17. Detaching a Disk 复制链接链接已复制到粘贴板!
You can detach a disk from a virtual machine.
Example 3.16. Detaching a disk
V3
V4
If the delete or remove request is successful, the examples output the text:
Detached disk vm1_disk1 successfully!
Detached disk vm1_disk1 successfully!
=== Starting a Virtual Machine
You can start a virtual machine.
These examples start the virtual machine using the start method.
V3
V4
If the start request is successful, the examples output the text:
Started 'vm1'.
Started 'vm1'.
The UP status indicates that the virtual machine is running.
=== Starting a Virtual Machine with Overridden Parameters
You can start a virtual machine, overriding its default parameters.
These examples boot a virtual machine with a Windows ISO and attach the virtio-win_x86.vfd floppy disk, which contains Windows drivers. This action is equivalent to using the Run Once window in the Administration Portal to start a virtual machine.
V3
V4
The CD image and floppy disk file must be available to the virtual machine. See Uploading Images to a Data Storage Domain for details.
=== Starting a Virtual Machine with Cloud-Init
You can start a virtual machine with a specific configuration, using the Cloud-Init tool.
These examples show you how to start a virtual machine using the Cloud-Init tool to set a host name and a static IP for the eth0 interface.
V3
V4
=== Checking System Events
Red Hat Virtualization Manager records and logs many system events. These event logs are accessible through the user interface, the system log files, and using the API. The ovirtsdk library exposes events using the events collection.
In this example the events collection is listed.
The query parameter of the list method is used to ensure that all available pages of results are returned. By default the list method returns only the first page of results, which is 100 records in length.
The returned list is sorted in reverse chronological order, to display the events in the order in which they occurred.
V3
V4
These examples output events in the following format:
YYYY-MM-DD_T_HH:MM:SS NORMAL CODE 30 - User admin@internal logged in. YYYY-MM-DD_T_HH:MM:SS NORMAL CODE 153 - VM vm1 was started by admin@internal (Host: MyHost). YYYY-MM-DD_T_HH:MM:SS NORMAL CODE 30 - User admin@internal logged in.
YYYY-MM-DD_T_HH:MM:SS NORMAL CODE 30 - User admin@internal logged in.
YYYY-MM-DD_T_HH:MM:SS NORMAL CODE 153 - VM vm1 was started by admin@internal (Host: MyHost).
YYYY-MM-DD_T_HH:MM:SS NORMAL CODE 30 - User admin@internal logged in.