Skip to content
Xu Tian edited this page Dec 30, 2016 · 1 revision

Navigation

virttest package

Subpackages

Submodules

virttest.RFBDes module

classvirttest.RFBDes.``Des(key)
Bases: object

Base Data Encryption Standard class. For details, please refer to: http://en.wikipedia.org/wiki/Data_Encryption_Standard

Initialize the instance.

Parameters:

key – Original used in DES.

E= [31, 0, 1, 2, 3, 4, 3, 4, 5, 6, 7, 8, 7, 8, 9, 10, 11, 12, 11, 12, 13, 14, 15, 16, 15, 16, 17, 18, 19, 20, 19, 20, 21, 22, 23, 24, 23, 24, 25, 26, 27, 28, 27, 28, 29, 30, 31, 0]

FP= [39, 7, 47, 15, 55, 23, 63, 31, 38, 6, 46, 14, 54, 22, 62, 30, 37, 5, 45, 13, 53, 21, 61, 29, 36, 4, 44, 12, 52, 20, 60, 28, 35, 3, 43, 11, 51, 19, 59, 27, 34, 2, 42, 10, 50, 18, 58, 26, 33, 1, 41, 9, 49, 17, 57, 25, 32, 0, 40, 8, 48, 16, 56, 24]

IP= [57, 49, 41, 33, 25, 17, 9, 1, 59, 51, 43, 35, 27, 19, 11, 3, 61, 53, 45, 37, 29, 21, 13, 5, 63, 55, 47, 39, 31, 23, 15, 7, 56, 48, 40, 32, 24, 16, 8, 0, 58, 50, 42, 34, 26, 18, 10, 2, 60, 52, 44, 36, 28, 20, 12, 4, 62, 54, 46, 38, 30, 22, 14, 6]

P= [15, 6, 19, 20, 28, 11, 27, 16, 0, 14, 22, 25, 4, 17, 30, 9, 1, 7, 23, 13, 31, 26, 2, 8, 18, 12, 29, 5, 21, 10, 3, 24]

PC1= [56, 48, 40, 32, 24, 16, 8, 0, 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2, 59, 51, 43, 35, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 60, 52, 44, 36, 28, 20, 12, 4, 27, 19, 11, 3]

PC2= [13, 16, 10, 23, 0, 4, 2, 27, 14, 5, 20, 9, 22, 18, 11, 3, 25, 7, 15, 6, 26, 19, 12, 1, 40, 51, 30, 36, 46, 54, 29, 39, 50, 44, 32, 47, 43, 48, 38, 55, 33, 52, 45, 41, 49, 35, 28, 31]

create_Kn()
Create the 16 subkeys,from K[0] to K[15], from the given key

crypt(data, crypt_type=0)
Crypt the data in blocks, running it through des_crypt()

Parameters:

  • data – Data to be encrypted/decrypted.
  • crypt_type – crypt type. 0 means encrypt, and 1 means decrypt.

des_crypt(data, crypt_type=0)
Crypt the block of data through DES bit-manipulation

Parameters:

  • data – data need to crypt.
  • crypt_type – crypt type. 0 means encrypt, and 1 means decrypt.

f(K)
The Feistel function (F-function) of DES, operates on half a block (32 bits) at a time and consists of four stages: 1. Expansion 2. Key mixing 3. Substitution 4. Permutation

Parameters:

K – One of sixteen 48-bit subkeys are derived from the main key.

getKey()
Just get the crypting key.

get_sub_list(table, block)
Return sub list of block according to index in table.

Parameters:

  • table – Index list.
  • block – bit list used to get sub list.

left_rotations= [1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1]

sbox= 14, 4, 13, 1, 2, 15, 11, 8, 3, 10, 6, 12, 5, 9, 0, 7, 0, 15, 7, 4, 14, 2, 13, 1, 10, 6, 12, 11, 9, 5, 3, 8, 4, 1, 14, 8, 13, 6, 2, 11, 15, 12, 9, 7, 3, 10, 5, 0, 15, 12, 8, 2, 4, 9, 1, 7, 5, 11, 3, 14, 10, 0, 6, 13], [15, 1, 8, 14, 6, 11, 3, 4, 9, 7, 2, 13, 12, 0, 5, 10, 3, 13, 4, 7, 15, 2, 8, 14, 12, 0, 1, 10, 6, 9, 11, 5, 0, 14, 7, 11, 10, 4, 13, 1, 5, 8, 12, 6, 9, 3, 2, 15, 13, 8, 10, 1, 3, 15, 4, 2, 11, 6, 7, 12, 0, 5, 14, 9], [10, 0, 9, 14, 6, 3, 15, 5, 1, 13, 12, 7, 11, 4, 2, 8, 13, 7, 0, 9, 3, 4, 6, 10, 2, 8, 5, 14, 12, 11, 15, 1, 13, 6, 4, 9, 8, 15, 3, 0, 11, 1, 2, 12, 5, 10, 14, 7, 1, 10, 13, 0, 6, 9, 8, 7, 4, 15, 14, 3, 11, 5, 2, 12], [7, 13, 14, 3, 0, 6, 9, 10, 1, 2, 8, 5, 11, 12, 4, 15, 13, 8, 11, 5, 6, 15, 0, 3, 4, 7, 2, 12, 1, 10, 14, 9, 10, 6, 9, 0, 12, 11, 7, 13, 15, 1, 3, 14, 5, 2, 8, 4, 3, 15, 0, 6, 10, 1, 13, 8, 9, 4, 5, 11, 12, 7, 2, 14], [2, 12, 4, 1, 7, 10, 11, 6, 8, 5, 3, 15, 13, 0, 14, 9, 14, 11, 2, 12, 4, 7, 13, 1, 5, 0, 15, 10, 3, 9, 8, 6, 4, 2, 1, 11, 10, 13, 7, 8, 15, 9, 12, 5, 6, 3, 0, 14, 11, 8, 12, 7, 1, 14, 2, 13, 6, 15, 0, 9, 10, 4, 5, 3], [12, 1, 10, 15, 9, 2, 6, 8, 0, 13, 3, 4, 14, 7, 5, 11, 10, 15, 4, 2, 7, 12, 9, 5, 6, 1, 13, 14, 0, 11, 3, 8, 9, 14, 15, 5, 2, 8, 12, 3, 7, 0, 4, 10, 1, 13, 11, 6, 4, 3, 2, 12, 9, 5, 15, 10, 11, 14, 1, 7, 6, 0, 8, 13], [4, 11, 2, 14, 15, 0, 8, 13, 3, 12, 9, 7, 5, 10, 6, 1, 13, 0, 11, 7, 4, 9, 1, 10, 14, 3, 5, 12, 2, 15, 8, 6, 1, 4, 11, 13, 12, 3, 7, 14, 10, 15, 6, 8, 0, 5, 9, 2, 6, 11, 13, 8, 1, 4, 10, 7, 9, 5, 0, 15, 14, 2, 3, 12], [13, 2, 8, 4, 6, 15, 11, 1, 10, 9, 3, 14, 5, 0, 12, 7, 1, 15, 13, 8, 10, 3, 7, 4, 12, 5, 6, 11, 0, 14, 9, 2, 7, 11, 4, 1, 9, 12, 14, 2, 0, 6, 10, 13, 15, 3, 5, 8, 2, 1, 14, 7, 4, 10, 8, 13, 15, 12, 9, 0, 3, 5, 6, 11

setKey(key)
Will set the crypting key for this object. RFB protocol for authentication requires client to encrypt challenge sent by server with password using DES method. However, bits in each byte of the password are put in reverse order before using it as encryption key.

Parameters:

key – Original used in DES.

virttest.arch module

virttest.arch.``get_kvm_module_list()

virttest.asset module

classvirttest.asset.``ConfigLoader(cfg, tmpdir='/tmp/avocado_Wt9Uw4', raise_errors=False)
Base class of the configuration parser

Instantiate ConfigParser and load data.

Parameters:

  • cfg – Where we’ll get configuration data. It can be either: * A URL containing the file * A valid file path inside the filesystem * A string containing configuration data
  • tmpdir – Where we’ll dump the temporary conf files.
  • raise_errors – Whether config value absences will raise ValueError exceptions.

check(section)
Check if the config file has valid values

check_parameter(param_type, parameter)
Check if a option has a valid value

get(section, option, default=None)
Get the value of a option.

Section of the config file and the option name. You can pass a default value if the option doesn’t exist.

Parameters:

  • section – Configuration file section.
  • option – Option we’re looking after.

Default:

In case the option is not available and raise_errors is set to False, return the default.

remove(section, option)
Remove an option.

save()
Save the configuration file with all modifications

set(section, option, value)
Set an option.

This change is not persistent unless saved with ‘save()’.

virttest.asset.``download_all_test_providers(update=False)
Download all available test providers.

virttest.asset.``download_asset(asset, interactive=True, restore_image=False)
Download an asset defined on an asset file.

Asset files are located under /shared/downloads, are .ini files with the following keys defined:

title
Title string to display in the download progress bar.

url
URL of the resource

sha1_url
URL with SHA1 information for the resource, in the form sha1sum file_basename

destination
Location of your file relative to the data directory (TEST_SUITE_ROOT/shared/data)

destination
Location of the uncompressed file relative to the data directory (TEST_SUITE_ROOT/shared/data)

uncompress_cmd
Command that needs to be executed with the compressed file as a parameter

Parameters:

  • asset – String describing an asset file.
  • interactive – Whether to ask the user before downloading the file.
  • restore_image – If the asset is a compressed image, we can uncompress in order to restore the image.

virttest.asset.``download_file(asset_info, interactive=False, force=False)
Verifies if file that can be find on url is on destination with right hash.

This function will verify the SHA1 hash of the file. If the file appears to be missing or corrupted, let the user know.

Parameters:

asset_info – Dictionary returned by get_asset_info

virttest.asset.``download_test_provider(provider, update=False)
Download a test provider defined on a .ini file inside test-providers.d.

This function will only download test providers that are in git repos. Local filesystems don’t need this functionality.

Parameters:

provider – Test provider name, such as ‘io-github-autotest-qemu’.

virttest.asset.``get_all_assets()

virttest.asset.``get_asset_info(asset, ini_dir=None, section=None)
” Parse $asset.ini file and returns a dictionary suitable for asset.download_file()

Parameters:

  • asset – Asset name. A file ending in .ini.
  • ini_dir – Directory where to search .ini file.
  • section – Name of the [] section in .ini file. If None, then use asset name.

virttest.asset.``get_file_asset(title, src_path, destination)

virttest.asset.``get_known_backends()
Return virtualization backends supported by avocado-vt.

virttest.asset.``get_test_provider_info(provider)
Get a dictionary with relevant test provider info, such as:

  • provider uri (git repo or filesystem location)
  • provider git repo data, such as branch, ref, pubkey
  • backends that this provider has tests for. For each backend type the
    provider has tests for, the ‘path’ will be also available.

Parameters:

provider – Test provider name, such as ‘io-github-autotest-qemu’.

virttest.asset.``get_test_provider_names(backend=None)
Get the names of all test providers available in test-providers.d.

Returns:

List with the names of all test providers.

virttest.asset.``get_test_provider_subdirs(backend=None)
Get information of all test provider subdirs for a given backend.

If no backend is provided, return all subdirs with tests.

Parameters:

backend – Backend type, such as ‘qemu’.

Returns:

List of directories that contain tests for the given backend.

virttest.asset.``uncompress_asset(asset_info, force=False)

virttest.base_installer module

This module implements classes that perform the installation of the virtualization software on a host system.

These classes can be, and usually are, inherited by subclasses that implement custom logic for each virtualization hypervisor/software.

classvirttest.base_installer.``BaseInstaller(mode, name, test=None, params=None)
Bases: object

Base virtualization software installer

This class holds all the skeleton features for installers and should be inherited from when creating a new installer.

Instantiates a new base installer

Parameters:

  • mode – installer mode, such as git_repo, local_src, etc
  • name – installer short name, foo for git_repo_foo
  • test – test
  • params – params

install(cleanup=True, download=True, prepare=True, build=True, install=True, init=True)
Performs the installation of the virtualization software

This is the main entry point of this class, and should either be reimplemented completely, or simply implement one or many of the install phases.

load_modules(module_list=None)
Load Linux Kernel modules the virtualization software may depend on

If module_directory is not set, the list of modules will simply be loaded by the system stock modprobe tool, meaning that modules will be looked for in the system default module paths.

Parameters:

module_list (builtin.list) – list of kernel modules names to load

reload_modules()
Reload the kernel modules (unload, then load)

reload_modules_if_needed()

set_install_params(test=None, params=None)
Called by test to setup parameters from the configuration file

uninstall()
Performs the uninstallations of the virtualization software

Note: This replaces old qemu_installer._clean_previous_install()

unload_modules(module_list=None)
Unloads kernel modules

By default, if no module list is explicitly provided, the list on params (coming from the configuration file) will be used.

write_version_keyval(test)

classvirttest.base_installer.``BaseLocalSourceInstaller(mode, name, test=None, params=None)
Bases: virttest.base_installer.BaseInstaller

Instantiates a new base installer

Parameters:

  • mode – installer mode, such as git_repo, local_src, etc
  • name – installer short name, foo for git_repo_foo
  • test – test
  • params – params

set_install_params(test, params)

classvirttest.base_installer.``FailedInstaller(msg='Virtualization software install failed')
Class used to be returned instead of the installer if a installation fails

Useful to make sure no installer object is used if virt installation fails

load_modules()
Will refuse to load the kerkel modules as install failed

classvirttest.base_installer.``GitRepoInstaller(mode, name, test=None, params=None)
Bases: virttest.base_installer.BaseLocalSourceInstaller

Instantiates a new base installer

Parameters:

  • mode – installer mode, such as git_repo, local_src, etc
  • name – installer short name, foo for git_repo_foo
  • test – test
  • params – params

get_version()

set_install_params(test, params)

classvirttest.base_installer.``KojiInstaller(mode, name, test=None, params=None)
Bases: virttest.base_installer.BaseInstaller

Handles virtualization software installation via koji/brew

It uses YUM to install and remove packages.

Change notice: this is not a subclass of YumInstaller anymore. The parameters this class uses are different (koji_tag, koji_pgks) and the install process runs YUM.

Instantiates a new base installer

Parameters:

  • mode – installer mode, such as git_repo, local_src, etc
  • name – installer short name, foo for git_repo_foo
  • test – test
  • params – params

get_version()

set_install_params(test, params)

classvirttest.base_installer.``LocalSourceDirInstaller(mode, name, test=None, params=None)
Bases: virttest.base_installer.BaseLocalSourceInstaller

Handles software installation by building/installing from a source dir

Instantiates a new base installer

Parameters:

  • mode – installer mode, such as git_repo, local_src, etc
  • name – installer short name, foo for git_repo_foo
  • test – test
  • params – params

set_install_params(test, params)

classvirttest.base_installer.``LocalSourceTarInstaller(mode, name, test=None, params=None)
Bases: virttest.base_installer.BaseLocalSourceInstaller

Handles software installation by building/installing from a tarball

Instantiates a new base installer

Parameters:

  • mode – installer mode, such as git_repo, local_src, etc
  • name – installer short name, foo for git_repo_foo
  • test – test
  • params – params

set_install_params(test, params)

exceptionvirttest.base_installer.``NoModuleError
Bases: exceptions.Exception

Error raised when no suitable modules were found to load

classvirttest.base_installer.``NoopInstaller(mode, name, test=None, params=None)
Bases: virttest.base_installer.BaseInstaller

Dummy installer that does nothing, useful when software is pre-installed

If no previous install test ran, try to figure out modules to load.

Parameters:

  • mode – Install mode (yum, git, etc).
  • name – Installer name.
  • test – Virt test object.
  • params – Dict with test params.

install()

classvirttest.base_installer.``RemoteSourceTarInstaller(mode, name, test=None, params=None)
Bases: virttest.base_installer.BaseLocalSourceInstaller

Handles software installation by building/installing from a remote tarball

Instantiates a new base installer

Parameters:

  • mode – installer mode, such as git_repo, local_src, etc
  • name – installer short name, foo for git_repo_foo
  • test – test
  • params – params

set_install_params(test, params)

exceptionvirttest.base_installer.``VirtInstallException
Bases: exceptions.Exception

Base virtualization software components installation exception

exceptionvirttest.base_installer.``VirtInstallFailed
Bases: virttest.base_installer.VirtInstallException

Installation of virtualization software components failed

exceptionvirttest.base_installer.``VirtInstallNotInstalled
Bases: virttest.base_installer.VirtInstallException

Virtualization software components are not installed

classvirttest.base_installer.``YumInstaller(mode, name, test=None, params=None)
Bases: virttest.base_installer.BaseInstaller

Installs virtualization software using YUM

Notice: this class implements a change of behaviour if compared to qemu_installer.YumInstaller.set_install_params(). There’s no longer a default package list, as each virtualization technology will have a completely different default. This should now be kept at the configuration file only.

For now this class implements support for installing from the configured yum repos only. If the use case of installing from local RPM packages arises, we’ll implement that.

Instantiates a new base installer

Parameters:

  • mode – installer mode, such as git_repo, local_src, etc
  • name – installer short name, foo for git_repo_foo
  • test – test
  • params – params

get_version()

set_install_params(test, params)

virttest.bootstrap module

virttest.bootstrap.``bootstrap(options, interactive=False)
Common virt test assistant module.

Parameters:

  • options – Command line options.
  • interactive – Whether to ask for confirmation.

Raises:

  • error.CmdError – If JeOS image failed to uncompress
  • ValueError – If 7za was not found

virttest.bootstrap.``create_config_files(test_dir, shared_dir, interactive, t_type, step=None, force_update=False)

virttest.bootstrap.``create_guest_os_cfg(t_type)

virttest.bootstrap.``create_subtests_cfg(t_type)

virttest.bootstrap.``get_config_filter()

virttest.bootstrap.``get_directory_structure(rootdir, guest_file)

virttest.bootstrap.``get_guest_os_info_list(test_name, guest_os)
Returns a list of matching assets compatible with the specified test name and guest OS

virttest.bootstrap.``haz_defcon(datadir, imagesdir, isosdir, tmpdir)
Compare current types from Defaults, or if default, compare on-disk type

virttest.bootstrap.``set_defcon(datadir, imagesdir, isosdir, tmpdir)
Tries to set datadir default contexts returns True if changed

virttest.bootstrap.``sync_download_dir(interactive)

virttest.bootstrap.``verify_mandatory_programs(t_type, guest_os)

virttest.bootstrap.``verify_recommended_programs(t_type)

virttest.bootstrap.``verify_selinux(datadir, imagesdir, isosdir, tmpdir, interactive, selinux=False)
Verify/Set/Warn about SELinux and default file contexts for testing.

Parameters:

  • datadir – Abs. path to data-directory symlink
  • imagesdir – Abs. path to data/images directory
  • isosdir – Abs. path to data/isos directory
  • tmpdir – Abs. path to avocado-vt tmp dir
  • interactive – True if running from console
  • selinux – Whether setup SELinux contexts for shared/data

virttest.bootstrap.``write_subtests_files(config_file_list, output_file_object, test_type=None)
Writes a collection of individual subtests config file to one output file

Optionally, for tests that we know their type, write the ‘virt_test_type’ configuration automatically.

virttest.build_helper module

classvirttest.build_helper.``GitRepoParamHelper(params, name, destination_dir)
Bases: avocado.utils.git.GitRepoHelper

Helps to deal with git repos specified in cartersian config files

This class attempts to make it simple to manage a git repo, by using a naming standard that follows this basic syntax:

<prefix>_name_<suffix>

<prefix> is always ‘git_repo’ and <suffix> sets options for this git repo. Example for repo named foo:

git_repo_foo_uri = git://git.foo.org/foo.git git_repo_foo_base_uri = /home/user/code/foo git_repo_foo_branch = master git_repo_foo_lbranch = master git_repo_foo_commit = bb5fb8e678aabe286e74c4f2993dc2a9e550b627

Instantiates a new GitRepoParamHelper

execute()

classvirttest.build_helper.``GnuSourceBuildHelper(source, build_dir, prefix, configure_options=[])
Bases: object

Handles software installation of GNU-like source code

This basically means that the build will go though the classic GNU autotools steps: ./configure, make, make install

Parameters:

  • source (string) – source directory or tarball
  • prefix (string) – installation prefix
  • build_dir (string) – temporary directory used for building the source code
  • configure_options (builtin.list) – options to pass to configure

Throws:

GnuSourceBuildInvalidSource

configure()
Runs the “configure” script passing appropriate command line options

enable_debug_symbols()
Enables option that leaves debug symbols on compiled software

This makes debugging a lot easier.

execute()
Runs appropriate steps for building this source code tree

get_available_configure_options()
Return the list of available options of a GNU like configure script

This will run the “configure” script at the source directory

Returns:

list of options accepted by configure script

get_configure_command()
Formats configure script with all options set

Returns:

string with all configure options, including prefix

get_configure_path()
Checks if ‘configure’ exists, if not, return ‘autogen.sh’ as a fallback

include_pkg_config_path()
Adds the current prefix to the list of paths that pkg-config searches

This is currently not optional as there is no observed adverse side effects of enabling this. As the “prefix” is usually only valid during a test run, we believe that having other pkg-config files (*.pc) in either <prefix>/share/pkgconfig or <prefix>/lib/pkgconfig is exactly for the purpose of using them.

Returns:

None

install()
Runs “make install”

make(failure_feedback=True)
Runs a parallel make, falling back to a single job in failure

Parameters:

failure_feedback – return information on build failure by raising the appropriate exceptions

Raise:

SourceBuildParallelFailed if parallel build fails, or SourceBuildFailed if single job build fails

make_clean()
Runs “make clean”

make_install()
Runs “make install”

make_non_parallel()
Runs “make”, using a single job

make_parallel()
Runs “make” using the correct number of parallel jobs

exceptionvirttest.build_helper.``GnuSourceBuildInvalidSource
Bases: exceptions.Exception

Exception raised when build source dir/file is not valid

classvirttest.build_helper.``GnuSourceBuildParamHelper(params, name, destination_dir, install_prefix)
Bases: virttest.build_helper.GnuSourceBuildHelper

Helps to deal with gnu_autotools build helper in cartersian config files

This class attempts to make it simple to build source coude, by using a naming standard that follows this basic syntax:

[<git_repo>|<local_src>]_<name>_<option> = value

To pass extra options to the configure script, while building foo from a git repo, set the following variable:

git_repo_foo_configure_options = –enable-feature

Instantiates a new GnuSourceBuildParamHelper

classvirttest.build_helper.``LinuxKernelBuildHelper(params, prefix, source)
Bases: object

Handles Building Linux Kernel.

Parameters:

  • params (dict) – dictionary containing the test parameters
  • source (string) – source directory or tarball
  • prefix (string) – installation prefix

cp_linux_kernel()
Copying Linux kernel to target path

execute()
Runs appropriate steps for building this source code tree

install()
Copying Linux kernel to target path

make(failure_feedback=True)
Runs a parallel make

Parameters:

failure_feedback – return information on build failure by raising the appropriate exceptions

Raise:

SourceBuildParallelFailed if parallel build fails, or

make_clean()
Runs “make clean”

make_guest_kernel()
Runs “make”, using a single job

classvirttest.build_helper.``LocalSourceDirHelper(source_dir, destination_dir)
Bases: object

Helper class to deal with source code sitting somewhere in the filesystem

Parameters:

  • source_dir
  • destination_dir

Returns:

new LocalSourceDirHelper instance

execute()
Copies the source directory to the destination directory

classvirttest.build_helper.``LocalSourceDirParamHelper(params, name, destination_dir)
Bases: virttest.build_helper.LocalSourceDirHelper

Helps to deal with source dirs specified in cartersian config files

This class attempts to make it simple to manage a source dir, by using a naming standard that follows this basic syntax:

<prefix>_name_<suffix>

<prefix> is always ‘local_src’ and <suffix> sets options for this source dir. Example for source dir named foo:

local_src_foo_path = /home/user/foo

Instantiate a new LocalSourceDirParamHelper

classvirttest.build_helper.``LocalTarHelper(source, destination_dir)
Bases: object

Helper class to deal with source code in a local tarball

execute()
Executes all action this helper is supposed to perform

This is the main entry point method for this class, and all other helper classes.

extract()
Extracts the tarball into the destination directory

classvirttest.build_helper.``LocalTarParamHelper(params, name, destination_dir)
Bases: virttest.build_helper.LocalTarHelper

Helps to deal with source tarballs specified in cartersian config files

This class attempts to make it simple to manage a tarball with source code, by using a naming standard that follows this basic syntax:

<prefix>_name_<suffix>

<prefix> is always ‘local_tar’ and <suffix> sets options for this source tarball. Example for source tarball named foo:

local_tar_foo_path = /tmp/foo-1.0.tar.gz

Instantiates a new LocalTarParamHelper

classvirttest.build_helper.``PatchHelper(source_dir, patches)
Bases: object

Helper that encapsulates the patching of source code with patch files

Initializes a new PatchHelper

download()
Copies patch files from remote locations to the source directory

execute()
Performs all steps necessary to download patches and apply them

patch()
Patches the source dir with all patch files

classvirttest.build_helper.``PatchParamHelper(params, prefix, source_dir)
Bases: virttest.build_helper.PatchHelper

Helps to deal with patches specified in cartersian config files

This class attempts to make it simple to patch source coude, by using a naming standard that follows this basic syntax:

[<git_repo>|<local_src>|<local_tar>|<remote_tar>]_<name>_patches

<prefix> is either a ‘local_src’ or ‘git_repo’, that, together with <name> specify a directory containing source code to receive the patches. That is, for source code coming from git repo foo, patches would be specified as:

git_repo_foo_patches = [‘http://foo/bar.patch‘, ‘http://foo/baz.patch‘]

And for for patches to be applied on local source code named also foo:

local_src_foo_patches = [‘http://foo/bar.patch‘, ‘http://foo/baz.patch‘]

Initializes a new PatchParamHelper instance

classvirttest.build_helper.``RemoteTarHelper(source_uri, destination_dir)
Bases: virttest.build_helper.LocalTarHelper

Helper that fetches a tarball and extracts it locally

execute()
Executes all action this helper class is supposed to perform

This is the main entry point method for this class, and all other helper classes.

This implementation fetches the remote tar file and then extracts it using the functionality present in the parent class.

classvirttest.build_helper.``RemoteTarParamHelper(params, name, destination_dir)
Bases: virttest.build_helper.RemoteTarHelper

Helps to deal with remote source tarballs specified in cartersian config

This class attempts to make it simple to manage a tarball with source code, by using a naming standard that follows this basic syntax:

<prefix>_name_<suffix>

<prefix> is always ‘local_tar’ and <suffix> sets options for this source tarball. Example for source tarball named foo:

remote_tar_foo_uri = http://foo.org/foo-1.0.tar.gz

Instantiates a new RemoteTarParamHelper instance

exceptionvirttest.build_helper.``SourceBuildFailed
Bases: exceptions.Exception

Exception raised when building with parallel jobs fails

This serves as feedback for code using virttest.build_helper.BuildHelper.

exceptionvirttest.build_helper.``SourceBuildParallelFailed
Bases: exceptions.Exception

Exception raised when building with parallel jobs fails

This serves as feedback for code using virttest.build_helper.BuildHelper.

virttest.cartesian_config module

Cartesian configuration format file parser.

Filter syntax:

  • , means OR
  • .. means AND
  • . means IMMEDIATELY-FOLLOWED-BY
  • (xx=yy) where xx=VARIANT_NAME and yy=VARIANT_VALUE

Example:

qcow2..(guest_os=Fedora).14, RHEL.6..raw..boot, smp2..qcow2..migrate..ide

means match all dicts whose names have:

(qcow2 AND ((guest_os=Fedora) IMMEDIATELY-FOLLOWED-BY 14)) OR
((RHEL IMMEDIATELY-FOLLOWED-BY 6) AND raw AND boot) OR
(smp2 AND qcow2 AND migrate AND ide)

Note:

  • qcow2..Fedora.14 is equivalent to Fedora.14..qcow2.
  • qcow2..Fedora.14 is not equivalent to qcow2..14.Fedora.
  • ide, scsi is equivalent to scsi, ide.

Filters can be used in 3 ways:

only <filter>
no <filter>
<filter>:

The last one starts a conditional block.

Formal definition: Regexp come from python. They’re not deterministic, but more readable for people. Spaces between terminals and nonterminals are only for better reading of definitions.

The base of the definitions come verbatim as follows:

E = {\n, #, :, "-", =, +=, <=, ?=, ?+=, ?<=, !, < , del, @, variants, include, only, no, name, value}

N = {S, DEL, FILTER, FILTER_NAME, FILTER_GROUP, PN_FILTER_GROUP, STAT, VARIANT, VAR-TYPE, VAR-NAME, VAR-NAME-F, VAR, COMMENT, TEXT, DEPS, DEPS-NAME-F, META-DATA, IDENTIFIER}``


I = I^n | n in N              // indentation from start of line
                              // where n is indentation length.
I = I^n+x | n,x in N          // indentation with shift

start symbol = S
end symbol = eps

S -> I^0+x STATV | eps

I^n    STATV
I^n    STATV

I^n STATV -> I^n STATV \n I^n STATV | I^n STAT | I^n variants VARIANT
I^n STAT -> I^n STAT \n I^n STAT | I^n COMMENT | I^n include INC
I^n STAT -> I^n del DEL | I^n FILTER

DEL -> name \n

I^n STAT -> I^n name = VALUE | I^n name += VALUE | I^n name <= VALUE
I^n STAT -> I^n name ?= VALUE | I^n name ?+= VALUE | I^n name ?<= VALUE

VALUE -> TEXT \n | 'TEXT' \n | "TEXT" \n

COMMENT_BLOCK -> #TEXT | //TEXT
COMMENT ->  COMMENT_BLOCK\n
COMMENT ->  COMMENT_BLOCK\n

TEXT = [^\n] TEXT            //python format regexp

I^n    variants VAR #comments:             add possibility for comment
I^n+x       VAR-NAME: DEPS
I^n+x+x2        STATV
I^n         VAR-NAME:

IDENTIFIER -> [A-Za-z0-9][A-Za-z0-9_-]*

VARIANT -> VAR COMMENT_BLOCK\n I^n+x VAR-NAME
VAR -> VAR-TYPE: | VAR-TYPE META-DATA: | :         // Named | unnamed variant

VAR-TYPE -> IDENTIFIER

variants _name_ [xxx] [zzz=yyy] [uuu]:

META-DATA -> [IDENTIFIER] | [IDENTIFIER=TEXT] | META-DATA META-DATA

I^n VAR-NAME -> I^n VAR-NAME \n I^n VAR-NAME | I^n VAR-NAME-N \n I^n+x STATV
VAR-NAME-N -> - @VAR-NAME-F: DEPS | - VAR-NAME-F: DEPS
VAR-NAME-F -> [a-zA-Z0-9\._-]+                  // Python regexp

DEPS -> DEPS-NAME-F | DEPS-NAME-F,DEPS
DEPS-NAME-F -> [a-zA-Z0-9\._- ]+                // Python regexp

INC -> name \n


FILTER_GROUP: STAT
    STAT

I^n STAT -> I^n PN_FILTER_GROUP | I^n ! PN_FILTER_GROUP

PN_FILTER_GROUP -> FILTER_GROUP: \n I^n+x STAT
PN_FILTER_GROUP -> FILTER_GROUP: STAT \n I^n+x STAT

only FILTER_GROUP
no FILTER_GROUP

FILTER -> only FILTER_GROUP \n | no FILTER_GROUP \n

FILTER_GROUP -> FILTER_NAME
FILTER_GROUP -> FILTER_GROUP..FILTER_GROUP
FILTER_GROUP -> FILTER_GROUP,FILTER_GROUP

FILTER_NAME -> FILTER_NAME.FILTER_NAME
FILTER_NAME -> VAR-NAME-F | (VAR-NAME-F=VAR-NAME-F)

copyright:

Red Hat 2008-2013

classvirttest.cartesian_config.``BlockFilter(blocked)
Bases: object

apply_to_dict(d)

blocked

classvirttest.cartesian_config.``Condition(lfilter, line)
Bases: virttest.cartesian_config.NoFilter

content

classvirttest.cartesian_config.``FileReader(filename)
Bases: virttest.cartesian_config.StrReader

Preprocess an input file for easy reading.

Initialize the reader.

Parse filename:

The name of the input file.

classvirttest.cartesian_config.``Filter(lfilter)
Bases: object

filter

match(ctx, ctx_set)

might_match(ctx, ctx_set, descendant_labels)

classvirttest.cartesian_config.``JoinFilter(lfilter, line)
Bases: virttest.cartesian_config.NoOnlyFilter

classvirttest.cartesian_config.``LAnd
Bases: virttest.cartesian_config.Token

identifier= '..'

classvirttest.cartesian_config.``LAppend
Bases: virttest.cartesian_config.LOperators

apply_to_dict(d)

identifier= '+='

classvirttest.cartesian_config.``LApplyPreDict
Bases: virttest.cartesian_config.LOperators

apply_to_dict(d)

identifier= 'apply_pre_dict'

set_operands(name, value)

classvirttest.cartesian_config.``LCoc
Bases: virttest.cartesian_config.Token

identifier= '.'

classvirttest.cartesian_config.``LColon
Bases: virttest.cartesian_config.Token

identifier= ':'

classvirttest.cartesian_config.``LComa
Bases: virttest.cartesian_config.Token

identifier= ','

classvirttest.cartesian_config.``LCond
Bases: virttest.cartesian_config.Token

identifier= ''

classvirttest.cartesian_config.``LDefault
Bases: virttest.cartesian_config.Token

identifier= '@'

classvirttest.cartesian_config.``LDel
Bases: virttest.cartesian_config.LOperators

apply_to_dict(d)

identifier= 'del'

classvirttest.cartesian_config.``LDot
Bases: virttest.cartesian_config.Token

identifier= '.'

classvirttest.cartesian_config.``LEndBlock(length)
Bases: virttest.cartesian_config.LIndent

classvirttest.cartesian_config.``LEndL
Bases: virttest.cartesian_config.Token

identifier= 'endl'

classvirttest.cartesian_config.``LIdentifier
Bases: str

checkAlpha()
Check if string contain only chars

checkChar(chars)

checkCharAlpha(chars)
Check if string contain only chars

checkCharAlphaNum(chars)
Check if string contain only chars

checkCharNumeric(chars)
Check if string contain only chars

checkNumbers()
Check if string contain only chars

identifier= 'Identifier re([A-Za-z0-9][A-Za-z0-9_-]*)'

classvirttest.cartesian_config.``LInclude
Bases: virttest.cartesian_config.Token

identifier= 'include'

classvirttest.cartesian_config.``LIndent(length)
Bases: virttest.cartesian_config.Token

identifier= 'indent'

length

classvirttest.cartesian_config.``LJoin
Bases: virttest.cartesian_config.Token

identifier= 'join'

classvirttest.cartesian_config.``LLBracket
Bases: virttest.cartesian_config.Token

identifier= '['

classvirttest.cartesian_config.``LLRBracket
Bases: virttest.cartesian_config.Token

identifier= '('

classvirttest.cartesian_config.``LNo
Bases: virttest.cartesian_config.Token

identifier= 'no'

classvirttest.cartesian_config.``LNotCond
Bases: virttest.cartesian_config.Token

identifier= '!'

classvirttest.cartesian_config.``LOnly
Bases: virttest.cartesian_config.Token

identifier= 'only'

classvirttest.cartesian_config.``LOperators
Bases: virttest.cartesian_config.Token

function= None

identifier= ''

name

set_operands(name, value)

value

classvirttest.cartesian_config.``LOr
Bases: virttest.cartesian_config.Token

identifier= ','

classvirttest.cartesian_config.``LPrepend
Bases: virttest.cartesian_config.LOperators

apply_to_dict(d)

identifier= '<='

classvirttest.cartesian_config.``LRBracket
Bases: virttest.cartesian_config.Token

identifier= ']'

classvirttest.cartesian_config.``LRRBracket
Bases: virttest.cartesian_config.Token

identifier= ')'

classvirttest.cartesian_config.``LRegExpAppend
Bases: virttest.cartesian_config.LOperators

apply_to_dict(d)

identifier= '?+='

classvirttest.cartesian_config.``LRegExpPrepend
Bases: virttest.cartesian_config.LOperators

apply_to_dict(d)

identifier= '?<='

classvirttest.cartesian_config.``LRegExpSet
Bases: virttest.cartesian_config.LOperators

apply_to_dict(d)

identifier= '?='

classvirttest.cartesian_config.``LRegExpStart
Bases: virttest.cartesian_config.Token

identifier= '${'

classvirttest.cartesian_config.``LRegExpStop
Bases: virttest.cartesian_config.Token

identifier= '}'

classvirttest.cartesian_config.``LSet
Bases: virttest.cartesian_config.LOperators

apply_to_dict(d)
Parameters:

d – Dictionary for apply value

identifier= '='

classvirttest.cartesian_config.``LString
Bases: virttest.cartesian_config.LIdentifier

identifier= 'String re(.+)'

classvirttest.cartesian_config.``LSuffix
Bases: virttest.cartesian_config.Token

identifier= 'suffix'

classvirttest.cartesian_config.``LUpdateFileMap
Bases: virttest.cartesian_config.LOperators

apply_to_dict(d)

dest

identifier= 'update_file_map'

set_operands(filename, name, dest='_name_map_file')

shortname

classvirttest.cartesian_config.``LVariant
Bases: virttest.cartesian_config.Token

identifier= '-'

classvirttest.cartesian_config.``LVariants
Bases: virttest.cartesian_config.Token

identifier= 'variants'

classvirttest.cartesian_config.``LWhite
Bases: virttest.cartesian_config.LIdentifier

identifier= 'WhiteSpace re(\\s)'

classvirttest.cartesian_config.``Label(name, next_name=None)
Bases: object

hash_name()

hash_val

hash_var

hash_variant()

long_name

name

var_name

classvirttest.cartesian_config.``Lexer(reader)
Bases: object

check_token(token, lType)

flush_until(end_tokens=None)

get_lexer()

get_next_check(lType)

get_next_check_nw(lType)

get_until(end_tokens=None)

get_until_check(lType, end_tokens=None)
Read tokens from iterator until get end_tokens or type of token not match ltype

Parameters:

  • lType – List of allowed tokens
  • end_tokens – List of tokens for end reading

Returns:

List of readed tokens.

get_until_gen(end_tokens=None)

get_until_no_white(end_tokens=None)
Read tokens from iterator until get one of end_tokens and strip LWhite

Parameters:

end_tokens – List of tokens for end reading

Returns:

List of readed tokens.

match(line, pos)

rest_line()

rest_line_as_LString()

rest_line_gen()

rest_line_no_white()

set_fast()

set_prev_indent(prev_indent)

set_strict()

exceptionvirttest.cartesian_config.``LexerError(msg, line=None, filename=None, linenum=None)
Bases: virttest.cartesian_config.ParserError

exceptionvirttest.cartesian_config.``MissingIncludeError(line, filename, linenum)
Bases: exceptions.Exception

classvirttest.cartesian_config.``NegativeCondition(lfilter, line)
Bases: virttest.cartesian_config.OnlyFilter

content

classvirttest.cartesian_config.``NoFilter(lfilter, line)
Bases: virttest.cartesian_config.NoOnlyFilter

is_irrelevant(ctx, ctx_set, descendant_labels)

might_pass(failed_ctx, failed_ctx_set, ctx, ctx_set, descendant_labels)

requires_action(ctx, ctx_set, descendant_labels)

classvirttest.cartesian_config.``NoOnlyFilter(lfilter, line)
Bases: virttest.cartesian_config.Filter

line

classvirttest.cartesian_config.``Node
Bases: object

append_to_shortname

children

content

default

dep

dump(indent, recurse=False)

failed_cases

filename

labels

name

q_dict

var_name

classvirttest.cartesian_config.``OnlyFilter(lfilter, line)
Bases: virttest.cartesian_config.NoOnlyFilter

is_irrelevant(ctx, ctx_set, descendant_labels)

might_pass(failed_ctx, failed_ctx_set, ctx, ctx_set, descendant_labels)

requires_action(ctx, ctx_set, descendant_labels)

classvirttest.cartesian_config.``Parser(filename=None, defaults=False, expand_defaults=[], debug=False)
Bases: object

assign(key, value)
Apply a only filter programatically and keep track of it.

Equivalent to parse a “key = value” line.

Parameters:

variant – String with the variant name.

drop_suffixes(d)

get_dicts(node=None, ctx=[], content=[], shortname=[], dep=[])
Process ‘join’ entry, unpack join filter for node ctx - node labels/names content - previous content in plain Return: dictionary

get_dicts_plain(node=None, ctx=[], content=[], shortname=[], dep=[])
Generate dictionaries from the code parsed so far. This should be called after parsing something.

Returns:

A dict generator.

mk_name(n1, n2)

multiply_join(onlys, node=None, ctx=[], content=[], shortname=[], dep=[])

no_filter(variant)
Apply a only filter programatically and keep track of it.

Equivalent to parse a “no variant” line.

Parameters:

variant – String with the variant name.

only_filter(variant)
Apply a only filter programatically and keep track of it.

Equivalent to parse a “only variant” line.

Parameters:

variant – String with the variant name.

parse_file(filename)
Parse a file.

Parameters:

filename – Path of the configuration file.

parse_string(s)
Parse a string.

Parameters:

s – String to parse.

exceptionvirttest.cartesian_config.``ParserError(msg, line=None, filename=None, linenum=None)
Bases: exceptions.Exception

classvirttest.cartesian_config.``StrReader(s)
Bases: object

Preprocess an input string for easy reading.

Initialize the reader.

Parameters:

s – The string to parse.

get_next_line(prev_indent)
Get the next line in the current block.

Parameters:

prev_indent – The indentation level of the previous block.

Returns:

(line, indent, linenum), where indent is the line’s indentation level. If no line is available, (None, -1, -1) is returned.

set_next_line(line, indent, linenum)
Make the next call to get_next_line() return the given line instead of the real next line.

classvirttest.cartesian_config.``Suffix
Bases: virttest.cartesian_config.LOperators

apply_to_dict(d)

identifier= 'apply_suffix'

classvirttest.cartesian_config.``Token
Bases: object

identifier= ''

virttest.cartesian_config.``apply_predict(lexer, node, pre_dict)

virttest.cartesian_config.``cmd_tokens(tokens1, tokens2)

virttest.cartesian_config.``compare_string(str1, str2)
Compare two int string and return -1, 0, 1. It can compare two memory value even in sufix

Parameters:

  • str1 – The first string
  • str2 – The second string

Return:

Rteurn -1, when str1< str2 0, when str1 = str2 1, when str1> str2

virttest.cartesian_config.``convert_data_size(size, default_sufix='B')
Convert data size from human readable units to an int of arbitrary size.

Parameters:

  • size – Human readable data size representation (string).
  • default_sufix – Default sufix used to represent data.

Returns:

Int with data size in the appropriate order of magnitude.

virttest.cartesian_config.``next_nw(gener)

virttest.cartesian_config.``parse_filter(lexer, tokens)
Returns:

Parsed filter

virttest.cartesian_config.``postfix_parse(dic)

virttest.cartesian_config.``print_dicts(options, dicts)

virttest.cartesian_config.``print_dicts_default(options, dicts)
Print dictionaries in the default mode

virttest.cartesian_config.``print_dicts_repr(options, dicts)

virttest.ceph module

CEPH Support This file has the functions that helps * To create rbd pool * To map/unmap rbd pool * To mount/umount cephfs to localhost * To return rbd uri which can be used as disk image file path.

exceptionvirttest.ceph.``CephError
Bases: exceptions.Exception

virttest.data_dir module

Library used to provide the appropriate data dir for virt test.

exceptionvirttest.data_dir.``MissingDepsDirError
Bases: exceptions.Exception

classvirttest.data_dir.``SubdirGlobList(basedir, globstr, filterlist=None)
Bases: virttest.data_dir.SubdirList

List of all files matching glob in all non-hidden basedir subdirectories

classvirttest.data_dir.``SubdirList(basedir, filterlist=None)
Bases: list

List of all non-hidden subdirectories beneath basedir

exceptionvirttest.data_dir.``UnknownBackendError(backend)
Bases: exceptions.Exception

virttest.data_dir.``clean_tmp_files()

virttest.data_dir.``get_backend_cfg_path(backend_type, cfg_basename)

virttest.data_dir.``get_backend_dir(backend_type)

virttest.data_dir.``get_backing_data_dir()

virttest.data_dir.``get_base_backend_dir()

virttest.data_dir.``get_base_download_dir()

virttest.data_dir.``get_base_test_providers_dir()

virttest.data_dir.``get_data_dir()

virttest.data_dir.``get_deps_dir(target=None)
For a given test provider, report the appropriate deps dir.

The little inspect trick is used to avoid callers having to do sys.modules[] tricks themselves.

Parameters:

target – File we want in deps folder. Will return the path to the target if set and available. Or will only return the path to dep folder.

virttest.data_dir.``get_download_dir()

virttest.data_dir.``get_local_backend_dir()

virttest.data_dir.``get_root_dir()

virttest.data_dir.``get_shared_dir()

virttest.data_dir.``get_test_provider_dir(provider)
Return a specific test providers dir, inside the base dir.

virttest.data_dir.``get_test_providers_dir()
Return the base test providers dir (at the moment, test-providers.d).

virttest.data_dir.``get_tmp_dir(public=True)
Get the most appropriate tmp dir location.

Parameters:

public – If public for all users’ access

virttest.defaults module

virttest.defaults.``get_default_guest_os_info()
Gets the default asset and variant information TODO: Check for the ARCH and choose corresponding default asset

virttest.element_path module

classvirttest.element_path.``Path(path)
find(element)

findall(element)

findtext(element, default=None)

virttest.element_path.``find(element, path)

virttest.element_path.``findall(element, path)

virttest.element_path.``findtext(element, path, default=None)

classvirttest.element_path.``xpath_descendant_or_self

virttest.element_path.``xpath_tokenizer()
findall(string[, pos[, endpos]]) –> list. Return a list of all non-overlapping matches of pattern in string.

virttest.element_tree module

virttest.element_tree.``Comment(text=None)

virttest.element_tree.``dump(elem)

virttest.element_tree.``Element(tag, attrib={}, **extra)

classvirttest.element_tree.``ElementTree(element=None, file=None)
Bases: object

find(path)

findall(path)

findtext(path, default=None)

getiterator(tag=None)

getroot()

parse(source, parser=None)

write(file, encoding='us-ascii')

virttest.element_tree.``fromstring(text)

virttest.element_tree.``iselement(element)

classvirttest.element_tree.``iterparse(source, events=None)
Bases: object

next()

virttest.element_tree.``parse(source, parser=None)

virttest.element_tree.``PI(target, text=None)

virttest.element_tree.``ProcessingInstruction(target, text=None)

classvirttest.element_tree.``QName(text_or_uri, tag=None)
Bases: object

virttest.element_tree.``SubElement(parent, tag, attrib={}, text=None, **extra)

virttest.element_tree.``tostring(element, encoding=None)

classvirttest.element_tree.``TreeBuilder(element_factory=None)
Bases: object

close()

data(data)

end(tag)

start(tag, attrs)

virttest.element_tree.``XML(text)

virttest.element_tree.``XMLParser
alias of XMLTreeBuilder

classvirttest.element_tree.``XMLTreeBuilder(html=0, target=None)
Bases: object

close()

doctype(name, pubid, system)

feed(data)

virttest.env_process module

virttest.env_process.``postprocess_image(test, params, image_name, vm_process_status=None)
Postprocess a single QEMU image according to the instructions in params.

Parameters:

  • test – An Autotest test object.
  • params – A dict containing image postprocessing parameters.
  • vm_process_status – (optional) vm process status like running, dead or None for no vm exist.

virttest.env_process.``postprocess_on_error(test, params, env)
Perform postprocessing operations required only if the test failed.

Parameters:

  • test – An Autotest test object.
  • params – A dict containing all VM and image parameters.
  • env – The environment (a dict-like object).

virttest.env_process.``postprocess_vm(test, params, env, name)
Postprocess a single VM object according to the instructions in params. Kill the VM if requested and get a screendump.

Parameters:

  • test – An Autotest test object.
  • params – A dict containing VM postprocessing parameters.
  • env – The environment (a dict-like object).
  • name – The name of the VM object.

virttest.env_process.``preprocess_image(test, params, image_name, vm_process_status=None)
Preprocess a single QEMU image according to the instructions in params.

Parameters:

  • test – Autotest test object.
  • params – A dict containing image preprocessing parameters.
  • vm_process_status – This is needed in postprocess_image. Add it here only for keep it work with process_images()

Note:

Currently this function just creates an image if requested.

virttest.env_process.``preprocess_vm(test, params, env, name)
Preprocess a single VM object according to the instructions in params. Start the VM if requested and get a screendump.

Parameters:

  • test – An Autotest test object.
  • params – A dict containing VM preprocessing parameters.
  • env – The environment (a dict-like object).
  • name – The name of the VM object.

virttest.env_process.``process(test, params, env, image_func, vm_func, vm_first=False)
Pre- or post-process VMs and images according to the instructions in params. Call image_func for each image listed in params and vm_func for each VM.

Parameters:

  • test – An Autotest test object.
  • params – A dict containing all VM and image parameters.
  • env – The environment (a dict-like object).
  • image_func – A function to call for each image.
  • vm_func – A function to call for each VM.
  • vm_first – Call vm_func first or not.

virttest.env_process.``process_command(test, params, env, command, command_timeout, command_noncritical)
Pre- or post- custom commands to be executed before/after a test is run

Parameters:

  • test – An Autotest test object.
  • params – A dict containing all VM and image parameters.
  • env – The environment (a dict-like object).
  • command – Command to be run.
  • command_timeout – Timeout for command execution.
  • command_noncritical – If True test will not fail if command fails.

virttest.env_process.``process_images(image_func, test, params, vm_process_status=None)
Wrapper which chooses the best way to process images.

Parameters:

  • image_func – Process function
  • test – An Autotest test object.
  • params – A dict containing all VM and image parameters.
  • vm_process_status – (optional) vm process status like running, dead or None for no vm exist.

virttest.env_process.``store_vm_register(vm, log_filename, append=False)
Store the register information of vm into a log file

Parameters:

  • vm (vm object) – VM object
  • log_filename (string) – log file name
  • append (bool) – Add the log to the end of the log file or not

Returns:

Store the vm register information to log file or not

Return type:

bool

virttest.error_context module

virttest.error_context.``format_error()

virttest.error_context.``context_aware(fn)
A decorator that must be applied to functions that call context().

virttest.error_context.``context(s='', log=None)
Set the context for the currently executing function and optionally log it.

Parameters:

  • s – A string. If not provided, the context for the current function will be cleared.
  • log – A logging function to pass the context message to. If None, no function will be called.

virttest.error_context.``get_context()
Return the current context (or None if none is defined).

virttest.error_context.``exception_context(e)
Return the context of a given exception (or None if none is defined).

virttest.funcatexit module

funcatexit.py - allow programmer to define multiple exit functions to be executed upon normal cases termination. Can be used for the environment clean up functions. The basic idea is like atexit from python libs.

virttest.funcatexit.``register(env, test_type, func, *targs, **kargs)
Register a function to be executed upon case termination. func is returned to facilitate usage as a decorator.

param env: the global objects used by tests param test_type: test type mark for exit functions param func: function to be called at exit param targs: optional arguments to pass to func param kargs: optional keyword arguments to pass to func

virttest.funcatexit.``run_exitfuncs(env, test_type)
Run any registered exit functions. exithandlers is traversed in reverse order so functions are executed last in, first out.

param env: the global objects used by tests param test_type: test type mark for exit functions

virttest.funcatexit.``unregister(env, test_type, func, *targs, **kargs)
Unregister a function to be executed upon case termination. func is returned to facilitate usage as a decorator.

param env: the global objects used by tests param test_type: test type mark for exit functions param func: function to be called at exit param targs: optional arguments to pass to func param kargs: optional keyword arguments to pass to func

virttest.gluster module

GlusterFS Support This file has the functions that helps * To create/check gluster volume. * To start/check gluster services. * To create gluster uri which can be used as disk image file path.

exceptionvirttest.gluster.``GlusterBrickError(error_mgs)
Bases: virttest.gluster.GlusterError

exceptionvirttest.gluster.``GlusterError
Bases: exceptions.Exception

virttest.gluster.``add_rpc_insecure(filepath)
Allow glusterd RPC authority insecure

virttest.gluster.``file_exists(params, filename_path)

virttest.gluster.``get_image_filename(params, image_name, image_format)
Form the image file name using gluster uri

virttest.gluster.``gluster_brick_create(brick_path, force=False)
Creates brick

virttest.gluster.``gluster_brick_delete(brick_path)
Creates brick

virttest.gluster.``glusterfs_mount(g_uri, mount_point)
Mount gluster volume to mountpoint.

Parameters:

g_uri (str) – stripped gluster uri from create_gluster_uri(.., True)

virttest.guest_agent module

Interfaces to the virt agent.

copyright:

2008-2012 Red Hat Inc.

classvirttest.guest_agent.``QemuAgent(vm, name, serial_type, serial_filename, get_supported_cmds=False, suppress_exceptions=False)
Bases: virttest.qemu_monitor.Monitor

Wraps qemu guest agent commands.

Connect to the guest agent socket, Also make sure the json module is available.

Parameters:

  • vm – The VM object who has this GuestAgent.
  • name – Guest agent identifier.
  • serial_type – Specific which serial type (firtio or isa) guest agent will use.
  • serial_filename – Guest agent socket filename.
  • get_supported_cmds – Try to get supported cmd list when initiation.
  • suppress_exceptions – If True, ignore VAgentError exception.

Raises:

CMD_TIMEOUT= 20

FSFREEZE_STATUS_FROZEN= 'frozen'

FSFREEZE_STATUS_THAWED= 'thawed'

PROMPT_TIMEOUT= 20

READ_OBJECTS_TIMEOUT= 5

RESPONSE_TIMEOUT= 20

SERIAL_TYPE_ISA= 'isa'

SERIAL_TYPE_VIRTIO= 'virtio'

SHUTDOWN_MODE_HALT= 'halt'

SHUTDOWN_MODE_POWERDOWN= 'powerdown'

SHUTDOWN_MODE_REBOOT= 'reboot'

SUPPORTED_SERIAL_TYPE= ['virtio', 'isa']

SUSPEND_MODE_DISK= 'disk'

SUSPEND_MODE_HYBRID= 'hybrid'

SUSPEND_MODE_RAM= 'ram'

check_has_command(cmd)
Check wheter guest agent support ‘cmd’.

Parameters:

cmd – command string which will be checked.

Returns:

True if cmd is supported, False if not supported.

cmd(cmd, args=None, timeout=20, debug=True, success_resp=True)
Send a guest agent command and return the response if success_resp.

Parameters:

  • cmd – Command to send
  • args – A dict containing command arguments, or None
  • timeout – Time duration to wait for response
  • debug – Whether to print the commands being sent and responses
  • fd – file object or file descriptor to pass

Returns:

The response received

Raises:

cmd_obj(obj, timeout=20)
Transform a Python object to JSON, send the resulting string to the guest agent, and return the response. Unlike cmd(), return the raw response dict without performing any checks on it.

Parameters:

  • obj – The object to send
  • timeout – Time duration to wait for response

Returns:

The response received

Raises:

cmd_raw(data, timeout=20, success_resp=True)
Send a raw string to the guest agent and return the response. Unlike cmd(), return the raw response dict without performing any checks on it.

Parameters:

  • data – The data to send
  • timeout – Time duration to wait for response

Returns:

The response received

Raises:

fsfreeze(*args, **kwargs)
Freeze File system on guest.

Parameters:

check_status – Force this function to check the fsreeze status before/after sending cmd.

Returns:

Frozen FS number if cmd succeed, -1 if guest agent doesn’t support fsfreeze cmd.

fsthaw(*args, **kwargs)
Thaw File system on guest.

Parameters:

check_status – Force this function to check the fsreeze status before/after sending cmd.

Returns:

Thaw FS number if cmd succeed, -1 if guest agent doesn’t support fsfreeze cmd.

fstrim(*args, **kwargs)
Discard unused blocks on a mounted filesystem by guest agent operation

get_fsfreeze_status()
Get guest ‘fsfreeze’ status. The status could be ‘frozen’ or ‘thawed’.

get_network_interface(*args, **kwargs)
Get the network interfaces of the guest by guest agent operation

get_time(*args, **kwargs)
Get the time of guest, return the time from Epoch of 1970-01-01 in UTC in nanoseconds

get_vcpus(*args, **kwargs)
Get the vcpus infomation

guest_info(*args, **kwargs)
Send “guest-info”, return all supported cmds.

set_time(*args, **kwargs)
set the time of guest, the params passed in is in nanoseconds

set_user_password(*args, **kwargs)
Set the new password for the user

set_vcpus(*args, **kwargs)
Set the status of vcpus, bring up/down the vcpus following action

shutdown(*args, **kwargs)
Send “guest-shutdown”, this cmd would not return any response.

Parameters:

mode – Speicfy shutdown mode, now qemu guest agent supports ‘powerdown’, ‘reboot’, ‘halt’ 3 modes.

Returns:

True if shutdown cmd is sent successfully, False if ‘shutdown’ is unsupported.

suspend(*args, **kwargs)
This function tries to execute the scripts provided by the pm-utils package via guest agent interface. If it’s not available, the suspend operation will be performed by manually writing to a sysfs file.

Notes:

  1. For the best results it’s strongly recommended to have the pm-utils package installed in the guest.
  2. The ram and ‘hybrid’ mode require QEMU to support the system_wakeup command. Thus, it’s required to query QEMU for the presence of the system_wakeup command before issuing guest agent command.

Parameters:

mode – Specify suspend mode, could be one of disk, ram, hybrid.

Returns:

True if shutdown cmd is sent successfully, False if suspend is unsupported.

Raises:

VAgentSuspendUnknownModeError – Raise if mode is not supported.

sync(*args, **kwargs)
Sync guest agent with cmd ‘guest-sync’ or ‘guest-sync-delimited’.

verify_fsfreeze_status(expected)
Verify the guest agent fsfreeze status is same as expected, if not, raise a VAgentFreezeStatusError.

Parameters:

expected – The expected status.

Raises:

VAgentFreezeStatusError – Raise if the guest fsfreeze status is unexpected.

verify_responsive()
Make sure the guest agent is responsive by sending a command.

exceptionvirttest.guest_agent.``VAgentCmdError(cmd, args, data)
Bases: virttest.guest_agent.VAgentError

exceptionvirttest.guest_agent.``VAgentCmdNotSupportedError(cmd)
Bases: virttest.guest_agent.VAgentError

exceptionvirttest.guest_agent.``VAgentConnectError
Bases: virttest.guest_agent.VAgentError

exceptionvirttest.guest_agent.``VAgentError
Bases: virttest.qemu_monitor.MonitorError

exceptionvirttest.guest_agent.``VAgentFreezeStatusError(vm_name, status, expected)
Bases: virttest.guest_agent.VAgentError

exceptionvirttest.guest_agent.``VAgentLockError
Bases: virttest.guest_agent.VAgentError

exceptionvirttest.guest_agent.``VAgentNotSupportedError
Bases: virttest.guest_agent.VAgentError

exceptionvirttest.guest_agent.``VAgentProtocolError
Bases: virttest.guest_agent.VAgentError

exceptionvirttest.guest_agent.``VAgentSocketError(msg, e)
Bases: virttest.guest_agent.VAgentError

exceptionvirttest.guest_agent.``VAgentSuspendError
Bases: virttest.guest_agent.VAgentError

exceptionvirttest.guest_agent.``VAgentSuspendUnknownModeError(mode)
Bases: virttest.guest_agent.VAgentSuspendError

exceptionvirttest.guest_agent.``VAgentSyncError(vm_name)
Bases: virttest.guest_agent.VAgentError

virttest.http_server module

classvirttest.http_server.``HTTPRequestHandler(request, client_address, server)
Bases: SimpleHTTPServer.SimpleHTTPRequestHandler

address_string()
This HTTP server does not care about name resolution for the requests

The first reason is that most of the times our clients are going to be virtual machines without a proper name resolution setup. Also, by not resolving names, we should be a bit faster and be resilient about misconfigured or resilient name servers.

copyfile_range(source_file, output_file, range_begin, range_end)
Copies a range of a file to destination.

do_GET()
Serve a GET request.

log_message(fmt, *args)

parse_header_byte_range()

send_head_range(range_begin, range_end)

translate_path(path)
Translate a /-separated PATH to the local filename syntax.

Components that mean special things to the local file system (e.g. drive or directory names) are ignored. (XXX They should probably be diagnosed.)

virttest.http_server.``http_server(port=8000, cwd=None, terminate_callable=None)

virttest.installer module

Installer classes are responsible for building and installing virtualization specific software components. This is the main entry point for tests that wish to install virtualization software components.

The most common use case is to simply call make_installer() inside your tests.

classvirttest.installer.``InstallerRegistry(**kwargs)
Bases: dict

Holds information on known installer classes

This class is used to create a single instance, named INSTALLER_REGISTRY, that will hold all information on known installer types.

For registering a new installer class, use the register() method. If the virt type is not set explicitly, it will be set to ‘base’. Example:

>>> INSTALLER_REGISTRY.register('yum', base_installer.YumInstaller)

If you want to register a virt specific installer class, set the virt (third) param:

>>> INSTALLER_REGISTRY.register('yum', qemu_installer.YumInstaller, 'qemu')

For getting a installer class, use the get_installer() method. This method has a fallback option ‘get_default_virt’ that will return a generic virt installer if set to true.

DEFAULT_VIRT_NAME= 'base'

get_installer(mode, virt=None, get_default_virt=False)
Gets a installer class that should be able to install the virt software

Always try to use classes that are specific to the virtualization technology that is being tested. If you have confidence that the installation is rather trivial and does not require custom steps, you may be able to get away with a base class (by setting get_default_virt to True).

get_modes(virt=None)
Returns a list of all registered installer modes

register(mode, klass, virt=None)
Register a class as responsible for installing virt software components

If virt is not set, it will assume a default of ‘base’.

virttest.installer.``make_installer(fullname, params, test=None)
Installer factory: returns a new installer for the chosen mode and vm type

This is the main entry point for acquiring an installer. Tests, such as the build test, should use this function.

Param priority evaluation order is ‘install_mode’, then ‘mode’. For virt type, ‘vm_type’ is consulted.

Parameters:

  • fullname – the full name of instance, eg: git_repo_foo
  • params – dictionary with parameters generated from cartersian config
  • test – the test instance

virttest.installer.``run_installers(params, test=None)
Runs the installation routines for all installers, one at a time

This is usually the main entry point for tests

virttest.iscsi module

Basic iscsi support for Linux host with the help of commands iscsiadm and tgtadm.

This include the basic operates such as login and get device name by target name. And it can support the real iscsi access and emulated iscsi in localhost then access it.

classvirttest.iscsi.``Iscsi
Bases: object

Basic iSCSI support class, which will handle the emulated iscsi export and access to both real iscsi and emulated iscsi device.

The class support different kinds of iSCSI backend (TGT and LIO), and return ISCSI instance.

staticcreate_iSCSI(params, root_dir='/tmp/avocado_Wt9Uw4')

classvirttest.iscsi.``IscsiLIO(params, root_dir)
Bases: virttest.iscsi._IscsiComm

iscsi support class for LIO backend used in RHEL7.

initialize LIO backend for iSCSI

Parameters:

params – parameters dict for LIO backend of iSCSI

delete_target()
Delete target from host.

export_target()
Export target in localhost for emulated iscsi

get_target_id()
Get target id from image name.

set_chap_acls_target()
set CHAP(acls) authentication on a target. it will require authentication before an initiator is allowed to log in and access devices.

notice:
Individual ACL entries override common TPG Authentication, which can be set by set_chap_auth_target().

set_chap_auth_target()
set up authentication information for every single initiator, which provides the capability to define common login information for all Endpoints in a TPG

classvirttest.iscsi.``IscsiTGT(params, root_dir)
Bases: virttest.iscsi._IscsiComm

iscsi support TGT backend used in RHEL6.

initialize TGT backend for iSCSI

Parameters:

params – parameters dict for TGT backend of iSCSI.

add_chap_account()
Add CHAP authentication account

delete_chap_account()
Delete the CHAP authentication account

delete_target()
Delete target from host.

export_target()
Export target in localhost for emulated iscsi

get_chap_accounts()
Get all CHAP authentication accounts

get_target_account_info()
Get the target account information

get_target_id()
Get target id from image name. Only works for emulated iscsi device

set_chap_auth_target()
Set CHAP authentication on a target, it will require authentication before an initiator is allowed to log in and access devices.

virttest.iscsi.``iscsi_discover(portal_ip)
Query from iscsi server for available targets

Parameters:

portal_ip – Ip for iscsi server

virttest.iscsi.``iscsi_get_nodes()
Get the iscsi nodes

virttest.iscsi.``iscsi_get_sessions()
Get the iscsi sessions activated

virttest.iscsi.``iscsi_login(target_name, portal)
Login to a target with the target name

Parameters:

target_name – Name of the target

Params portal:

Hostname/Ip for iscsi server

virttest.iscsi.``iscsi_logout(target_name=None)
Logout from a target. If the target name is not set then logout all targets.

Params target_name:

 

Name of the target.

virttest.iscsi.``iscsi_node_del(target_name=None)
Delete target node record, if the target name is not set then delete all target node records.

Params target_name:

 

Name of the target.

virttest.iscsi.``restart_iscsid(reset_failed=True)
Restart iscsid service.

virttest.iscsi.``restart_tgtd(reset_failed=True)
Restart tgtd service.

virttest.libvirt_storage module

Classes and functions to handle block/disk images for libvirt.

This exports:

  • two functions for get image/blkdebug filename
  • class for image operates and basic parameters
  • class for storage pool operations

classvirttest.libvirt_storage.``PoolVolume(pool_name, virsh_instance=<module 'virttest.virsh' from '/tmp/avocado-vt/virttest/virsh.py'>)
Bases: object

Volume Manager for libvirt storage pool.

clone_volume(old_name, new_name)
Clone a volume

create_volume(name, capability, allocation=None, frmt=None)
Create a volume in pool.

delete_volume(name)
Remove a volume.

list_volumes()
Return a dict include volumes’ name(key) and path(value).

volume_exists(name)

volume_info(name)
Get volume’s information with command vol-info.

classvirttest.libvirt_storage.``QemuImg(params, root_dir, tag)
Bases: virttest.storage.QemuImg

libvirt class for handling operations of disk/block images.

Init the default value for image object.

Parameters:

  • params – Dictionary containing the test parameters.
  • root_dir – Base directory for relative filenames.
  • tag – Image tag defined in parameter images.

check_image(params, root_dir)
Check an image using the appropriate tools for each virt backend.

Parameters:

  • params – Dictionary containing the test parameters.
  • root_dir – Base directory for relative filenames.

Note:

params should contain:

Raises:

VMImageCheckError – In case qemu-img check fails on the image.

commit()
Commit image to it’s base file

convert(params, root_dir)
Convert image

Parameters:

  • params – A dict
  • root_dir – dir for save the convert image

Note:

params should contain:

create(params)
Create an image.

Parameters:

params – Dictionary containing the test parameters.

Note:

params should contain:

rebase(params)
Rebase image

Parameters:

params – A dict

Note:

params should contain:

remove()
Remove an image file.

Note:

params should contain:

snapshot_create()
Create a snapshot image.

Note:

params should contain:

snapshot_del(blkdebug_cfg='')
Delete a snapshot image.

Parameters:

blkdebug_cfg – The configure file of blkdebug

Note:

params should contain: snapshot_image_name – the name of snapshot image file

classvirttest.libvirt_storage.``StoragePool(virsh_instance=<module 'virttest.virsh' from '/tmp/avocado-vt/virttest/virsh.py'>)
Bases: object

Pool Manager for libvirt storage with virsh commands

build_pool(name)
Build pool.

define_dir_pool(name, target_path)
Define a directory type pool.

define_disk_pool(name, block_device, target_path)
Define a disk type pool.

define_fs_pool(name, block_device, target_path)
Define a filesystem type pool.

define_iscsi_pool(name, source_host, source_dev, target_path)
Define a iscsi type pool.

define_lvm_pool(name, block_device, vg_name, target_path)
Define a lvm type pool.

define_netfs_pool(name, source_host, source_path, target_path)
Define a netfs type pool.

define_rbd_pool(name, source_host, source_name, extra='')
Define a rbd type pool.

delete_pool(name)
Destroy and Delete a pool if it exists on given libvirt

It’s reasonable to delete a pool by calling pool-delete. However, due to pool-delete operation is non-recoverable. Redhat suggests to achieve this objective by virsh, 1) virsh pool-destroy pool-name 2) virsh pool-undefine pool-name

Please refer to the following URI for more details. https://access.redhat.com/documentation/en-US /Red_Hat_Enterprise_Linux/6/html /Virtualization_Administration_Guide /chap-Virtualization_Administration_Guide -Storage_Pools-Storage_Pools.html#delete-ded-disk-storage-pool

destroy_pool(name)
Destroy pool if it is active.

get_pool_uuid(name)
Get pool’s uuid.

Returns:

Pool uuid.

is_pool_active(name)
Check whether pool is active on given libvirt

is_pool_persistent(name)
Check whether pool is persistent

list_pools()
Return a dict include pools’ information with structure:
pool_name ==> pool_details(a dict: feature ==> value)

pool_exists(name)
Check whether pool exists on given libvirt

pool_info(name)
Get pool’s information.

Returns:

A dict include pool’s information: Name ==> value UUID ==> value ...

pool_state(name)
Get pool’s state.

Returns:

active/inactive, and None when something wrong.

set_pool_autostart(name, extra='')
Set given pool as autostart

start_pool(name)
Start pool if it is inactive.

virttest.libvirt_vm module

Utility classes and functions to handle Virtual Machine creation using libvirt.

copyright:

2011 Red Hat Inc.

classvirttest.libvirt_vm.``VM(name, params, root_dir, address_cache, state=None)
Bases: virttest.virt_vm.BaseVM

This class handles all basic VM operations for libvirt.

Initialize the object and set a few attributes.

Parameters:

  • name – The name of the object
  • params – A dict containing VM params (see method make_create_command for a full description)
  • root_dir – Base directory for relative filenames
  • address_cache – A dict that maps MAC addresses to IP addresses
  • state – If provided, use this as self.__dict__

activate_nic(nic_index_or_name)

attach_disk(source, target=None, prefix='vd', extra='', ignore_status=False, debug=False)
Attach a disk to VM and return the target device name.

Parameters:

  • source – source of disk device
  • target – target of disk device, None for automatic assignment.
  • prefix – disk device prefix.
  • extra – additional arguments to command

Returns:

target device name if succeed, Otherwise None

attach_interface(option='', ignore_status=False, debug=False)
Attach a NIC to VM.

backup_xml(active=False)
Backup the guest’s xmlfile.

cleanup_serial_console()
Close serial console and associated log file

cleanup_swap()
Cleanup environment changed by create_swap_partition() or create_swap_file().

clone(name=None, params=None, root_dir=None, address_cache=None, copy_state=False)
Return a clone of the VM object with optionally modified parameters. The clone is initially not alive and needs to be started using create(). Any parameters not passed to this function are copied from the source VM.

Parameters:

  • name – Optional new VM name
  • params – Optional new VM creation parameters
  • root_dir – Optional new base directory for relative filenames
  • address_cache – A dict that maps MAC addresses to IP addresses
  • copy_state – If True, copy the original VM’s state to the clone. Mainly useful for make_create_command().

create(*args, **kwargs)
Start the VM by running a qemu command. All parameters are optional. If name, params or root_dir are not supplied, the respective values stored as class attributes are used.

Parameters:

  • name – The name of the object
  • params – A dict containing VM params
  • root_dir – Base directory for relative filenames
  • migration_mode – If supplied, start VM for incoming migration using this protocol (either ‘tcp’, ‘unix’ or ‘exec’)
  • migration_exec_cmd – Command to embed in ‘-incoming “exec: ...”’ (e.g. ‘gzip -c -d filename’) if migration_mode is ‘exec’
  • mac_source – A VM object from which to copy MAC addresses. If not specified, new addresses will be generated.

Raises:

create_serial_console()
Establish a session with the serial console.

The libvirt version uses virsh console to manage it.

create_swap_file(swapfile='/swapfile')
Make a swap file and active it through a session.

A cleanup_swap() should be call after use to clean up the environment changed.

Parameters:

swapfile – Swap file path in VM to be created.

create_swap_partition(swap_path=None)
Make a swap partition and active it.

A cleanup_swap() should be call after use to clean up the environment changed.

Parameters:

swap_path – Swap image path.

deactivate_nic(nic_index_or_name)

define(xml_file)
Define the VM.

destroy(gracefully=True, free_mac_addresses=True)
Destroy the VM.

If gracefully is True, first attempt to shutdown the VM with a shell command. If that fails, send SIGKILL to the qemu process.

Parameters:

  • gracefully – If True, an attempt will be made to end the VM using a shell command before trying to end the qemu process with a ‘quit’ or a kill signal.
  • free_mac_addresses – If vm is undefined with libvirt, also release/reset associated mac address

detach_disk(target, extra='', ignore_status=False, debug=False)
Detach a disk from VM.

Parameters:

  • target – target of disk device need to be detached.
  • extra – additional arguments to command

detach_interface(option='', ignore_status=False, debug=False)
Detach a NIC from VM.

dominfo()
Return a dict include vm’s information.

domjobabort()
Abort job for vm.

dump(path, option='')
Dump self to path.

Raise:

exceptions.TestFail if dump fail.

exists()
Return True if VM exists.

get_blk_devices()
Get vm’s block devices.

Return a dict include all devices detail info. example: {target: {‘type’: value, ‘device’: value, ‘source’: value}}

get_cpu_topology_in_cmdline()
Return the VM’s cpu topology in VM cmdline.

Returns:

A dirt of cpu topology

get_cpu_topology_in_vm()

get_device_details(device_target)

get_device_size(device_target)

get_disk_devices()
Get vm’s disk type block devices.

get_disks(diskname=None)
Get disks in vm.

Parameters:

diskname – Specify disk to be listed, used for checking given disk.

get_distro()
Get distribution name of the vm instance.

get_first_disk_devices()
Get vm’s first disk type block devices.

get_id()
Return VM’s ID.

get_ifname(nic_index=0)

get_interface_mac(interface)
Get mac address of interface by given name.

get_interfaces()
Get available interfaces in vm.

get_job_type()

get_max_mem()
Get vm’s maximum memory(kilobytes).

get_pci_devices(device_str=None)
Get PCI devices in vm accroding to given device character.

Parameters:

device_str – a string to identify device.

get_pid()
Return the VM’s PID.

Returns:

int with PID. If VM is not alive, returns None.

get_serial_console_filename(name)
Return the serial console filename.

Parameters:

name – The serial port name.

get_serial_console_filenames()
Return a list of all serial console filenames (as specified in the VM’s params).

get_shared_meminfo()
Returns the VM’s shared memory information.

Returns:

Shared memory used by VM (MB)

get_shell_pid()
Return the PID of the parent shell process.

Note:

This works under the assumption that self.process.get_pid() returns the PID of the parent shell process.

get_used_mem()
Get vm’s current memory(kilobytes).

get_uuid()
Return VM’s UUID.

get_vcpus_pid()
Return the vcpu’s pid for a given VM.

Returns:

list of PID of vcpus of a VM.

get_virsh_mac_address(nic_index=0)
Get the MAC of this VM domain.

Parameters:

nic_index – Index of the NIC

Raises:

VMMACAddressMissingError – If no MAC address is defined for the requested NIC

get_xml()
Return VM’s xml file.

getenforce()
Set SELinux mode in the VM.

Returns:

SELinux mode [Enforcing|Permissive|Disabled]

has_swap()
Check if there is any active swap partition/file.

:return : True if swap is on or False otherwise.

install_package(name)
Install a package on VM. ToDo: Support multiple package manager.

Parameters:

name – Name of package to be installed

is_alive()
Return True if VM is alive.

is_autostart()
Return True if VM is autostart.

is_dead()
Return True if VM is dead.

is_esx()
Return True if VM is a esx guest.

is_lxc()
Return True if VM is linux container.

is_paused()
Return True if VM is paused.

is_persistent()
Return True if VM is persistent.

is_qemu()
Return True if VM is a qemu guest.

is_xen()
Return True if VM is a xen guest.

make_create_command(name=None, params=None, root_dir=None)
Generate a libvirt command line. All parameters are optional. If a parameter is not supplied, the corresponding value stored in the class attributes is used.

Parameters:

  • name – The name of the object
  • params – A dict containing VM params
  • root_dir – Base directory for relative filenames

Note:

The params dict should contain: mem – memory size in MBs cdrom – ISO filename to use with the qemu -cdrom parameter extra_params – a string to append to the qemu command shell_port – port of the remote shell daemon on the guest (SSH, Telnet or the home-made Remote Shell Server) shell_client – client program to use for connecting to the remote shell daemon on the guest (ssh, telnet or nc) x11_display – if specified, the DISPLAY environment variable will be be set to this value for the qemu process (useful for SDL rendering) images – a list of image object names, separated by spaces nics – a list of NIC object names, separated by spaces

For each image in images: drive_format – string to pass as ‘if’ parameter for this image (e.g. ide, scsi) image_snapshot – if yes, pass ‘snapshot=on’ to qemu for this image image_boot – if yes, pass ‘boot=on’ to qemu for this image In addition, all parameters required by get_image_filename.

For each NIC in nics: nic_model – string to pass as ‘model’ parameter for this NIC (e.g. e1000)

managedsave()
Managed save of VM’s state

migrate(dest_uri='', option='--live --timeout 60', extra='', ignore_status=False, debug=False)
Migrate a VM to a remote host.

Parameters:

  • dest_uri – Destination libvirt URI
  • option – Migration options before <domain> <desturi>
  • extra – Migration options after <domain> <desturi>

Returns:

True if command succeeded

pause()

pmsuspend(target='mem', duration=0)
Suspend a domain gracefully using power management functions

pmwakeup()
Wakeup a domain from pmsuspended state

prepare_guest_agent(prepare_xml=True, channel=True, start=True)
Prepare qemu guest agent on the VM.

Parameters:

  • prepare_xml – Whether change VM’s XML
  • channel – Whether add agent channel in VM. Only valid if prepare_xml is True
  • start – Whether install and start the qemu-ga service

reboot(*args, **kwargs)
Reboot the VM and wait for it to come back up by trying to log in until timeout expires.

Parameters:

  • session – A shell session object or None.
  • method – Reboot method. Can be “shell” (send a shell reboot command).
  • nic_index – Index of NIC to access in the VM, when logging in after rebooting.
  • timeout – Time to wait for login to succeed (after rebooting).
  • serial – Just use to unify api in virt_vm module.

Returns:

A new shell session object.

remove()

remove_package(name)
Remove a package from VM. ToDo: Support multiple package manager.

Parameters:

name – Name of package to be removed

remove_with_storage()
Virsh undefine provides an option named –remove-all-storage, but it only removes the storage which is managed by libvirt.

This method undefines vm and removes the all storages related with this vm, no matter storages are managed by libvirt or not.

restore_from_file(path)
Override BaseVM restore_from_file method

resume()

save_to_file(path)
Override BaseVM save_to_file method

screendump(filename, debug=False)

set_boot_kernel(index, debug_kernel=False)
Set default kernel to the second one or to debug kernel

Parameters:

  • index – index of kernel to set to default
  • debug_kernel – True if set debug kernel to default

Returns:

default kernel

set_console_getty(device, getty='mgetty', remove=False)
Set getty for given console device.

Parameters:

  • device – a console device
  • getty – getty type: agetty, mgetty and so on.
  • remove – do remove operation

set_kernel_console(device, speed=None, remove=False)
Set kernel parameter for given console device.

Parameters:

  • device – a console device
  • speed – speed of serial console
  • remove – do remove operation

set_kernel_param(parameter, value=None, remove=False)
Set a specific kernel parameter.

Parameters:

  • option – A kernel parameter to set.
  • value – The value of the parameter to be set.
  • remove – Remove the parameter if True.

Returns:

True if succeed of False if failed.

set_root_serial_console(device, remove=False)
Allow or ban root to login through serial console.

Parameters:

  • device – device to set root login
  • allow_root – do remove operation

setenforce(mode)
Set SELinux mode in the VM.

Parameters:

mode – SELinux mode [Enforcing|Permissive|1|0]

shutdown()
Shuts down this VM.

start(autoconsole=True)
Starts this VM.

state()
Return domain state.

undefine(options=None)
Undefine the VM.

vcpuinfo()
Return a dict’s list include vm’s vcpu information.

vcpupin(vcpu, cpu_list, options='')
To pin vcpu to cpu_list

verify_alive()
Make sure the VM is alive.

Raises:

VMDeadError – If the VM is dead

wait_for_login(nic_index=0, timeout=None, internal_timeout=None, serial=False, restart_network=False, username=None, password=None)
Override the wait_for_login method of virt_vm to support other guest in libvirt.

If connect_uri is lxc related, we call wait_for_serial_login() directly, without attempting login it via network.

Other connect_uri, call virt_vm.wait_for_login().

wait_for_shutdown(count=60)
Return True on successful domain shutdown.

Wait for a domain to shutdown, libvirt does not block on domain shutdown so we need to watch for successful completion.

Parameters:

  • name – VM name
  • name – Optional timeout value

virttest.libvirt_vm.``complete_uri(ip_address, protocol=None, port=None)
Return a complete URI with the combination of ip_address and local uri. It is useful when you need to connect remote hypervisor.

Parameters:

  • ip_address – an ip address or a hostname
  • protocol – protocol for uri eg: tcp, spice etc.
  • port – port for the protocol

Returns:

a complete uri

virttest.libvirt_vm.``get_uri_with_transport(uri_type='qemu', transport='', dest_ip='')
Return a URI to connect driver on dest with a specified transport.

Parameters:

  • origin_uri – The URI on dest used to connect itself directly.
  • transport – The transport type connect to dest.
  • dest_ip – The ip of destination.

virttest.libvirt_vm.``normalize_connect_uri(connect_uri)
Processes connect_uri Cartesian into something virsh can use

Parameters:

connect_uri – Cartesian Params setting

Returns:

Normalized connect_uri

virttest.lvm module

Base module for support lvm in qemu test;

For EmulatedLVM, no need any special configuration, lvm params will generate automatically. Of course, customizable params is accept; For real lvm partition, we need to specify some params, at lest, vg_name and it’s a real volume group on your host. If not, both pv_name and vg_name are required and a new volumegroup will be created on device named pv_name, But it will destroy data on your device and it’s not recommended;

Required params:
lv_name:
lv_name like /dev/vg/lv; If not params[“vg_name”] is requried and if lv_name not set, use guest_name as lv_name; device mapper path (eg, /dev/mapper/vg-lv) doesn’t support it now;

lv_size
string (eg, 30G) if not set image_size will be used;

vg_name
LogicalVolume group name, eg, “test_vg”;

pv_name
PhysicalVolume name eg, /dev/sdb or /dev/sdb1;

classvirttest.lvm.``EmulatedLVM(params, root_dir='/tmp/avocado_Wt9Uw4')
Bases: virttest.lvm.LVM

cleanup()
Cleanup created logical volumes;

get_emulate_image_name()

make_emulate_image()
Create emulate image via dd with 8M block size;

make_volume(img_file, extra_args='')
Map a file to loop back device;

Parameters:

img_file – image file path;

Returns:

loop back device name;

setup()
Main function to setup a lvm environments;

Returns:

LogicalVolume path

setup_pv(vg)
Setup physical volume device if exists return it directly;

classvirttest.lvm.``LVM(params)
Bases: object

cleanup()
Remove useless lv, vg and pv then reload lvm releated service;

generate_id(params)
Create prefix with image_name;

get_vol(vname, vtype)
Get a exists volume object;

Parameters:

  • vname – volume name;
  • vtype – volume type eg, ‘pvs’, ‘vgs’, ‘lvs’;

Returns:

Volume object or None;

register(vol)
Register new volume;

Parameters:

vol – Volume object or VolumeGroup objects

rescan()
Rescan lvm , used before create volume or after remove volumes;

setup()
Main function to setup a lvm environments;

Returns:

LogicalVolume path

setup_lv()
Setup a logical volume, if a exist logical volume resize it else then create it on specify volumegroup;

Parameters:

  • params**["lv_name"]****** – logical volume name;
  • params**["lv_name"]****** – logical volume size;

Returns:

logical volume object;

setup_pv(vg)
Create a physical volume devices;

Parameters:

  • params**["pv_name"]****** – Physical volume devices path or mount point;
  • vg – VolumeGroup object;

Returns:

list of PhysicalVolume object;

setup_vg(lv)
Setup logical volumegroup which specify on volumegroup specify by params[“vg_name”];

Parameters:

params**["vg_name"]****** – volumegroup name;

Returns:

volumegroup object;

unregister(vol)
Unregister volume or VolumeGroup;

Parameters:

vol – Volume object or VolumeGroup objects

classvirttest.lvm.``LogicalVolume(name, size, vg)
Bases: virttest.lvm.Volume

create()
Create LogicalVolume device;

Returns:

path of logical volume;

display(extra_args='')
Shown logical volume detials, warper of lvm command lvdisplay;

Extra_args:

extra argurments pass to lvdisplay command;

Raise:

CmdError when command exit code not equal 0;

get_attr(attr)
Get logical volume attribues if not found return None;

Parameters:

attr – attribue name;

Returns:

attribue value string or None;

Raise:

CmdError when command exit code not equal 0;

remove(extra_args='-ff --yes', timeout=300)
Remove LogicalVolume device;

Parameters:

  • extra_args – extra argurments pass to lvm command;
  • timeout – timeout in seconds;

resize(size, extra_args='-ff')
Resize LogicalVolume to new size;

Parameters:

  • size – new size of logical volume;
  • extra_args – extra argurments pass to lvm command;

Returns:

size of logical volume;

classvirttest.lvm.``PhysicalVolume(name, size)
Bases: virttest.lvm.Volume

create(extra_args='-ff --yes')
Create physical volume on specify physical volume;

Parameters:

extra_args – extra argurments for pvcreate command;

Raise:

CmdError or TestError;

Returns:

physical volume abspath

display()
Show physical volume detials

Raise:

CmdError

get_attr(attr)
Get attribue of physical volume, if not found return None;

Parameters:

attr – attribue name of the volume;

Returns:

string or None

remove(extra_args=' -ff --yes')
Remove a physical volume

Parameters:

extra_args – extra argurments for pvremove command

Raise:

CmdError

resize(size, extra_args='-ff --yes')
Resize a physical volume;

Parameters:

  • size – new size of the physical volume device;
  • extra_args – extra argurments for pvresize command;

set_vg(vg)
Set VolumeGroup of the physical volume device;

Parameters:

vg – VolumeGroup object

classvirttest.lvm.``Volume(name, size)
Bases: object

exists()
Check is the volume really exists or not;

get_attr(cmd, attr, res='[\\w/]+')
Get attribue of volume, if not found return None;

Parameters:

  • cmd – command used to display volume info;
  • attr – attribue name of the volume;
  • res – regular expression to reading the attribue;

Returns:

string or None

umount(extra_args='-f')
Unmount volume;

classvirttest.lvm.``VolumeGroup(name, size, pvs)
Bases: object

append_lv(lv)
Collect Logical Volumes on the VolumeGroup;

Parameters:

lv – LogicalVolume Object

create(extra_args='-ff --yes')
Create volume group with specify physical volumes;

Parameters:

extra_args – extra argurments for lvm command;

Raise:

CmdError or TestError;

Returns:

volume group name;

exists()
Check VolumeGroup exists or not;

Returns:

bool type, if exists True else False;

extend_pv(pv, extra_args='')
Add PhysicalVolume into VolumeGroup;

Parameters:

  • pv – PhysicalVolume object
  • extra_args – extra argurments used for vgextend command

get_attr(attr)
Get VolumeGroup attribue;

Parameters:

attr – attribue name;

Returns:

string or None;

reduce_pv(pv, extra_args='-ff --yes')
Reduce a PhysicalVolume from VolumeGroup;

Parameters:

  • pv – PhysicalVolume object;
  • extra_args – extra argurments pass to lvm command;

remove(extra_args='-ff --yes')
Remove the VolumeGroup;

Parameters:

extra_args – extra argurments for lvm command;

virttest.lvm.``cmd_output(cmd, res='[\\w/]+')

virttest.lvm.``normalize_data_size(size)

virttest.lvsb module

Higher order classes and functions for Libvirt Sandbox (lxc) container testing

copyright:

2013 Red Hat Inc.

classvirttest.lvsb.``TestBaseSandboxes(params, env)
Bases: virttest.lvsb_base.TestSandboxes

Simplistic sandbox aggregate manager

Initialize to run, all SandboxCommandBase’s

command_suffixes()
Append command after a –

results(each_timeout=5)
Run sandboxe(s), allowing each_timeout to complete, return output list

classvirttest.lvsb.``TestComplexSandboxes(params, env)
Bases: virttest.lvsb.TestBaseSandboxes

Executes a command with complex options

classvirttest.lvsb.``TestSimpleSandboxes(params, env)
Bases: virttest.lvsb.TestBaseSandboxes

Executes a command with simple options

Initialize to run, all SandboxCommandBase’s

virttest.lvsb.``make_sandboxes(params, env, extra_ns=None)
Return list of instantiated lvsb_testsandboxes classes from params

Parameters:

  • params – an undiluted Params instance
  • env – the current env instance
  • extra_ns – An extra, optional namespace to search for classes

virttest.lvsb_base module

Base classes supporting Libvirt Sandbox (lxc) container testing

copyright:

2013 Red Hat Inc.

classvirttest.lvsb_base.``SandboxBase(params)
Bases: object

Base operations for sandboxed command

Create a new sandbox interface instance based on this type from params

auto_clean(boolean)
Change behavior of asynchronous background sandbox process on __del__

exit_code()
Block until asynchronous background sandbox process ends, returning code

fini()
Finalize asynchronous background sandbox process (destroys state!)

instances= None

make_sandbox_command_line(extra=None)
Return the fully formed command-line for the sandbox using self.options

recv()
Return stdout and stderr from asynchronous background sandbox process

recverr()
return only stderr from asynchronous background sandbox process

recvout()
Return only stdout from asynchronous background sandbox process

run(extra=None)
Launch new sandbox as asynchronous background sandbox process

Parameters:

extra – String of extra command-line to use but not store

running()
Return True/False if asynchronous background sandbox process executing

send(data)
Send data to asynchronous background sandbox process

stop()
Destroy but don’t finalize asynchronous background sandbox process

classvirttest.lvsb_base.``SandboxCommandBase(params, name=None)
Bases: virttest.lvsb_base.SandboxBase

Connection to a single new or existing sandboxed command

Initialize sandbox-command with params and name, autogenerate if None

BINARY_PATH_PARAM= 'virt_sandbox_binary'

add_flag(option)
Add a flag into the list of command line options

add_mm()
Append a – to the end of the current option list

add_optarg(option, argument)
Add an option with an argument into the list of command line options

add_pos(argument)
Add a positional option into the list of command line options

staticflaten_options(options)
Convert a list of tuples into space-seperated options+argument string

list_flags()
Return a list of all flags (options without arguments)

list_long_options()
Return a list of all long options with an argument

list_pos()
Return a list of all positional arguments

list_short_options()
Return a list of all short options with an argument

make_sandbox_command_line(extra=None)
Return entire command-line string needed to start sandbox

name
Represent a unique sandbox name generated from class and identifier

exceptionvirttest.lvsb_base.``SandboxException(message)
Bases: exceptions.Exception

Basic exception class for problems occurring in SandboxBase or subclasses

classvirttest.lvsb_base.``SandboxSession
Bases: object

Connection instance to asynchronous I/O redirector process

auto_clean(boolean)
Make session cleanup on GC if True

close_session(warn_if_nonexist=True)
Finalize assigned opaque session object

connected
Represents True/False value if background process was created/opened

exit_code()
Block, and return exit code from session

is_running()
Return True if exit_code() would block

kill_session(sig=15)
Send a signal to the opaque session object

new_session(command)
Create and set new opaque session object

open_session(a_id)
Restore connection to existing session identified by a_id

recv()
Return combined stdout/stderr output received so far

recverr()
Return just stderr output

recvout()
Return just stdout output

send(a_string)
Send a_string to session

session_id
Returns unique & persistent identifier for the background process

used= False

classvirttest.lvsb_base.``TestSandboxes(params, env)
Bases: object

Aggregate manager class of SandboxCommandBase or subclass instances

Create instance(s) of sandbox from a command

SANDBOX_TYPE
alias of SandboxCommandBase

are_failed()
Return the number of sandbox processes with non-zero exit codes

are_running()
Return the number of sandbox processes still running

for_each(do_something, *args, **dargs)
Iterate over all sandboxes, calling do_something on each

Parameters:

do_sometihng – Called with the item and *args, **dargs

init_sandboxes()
Create self.count Sandbox instances

virttest.lvsbs module

Higher order classes for Libvirt Sandbox Service (lxc) service container testing

classvirttest.lvsbs.``SandboxService(params, service_name, uri='lxc:///')
Bases: object

Management for a single new/existing sandboxed service

Initialize connection to sandbox service with name and parameters

create()

destroy()

list
Return list of dictionaries mapping column names to values

service_name

uri

xmlstr

virttest.nfs module

Basic nfs support for Linux host. It can support the remote nfs mount and the local nfs set up and mount.

classvirttest.nfs.``Exportfs(path, client='*', options='', ori_exported=None)
Bases: object

Add or remove one entry to exported nfs file system.

export()
Export one directory if it is not in exported list.

Returns:

Export nfs file system succeed or not

is_exported()
Check if the directory is already exported.

Returns:

If the entry is exported

Return type:

Boolean

need_reexport()
Check if the entry is already exported but the options are not the same as we required.

Returns:

Need re export the entry or not

Return type:

Boolean

reset_export()
Reset the exportfs to the original status before we export the specific entry.

unexport()
Unexport an entry.

classvirttest.nfs.``NFSClient(params)
Bases: object

NFSClient class for handle nfs remotely mount and umount.

cleanup(ssh_auto_recover=True)
Cleanup NFS client.

is_mounted()
Check the NFS is mounted or not.

Returns:

If the src is mounted as expect

Return type:

Boolean

setup()
Setup NFS client.

setup_remote()
Mount sharing directory to remote host.

classvirttest.nfs.``Nfs(params)
Bases: object

Nfs class for handle nfs mount and umount. If a local nfs service is required, it will configure a local nfs server accroding the params.

cleanup()
Clean up the host env.

Umount NFS from the mount point. If there has some change for exported file system in host when setup, also clean up that.

is_mounted()
Check the NFS is mounted or not.

Returns:

If the src is mounted as expect

Return type:

Boolean

mount()
Mount source into given mount point.

setup()
Setup NFS in host.

Mount NFS as configured. If a local nfs is requested, setup the NFS service and exportfs too.

umount()
Umount the given mount point.

virttest.nfs.``nfs_exported()
Get the list for nfs file system already exported

Returns:

a list of nfs that is already exported in system

Return type:

a lit of nfs file system exported

virttest.openvswitch module

Wrapper around module.

Necessary for pickling of dynamic class.

classvirttest.openvswitch.``OpenVSwitch(tmpdir, db_path=None, db_socket=None, db_pidfile=None, ovs_pidfile=None, dbschema=None, install_prefix=None)
Bases: virttest.openvswitch.OpenVSwitchSystem

OpenVSwtich class.

Makes initialization of OpenVSwitch.

Parameters:

  • tmpdir – Tmp directory for save openvswitch test files.
  • db_path – Path of OVS database.
  • db_socket – Path of OVS db socket.
  • db_pidfile – Path of OVS db ovsdb-server pid.
  • ovs_pidfile – Path of OVS ovs-vswitchd pid.
  • install_prefix – Path where is openvswitch installed.

clean()

init_db()

init_new()
Create new dbfile without any configuration.

start_ovs_vswitchd()

classvirttest.openvswitch.``OpenVSwitchControl
Bases: object

Class select the best matches control class for installed version of OpenVSwitch.

OpenVSwtich parameters are described in man ovs-vswitchd.conf.db

Makes initialization of OpenVSwitch.

Parameters:

  • tmpdir – Tmp directory for save openvswitch test files.
  • db_path – Path of OVS databimpoty ase.
  • db_socket – Path of OVS db socket.
  • db_pidfile – Path of OVS db ovsdb-server pid.
  • ovs_pidfile – Path of OVS ovs-vswitchd pid.
  • install_prefix – Path where is openvswitch installed.

add_br(br_name)

add_port(br_name, port_name)

add_port_tag(port_name, tag)

add_port_trunk(port_name, trunk)

br_exist(br_name)

check_port_in_br(br_name, port_name)

staticconvert_version_to_int(version)
Parameters:

version – (int) Converted from version string 1.4.0 => int 140

del_br(br_name)

del_port(br_name, port_name)

classmethodget_version()
Get version of installed OpenVSwtich.

Returns:

Version of OpenVSwtich.

list_br()

set_vlanmode(port_name, vlan_mode)

status()

classvirttest.openvswitch.``OpenVSwitchControlCli_140
Bases: virttest.openvswitch.OpenVSwitchControl

Don’t use this class directly. This class is automatically selected by OpenVSwitchControl.

Makes initialization of OpenVSwitch.

Parameters:

  • tmpdir – Tmp directory for save openvswitch test files.
  • db_path – Path of OVS databimpoty ase.
  • db_socket – Path of OVS db socket.
  • db_pidfile – Path of OVS db ovsdb-server pid.
  • ovs_pidfile – Path of OVS ovs-vswitchd pid.
  • install_prefix – Path where is openvswitch installed.

add_br(br_name)

add_fake_br(br_name, parent, vlan)

add_port(br_name, port_name)

add_port_tag(port_name, tag)

add_port_trunk(port_name, trunk)
Parameters:

trunk – list of vlans id.

br_exist(br_name)

del_br(br_name)

del_port(br_name, port_name)

list_br()

list_ports(br_name)

ovs_vsctl(params, ignore_status=False)

port_to_br(port_name)
Return bridge which contain port.

Parameters:

port_name – Name of port.

Returns:

Bridge name or None if there is no bridge which contain port.

set_vlanmode(port_name, vlan_mode)

status()

classvirttest.openvswitch.``OpenVSwitchControlCli_CNT
Bases: virttest.versionable_class.VersionableClass

If this method is invoked it means that something went wrong because this class should be replaced by Manager factory.

classvirttest.openvswitch.``OpenVSwitchControlDB_140
Bases: virttest.openvswitch.OpenVSwitchControl

Don’t use this class directly. This class is automatically selected by OpenVSwitchControl.

Makes initialization of OpenVSwitch.

Parameters:

  • tmpdir – Tmp directory for save openvswitch test files.
  • db_path – Path of OVS databimpoty ase.
  • db_socket – Path of OVS db socket.
  • db_pidfile – Path of OVS db ovsdb-server pid.
  • ovs_pidfile – Path of OVS ovs-vswitchd pid.
  • install_prefix – Path where is openvswitch installed.

classvirttest.openvswitch.``OpenVSwitchControlDB_CNT
Bases: virttest.versionable_class.VersionableClass

If this method is invoked it means that something went wrong because this class should be replaced by Manager factory.

classvirttest.openvswitch.``OpenVSwitchSystem(db_path=None, db_socket=None, db_pidfile=None, ovs_pidfile=None, dbschema=None, install_prefix=None)
Bases: virttest.openvswitch.OpenVSwitchControlCli_CNT, virttest.openvswitch.OpenVSwitchControlDB_CNT

OpenVSwtich class.

Makes initialization of OpenVSwitch.

Parameters:

  • db_path – Path of OVS database.
  • db_socket – Path of OVS db socket.
  • db_pidfile – Path of OVS db ovsdb-server pid.
  • ovs_pidfile – Path of OVS ovs-vswitchd pid.
  • install_prefix – Path where is openvswitch installed.

check()

check_db_daemon()
Check if OVS daemon is started correctly.

check_db_file()
Check if db_file exists.

check_db_socket()
Check if db socket exists.

check_switch_daemon()
Check if OVS daemon is started correctly.

clean()
Empty cleanup function

init_system()
Create new dbfile without any configuration.

is_installed()
Check if OpenVSwitch is already installed in system on default places.

Returns:

Version of OpenVSwtich.

classvirttest.openvswitch.``ServiceManager
Bases: virttest.versionable_class.VersionableClass

If this method is invoked it means that something went wrong because this class should be replaced by Manager factory.

classvirttest.openvswitch.``ServiceManagerInterface
Bases: object

classmethodget_version()
Get version of ServiceManager. :return: Version of ServiceManager.

restart(service_name)

start(service_name)

status(service_name)

stop(service_name)

classvirttest.openvswitch.``ServiceManagerSystemD
Bases: virttest.openvswitch.ServiceManagerSysvinit

restart(service_name)

start(service_name)

status(service_name)

stop(service_name)

classvirttest.openvswitch.``ServiceManagerSysvinit
Bases: virttest.openvswitch.ServiceManagerInterface

restart(service_name)

start(service_name)

stop(service_name)

virttest.ovirt module

oVirt SDK wrapper module.

copyright:

2008-2012 Red Hat Inc.

classvirttest.ovirt.``ClusterManager(params)
Bases: object

This class handles all basic cluster operations.

add(dc_name, cpu_type='Intel Nehalem Family')
Add a new cluster into data center.

list()
List all of clusters.

classvirttest.ovirt.``DataCenterManager(params)
Bases: object

This class handles all basic datacenter operations.

add(storage_type)
Add a new data center.

list()
List all of datacenters.

classvirttest.ovirt.``HostManager(params)
Bases: object

This class handles all basic host operations.

add(host_address, host_password, cluster_name, timeout=300)
Register a host into specified cluster.

get_address()
Return host IP address.

list()
List all of hosts.

state()
Return host state.

classvirttest.ovirt.``StorageDomainManager(params)
Bases: object

This class handles all basic storage domain operations.

attach_iso_export_domain_into_datacenter(address, path, dc_name, host_name, domain_type, storage_type='nfs', name='my_iso')
Attach ISO/export domain into data center.

Parameters:

  • name – ISO or Export name.
  • host_name – host name.
  • dc_name – data center name.
  • path – ISO/export domain path.
  • address – ISO/export domain address.
  • domain_type – storage domain type, it may be ‘iso’ or ‘export’.
  • storage_type – storage type, it may be ‘nfs’, ‘iscsi’, or ‘fc’.

list()
List all of storagedomains.

classvirttest.ovirt.``VMManager(name, params, root_dir=None, address_cache=None, state=None)
Bases: virttest.virt_vm.BaseVM

This class handles all basic VM operations for oVirt.

Initialize the object and set a few attributes.

Parameters:

  • name – The name of the object
  • params – A dict containing VM params (see method make_create_command for a full description)
  • root_dir – Base directory for relative filenames
  • address_cache – A dict that maps MAC addresses to IP addresses
  • state – If provided, use this as self.__dict__

add(memory, disk_size, cluster_name, storage_name, nic_name='eth0', network_interface='virtio', network_name='ovirtmgmt', disk_interface='virtio', disk_format='raw', template_name='Blank', timeout=300)
Create VM with one NIC and one Disk.

Parameters:

  • memory – VM’s memory size such as 1024*1024*1024=1GB.
  • disk_size – VM’s disk size such as 512*1024=512MB.
  • nic_name – VM’s NICs name such as ‘eth0’.
  • network_interface – VM’s network interface such as ‘virtio’.
  • network_name – network such as ovirtmgmt for ovirt, rhevm for rhel.
  • disk_format – VM’s disk format such as ‘raw’ or ‘cow’.
  • disk_interface – VM’s disk interface such as ‘virtio’.
  • cluster_name – cluster name.
  • storage_name – storage domain name.
  • template_name – VM’s template name, default is ‘Blank’.
  • timeout – Time out

add_vm_from_template(cluster_name, template_name='Blank', new_name='my_new_vm', timeout=300)
Create a VM from template.

Parameters:

  • cluster_name – cluster name.
  • template_name – default template is ‘Blank’.
  • new_name – ‘my_new_vm’ is a default new VM’s name.
  • timeout – Time out

create_template(cluster_name, template_name='my_template', timeout=300)
Create a template from VM.

Parameters:

  • cluster_name – cluster name.
  • template_name – ‘my_template’ is default template name.
  • timeout – Time out

delete(timeout=300)
Delete a VM.

delete_from_export_domain(export_name)
Remove a VM from specified export domain.

Parameters:

export_name – export domain name.

destroy(gracefully=False)
Destroy a VM.

export_from_export_domain(export_name, timeout=300)
Export a VM from storage domain to export domain.

Parameters:

export_name – Export domain name.

get_address(index=0)
Return the address of the guest through ovirt node tcpdump cache.

Parameters:

index – Name or index of the NIC whose address is requested.

Returns:

IP address of NIC.

Raises:

VMIPAddressMissingError – If no IP address is found for the the NIC’s MAC address

get_mac_address(net_name='*')
Return MAC address of a VM.

import_from_export_domain(export_name, storage_name, cluster_name, timeout=300)
Import a VM from export domain to data domain.

Parameters:

  • export_name – Export domain name.
  • storage_name – Storage domain name.
  • cluster_name – Cluster name.

is_alive()
Judge if a VM is alive.

is_dead()
Judge if a VM is dead.

is_paused()
Return if VM is suspend.

list()
List all of VMs.

lookup_by_storagedomains(storage_name)
Lookup VM object in storage domain according to VM name.

resume(timeout)
Resume a suspended VM.

shutdown(gracefully=True, timeout=300)
Shut down a running VM.

snapshot(snapshot_name='my_snapshot', timeout=300)
Create a snapshot to VM.

Parameters:

  • snapshot_name – ‘my_snapshot’ is default snapshot name.
  • timeout – Time out

start(wait_for_up=True, timeout=300)
Start a VM.

state()
Return VM state.

suspend(timeout)
Suspend a VM.

update_instance()

exceptionvirttest.ovirt.``WaitHostStateTimeoutError(msg, output)
Bases: virttest.ovirt.WaitStateTimeoutError

exceptionvirttest.ovirt.``WaitStateTimeoutError(msg, output)
Bases: exceptions.Exception

exceptionvirttest.ovirt.``WaitVMStateTimeoutError(msg, output)
Bases: virttest.ovirt.WaitStateTimeoutError

virttest.ovirt.``connect(params)
Connect ovirt manager API.

virttest.ovirt.``disconnect()
Disconnect ovirt manager connection.

virttest.ovs_utils module

classvirttest.ovs_utils.``Machine(vm=None, src=None)
Bases: object

add_vlan_iface(iface, vlan_id)
Add vlan link for interface

Parameters:

  • iface – Interface on which should be added vlan.
  • vlan_id – Id of vlan.

bring_iface_down(iface)
Bring interface up

bring_iface_up(iface)
Bring interface up

cmd(cmd, timeout=60)
Return outpu of command.

cmd_in_src(cmd, timeout=60)

cmd_state(cmd, timeout=60)
Return status of command.

compile_autotools_app_tar(path, package_name)
Compile app on machine in src dir.

Parameters:

  • path – Path where shoule be program compiled.
  • dst_dir – Installation path.

copy_to(src, dst)

del_vlan_iface(iface, vlan_id)
Del vlan link for interface

Parameters:

  • iface – Interface from which should be deleted vlan.
  • vlan_id – Id of vlan.

fill_addrs()

get_if_vlan_name(ifname, vlan_id=0)

get_linkv6_addr(ifname)
Get IPv6 address with link range.

Parameters:

ifname – String or int. Int could be used only for virt Machine.

Returns:

IPv6 link address.

get_vlans_ifname()
Return vlans interface name.

Returns:

dict of {“ifname”: [(vlanid, ifname),(...)],...}

is_virtual()
Returns:

True when Machine is virtual.

ping(dst, iface=None, count=1, vlan=0, ipv=None)
Ping destination.

prepare_directory(path, cleanup=False)
Prepare dest directory. Create if directory not exist.

Parameters:

  • path – Path to directory
  • cleanup – It true clears the contents of directory.

virttest.passfd module

virttest.passfd_setup module

virttest.passfd_setup.``import_passfd()
Imports and lazily sets up the passfd module

Returns:

passfd module

virttest.passfd_setup.``passfd_setup(output_dir='/tmp/avocado-vt/virttest')
Compiles the passfd python extension.

Parameters:

output_dir – where the _passfd.so module will be saved

Returns:

None

virttest.postprocess_iozone module

Postprocessing module for IOzone. It is capable to pick results from an IOzone run, calculate the geometric mean for all throughput results for a given file size or record size, and then generate a series of 2D and 3D graphs. The graph generation functionality depends on gnuplot, and if it is not present, functionality degrates gracefully.

copyright:

Red Hat 2010

classvirttest.postprocess_iozone.``AnalyzerLoggingConfig(use_console=True, set_fmt=True)
Bases: virttest.utils_misc.LoggingConfig

configure_logging(results_dir=None, verbose=False)

classvirttest.postprocess_iozone.``IOzoneAnalyzer(list_files, output_dir)
Bases: object

Analyze an unprocessed IOzone file, and generate the following types of report:

  • Summary of throughput for all file and record sizes combined
  • Summary of throughput for all file sizes
  • Summary of throughput for all record sizes

If more than one file is provided to the analyzer object, a comparison between the two runs is made, searching for regressions in performance.

analyze()
Analyzes and eventually compares sets of IOzone data.

average_performance(results, size=None)
Flattens a list containing performance results.

Parameters:

  • results – List of n lists containing data from performance runs.
  • size – Numerical value of a size (say, file_size) that was used to filter the original results list.

Returns:

List with 1 list containing average data from the performance run.

parse_file(fileobj)
Parse an IOzone results file.

Parameters:

file – File object that will be parsed.

Returns:

Matrix containing IOzone results extracted from the file.

process_results(results, label=None)
Process a list of IOzone results according to label.

Parameters:

  • label – IOzone column label that we’ll use to filter and compute geometric mean results, in practical term either ‘file_size’ or ‘record_size’.
  • result – A list of n x m columns with original iozone results.

Returns:

A list of n-? x (m-1) columns with geometric averages for values of each label (ex, average for all file_sizes).

report(overall_results, record_size_results, file_size_results)
Generates analysis data for IOZone run.

Generates a report to both logs (where it goes with nice headers) and output files for further processing (graph generation).

Parameters:

  • overall_results – 1x15 Matrix containing IOzone results for all file sizes
  • record_size_results – nx15 Matrix containing IOzone results for each record size tested.
  • file_size_results – nx15 Matrix containing file size results for each file size tested.

report_comparison(record, file_size_results)
Generates comparison data for 2 IOZone runs.

It compares 2 sets of nxm results and outputs a table with differences. If a difference higher or smaller than 5% is found, a warning is triggered.

Parameters:

  • record – Tuple with 4 elements containing results for record size.
  • file_size_results – Tuple with 4 elements containing results for file size.

classvirttest.postprocess_iozone.``IOzonePlotter(results_file, output_dir)
Bases: object

Plots graphs based on the results of an IOzone run.

Plots graphs based on the results of an IOzone run. Uses gnuplot to generate the graphs.

generate_data_source()
Creates data file without headers for gnuplot consumption.

plot_2d_graphs()
For each one of the throughput parameters, generate a set of gnuplot commands that will create a parametric surface with file size vs. record size vs. throughput.

plot_3d_graphs()
For each one of the throughput parameters, generate a set of gnuplot commands that will create a parametric surface with file size vs. record size vs. throughput.

plot_all()
Plot all graphs that are to be plotted, provided that we have gnuplot.

virttest.postprocess_iozone.``compare_matrices(matrix1, matrix2, treshold=0.05)
Compare 2 matrices nxm and return a matrix nxm with comparison data

Parameters:

  • matrix1 – Reference Matrix with numeric data
  • matrix2 – Matrix that will be compared
  • treshold – Any difference bigger than this percent treshold will be reported.

virttest.postprocess_iozone.``geometric_mean(values)
Evaluates the geometric mean for a list of numeric values.

Parameters:

values – List with values.

Returns:

Single value representing the geometric mean for the list values.

See:

Geometric mean definition

virttest.ppm_utils module

Utility functions to deal with ppm (qemu screendump format) files.

copyright:

Red Hat 2008-2009

virttest.ppm_utils.``cal_hamming_distance(h1, h2)
Calculate the hamming distance

virttest.ppm_utils.``find_id_for_screendump(md5sum, data_dir)
Search dir for a PPM file whose name ends with md5sum.

Parameters:

  • md5sum – md5 sum string
  • dir – Directory that holds the PPM files.

Returns:

The file’s basename without any preceding path, e.g. 20080101_120000_d41d8cd98f00b204e9800998ecf8427e.ppm

virttest.ppm_utils.``generate_id_for_screendump(md5sum, data_dir)
Generate a unique filename using the given MD5 sum.

Returns:

Only the file basename, without any preceding path. The filename consists of the current date and time, the MD5 sum and a .ppm extension, e.g. 20080101_120000_d41d8cd98f00b204e9800998ecf8427e.ppm.

virttest.ppm_utils.``get_data_dir(steps_filename)
Return the data dir of the given steps filename.

virttest.ppm_utils.``get_region_md5sum(width, height, data, x1, y1, dx, dy, cropped_image_filename=None)
Return the md5sum of a cropped region.

Parameters:

  • width – Original image width
  • height – Original image height
  • data – Image data
  • x1 – Desired x coord of the cropped region
  • y1 – Desired y coord of the cropped region
  • dx – Desired width of the cropped region
  • dy – Desired height of the cropped region
  • cropped_image_filename – if not None, write the resulting cropped image to a file with this name

virttest.ppm_utils.``have_similar_img(base_img, comp_img_path, threshold=10)
Check whether comp_img_path have a image looks like base_img.

virttest.ppm_utils.``image_average_hash(image, img_wd=8, img_ht=8)
Resize and convert the image, then get image data as sequence object, calculate the average hash :param image: an image path or an opened image object

virttest.ppm_utils.``image_comparison(width, height, data1, data2)
Generate a green-red comparison image from two given images.

Parameters:

  • width – Width of both images
  • height – Height of both images
  • data1 – Data of first image
  • data2 – Data of second image

Returns:

A 3-element tuple containing the width, height and data of the generated comparison image.

Note:

Input images must be the same size.

virttest.ppm_utils.``image_crop(width, height, data, x1, y1, dx, dy)
Crop an image.

Parameters:

  • width – Original image width
  • height – Original image height
  • data – Image data
  • x1 – Desired x coordinate of the cropped region
  • y1 – Desired y coordinate of the cropped region
  • dx – Desired width of the cropped region
  • dy – Desired height of the cropped region

Returns:

A 3-tuple containing the width, height and data of the cropped image.

virttest.ppm_utils.``image_crop_save(image, new_image, box=None)
Crop an image and save it to a new image.

Parameters:

  • image – Full path of the original image
  • new_image – Full path of the cropped image
  • box – A 4-tuple defining the left, upper, right, and lower pixel coordinate.

Returns:

True if crop and save image succeed

virttest.ppm_utils.``image_fuzzy_compare(width, height, data1, data2)
Return the degree of equality of two given images.

Parameters:

  • width – Width of both images
  • height – Height of both images
  • data1 – Data of first image
  • data2 – Data of second image

Returns:

Ratio equal_pixel_count / total_pixel_count.

Note:

Input images must be the same size.

virttest.ppm_utils.``image_histogram_compare(image_a, image_b, size=(0, 0))
Compare the histogram of two images and return similar degree.

Parameters:

  • image_a – Full path of the first image
  • image_b – Full path of the second image
  • size – Convert image to size(width, height), and if size=(0, 0), the function will convert the big size image align with the small one.

virttest.ppm_utils.``image_md5sum(width, height, data)
Return the md5sum of an image.

Parameters:

  • width – PPM file width
  • height – PPM file height
  • data – PPM file data

virttest.ppm_utils.``image_read_from_ppm_file(filename)
Read a PPM image.

Returns:

A 3 element tuple containing the width, height and data of the image.

virttest.ppm_utils.``image_verify_ppm_file(filename)
Verify the validity of a PPM file.

Parameters:

filename – Path of the file being verified.

Returns:

True if filename is a valid PPM image file. This function reads only the first few bytes of the file so it should be rather fast.

virttest.ppm_utils.``image_write_to_ppm_file(filename, width, height, data)
Write a PPM image with the given width, height and data.

Parameters:

  • filename – PPM file path
  • width – PPM file width (pixels)
  • height – PPM file height (pixels)

virttest.ppm_utils.``img_ham_distance(base_img, comp_img)
Calculate two images hamming distance

virttest.ppm_utils.``img_similar(base_img, comp_img, threshold=10)
check whether two images are similar by hamming distance

virttest.ppm_utils.``md5eval(data)
Returns a md5 hash evaluator. This function is implemented in order to encapsulate objects in a way that is compatible with python 2.4 and python 2.6 without warnings.

Parameters:

data – Optional input string that will be used to update the object.

virttest.propcan module

Class which allows property and dict-like access to a fixed set of instance attributes. Attributes are locked by __slots__, however accessor methods may be created/removed on instances, or defined by the subclass. An INITIALIZED attribute is provided to signel completion of __init__() for use by accessor methods (i.e. so they know when __init__ may be setting values).

Subclasses must define a __slots__ class attribute containing the list of attribute names to reserve. All additional subclass descendents must explicitly copy __slots__ from the parent in their definition.

Users of subclass instances are expected to get/set/del attributes only via the standard object or dict-like interface. i.e.

instance.attribute = whatever or instance[‘attribute’] = whatever

Internally, methods are free to call the accessor methods. Only accessor methods should use the special __dict_*__() and __super_*__() methods. These are there to allow convenient access to the internal dictionary values and subclass-defined attributes (such as __slots__).

example:

class A(PropCan):
   # Class with *attributes*
    __slots__ = ('a', 'b')
    # 'a' has defined a set/get/del by definition of method with prefix
    #     set_a, get_a, del_a
    # 'b' doesn't have defined set/get/del then classic set/get/del will be
    #     called instead.


    def __init__(self, a=1, b='b'):
       super(A, self).__init__(a, b)


    def set_a(self, value)
        # If is_instance(obj, A) then obj.a = "val" call this method.
        self.__dict_set__("a", value)


    def get_a(self, value)
        # If is_instance(obj, A) then xx = obj.a call this method.
        return self.__dict_get__("a")


    def del_a(self, value)
        # If is_instance(obj, A) then del obj.a call this method.
        self.__dict_del__("a")


class B(PropCan):
   # Class without *attributes*
   # ***** Even if class doesn't have attributes there should be
   # defined __slots__ = []. Because it is preferred by new style of class.
   # *****
    __slots__ = []


    def __init__(self):
       super(B, self).__init__()

classvirttest.propcan.``PropCan(*args, **dargs)
Bases: virttest.propcan.PropCanBase

Special value handling on retrieval of None values

Initialize contents directly or by way of accessors

Parameters:

  • args – Initial values for __slots__ keys, same as dict.
  • dargs – Initial values for __slots__ keys, same as dict.

has_key(key)

items()

keys()

set_if_none(key, value)
Set the value of key, only if it’s not set or None

set_if_value_not_none(key, value)
Set the value of key, only if value is not None

values()

classvirttest.propcan.``PropCanBase(*args, **dargs)
Bases: dict, virttest.propcan.PropCanInternal

Objects with optional accessor methods and dict-like access to fixed set of keys

Initialize contents directly or by way of accessors

Parameters:

  • args – Initial values for __slots__ keys, same as dict.
  • dargs – Initial values for __slots__ keys, same as dict.

INITIALIZED= False

copy()
Copy properties by value, not by reference.

update(other=None, excpt=<type 'exceptions.AttributeError'>, **kwargs)
Update properties in __all_slots__ with another dict.

classvirttest.propcan.``PropCanInternal
Bases: object

Semi-private methods for use only by PropCanBase subclasses (NOT instances)

classvirttest.propcan.``classproperty
Bases: property

virttest.qemu_installer module

Installer code that implement KVM specific bits.

See BaseInstaller class in base_installer.py for interface details.

classvirttest.qemu_installer.``GitRepoInstaller(mode, name, test=None, params=None)
Bases: virttest.qemu_installer.QEMUBaseInstaller, virttest.base_installer.GitRepoInstaller

Installer that deals with source code on Git repositories

Instantiates a new base installer

Parameters:

  • mode – installer mode, such as git_repo, local_src, etc
  • name – installer short name, foo for git_repo_foo
  • test – test
  • params – params

classvirttest.qemu_installer.``LocalSourceDirInstaller(mode, name, test=None, params=None)
Bases: virttest.qemu_installer.QEMUBaseInstaller, virttest.base_installer.LocalSourceDirInstaller

Installer that deals with source code on local directories

Instantiates a new base installer

Parameters:

  • mode – installer mode, such as git_repo, local_src, etc
  • name – installer short name, foo for git_repo_foo
  • test – test
  • params – params

classvirttest.qemu_installer.``LocalSourceTarInstaller(mode, name, test=None, params=None)
Bases: virttest.qemu_installer.QEMUBaseInstaller, virttest.base_installer.LocalSourceTarInstaller

Installer that deals with source code on local tarballs

Instantiates a new base installer

Parameters:

  • mode – installer mode, such as git_repo, local_src, etc
  • name – installer short name, foo for git_repo_foo
  • test – test
  • params – params

classvirttest.qemu_installer.``RemoteSourceTarInstaller(mode, name, test=None, params=None)
Bases: virttest.qemu_installer.QEMUBaseInstaller, virttest.base_installer.RemoteSourceTarInstaller

Installer that deals with source code on remote tarballs

Instantiates a new base installer

Parameters:

  • mode – installer mode, such as git_repo, local_src, etc
  • name – installer short name, foo for git_repo_foo
  • test – test
  • params – params

virttest.qemu_io module

classvirttest.qemu_io.``QemuIO(test, params, image_name, blkdebug_cfg='', prompt='qemu-io>\s*$', log_filename=None, io_options='', log_func=None)
Bases: object

A class for execute qemu-io command

close()
Clean up

cmd_output(command)
Run a command in qemu-io

get_cmd_line(ignore_option=[], essential_option=[], forbid_option=[])
Generate the command line for qemu-io from the parameters :params ignore_option: list for the options should not in command :params essential_option: list for the essential options :params forbid_option: list for the option should not in command :return: qemu-io command line

exceptionvirttest.qemu_io.``QemuIOParamError
Bases: exceptions.Exception

Parameter Error for qemu-io command

classvirttest.qemu_io.``QemuIOShellSession(test, params, image_name, blkdebug_cfg='', prompt='qemu+-io>\s*$', log_filename=None, io_options='', log_func=None)
Bases: virttest.qemu_io.QemuIO

Use a shell session to execute qemu-io command

close()
Close the shell session for qemu-io

cmd_output(*args, **kwargs)
Get output from shell session. If the create flag is True, init the shell session and set the create flag to False. :param command: command to execute in qemu-io :param timeout: timeout for execute the command

classvirttest.qemu_io.``QemuIOSystem(test, params, image_name, blkdebug_cfg='', prompt='qemu-io>\s*$', log_filename=None, io_options='', log_func=None)
Bases: virttest.qemu_io.QemuIO

Run qemu-io with a command line which will return immediately

close()
To keep the the same interface with QemuIOShellSession

cmd_output(*args, **kwargs)
Get output from system_output. Add the command to the qemu-io command line with -c and record the output in the log file. :param command: command to execute in qemu-io :param timeout: timeout for execute the command

virttest.qemu_monitor module

Interfaces to the QEMU monitor.

copyright:

2008-2010 Red Hat Inc.

classvirttest.qemu_monitor.``HumanMonitor(vm, name, filename, suppress_exceptions=False)
Bases: virttest.qemu_monitor.Monitor

Wraps “human monitor” commands.

Connect to the monitor socket and find the (qemu) prompt.

Parameters:

  • vm – The VM which this monitor belongs to.
  • name – Monitor identifier (a string)
  • filename – Monitor socket filename

Raises:

  • MonitorConnectError – Raised if the connection fails and suppress_exceptions is False
  • MonitorProtocolError – Raised if the initial (qemu) prompt isn’t found and suppress_exceptions is False

Note:

Other exceptions may be raised. See cmd()’s docstring.

CMD_TIMEOUT= 120

PROMPT_TIMEOUT= 60

balloon(size)
Balloon VM memory to given size bytes;

Parameters:

size – int type size value.

block_commit(device, speed=None, base=None, top=None, cmd='block_commit', correct=True)
Start block-commit job

Parameters:

  • device – device ID
  • speed – int type, limited speed(B/s)
  • base – base file
  • top – top file
  • cmd – block commit job command
  • correct – auto correct command, correct by default

Returns:

The command’s output

block_mirror(device, target, sync, cmd='drive_mirror', correct=True, **kwargs)
Start mirror type block device copy job

Parameters:

  • device – device name to operate on
  • target – name of new image file
  • sync – what parts of the disk image should be copied to the destination
  • cmd – block mirror command
  • correct – auto correct command, correct by default
  • kwargs – optional keyword arguments including but not limited to below
  • Args – format (str): format of target image file mode (str): target image create mode, ‘absolute-paths’ or ‘existing’ speed (int): maximum speed of the streaming job, in bytes per second

Returns:

The command’s output

block_reopen(device, new_image_file, image_format, cmd='block_job_complete', correct=True)
Reopen new target image

Parameters:

  • device – device ID
  • new_image_file – new image file name
  • image_format – new image file format
  • cmd – image reopen command
  • correct – auto correct command, correct by default

Returns:

The command’s output

block_resize(device, size)
Resize the block device size

Parameters:

  • device – Block device name
  • size – Block device size need to set to. To keep the same with qmp monitor will use bytes as unit for the block size

Returns:

Command output

block_stream(device, speed=None, base=None, cmd='block_stream', correct=True)
Start block-stream job;

Parameters:

  • device – device ID
  • speed – int type, lmited speed(B/s)
  • base – base file
  • correct – auto correct command, correct by default

Returns:

The command’s output

cancel_block_job(device, cmd='block_job_cancel', correct=True)
Cancel running block stream/mirror job on the device

Parameters:

  • device – device ID
  • correct – auto correct command, correct by default

Returns:

The command’s output

change_media(device, target)
Change media of cdrom of drive;

closefd(fd, name)
Close a file descriptor

Parameters:

  • fd – File descriptor to pass to QEMU
  • name – File descriptor name (internal to QEMU)

Returns:

The command’s output

cmd(cmd, timeout=120, debug=True, fd=None)
Send command to the monitor.

Parameters:

  • cmd – Command to send to the monitor
  • timeout – Time duration to wait for the (qemu) prompt to return
  • debug – Whether to print the commands being sent and responses

Returns:

Output received from the monitor

Raises:

eject_cdrom(device, force=False)
Eject media of cdrom and open cdrom door;

get_backingfile(device)
Return “backing_file” path of the device

Parameters:

device – device ID

Returns:

string, backing_file path

get_migrate_cache_size()
Get the xbzrel cache size. e.g. xbzrel cache size: 1048576 kbytes

get_migrate_capability(capability)
Get the state of migrate-capability.

Parameters:

capability – capability which need to get.

Returns:

the state of migrate-capability.

get_migrate_parameter(parameter)
Get the parameter value. e.g. cpu-throttle-initial: 30

Parameters:

parameter – the parameter which need to get

get_status()

getfd(fd, name)
Receives a file descriptor

Parameters:

  • fd – File descriptor to pass to QEMU
  • name – File descriptor name (internal to QEMU)

Returns:

The command’s output

human_monitor_cmd(cmd='', timeout=120, debug=True, fd=None)
Send human monitor command directly

Parameters:

  • cmd – human monitor command.
  • timeout – Time duration to wait for response
  • debug – Whether to print the commands being sent and responses
  • fd – file object or file descriptor to pass

Returns:

The response to the command

info(what, debug=True)
Request info about something and return the output. :param debug: Whether to print the commands being sent and responses

live_snapshot(device, snapshot_file, **kwargs)
Take a live disk snapshot.

Parameters:

  • device – the name of the device to generate the snapshot from.
  • snapshot_file – the target of the new image. A new file will be created.
  • kwargs – optional keyword arguments to pass to func.
  • (optional) (args) – format: the format of the snapshot image, default is ‘qcow2’.

Returns:

The response to the command.

migrate(uri, full_copy=False, incremental_copy=False, wait=False)
Migrate.

Parameters:

  • uri – destination URI
  • full_copy – If true, migrate with full disk copy
  • incremental_copy – If true, migrate with incremental disk copy
  • wait – If true, wait for completion

Returns:

The command’s output

migrate_set_downtime(value)
Set maximum tolerated downtime (in seconds) for migration.

Parameters:

value – maximum downtime (in seconds)

Returns:

The command’s output

migrate_set_speed(value)
Set maximum speed (in bytes/sec) for migrations.

Parameters:

value – Speed in bytes/sec

Returns:

The command’s output

mouse_button(state)
Set mouse button state.

Parameters:

state – Button state (1=L, 2=M, 4=R)

Returns:

The command’s output

mouse_move(dx, dy)
Move mouse.

Parameters:

  • dx – X amount
  • dy – Y amount

Returns:

The command’s output

nmi()
Inject a NMI on all guest’s CPUs.

pause_block_job(device, cmd='block_job_pause', correct=True)
Pause an active block streaming operation. :param device: device ID :param cmd: pause block job command :param correct: auto correct command, correct by default

Returns:

The command’s output

query(what)
Alias for info.

query_block_job(device)
Get block job status on the device

Parameters:

device – device ID

Returns:

dict about job info, return empty dict if no active job

quit()
Send “quit” without waiting for output.

resume_block_job(device, cmd='block_job_resume', correct=True)
Resume a paused block streaming operation. :param device: device ID :param cmd: resume block job command :param correct: auto correct command, correct by default

Returns:

The command’s output

screendump(filename, debug=True)
Request a screendump.

Parameters:

filename – Location for the screendump

Returns:

The command’s output

send_args_cmd(cmdlines, timeout=120, convert=True)
Send a command with/without parameters and return its output. Have same effect with cmd function. Implemented under the same name for both the human and QMP monitors. Command with parameters should in following format e.g.: ‘memsave val=0 size=10240 filename=memsave’ Command without parameter: ‘sendkey ctrl-alt-f1’

Parameters:

  • cmdlines – Commands send to qemu which is separated by ”;”. For command with parameters command should send in a string with this format: $command $arg_name=$arg_value $arg_name=$arg_value
  • timeout – Time duration to wait for (qemu) prompt after command
  • convert – If command need to convert. For commands such as: $command $arg_value

Returns:

The output of the command

Raises:

  • MonitorLockError – Raised if the lock cannot be acquired
  • MonitorSendError – Raised if the command cannot be sent
  • MonitorProtocolError – Raised if the (qemu) prompt cannot be found after sending the command

sendkey(keystr, hold_time=1)
Send key combination to VM.

Parameters:

  • keystr – Key combination string
  • hold_time – Hold time in ms (should normally stay 1 ms)

Returns:

The command’s output

set_block_job_speed(device, speed=0, cmd='block_job_set_speed', correct=True)
Set limited speed for runnig job on the device

Parameters:

  • device – device ID
  • speed – int type, limited speed(B/s)
  • correct – auto correct command, correct by default

Returns:

The command’s output

set_link(name, up)
Set link up/down.

Parameters:

  • name – Link name
  • up – Bool value, True=set up this link, False=Set down this link

Returns:

The response to the command

set_migrate_cache_size(value)
Set the cache size of migrate to value.

Parameters:

value – the cache size to set.

set_migrate_capability(state, capability)
Set the capability of migrate to state.

Parameters:

  • state – Bool value of capability.
  • capability – capability which need to set.

set_migrate_parameter(parameter, value)
Set parameters of migrate.

Parameters:

  • parameter – the parameter which need to set
  • value – the value of parameter

system_powerdown()
Requests that a guest perform a powerdown operation.

system_reset()
Reset guest system

system_wakeup()
Wakeup suspended guest.

verify_responsive()
Make sure the monitor is responsive by sending a command.

verify_status(status)
Verify VM status

Parameters:

status – Optional VM status, ‘running’ or ‘paused’

Returns:

return True if VM status is same as we expected

classvirttest.qemu_monitor.``Monitor(vm, name, filename, suppress_exceptions=False)
Common code for monitor classes.

Initialize the instance.

Parameters:

  • vm – The VM which this monitor belongs to.
  • name – Monitor identifier (a string)
  • filename – Monitor socket filename

Raises:

MonitorConnectError – Raised if the connection fails

ACQUIRE_LOCK_TIMEOUT= 20

CONNECT_TIMEOUT= 60

DATA_AVAILABLE_TIMEOUT= 0

close()
Close the connection to the monitor and its log file.

correct(cmd)
Automatic conversion “-” and “_” in commands if the translate command is supported commands;

human_monitor_cmd(cmd='', timeout=None, debug=True, fd=None)
Send HMP command

This method allows code to send HMP commands without the need to check if the monitor is QMPMonitor or HumanMonitor.

Parameters:

  • cmd – human monitor command.
  • timeout – Time duration to wait for response
  • debug – Whether to print the commands being sent and responses
  • fd – file object or file descriptor to pass

Returns:

The response to the command

info(what, debug=True)
Request info about something and return the response.

info_block(debug=True)
Request info about blocks and return dict of parsed results :return: Dict of disk parameters

info_numa()
Run ‘info numa’ command and parse returned information

Returns:

An array of (ram, cpus) tuples, where ram is the RAM size in MB and cpus is a set of CPU numbers

is_responsive()
Return True if the monitor is responsive.

classmethodparse_info_numa(r)
Parse ‘info numa’ output

See info_numa() for information about the return value.

re_numa_node_info= <_sre.SRE_Pattern object at 0x59bf310>

re_numa_nodes= <_sre.SRE_Pattern object at 0x79106c0>

verify_supported_cmd(cmd)
Verify whether cmd is supported by monitor. If not, raise a MonitorNotSupportedCmdError Exception.

Parameters:

cmd – The cmd string need to verify.

exceptionvirttest.qemu_monitor.``MonitorConnectError(monitor_name)
Bases: virttest.qemu_monitor.MonitorError

exceptionvirttest.qemu_monitor.``MonitorError
Bases: exceptions.Exception

exceptionvirttest.qemu_monitor.``MonitorLockError
Bases: virttest.qemu_monitor.MonitorError

exceptionvirttest.qemu_monitor.``MonitorNotSupportedCmdError(monitor, cmd)
Bases: virttest.qemu_monitor.MonitorNotSupportedError

exceptionvirttest.qemu_monitor.``MonitorNotSupportedError
Bases: virttest.qemu_monitor.MonitorError

exceptionvirttest.qemu_monitor.``MonitorProtocolError
Bases: virttest.qemu_monitor.MonitorError

exceptionvirttest.qemu_monitor.``MonitorSocketError(msg, e)
Bases: virttest.qemu_monitor.MonitorError

exceptionvirttest.qemu_monitor.``QMPCmdError(cmd, qmp_args, data)
Bases: virttest.qemu_monitor.MonitorError

exceptionvirttest.qemu_monitor.``QMPEventError(cmd, qmp_event, name)
Bases: virttest.qemu_monitor.MonitorError

classvirttest.qemu_monitor.``QMPMonitor(vm, name, filename, suppress_exceptions=False)
Bases: virttest.qemu_monitor.Monitor

Wraps QMP monitor commands.

Connect to the monitor socket, read the greeting message and issue the qmp_capabilities command. Also make sure the json module is available.

Parameters:

  • vm – The VM which this monitor belongs to.
  • name – Monitor identifier (a string)
  • filename – Monitor socket filename

Raises:

Note:

Other exceptions may be raised if the qmp_capabilities command fails. See cmd()’s docstring.

CMD_TIMEOUT= 900

PROMPT_TIMEOUT= 90

READ_OBJECTS_TIMEOUT= 10

RESPONSE_TIMEOUT= 600

balloon(size)
Balloon VM memory to size bytes;

Parameters:

size – int type values.

block_commit(device, speed=None, base=None, top=None, cmd='block-commit', correct=True)
Start block-commit job

Parameters:

  • device – device ID
  • speed – int type, limited speed(B/s)
  • base – base file
  • top – top file
  • cmd – block commit job command
  • correct – auto correct command, correct by default

Returns:

The command’s output

block_mirror(device, target, sync, cmd='drive-mirror', correct=True, **kwargs)
Start mirror type block device copy job

Parameters:

  • device – device name to operate on
  • target – name of new image file
  • sync – what parts of the disk image should be copied to the destination
  • cmd – block mirror command
  • correct – auto correct command, correct by default
  • kwargs – optional keyword arguments including but not limited to below
  • Args – format (str): format of target image file mode (str): target image create mode, ‘absolute-paths’ or ‘existing’ speed (int): maximum speed of the streaming job, in bytes per second replaces (str): the block driver node name to replace when finished granularity (int): granularity of the dirty bitmap, in bytes buf_size (int): maximum amount of data in flight from source to target, in bytes on-source-error (str): the action to take on an error on the source on-target-error (str): the action to take on an error on the target

Returns:

The command’s output

block_reopen(device, new_image_file, image_format, cmd='block-job-complete', correct=True)
Reopen new target image;

Parameters:

  • device – device ID
  • new_image_file – new image file name
  • image_format – new image file format
  • cmd – image reopen command
  • correct – auto correct command, correct by default

Returns:

the command’s output

block_resize(device, size)
Resize the block device size

Parameters:

  • device – Block device name
  • size – Block device size need to set to. Unit is bytes.

Returns:

Command output

block_stream(device, speed=None, base=None, cmd='block-stream', correct=True)
Start block-stream job;

Parameters:

  • device – device ID
  • speed – int type, limited speed(B/s)
  • base – base file
  • correct – auto correct command, correct by default

Returns:

The command’s output

cancel_block_job(device, cmd='block-job-cancel', correct=True)
Cancel running block stream/mirror job on the device

Parameters:

  • device – device ID
  • correct – auto correct command, correct by default

Returns:

The command’s output

change_media(device, target)
Change media of cdrom of drive;

clear_event(name)
Clear a kinds of events in events list only.

Raises:

MonitorLockError – Raised if the lock cannot be acquired

clear_events()
Clear the list of asynchronous events.

Raises:

MonitorLockError – Raised if the lock cannot be acquired

closefd(fd, name)
Close a file descriptor

Parameters:

  • fd – File descriptor to pass to QEMU
  • name – File descriptor name (internal to QEMU)

Returns:

The response to the command

cmd(cmd, args=None, timeout=900, debug=True, fd=None)
Send a QMP monitor command and return the response.

Note: an id is automatically assigned to the command and the response is checked for the presence of the same id.

Parameters:

  • cmd – Command to send
  • args – A dict containing command arguments, or None
  • timeout – Time duration to wait for response
  • debug – Whether to print the commands being sent and responses
  • fd – file object or file descriptor to pass

Returns:

The response received

Raises:

cmd_obj(obj, timeout=900)
Transform a Python object to JSON, send the resulting string to the QMP monitor, and return the response. Unlike cmd(), return the raw response dict without performing any checks on it.

Parameters:

  • obj – The object to send
  • timeout – Time duration to wait for response

Returns:

The response received

Raises:

cmd_qmp(cmd, args=None, q_id=None, timeout=900)
Build a QMP command from the passed arguments, send it to the monitor and return the response. Unlike cmd(), return the raw response dict without performing any checks on it.

Parameters:

  • cmd – Command to send
  • args – A dict containing command arguments, or None
  • id – An id for the command, or None
  • timeout – Time duration to wait for response

Returns:

The response received

Raises:

cmd_raw(data, timeout=900)
Send a raw string to the QMP monitor and return the response. Unlike cmd(), return the raw response dict without performing any checks on it.

Parameters:

  • data – The data to send
  • timeout – Time duration to wait for response

Returns:

The response received

Raises:

drive_backup(device, target, format, sync, speed=0, mode='absolute-paths', bitmap='')
Start a point-in-time copy of a block device to a new destination.

Parameters:

  • device – the device name or node-name of a root node which should be copied
  • target – the target of the new image
  • format – the format of the new destination, default is to probe if ‘mode’ is ‘existing’, else the format of the source
  • sync – what parts of the disk image should be copied to the destination; possibilities include “full” for all the disk, “top” for only the sectors allocated in the topmost image, “incremental” for only the dirty sectors in the bitmap, or “none” to only replicate new I/O
  • speed – the maximum speed, in bytes per second
  • mode – whether and how QEMU should create a new image (NewImageMode, optional, default ‘absolute-paths’)
  • bitmap – dirty bitmap name for sync==incremental. Must be present if sync is “incremental”, must NOT be present otherwise

eject_cdrom(device, force=False)
Eject media of cdrom and open cdrom door;

get_backingfile(device)
Return “backing_file” path of the device

Parameters:

device – device ID

Returns:

string, backing_file path

get_event(name)
Look for an event with the given name in the list of events.

Parameters:

name – The name of the event to look for (e.g. ‘RESET’)

Returns:

An event object or None if none is found

get_events()
Return a list of the asynchronous events received since the last clear_events() call.

Returns:

A list of events (the objects returned have an “event” key)

Raises:

MonitorLockError – Raised if the lock cannot be acquired

get_greeting()
Return QMP greeting message.

get_migrate_cache_size()
Get the xbzrel cache size.

get_migrate_capability(capability)
Get the state of migrate-capability.

Parameters:

capability – capability which need to get.

Returns:

the state of migrate-capability.

get_migrate_parameter(parameter)
Get the value of parameter.

Parameters:

parameter – parameter which need to get.

get_status()
Get VM status.

Returns:

return VM status

getfd(fd, name)
Receives a file descriptor

Parameters:

  • fd – File descriptor to pass to QEMU
  • name – File descriptor name (internal to QEMU)

Returns:

The response to the command

human_monitor_cmd(cmd='', timeout=900, debug=True, fd=None)
Run human monitor command in QMP through human-monitor-command

Parameters:

  • cmd – human monitor command.
  • timeout – Time duration to wait for response
  • debug – Whether to print the commands being sent and responses
  • fd – file object or file descriptor to pass

Returns:

The response to the command

info(what, debug=True)
Request info about something and return the response.

live_snapshot(device, snapshot_file, **kwargs)
Take a live disk snapshot.

Parameters:

  • device – the name of the device to generate the snapshot from.
  • snapshot_file – the target of the new image. A new file will be created if mode is “absolute-paths”.
  • kwargs – optional keyword arguments to pass to func.
  • (optional) (args) – format: the format of the snapshot image, default is ‘qcow2’. mode: whether and how QEMU should create a new image, default is ‘absolute-paths’.

Returns:

The response to the command

migrate(uri, full_copy=False, incremental_copy=False, wait=False)
Migrate.

Parameters:

  • uri – destination URI
  • full_copy – If true, migrate with full disk copy
  • incremental_copy – If true, migrate with incremental disk copy
  • wait – If true, wait for completion

Returns:

The response to the command

migrate_set_downtime(value)
Set maximum tolerated downtime (in seconds) for migration.

Parameters:

value – maximum downtime (in seconds)

Returns:

The command’s output

migrate_set_speed(value)
Set maximum speed (in bytes/sec) for migrations.

Parameters:

value – Speed in bytes/sec

Returns:

The response to the command

nmi()
Inject a NMI on all guest’s CPUs.

operate_dirty_bitmap(operation, node, name, granularity=65536)
Add, remove or clear a dirty bitmap.

Parameters:

  • operation – operations to bitmap, can be ‘add’, ‘remove’, and ‘clear’
  • node – device/node on which to operate dirty bitmap
  • name – name of the dirty bitmap to operate
  • granularity – granularity to track writes with

pause_block_job(device, cmd='block-job-pause', correct=True)
Pause an active block streaming operation. :param device: device ID :param cmd: pause block job command :param correct: auto correct command, correct by default

Returns:

The command’s output

qom_get(path, qproperty)
Get output of cmd “qom-get”.

Parameters:

  • path – device path.
  • qproperty – property which needs set.

Returns:

the output of cmd “qom-get”.

qom_set(path, qproperty, qvalue)
Set the property to value for the device.

Parameters:

  • path – device path.
  • qproperty – property which needs set.
  • qvalue – value of the property.

query(what, debug=True)
Alias for info.

query_block_job(device)
Get block job status on the device

Parameters:

device – device ID

Returns:

dict about job info, return empty dict if no active job

quit()
Send “quit” and return the response.

resume_block_job(device, cmd='block-job-resume', correct=True)
Resume a paused block streaming operation. :param device: device ID :param cmd: resume block job command :param correct: auto correct command, correct by default

Returns:

The command’s output

screendump(filename, debug=True)
Request a screendump.

Parameters:

  • filename – Location for the screendump
  • debug – Whether to print the commands being sent and responses

Returns:

The response to the command

send_args_cmd(cmdlines, timeout=900, convert=True)
Send a command with/without parameters and return its output. Have same effect with cmd function. Implemented under the same name for both the human and QMP monitors. Command with parameters should in following format e.g.: ‘memsave val=0 size=10240 filename=memsave’ Command without parameter: ‘query-vnc’

Parameters:

  • cmdlines – Commands send to qemu which is separated by ”;”. For command with parameters command should send in a string with this format: $command $arg_name=$arg_value $arg_name=$arg_value
  • timeout – Time duration to wait for (qemu) prompt after command
  • convert – If command need to convert. For commands not in standard format such as: $command $arg_value

Returns:

The response to the command

Raises:

sendkey(keystr, hold_time=1)
Send key combination to VM.

Parameters:

  • keystr – Key combination string
  • hold_time – Hold time in ms (should normally stay 1 ms)

Returns:

The response to the command

set_block_job_speed(device, speed=0, cmd='block-job-set-speed', correct=True)
Set limited speed for runnig job on the device

Parameters:

  • device – device ID
  • speed – int type, limited speed(B/s)
  • correct – auto correct command, correct by default

Returns:

The command’s output

set_link(name, up)
Set link up/down.

Parameters:

  • name – Link name
  • up – Bool value, True=set up this link, False=Set down this link

Returns:

The response to the command

set_migrate_cache_size(value)
Set the cache size of migrate to value.

Parameters:

value – the cache size to set.

set_migrate_capability(state, capability)
Set the capability of migrate to state.

Parameters:

  • state – Bool value of capability.
  • capability – capability which need to set.

set_migrate_parameter(parameter, value)
Set the parameters of migrate.

Parameters:

  • parameter – the parameter which need to set.
  • value – the value of parameter

system_powerdown()
Requests that a guest perform a powerdown operation.

system_reset()
Reset guest system

system_wakeup()
Wakeup suspended guest.

transaction(job_list)
Atomically operate on a group of one or more block devices.

Parameters:

job_list – List of block jobs information.

Returns:

nothing on success If @device is not a valid block device, DeviceNotFound

verify_responsive()
Make sure the monitor is responsive by sending a command.

verify_status(status)
Verify VM status

Parameters:

status – Optional VM status, ‘running’ or ‘paused’

Returns:

return True if VM status is same as we expected

verify_supported_hmp_cmd(cmd)
Verify whether cmd is supported by hmp monitor. If not, raise a MonitorNotSupportedCmdError Exception.

Parameters:

cmd – The cmd string need to verify.

virttest.qemu_monitor.``create_monitor(vm, monitor_name, monitor_params)
Create monitor object and connect to the monitor socket.

Parameters:

  • vm – The VM object which has the monitor.
  • monitor_name – The name of this monitor object.
  • monitor_params – The dict for creating this monitor object.

virttest.qemu_monitor.``get_monitor_filename(vm, monitor_name)
Return the filename corresponding to a given monitor name.

Parameters:

  • vm – The VM object which has the monitor.
  • monitor_name – The monitor name.

Returns:

The string of socket file name for qemu monitor.

virttest.qemu_monitor.``get_monitor_filenames(vm)
Return a list of all monitor filenames (as specified in the VM’s params).

Parameters:

vm – The VM object which has the monitors.

virttest.qemu_monitor.``wait_for_create_monitor(vm, monitor_name, monitor_params, timeout)
Wait for the progress of creating monitor object. This function will retry to create the Monitor object until timeout.

Parameters:

  • vm – The VM object which has the monitor.
  • monitor_name – The name of this monitor object.
  • monitor_params – The dict for creating this monitor object.
  • timeout – Time to wait for creating this monitor object.

virttest.qemu_qtree module

Utility classes and functions to handle KVM Qtree parsing and verification.

author:

Lukas Doktor <[email protected]>

copyright:

2012 Red Hat Inc.

exceptionvirttest.qemu_qtree.``IncompatibleTypeError(prop, desired_type, value)
Bases: exceptions.TypeError

classvirttest.qemu_qtree.``QtreeBus
Bases: virttest.qemu_qtree.QtreeNode

bus: qtree object

add_child(child)

guess_type()

classvirttest.qemu_qtree.``QtreeContainer
Bases: object

Container for Qtree

get_nodes()
Returns:

flat list of all qtree nodes (last one is main-system-bus)

get_qtree()
Returns:

root of qtree

parse_info_qtree(info)
Parses ‘info qtree’ output. Creates list of self.nodes. Last node is the main-system-bus (whole qtree)

classvirttest.qemu_qtree.``QtreeDev
Bases: virttest.qemu_qtree.QtreeNode

dev: qtree object

add_child(child)

guess_type()

classvirttest.qemu_qtree.``QtreeDisk
Bases: virttest.qemu_qtree.QtreeDev

qtree disk object

generate_params()

get_block()

get_qname()

set_block_prop(prop, value)

update_block_prop(prop, value)

classvirttest.qemu_qtree.``QtreeDisksContainer(nodes)
Bases: object

Container for QtreeDisks verification. It’s necessary because some information can be verified only from informations about all disks, not only from single disk.

work only with QtreeDisks instances

check_disk_params(params)
Check gathered info from qtree/block with params :param params: autotest params :return: number of errors

check_guests_proc_scsi(info)
Check info from guest’s /proc/scsi/scsi file with qtree/block info

Note:

Not tested disks are of different type (virtio_blk, ...)

Parameters:

info – contents of guest’s /proc/scsi/scsi file

Returns:

Number of disks missing in guest os, disks missing in qtree, disks not tested from qtree, disks not tested from guest)

generate_params()
Generate params from current self.qtree and self.block info. :note: disk name is not yet the one from autotest params :return: number of fails

parse_info_block(info)
Extracts all information about self.disks and fills them in.

Parameters:

info – output of info block command

Returns:

self.disks defined in qtree but not in info block, self.disks defined in block info but not in qtree

classvirttest.qemu_qtree.``QtreeNode
Bases: object

Generic Qtree node

add_child(child)

generate_params()

get_children()

get_params()

get_parent()

get_qtree()

guess_type()
Detect type of this object from qtree props

replace_child(oldchild, newchild)

set_parent(parent)

set_qtree(qtree)

set_qtree_prop(prop, value)

str_qtree()

str_short()

update_params(param, value)

update_qtree_prop(prop, value)

verify()

virttest.qemu_qtree.``traverse(qtree_node)
Use generator to traverse the given qtree node

Parameters:

qtree_node – qtree node to be traversed

virttest.qemu_storage module

Classes and functions to handle block/disk images for KVM.

This exports:

  • two functions for get image/blkdebug filename
  • class for image operates and basic parameters

classvirttest.qemu_storage.``Iscsidev(params, root_dir, tag)
Bases: virttest.storage.Iscsidev

Class for handle iscsi devices for VM

Init the default value for image object.

Parameters:

  • params – Dictionary containing the test parameters.
  • root_dir – Base directory for relative filenames.
  • tag – Image tag defined in parameter images

cleanup()
Logout the iscsi target and clean up the config and image.

setup()
Access the iscsi target. And return the local raw device name.

classvirttest.qemu_storage.``LVMdev(params, root_dir, tag)
Bases: virttest.storage.LVMdev

Class for handle lvm devices for VM

Init the default value for image object.

Parameters:

  • params – Dictionary containing the test parameters.
  • root_dir – Base directory for relative filenames.
  • tag – Image tag defined in parameter images

cleanup()
Cleanup useless volumes;

setup()
Get logical volume path;

classvirttest.qemu_storage.``QemuImg(params, root_dir, tag)
Bases: virttest.storage.QemuImg

KVM class for handling operations of disk/block images.

Init the default value for image object.

Parameters:

  • params – Dictionary containing the test parameters.
  • root_dir – Base directory for relative filenames.
  • tag – Image tag defined in parameter images

amend(params, cache_mode=None, ignore_status=False)
Amend the image format specific options for the image

Parameters:

  • params – dictionary containing the test parameters
  • cache_mode – the cache mode used to write the output disk image, the valid options are: ‘none’, ‘writeback’ (default), ‘writethrough’, ‘directsync’ and ‘unsafe’.
  • ignore_status – Whether to raise an exception when command returns =! 0 (False), or not (True).

Note:

params may contain amend options:

amend_size
virtual disk size of the image (a string qemu-img can understand, such as ‘10G’)

amend_compat
compatibility level (0.10 or 1.1)

amend_backing_file
file name of a base image

amend_backing_fmt
image format of the base image

amend_encryption
encrypt the image, allowed values: on and off. Default is “off”

amend_cluster_size
cluster size for the image

amend_preallocation
preallocation mode when create image, allowed values: off, metadata. Default is “off”

amend_lazy_refcounts
postpone refcount updates, allowed values: on and off. Default is “off”

amend_refcount_bits
width of a reference count entry in bits

amend_extra_params
additional options, used for extending amend

Returns:

process.CmdResult object containing the result of the command

check_image(params, root_dir)
Check an image using the appropriate tools for each virt backend.

Parameters:

  • params – Dictionary containing the test parameters.
  • root_dir – Base directory for relative filenames.

Note:

params should contain: image_name – the name of the image file, without extension image_format – the format of the image (qcow2, raw etc)

Raises:

VMImageCheckError – In case qemu-img check fails on the image.

commit(params={}, cache_mode=None)
Commit image to it’s base file

Parameters:

cache_mode – the cache mode used to write the output disk image, the valid options are: ‘none’, ‘writeback’ (default), ‘writethrough’, ‘directsync’ and ‘unsafe’.

compare_images(image1, image2, strict_mode=False, verbose=True)
Compare 2 images using the appropriate tools for each virt backend.

Parameters:

  • image1 – image path of first image
  • image2 – image path of second image
  • strict_mode – Boolean value, True for strict mode, False for default mode.
  • verbose – Record output in debug file or not

Returns:

process.CmdResult object containing the result of the command

convert(params, root_dir, cache_mode=None)
Convert image

Parameters:

  • params – dictionary containing the test parameters
  • root_dir – dir for save the convert image
  • cache_mode – The cache mode used to write the output disk image. Valid options are: none, writeback (default), writethrough, directsync and unsafe.

Note:

params should contain:

convert_image_tag
the image name of the convert image

convert_filename
the name of the image after convert

convert_fmt
the format after convert

compressed
indicates that target image must be compressed

encrypted
there are two value “off” and “on”, default value is “off”

create(*args, **kwargs)
Create an image using qemu_img or dd.

Parameters:

  • params – Dictionary containing the test parameters.
  • ignore_errors – Whether to ignore errors on the image creation cmd.

Note:

params should contain:

image_name
name of the image file, without extension

image_format
format of the image (qcow2, raw etc)

image_cluster_size (optional)
cluster size for the image

image_size
requested size of the image (a string qemu-img can understand, such as ‘10G’)

create_with_dd
use dd to create the image (raw format only)

base_image(optional)
the base image name when create snapshot

base_format(optional)
the format of base image

encrypted(optional)
if the image is encrypted, allowed values: on and off. Default is “off”

preallocated(optional)
if preallocation when create image, allowed values: off, metadata. Default is “off”

Returns:

tuple (path to the image created, process.CmdResult object containing the result of the creation command).

get_format()
Get the fimage file format.

info()
Run qemu-img info command on image file and return its output.

rebase(params, cache_mode=None)
Rebase image.

Parameters:

  • params – dictionary containing the test parameters
  • cache_mode – the cache mode used to write the output disk image, the valid options are: ‘none’, ‘writeback’ (default), ‘writethrough’, ‘directsync’ and ‘unsafe’.

Note:

params should contain:

cmd
qemu-img cmd

snapshot_img
the snapshot name

base_img
base image name

base_fmt
base image format

snapshot_fmt
the snapshot format

mode
there are two value, “safe” and “unsafe”, default is “safe”

remove()
Remove an image file.

snapshot_apply()
Apply a snapshot image.

Note:

params should contain: snapshot_image_name – the name of snapshot image file

snapshot_create()
Create a snapshot image.

Note:

params should contain: snapshot_image_name – the name of snapshot image file

snapshot_del(blkdebug_cfg='')
Delete a snapshot image.

Parameters:

blkdebug_cfg – The configure file of blkdebug

Note:

params should contain: snapshot_image_name – the name of snapshot image file

snapshot_list()
List all snapshots in the given image

support_cmd(cmd)
Verifies whether qemu-img supports command cmd.

Parameters:

cmd – Command string.

virttest.qemu_virtio_port module

Interfaces and helpers for the virtio_serial ports.

copyright:

2012 Red Hat Inc.

classvirttest.qemu_virtio_port.``GuestWorker(vm)
Bases: object

Class for executing “virtio_console_guest” script on guest

Initialize worker for use (including port init on guest)

cleanup()
Cleanup ports and quit the worker

cleanup_ports()
Clean state of all ports and set port to default state.

Default state: No data on port or in port buffer. Read mode = blocking.

cmd(cmd, timeout=10, patterns=None)
Wrapper around the self.cmd command which executes the command on guest. Unlike self._cmd command when the command fails it raises the test exceptions. :param command: Command that will be executed. :param timeout: Timeout used to verify expected output. :return: Tuple (match index, data)

read_nonblocking(internal_timeout=None, timeout=None)
Reads-out all remaining output from GuestWorker.

Parameters:

  • internal_timeout – Time (seconds) to wait before we give up reading from the child process, or None to use the default value.
  • timeout – Timeout for reading child process output.

reconnect(vm, timeout=10)
Reconnect to guest_worker (eg. after migration) :param vm: New VM object

safe_exit_loopback_threads(send_pts, recv_pts)
Safely executes on_guest(“virt.exit_threads()”) using workaround of the stuck thread in loopback in mode=virt.LOOP_NONE . :param send_pts: list of possible send sockets we need to work around. :param recv_pts: list of possible recv sockets we need to read-out.

classvirttest.qemu_virtio_port.``ThRecv(port, event, blocklen=1024, quiet=False)
Bases: threading.Thread

Receives data and throws it away.

Parameters:

  • port – Data source port.
  • event – Exit event.
  • blocklen – Block length.
  • quiet – If true don’t raise event when crash.

run()

classvirttest.qemu_virtio_port.``ThRecvCheck(port, buff, exit_event, blocklen=1024, sendlen=0, migrate_event=None, debug=None)
Bases: threading.Thread

Random data receiver/checker thread.

Parameters:

  • port – Source port.
  • buff – Control data buffer (FIFO).
  • exit_event – Exit event.
  • blocklen – Block length.
  • sendlen – Block length of the send function (on guest)
  • migrate_event – Event indicating port was changed and is ready.
  • debug – Set the execution mode, when nothing run normal.

reload_loss_idx()
This function reloads the acceptable loss to the original value (Reload the self.sendidx to self.sendlen) :note: This function is automatically called during port reconnection.

run()
Pick the right mode and execute it

run_debug()
viz run_normal. Additionally it stores last n verified characters and in case of failures it quickly receive enough data to verify failure or allowed loss and then analyze this data. It provides more info about the situation. Unlike normal run this one supports booth - loss and duplications. It’s not friendly to data corruption.

run_normal()
Receives data and verifies, whether they match the self.buff (queue). It allow data loss up to self.sendidx which can be manually loaded after host socket reconnection or you can overwrite this value from other thread.

classvirttest.qemu_virtio_port.``ThSend(port, data, exit_event, quiet=False)
Bases: threading.Thread

Random data sender thread.

Parameters:

  • port – Destination port.
  • data – The data intend to be send in a loop.
  • exit_event – Exit event.
  • quiet – If true don’t raise event when crash.

run()

classvirttest.qemu_virtio_port.``ThSendCheck(port, exit_event, queues, blocklen=1024, migrate_event=None, reduced_set=False)
Bases: threading.Thread

Random data sender thread.

Parameters:

  • port – Destination port
  • exit_event – Exit event
  • queues – Queues for the control data (FIFOs)
  • blocklen – Block length
  • migrate_event – Event indicating port was changed and is ready.

run()

classvirttest.qemu_virtio_port.``VirtioConsole(qemu_id, name, hostfile)
Bases: virttest.qemu_virtio_port._VirtioPort

Class for handling virtio-console

Parameters:

  • name – Name of port for guest side.
  • hostfile – Path to port on host side.

exceptionvirttest.qemu_virtio_port.``VirtioPortException
Bases: exceptions.Exception

General virtio_port exception

exceptionvirttest.qemu_virtio_port.``VirtioPortFatalException
Bases: virttest.qemu_virtio_port.VirtioPortException

Fatal virtio_port exception

classvirttest.qemu_virtio_port.``VirtioSerial(qemu_id, name, hostfile)
Bases: virttest.qemu_virtio_port._VirtioPort

Class for handling virtio-serialport

Parameters:

  • name – Name of port for guest side.
  • hostfile – Path to port on host side.

virttest.qemu_vm module

Utility classes and functions to handle Virtual Machine creation using qemu.

copyright:

2008-2009, 2014 Red Hat Inc.

exceptionvirttest.qemu_vm.``ImageUnbootableError(name)
Bases: virttest.virt_vm.VMError

exceptionvirttest.qemu_vm.``KVMInternalError(*args)
Bases: virttest.virt_vm.VMError

exceptionvirttest.qemu_vm.``QemuSegFaultError(crash_message)
Bases: virttest.virt_vm.VMError

classvirttest.qemu_vm.``VM(name, params, root_dir, address_cache, state=None)
Bases: virttest.virt_vm.BaseVM

This class handles all basic VM operations.

Initialize the object and set a few attributes.

Parameters:

  • name – The name of the object
  • params – A dict containing VM params (see method make_create_command for a full description)
  • root_dir – Base directory for relative filenames
  • address_cache – A dict that maps MAC addresses to IP addresses
  • state – If provided, use this as self.__dict__

CLOSE_SESSION_TIMEOUT= 30

MIGRATION_PROTOS= ['rdma', 'x-rdma', 'tcp', 'unix', 'exec', 'fd']

activate_netdev(*args, **kwargs)
Activate an inactive host-side networking device

Raise:

IndexError if nic doesn’t exist

Raise:

VMUnknownNetTypeError: if nettype is unset/unsupported

Raise:

IOError if TAP device node cannot be opened

Raise:

VMAddNetDevError: if operation failed

activate_nic(*args, **kwargs)
Activate an VM’s inactive NIC device and verify state

Parameters:

nic_index_or_name – name or index number for existing NIC

add_netdev(*args, **kwargs)
Hotplug a netdev device.

Parameters:

params – NIC info. dict.

Returns:

netdev_id

add_nic(**params)
Add new or setup existing NIC, optionally creating netdev if None

Parameters:

  • params – Parameters to set
  • nic_name – Name for existing or new device
  • nic_model – Model name to emulate
  • netdev_id – Existing qemu net device ID name, None to create new
  • mac – Optional MAC address, None to randomly generate.

balloon(size)
Balloon memory to given size megat-bytes

Parameters:

size – memory size in mega-bytes

block_commit(device, speed, base=None, top=None, correct=True)
start to commit block device, aka merge snapshot

Parameters:

  • device – device ID
  • speed – limited speed, default unit B/s
  • base – base file
  • top – top file
  • correct – auto correct cmd, correct by default

block_mirror(device, target, sync, correct=True, **kwargs)
Mirror block device to target file;

Parameters:

  • device – device ID
  • target – destination image file name;
  • sync – what parts of the disk image should be copied to the destination;
  • correct – auto correct cmd, correct by default
  • kwargs – optional keyword arguments including but not limited to below
  • Args – format (str): format of target image file mode (str): target image create mode, ‘absolute-paths’ or ‘existing’ speed (int): maximum speed of the streaming job, in bytes per second replaces (str): the block driver node name to replace when finished granularity (int): granularity of the dirty bitmap, in bytes buf_size (int): maximum amount of data in flight from source to target, in bytes on-source-error (str): the action to take on an error on the source on-target-error (str): the action to take on an error on the target

block_reopen(device, new_image, format='qcow2', correct=True)
Reopen a new image, no need to do this step in rhel7 host

Parameters:

  • device – device ID
  • new_image – new image filename
  • format – new image format
  • correct – auto correct cmd, correct by default

block_stream(device, speed, base=None, correct=True)
start to stream block device, aka merge snapshot;

Parameters:

  • device – device ID;
  • speed – limited speed, default unit B/s;
  • base – base file;
  • correct – auto correct cmd, correct by default

cancel_block_job(device, correct=True)
cancel active job on the image_file

Parameters:

  • device – device ID
  • correct – auto correct cmd, correct by default

catch_monitor
Return the catch monitor object, selected by the parameter catch_monitor. If catch_monitor isn’t defined or it refers to a nonexistent monitor, return the last monitor. If no monitors exist, return None.

change_media(device, target)
Change media of cdrom;

Parameters:

  • device – Device ID;
  • target – new media file;

check_block_locked(value)
Check whether specified block device is locked or not. Return True, if device is locked, else False.

Parameters:

  • vm – VM object
  • value – Parameter that can specify block device. Can be any possible identification of a device, Such as device name/image file name/...

Returns:

True if device is locked, False if device is unlocked.

cleanup_serial_console()
Close serial console and associated log file

clone(name=None, params=None, root_dir=None, address_cache=None, copy_state=False)
Return a clone of the VM object with optionally modified parameters. The clone is initially not alive and needs to be started using create(). Any parameters not passed to this function are copied from the source VM.

Parameters:

  • name – Optional new VM name
  • params – Optional new VM creation parameters
  • root_dir – Optional new base directory for relative filenames
  • address_cache – A dict that maps MAC addresses to IP addresses
  • copy_state – If True, copy the original VM’s state to the clone. Mainly useful for make_create_command().

create(*args, **kwargs)
Start the VM by running a qemu command. All parameters are optional. If name, params or root_dir are not supplied, the respective values stored as class attributes are used.

Parameters:

  • name – The name of the object
  • params – A dict containing VM params
  • root_dir – Base directory for relative filenames
  • migration_mode – If supplied, start VM for incoming migration using this protocol (either ‘rdma’, ‘x-rdma’, ‘rdma’, ‘tcp’, ‘unix’ or ‘exec’)
  • migration_exec_cmd – Command to embed in ‘-incoming “exec: ...”’ (e.g. ‘gzip -c -d filename’) if migration_mode is ‘exec’ default to listening on a random TCP port
  • migration_fd – Open descriptor from machine should migrate.
  • mac_source – A VM object from which to copy MAC addresses. If not specified, new addresses will be generated.

Raises:

create_serial_console()
Establish a session with the serial console.

Let’s consider the first serial port as serial console. Note: requires a version of netcat that supports -U

create_virtio_console()
Establish a session with the serial console.

deactivate_netdev(*args, **kwargs)
Reverses what activate_netdev() did

Param:

nic_index_or_name: name or index number for existing NIC

deactivate_nic(*args, **kwargs)
Reverses what activate_nic did

Parameters:

  • nic_index_or_name – name or index number for existing NIC
  • wait – Time test will wait for the guest to unplug the device

del_netdev(*args, **kwargs)
Remove netdev info. from nic on VM, does not deactivate.

Param:

nic_index_or_name: name or index number for existing NIC

del_nic(*args, **kwargs)
Undefine nic prameters, reverses what add_nic did.

Parameters:

  • nic_index_or_name – name or index number for existing NIC
  • wait – Time test will wait for the guest to unplug the device

destroy(gracefully=True, free_mac_addresses=True)
Destroy the VM.

If gracefully is True, first attempt to shutdown the VM with a shell command. Then, attempt to destroy the VM via the monitor with a ‘quit’ command. If that fails, send SIGKILL to the qemu process.

Parameters:

  • gracefully – If True, an attempt will be made to end the VM using a shell command before trying to end the qemu process with a ‘quit’ or a kill signal.
  • free_mac_addresses – If True, the MAC addresses used by the VM will be freed.

eject_cdrom(device, force=False)
Eject cdrom and open door of the CDROM;

Parameters:

  • device – device ID;
  • force – force eject or not;

get_block(p_dict={})
Get specified block device from monitor’s info block command. The block device is defined by parameter in p_dict.

Parameters:

p_dict – Dictionary that contains parameters and its value used to define specified block device.

Returns:

Matched block device name, None when not find any device.

get_block_old(blocks_info, p_dict={})
Get specified block device from monitor’s info block command. The block device is defined by parameter in p_dict.

Parameters:

  • p_dict – Dictionary that contains parameters and its value used to define specified block device.
  • blocks_info – the results of monitor command ‘info block’

Returns:

Matched block device name, None when not find any device.

get_ifname(nic_index=0)
Return the ifname of a bridge/tap device associated with a NIC.

Parameters:

nic_index – Index of the NIC

get_job_status(device)
get block job info;

Parameters:

device – device ID

get_monitors_by_type(mon_type)
Return list of monitors of mon_type type. :param mon_type: desired monitor type (qmp, human)

get_peer(netid)
Return the peer of netdev or network deivce.

Parameters:

netid – id of netdev or device

Returns:

id of the peer device otherwise None

get_pid()
Return the VM’s PID. If the VM is dead return None.

Note:

This works under the assumption that self.process.get_pid()

Returns:

the PID of the parent shell process.

get_qemu_threads()
Return the list of qemu SPIDs

Returns:

the list of qemu SPIDs

get_serial_console_filename(name=None)
Return the serial console filename.

Parameters:

name – The serial port name.

get_serial_console_filenames()
Return a list of all serial console filenames (as specified in the VM’s params).

get_shared_meminfo()
Returns the VM’s shared memory information.

Returns:

Shared memory used by VM (MB)

get_shell_pid()
Return the PID of the parent shell process.

Note:

This works under the assumption that self.process.get_pid()

Returns:

the PID of the parent shell process.

get_spice_var(spice_var)
Returns string value of spice variable of choice or None :param spice_var - spice related variable ‘spice_port’, ...

get_vcpu_pids(vcpu_thread_pattern)
Return the list of vcpu PIDs

Returns:

the list of vcpu PIDs

get_vhost_threads(vhost_thread_pattern)
Return the list of vhost threads PIDs

Parameters:

vhost_thread_pattern (string) – a regex to match the vhost threads

Returns:

a list of vhost threads PIDs

Return type:

builtin.list

get_virtio_port_filenames()
Get socket file of virtio ports

get_vnc_port()
Return self.vnc_port.

graceful_shutdown(timeout=60)
Try to gracefully shut down the VM.

Returns:

True if VM was successfully shut down, None otherwise.

Note that the VM is not necessarily dead when this function returns True. If QEMU is running in -no-shutdown mode, the QEMU process may be still alive.

hotplug_nic(*args, **kwargs)
Convenience method wrapper for add_nic() and add_netdev().

Returns:

dict-like object containing nic’s details

hotplug_vcpu(*args, **kwargs)
Hotplug a vcpu, if not assign the cpu_id, will use the minimum unused. the function will use the plug_command if you assigned it, else the function will use the command automatically generated based on the type of monitor

:param cpu_id the cpu_id you want hotplug.

hotunplug_nic(*args, **kwargs)
Convenience method wrapper for del/deactivate nic and netdev.

is_alive()
Return True if the VM is alive and its monitor is responsive.

is_dead()
Return True if the qemu process is dead.

is_paused()
Return True if the qemu process is paused (‘stop’ed)

live_snapshot(base_file, snapshot_file, snapshot_format='qcow2')
Take a live disk snapshot.

Parameters:

  • base_file – base file name
  • snapshot_file – snapshot file name
  • snapshot_format – snapshot file format

Returns:

File name of disk snapshot.

loadvm(tag_name)
Override BaseVM loadvm method

make_create_command(name=None, params=None, root_dir=None)
Generate a qemu command line. All parameters are optional. If a parameter is not supplied, the corresponding value stored in the class attributes is used.

Parameters:

  • name – The name of the object
  • params – A dict containing VM params
  • root_dir – Base directory for relative filenames

Note:

The params dict should contain: mem – memory size in MBs cdrom – ISO filename to use with the qemu -cdrom parameter extra_params – a string to append to the qemu command shell_port – port of the remote shell daemon on the guest (SSH, Telnet or the home-made Remote Shell Server) shell_client – client program to use for connecting to the remote shell daemon on the guest (ssh, telnet or nc) x11_display – if specified, the DISPLAY environment variable will be be set to this value for the qemu process (useful for SDL rendering) images – a list of image object names, separated by spaces nics – a list of NIC object names, separated by spaces

For each image in images: drive_format – string to pass as ‘if’ parameter for this image (e.g. ide, scsi) image_snapshot – if yes, pass ‘snapshot=on’ to qemu for this image image_boot – if yes, pass ‘boot=on’ to qemu for this image In addition, all parameters required by get_image_filename.

For each NIC in nics: nic_model – string to pass as ‘model’ parameter for this NIC (e.g. e1000)

mig_cancelled()

mig_failed()

mig_finished()

mig_succeeded()

migrate(*args, **kwargs)
Migrate the VM.

If the migration is local, the VM object’s state is switched with that of the destination VM. Otherwise, the state is switched with that of a dead VM (returned by self.clone()).

Parameters:

  • timeout – Time to wait for migration to complete.
  • protocol – Migration protocol (as defined in MIGRATION_PROTOS)
  • cancel_delay – If provided, specifies a time duration after which migration will be canceled. Used for testing migrate_cancel.
  • offline – If True, pause the source VM before migration.
  • stable_check – If True, compare the VM’s state after migration to its state before migration and raise an exception if they differ.
  • clean – If True, delete the saved state files (relevant only if stable_check is also True).
  • save_path – The path for state files.
  • dest_host – Destination host (defaults to ‘localhost’).
  • remote_port – Port to use for remote migration.
  • not_wait_for_migration – If True migration start but not wait till the end of migration.
  • fd_s – File descriptor for migration to which source VM write data. Descriptor is closed during the migration.
  • fd_d – File descriptor for migration from which destination VM read data.
  • migration_exec_cmd_src – Command to embed in ‘-incoming “exec: “’ (e.g. ‘exec:gzip -c > filename’) if migration_mode is ‘exec’ default to listening on a random TCP port
  • migration_exec_cmd_dst – Command to embed in ‘-incoming “exec: “’ (e.g. ‘gzip -c -d filename’) if migration_mode is ‘exec’ default to listening on a random TCP port
  • env – Dictionary with test environment
  • migrate_capabilities – The capabilities for migration to need set.

monitor
Return the main monitor object, selected by the parameter main_monitor. If main_monitor isn’t defined or it refers to a nonexistent monitor, return the first monitor. If no monitors exist, return None.

pause()
Pause the VM operation.

pause_block_job(device, correct=True)
Pause an active block streaming operation. :param device: device ID :param correct: auto correct command, correct by default

Returns:

The command’s output

process_info_block(blocks_info)
Process the info block, so that can deal with the new and old qemu format.

Parameters:

blocks_info – the output of qemu command ‘info block’

reboot(*args, **kwargs)
Reboot the VM and wait for it to come back up by trying to log in until timeout expires.

Parameters:

  • session – A shell session object or None.
  • method – Reboot method. Can be “shell” (send a shell reboot command) or “system_reset” (send a system_reset monitor command).
  • nic_index – Index of NIC to access in the VM, when logging in after rebooting.
  • timeout – Time to wait for login to succeed (after rebooting).
  • serial – Serial login or not (default is False).

Returns:

A new shell session object.

restore_from_file(path)
Override BaseVM restore_from_file method

resume()
Resume the VM operation in case it’s stopped.

resume_block_job(device, correct=True)
Resume a paused block streaming operation. :param device: device ID :param correct: auto correct command, correct by default

Returns:

The command’s output

save_to_file(path)
Override BaseVM save_to_file method

savevm(tag_name)
Override BaseVM savevm method

screendump(filename, debug=True)

send_fd(*args, **kwargs)
Send file descriptor over unix socket to VM.

Parameters:

  • fd – File descriptor.
  • fd_name – File descriptor identificator in VM.

send_key(keystr)
Send a key event to the VM.

Parameters:

keystr – A key event string (e.g. “ctrl-alt-delete”)

set_job_speed(device, speed='0', correct=True)
set max speed of block job;

Parameters:

  • device – device ID
  • speed – max speed of block job
  • correct – auto correct cmd, correct by default

set_link(netdev_name, up)
Set link up/down.

Parameters:

  • name – Link name
  • up – Bool value, True=set up this link, False=Set down this link

system_reset()
Send system_reset to monitor

update_system_dependent_devs()

update_vga_global_default(params, migrate=None)
Update VGA global default settings

Parameters:

  • params – dict for create vm
  • migrate – is vm create for migration

verify_alive()
Make sure the VM is alive and that the main monitor is responsive.

Raises:

VMDeadError – If the VM is dead

Raise:

Various monitor exceptions if the monitor is unresponsive

verify_disk_image_bootable()

verify_kvm_internal_error()
Verify KVM internal error.

verify_status(status)
Check VM status

Parameters:

status – Optional VM status, ‘running’ or ‘paused’

Raises:

VMStatusError – If the VM status is not same as parameter

verify_userspace_crash()
Verify if the userspace component (qemu) crashed.

wait_for_migration(timeout)

wait_for_shutdown(timeout=60)
Wait until guest shuts down.

Helps until the VM is shut down by the guest.

Returns:

True in case the VM was shut down, None otherwise.

Note that the VM is not necessarily dead when this function returns True. If QEMU is running in -no-shutdown mode, the QEMU process may be still alive.

wait_for_status(status, timeout, first=0.0, step=1.0, text=None)
Wait until the VM status changes to specified status

Parameters:

  • timeout – Timeout in seconds
  • first – Time to sleep before first attempt
  • steps – Time to sleep between attempts in seconds
  • text – Text to print while waiting, for debug purposes

Returns:

True in case the status has changed before timeout, otherwise return None.

wait_until_dead(timeout, first=0.0, step=1.0)
Wait until VM is dead.

Returns:

True if VM is dead before timeout, otherwise returns None.

Parameters:

  • timeout – Timeout in seconds
  • first – Time to sleep before first attempt
  • steps – Time to sleep between attempts in seconds

wait_until_paused(timeout)
Wait until the VM is paused.

Parameters:

timeout – Timeout in seconds.

Returns:

True in case the VM is paused before timeout, otherwise return None.

exceptionvirttest.qemu_vm.``VMMigrateProtoUnsupportedError(protocol=None, output=None)
Bases: virttest.virt_vm.VMMigrateProtoUnknownError

When QEMU tells us it doesn’t know about a given migration protocol.

This usually happens when we’re testing older QEMU. It makes sense to skip the test in this situation.

virttest.qemu_vm.``clean_tmp_files()

virttest.remote module

Functions and classes used for logging into guests and transferring files.

classvirttest.remote.``AexpectIOWrapperOut(obj)
Bases: virttest.remote_commander.messenger.StdIOWrapperOutBase64

Basic implementation of IOWrapper for stdout

Parameters:

obj – IO obj for example file decriptor.

close()

fileno()

write(data)

exceptionvirttest.remote.``LoginAuthenticationError(msg, output)
Bases: virttest.remote.LoginError

exceptionvirttest.remote.``LoginBadClientError(client)
Bases: virttest.remote.LoginError

exceptionvirttest.remote.``LoginError(msg, output)
Bases: exceptions.Exception

exceptionvirttest.remote.``LoginProcessTerminatedError(status, output)
Bases: virttest.remote.LoginError

exceptionvirttest.remote.``LoginTimeoutError(output)
Bases: virttest.remote.LoginError

classvirttest.remote.``RemoteFile(address, client, username, password, port, remote_path, limit='', log_filename=None, verbose=False, timeout=600)
Bases: object

Class to handle the operations of file on remote host or guest.

Initialization of RemoteFile class.

Parameters:

  • address – Address of remote host(guest)
  • client – Type of transfer client
  • username – Username (if required)
  • password – Password (if requried)
  • remote_path – Path of file which we want to edit on remote.
  • limit – Speed limit of file transfer.
  • log_filename – If specified, log all output to this file(SCP only)
  • verbose – If True, log some stats using logging.debug (RSS only)
  • timeout – The time duration (in seconds) to wait for the transfer tocomplete.

add(line_list, linesep=None)
Append lines in line_list into file on remote.

Parameters:

  • line_list – string consists of lines
  • linesep – end up with a separator

remove(pattern_list)
Remove the lines in remote file which matchs a pattern in pattern_list.

sub(pattern2repl_dict)
Replace the string which match the pattern to the value contained in pattern2repl_dict.

sub_else_add(pattern2repl_dict)
Replace the string which match the pattern. If no match in the all lines, append the value to the end of file.

truncate(length=0)
Truncate the detail of remote file to assigned length Content before line 1 line 2 line 3 remote_file.truncate(length=1) Content after line 1

Parameters:

length – how many lines you want to keep

classvirttest.remote.``RemoteRunner(client='ssh', host=None, port='22', username='root', password=None, prompt='[\#\$]\s*$', linesep='n', log_filename=None, timeout=240, internal_timeout=10, session=None)
Bases: object

Class to provide a utils.run-like method to execute command on remote host or guest. Provide a similar interface with utils.run on local.

Initialization of RemoteRunner. Init a session login to remote host or guest.

Parameters:

  • client – The client to use (‘ssh’, ‘telnet’ or ‘nc’)
  • host – Hostname or IP address
  • port – Port to connect to
  • username – Username (if required)
  • password – Password (if required)
  • prompt – Shell prompt (regular expression)
  • linesep – The line separator to use when sending lines (e.g. ‘n’ or ‘rn’)
  • log_filename – If specified, log all output to this file
  • timeout – Total time duration to wait for a successful login
  • internal_timeout – The maximal time duration (in seconds) to wait for each step of the login procedure (e.g. the “Are you sure” prompt or the password prompt)
  • session – An existing session

See:

wait_for_login()

Raise:

Whatever wait_for_login() raises

run(command, timeout=60, ignore_status=False)
Method to provide a utils.run-like interface to execute command on remote host or guest.

Parameters:

  • timeout – Total time duration to wait for command return.
  • ignore_status – If ignore_status=True, do not raise an exception, no matter what the exit code of the command is. Else, raise CmdError if exit code of command is not zero.

classvirttest.remote.``Remote_Package(address, client, username, password, port, remote_path)
Bases: object

Initialization of Remote Package class.

Parameters:

  • address – Address of remote host(guest)
  • client – The client to use (‘ssh’, ‘telnet’ or ‘nc’)
  • username – Username (if required)
  • password – Password (if requried)
  • port – Port to connect to
  • remote_path – Rmote package path

pull_file(local_path, timeout=600)
Copy file from remote to local.

push_file(local_path, timeout=600)
Copy file from local to remote.

exceptionvirttest.remote.``SCPAuthenticationError(msg, output)
Bases: virttest.remote.SCPError

exceptionvirttest.remote.``SCPAuthenticationTimeoutError(output)
Bases: virttest.remote.SCPAuthenticationError

exceptionvirttest.remote.``SCPError(msg, output)
Bases: exceptions.Exception

exceptionvirttest.remote.``SCPTransferFailedError(status, output)
Bases: virttest.remote.SCPError

exceptionvirttest.remote.``SCPTransferTimeoutError(output)
Bases: virttest.remote.SCPError

virttest.remote.``copy_files_from(*args, **kwargs)

virttest.remote.``copy_files_to(*args, **kwargs)

virttest.remote.``handle_prompts(session, username, password, prompt, timeout=10, debug=False)
Connect to a remote host (guest) using SSH or Telnet or else.

Wait for questions and provide answers. If timeout expires while waiting for output from the child (e.g. a password prompt or a shell prompt) – fail.

Parameters:

  • session – An Expect or ShellSession instance to operate on
  • username – The username to send in reply to a login prompt
  • password – The password to send in reply to a password prompt
  • prompt – The shell prompt that indicates a successful login
  • timeout – The maximal time duration (in seconds) to wait for each step of the login procedure (i.e. the “Are you sure” prompt, the password prompt, the shell prompt, etc)

Raises:

Returns:

If connect succeed return the output text to script for further debug.

virttest.remote.``nc_copy_between_remotes(src, dst, s_port, s_passwd, d_passwd, s_name, d_name, s_path, d_path, c_type='ssh', c_prompt='\n', d_port='8888', d_protocol='tcp', timeout=2, check_sum=True, s_session=None, d_session=None, file_transfer_timeout=600)
Copy files from guest to guest using netcat.

This method only supports linux guest OS.

Parameters:

  • src/dst – Hostname or IP address of src and dst
  • s_name/d_name – Username (if required)
  • s_passwd/d_passwd – Password (if required)
  • s_path/d_path – Path on the remote machine where we are copying
  • c_type – Login method to remote host(guest).
  • c_prompt – command line prompt of remote host(guest)
  • d_port – the port data transfer
  • d_protocol – nc protocol use (tcp or udp)
  • timeout – If a connection and stdin are idle for more than timeout seconds, then the connection is silently closed.
  • s_session – A shell session object for source or None.
  • d_session – A shell session object for dst or None.
  • timeout – timeout for file transfer.

Returns:

True on success and False on failure.

virttest.remote.``remote_commander(client, host, port, username, password, prompt, linesep='\n', log_filename=None, timeout=10, path=None)
Log into a remote host (guest) using SSH/Telnet/Netcat.

Parameters:

  • client – The client to use (‘ssh’, ‘telnet’ or ‘nc’)
  • host – Hostname or IP address
  • port – Port to connect to
  • username – Username (if required)
  • password – Password (if required)
  • prompt – Shell prompt (regular expression)
  • linesep – The line separator to use when sending lines (e.g. ‘n’ or ‘rn’)
  • log_filename – If specified, log all output to this file
  • timeout – The maximal time duration (in seconds) to wait for each step of the login procedure (i.e. the “Are you sure” prompt or the password prompt)
  • path – The path to place where remote_runner.py is placed.

Raises:

LoginBadClientError – If an unknown client is requested

Raise:

Whatever handle_prompts() raises

Returns:

A ShellSession object.

virttest.remote.``remote_login(client, host, port, username, password, prompt, linesep='\n', log_filename=None, timeout=10, interface=None, status_test_command='echo $?', verbose=False)
Log into a remote host (guest) using SSH/Telnet/Netcat.

Parameters:

  • client – The client to use (‘ssh’, ‘telnet’ or ‘nc’)
  • host – Hostname or IP address
  • port – Port to connect to
  • username – Username (if required)
  • password – Password (if required)
  • prompt – Shell prompt (regular expression)
  • linesep – The line separator to use when sending lines (e.g. ‘n’ or ‘rn’)
  • log_filename – If specified, log all output to this file
  • timeout – The maximal time duration (in seconds) to wait for each step of the login procedure (i.e. the “Are you sure” prompt or the password prompt)
  • status_test_command – Command to be used for getting the last exit status of commands run inside the shell (used by cmd_status_output() and friends).

Interface:

The interface the neighbours attach to (only use when using ipv6 linklocal address.)

Raises:

  • LoginError – If using ipv6 linklocal but not assign a interface that the neighbour attache
  • LoginBadClientError – If an unknown client is requested

Raise:

Whatever handle_prompts() raises

Returns:

A ShellSession object.

virttest.remote.``remote_scp(command, password_list, log_filename=None, transfer_timeout=600, login_timeout=20)
Transfer files using SCP, given a command line.

Parameters:

  • command – The command to execute (e.g. “scp -r foobar root@localhost:/tmp/”).
  • password_list – Password list to send in reply to a password prompt.
  • log_filename – If specified, log all output to this file
  • transfer_timeout – The time duration (in seconds) to wait for the transfer to complete.
  • login_timeout – The maximal time duration (in seconds) to wait for each step of the login procedure (i.e. the “Are you sure” prompt or the password prompt)

Raise:

Whatever _remote_scp() raises

virttest.remote.``scp_between_remotes(src, dst, port, s_passwd, d_passwd, s_name, d_name, s_path, d_path, limit='', log_filename=None, timeout=600, src_inter=None, dst_inter=None)
Copy files from a remote host (guest) to another remote host (guest).

Parameters:

  • src/dst – Hostname or IP address of src and dst
  • s_name/d_name – Username (if required)
  • s_passwd/d_passwd – Password (if required)
  • s_path/d_path – Path on the remote machine where we are copying from/to
  • limit – Speed limit of file transfer.
  • log_filename – If specified, log all output to this file
  • timeout – The time duration (in seconds) to wait for the transfer to complete.

Src_inter:

The interface on local that the src neighbour attache

Dst_inter:

The interface on the src that the dst neighbour attache

Returns:

True on success and False on failure.

virttest.remote.``scp_from_remote(host, port, username, password, remote_path, local_path, limit='', log_filename=None, timeout=600, interface=None)
Copy files from a remote host (guest).

Parameters:

  • host – Hostname or IP address
  • username – Username (if required)
  • password – Password (if required)
  • local_path – Path on the local machine where we are copying from
  • remote_path – Path on the remote machine where we are copying to
  • limit – Speed limit of file transfer.
  • log_filename – If specified, log all output to this file
  • timeout – The time duration (in seconds) to wait for the transfer to complete.

Interface:

The interface the neighbours attach to (only use when using ipv6 linklocal address.)

Raise:

Whatever remote_scp() raises

virttest.remote.``scp_to_remote(host, port, username, password, local_path, remote_path, limit='', log_filename=None, timeout=600, interface=None)
Copy files to a remote host (guest) through scp.

Parameters:

  • host – Hostname or IP address
  • username – Username (if required)
  • password – Password (if required)
  • local_path – Path on the local machine where we are copying from
  • remote_path – Path on the remote machine where we are copying to
  • limit – Speed limit of file transfer.
  • log_filename – If specified, log all output to this file
  • timeout – The time duration (in seconds) to wait for the transfer to complete.

Interface:

The interface the neighbours attach to (only use when using ipv6 linklocal address.)

Raise:

Whatever remote_scp() raises

virttest.remote.``throughput_transfer(func)
wrapper function for copy_files_to/copy_files_from function, will print throughput if filesize is not none, else will print elapsed time

virttest.remote.``udp_copy_between_remotes(src, dst, s_port, s_passwd, d_passwd, s_name, d_name, s_path, d_path, c_type='ssh', c_prompt='\n', d_port='9000', timeout=600)
Copy files from guest to guest using udp.

Parameters:

  • src/dst – Hostname or IP address of src and dst
  • s_name/d_name – Username (if required)
  • s_passwd/d_passwd – Password (if required)
  • s_path/d_path – Path on the remote machine where we are copying
  • c_type – Login method to remote host(guest).
  • c_prompt – command line prompt of remote host(guest)
  • d_port – the port data transfer
  • timeout – data transfer timeout

virttest.remote.``wait_for_login(client, host, port, username, password, prompt, linesep='\n', log_filename=None, timeout=240, internal_timeout=10, interface=None)
Make multiple attempts to log into a guest until one succeeds or timeouts.

Parameters:

  • timeout – Total time duration to wait for a successful login
  • internal_timeout – The maximum time duration (in seconds) to wait for each step of the login procedure (e.g. the “Are you sure” prompt or the password prompt)

Interface:

The interface the neighbours attach to (only use when using ipv6 linklocal address.)

See:

remote_login()

Raise:

Whatever remote_login() raises

Returns:

A ShellSession object.

virttest.remote_build module

exceptionvirttest.remote_build.``BuildError(error_info)
Bases: exceptions.Exception

classvirttest.remote_build.``Builder(params, address, source, shell_client=None, shell_port=None, file_transfer_client=None, file_transfer_port=None, username=None, password=None, make_flags='', build_dir=None, build_dir_prefix=None, shell_linesep=None, shell_prompt=None)
Bases: object

Parameters:

  • params – Dictionary with test parameters, used to get the default values of all named parameters.
  • address – Remote host or guest address
  • source – Directory containing the source on the machine where this script is running
  • shell_client – The client to use (‘ssh’, ‘telnet’ or ‘nc’)
  • shell_port – Port to connect to for the shell client
  • file_transfer_client – The file transfer client to use (‘scp’ or ‘rss’)
  • file_transfer_port – Port to connect to for the file transfer client
  • username – Username (if required)
  • password – Password (if required)
  • make_flags – Flags to pass to the make process, default: “”
  • build_dir – Where to copy and build the files on target. If None, use params[‘tmp_dir’]
  • build_dir_prefix – What to name the build directory on target If None, use the name of the source directory.
  • shell_linesep – Line separator in the shell
  • shell_prompt – Regexp that matches the prompt in the shell.

build()
Synchronize all files and execute ‘make’ on the remote system if needed. :returns: The path to the build directory on the remote machine

make()
Execute make on the remote system

sync_directories()
Synchronize the directories between the local and remote machines :returns: True if any files needed to be copied; False otherwise. Does not support symlinks.

virttest.rss_client module

Client for file transfer services offered by RSS (Remote Shell Server).

author:

Michael Goldish ([email protected])

copyright:

2008-2010 Red Hat Inc.

classvirttest.rss_client.``FileDownloadClient(address, port, log_func=None, timeout=20)
Bases: virttest.rss_client.FileTransferClient

Connect to a RSS (remote shell server) and download files or directory trees.

Connect to a server.

Parameters:

  • address – The server’s address
  • port – The server’s port
  • log_func – If provided, transfer stats will be passed to this function during the transfer
  • timeout – Time duration to wait for connection to succeed

Raises:

download(src_pattern, dst_path, timeout=600)
Receive files or directory trees from the server. The semantics of src_pattern and dst_path are similar to those of scp.

For example, the following are OK:

src_pattern='C:\foo.txt', dst_path='/tmp'
    (downloads a single file)
src_pattern='C:\Windows', dst_path='/tmp'
    (downloads a directory tree recursively)
src_pattern='C:\Windows\*', dst_path='/tmp'
    (downloads all files and directory trees under C:\Windows)

The following is not OK:

src_pattern='C:\Windows', dst_path='/tmp/*'
    (wildcards are only allowed in src_pattern)

Parameters:

  • src_pattern – A path or wildcard pattern specifying the files or directories, in the server’s filesystem, that will be sent to the client
  • dst_path – A path in the local filesystem where the files will be saved
  • timeout – Time duration in seconds to wait for the transfer to complete

Raises:

Note:

Other exceptions can be raised.

classvirttest.rss_client.``FileTransferClient(address, port, log_func=None, timeout=20)
Bases: object

Connect to a RSS (remote shell server) and transfer files.

Connect to a server.

Parameters:

  • address – The server’s address
  • port – The server’s port
  • log_func – If provided, transfer stats will be passed to this function during the transfer
  • timeout – Time duration to wait for connection to succeed

Raises:

FileTransferConnectError – Raised if the connection fails

close()
Close the connection.

exceptionvirttest.rss_client.``FileTransferConnectError(msg, e=None, filename=None)
Bases: virttest.rss_client.FileTransferError

exceptionvirttest.rss_client.``FileTransferError(msg, e=None, filename=None)
Bases: exceptions.Exception

exceptionvirttest.rss_client.``FileTransferNotFoundError(msg, e=None, filename=None)
Bases: virttest.rss_client.FileTransferError

exceptionvirttest.rss_client.``FileTransferProtocolError(msg, e=None, filename=None)
Bases: virttest.rss_client.FileTransferError

exceptionvirttest.rss_client.``FileTransferServerError(errmsg)
Bases: virttest.rss_client.FileTransferError

exceptionvirttest.rss_client.``FileTransferSocketError(msg, e=None, filename=None)
Bases: virttest.rss_client.FileTransferError

exceptionvirttest.rss_client.``FileTransferTimeoutError(msg, e=None, filename=None)
Bases: virttest.rss_client.FileTransferError

classvirttest.rss_client.``FileUploadClient(address, port, log_func=None, timeout=20)
Bases: virttest.rss_client.FileTransferClient

Connect to a RSS (remote shell server) and upload files or directory trees.

Connect to a server.

Parameters:

  • address – The server’s address
  • port – The server’s port
  • log_func – If provided, transfer stats will be passed to this function during the transfer
  • timeout – Time duration to wait for connection to succeed

Raises:

upload(src_pattern, dst_path, timeout=600)
Send files or directory trees to the server.

The semantics of src_pattern and dst_path are similar to those of scp. For example, the following are OK:

src_pattern='/tmp/foo.txt', dst_path='C:\'
    (uploads a single file)
src_pattern='/usr/', dst_path='C:\Windows\'
    (uploads a directory tree recursively)
src_pattern='/usr/*', dst_path='C:\Windows\'
    (uploads all files and directory trees under /usr/)

The following is not OK:

src_pattern='/tmp/foo.txt', dst_path='C:\Windows\*'
    (wildcards are only allowed in src_pattern)

Parameters:

  • src_pattern – A path or wildcard pattern specifying the files or directories to send to the server
  • dst_path – A path in the server’s filesystem where the files will be saved
  • timeout – Time duration in seconds to wait for the transfer to complete

Raises:

Note:

Other exceptions can be raised.

virttest.rss_client.``download(address, port, src_pattern, dst_path, log_func=None, timeout=60, connect_timeout=20)
Connect to server and upload files.

:see:: FileDownloadClient

virttest.rss_client.``main()

virttest.rss_client.``upload(address, port, src_pattern, dst_path, log_func=None, timeout=60, connect_timeout=20)
Connect to server and upload files.

:see:: FileUploadClient

virttest.scan_autotest_results module

Program that parses the autotest results and return a nicely printed final test result.

copyright:

Red Hat 2008-2009

virttest.scan_autotest_results.``main(resfiles)

virttest.scan_autotest_results.``parse_results(text)
Parse text containing Autotest results.

Returns:

A list of result 4-tuples.

virttest.scan_autotest_results.``print_result(result, name_width)
Nicely print a single Autotest result.

Parameters:

  • result – a 4-tuple
  • name_width – test name maximum width

virttest.scheduler module

classvirttest.scheduler.``scheduler(tests, num_workers, total_cpus, total_mem, bindir)
A scheduler that manages several parallel test execution pipelines on a single host.

Initialize the class.

Parameters:

  • tests – A list of test dictionaries.
  • num_workers – The number of workers (pipelines).
  • total_cpus – The total number of CPUs to dedicate to tests.
  • total_mem – The total amount of memory to dedicate to tests.
  • bindir – The directory where environment files reside.

scheduler()
The scheduler function.

Sends commands to workers, telling them to run tests, clean up or terminate execution.

worker(index, run_test_func)
The worker function.

Waits for commands from the scheduler and processes them.

Parameters:

  • index – The index of this worker (in the range 0..num_workers-1).
  • run_test_func – A function to be called to run a test (e.g. job.run_test).

virttest.ssh_key module

virttest.ssh_key.``get_public_key()
Return a valid string ssh public key for the user executing autoserv or autotest. If there’s no DSA or RSA public key, create a DSA keypair with ssh-keygen and return it.

Returns:

a ssh public key

Return type:

str

virttest.ssh_key.``get_remote_public_key(session)
Return a valid string ssh public key for the user executing autoserv or autotest. If there’s no DSA or RSA public key, create a DSA keypair with ssh-keygen and return it.

Parameters:

session – A ShellSession for remote host

Returns:

a ssh public key

Return type:

str

virttest.ssh_key.``setup_remote_known_hosts_file(client_ip, server_ip, server_user, server_pwd)
Set the ssh host key of local host to remote host

Parameters:

  • client_ip (str) – local host ip whose host key is sent to remote host
  • server_ip (str) – remote host ip address where host key is stored to
  • server_user (str) – user to log on remote host
  • server_pwd (str) – password for the user for log on remote host

Returns:

a RemoteFile object for the file known_hosts on remote host

Return type:

remote.RemoteFile

Returns:

None if required command is not found

virttest.ssh_key.``setup_remote_ssh_key(hostname1, user1, password1, hostname2=None, user2=None, password2=None, port=22, config_options=None)
Setup up remote to remote login in another server by using public key If hostname2 is not supplied, setup to local.

Parameters:

  • hostname1 – the server wants to login other host
  • hostname2 – the server to be logged in
  • user (str) – user to login
  • password (str) – password
  • port (int) – port number
  • config_options (list of str) – list of options eg: [“StrictHostKeyChecking=no”]

virttest.ssh_key.``setup_ssh_key(hostname, user, password, port=22)
Setup up remote login in another server by using public key

Parameters:

  • hostname (str) – the server to login
  • user (str) – user to login
  • password (str) – password
  • port (int) – port number

virttest.standalone_test module

virttest.standalone_test.``find_default_qemu_paths(options_qemu=None, options_dst_qemu=None)

virttest.standalone_test.``get_cartesian_parser_details(cartesian_parser)
Print detailed information about filters applied to the cartesian cfg.

Parameters:

cartesian_parser – Cartesian parser object.

virttest.standalone_test.``get_guest_name_list(options)

virttest.standalone_test.``get_guest_name_parser(options)

virttest.step_editor module

Step file creator/editor.

copyright:

Red Hat Inc 2009

author:

[email protected] (Michael Goldish)

classvirttest.step_editor.``StepEditor(filename=None)
Bases: virttest.step_editor.StepMakerWindow

cleanup(action)

copy_step(action)

delete_event(widget, event)

event_entry_step_activated(widget)

event_first_clicked(widget)

event_last_clicked(widget)

event_next_clicked(widget)

event_prev_clicked(widget)

event_remove_clicked(widget)

event_replace_clicked(widget)

event_save_clicked(widget)

insert_after(action)

insert_before(action)

insert_steps(filename, index)

insert_steps_after(action)

insert_steps_before(action)

open_steps_file(action)

quit(action)

read_steps_file(filename)

save_step()

set_step(index)

set_steps_file(filename)

ui= '<ui>\n <menubar name="MenuBar">\n <menu action="File">\n <menuitem action="Open"/>\n <separator/>\n <menuitem action="Quit"/>\n </menu>\n <menu action="Edit">\n <menuitem action="CopyStep"/>\n <menuitem action="DeleteStep"/>\n </menu>\n <menu action="Insert">\n <menuitem action="InsertNewBefore"/>\n <menuitem action="InsertNewAfter"/>\n <separator/>\n <menuitem action="InsertStepsBefore"/>\n <menuitem action="InsertStepsAfter"/>\n </menu>\n <menu action="Tools">\n <menuitem action="CleanUp"/>\n </menu>\n </menubar>\n</ui>'

verify_save()

write_steps_file(filename)

classvirttest.step_editor.``StepMakerWindow
Bases: object

add_key(key)

clear_barrier_state()

clear_image()

clear_keys()

clear_state(clear_screendump=True)

delete_event(widget, event)

destroy(widget)

event_button_press(widget, event)

event_button_release(widget, event)

event_check_barrier_toggled(widget)

event_check_sleep_toggled(widget)

event_clear_clicked(widget)

event_drag_motion(widget, event)

event_expose(widget, event)

event_key_press(widget, event)

event_manual_toggled(widget)

filedialog(title=None, default_filename=None)

get_keys()

get_step_lines(data_dir=None)

inputdialog(text, title, default_response='')

message(text, title)

question_yes_no(text, title)

redirect_event_box_input(press=None, release=None, scroll=None, motion=None, expose=None)

set_image(w, h, data)

set_image_from_file(filename)

set_state_from_step_lines(sr, data_dir, warn=True)

update_barrier_info()

update_mouse_click_info()

update_screendump_id(data_dir)

virttest.step_editor.``corner_and_size_clipped(startpoint, endpoint, limits)

virttest.step_editor.``key_event_to_qemu_string(event)

virttest.storage module

Classes and functions to handle storage devices.

This exports:

  • two functions for get image/blkdebug filename
  • class for image operates and basic parameters

classvirttest.storage.``Iscsidev(params, root_dir, tag)
Bases: virttest.storage.Rawdev

Class for handle iscsi devices for VM

Init the default value for image object.

Parameters:

  • params – Dictionary containing the test parameters.
  • root_dir – Base directory for relative filenames.
  • tag – Image tag defined in parameter images

classvirttest.storage.``LVMdev(params, root_dir, tag)
Bases: virttest.storage.Rawdev

Class for handle LVM devices for VM

Init the default value for image object.

Parameters:

  • params – Dictionary containing the test parameters.
  • root_dir – Base directory for relative filenames.
  • tag – Image tag defined in parameter images

exceptionvirttest.storage.``OptionMissing(option)
Bases: exceptions.Exception

Option not found in the odbject

classvirttest.storage.``QemuImg(params, root_dir, tag)
Bases: object

A basic class for handling operations of disk/block images.

Init the default value for image object.

Parameters:

  • params – Dictionary containing the test parameters.
  • root_dir – Base directory for relative filenames.
  • tag – Image tag defined in parameter images.

backup_image(params, root_dir, action, good=True, skip_existing=False)
Backup or restore a disk image, depending on the action chosen.

Parameters:

  • params – Dictionary containing the test parameters.
  • root_dir – Base directory for relative filenames.
  • action – Whether we want to backup or restore the image.
  • good – If we are backing up a good image(we want to restore it) or a bad image (we are saving a bad image for posterior analysis).

Note:

params should contain: image_name – the name of the image file, without extension image_format – the format of the image (qcow2, raw etc)

check_option(option)
Check if object has the option required.

Parameters:

option – option should be checked

staticclone_image(params, vm_name, image_name, root_dir)
Clone master image to vm specific file.

Parameters:

  • params – Dictionary containing the test parameters.
  • vm_name – Vm name.
  • image_name – Master image name.
  • root_dir – Base directory for relative filenames.

is_remote_image()
Check if image is from a remote server or not

staticrm_cloned_image(params, vm_name, image_name, root_dir)
Remove vm specific file.

Parameters:

  • params – Dictionary containing the test parameters.
  • vm_name – Vm name.
  • image_name – Master image name.
  • root_dir – Base directory for relative filenames.

classvirttest.storage.``Rawdev(params, root_dir, tag)
Bases: object

Base class for raw storage devices such as iscsi and local disks

Init the default value for image object.

Parameters:

  • params – Dictionary containing the test parameters.
  • root_dir – Base directory for relative filenames.
  • tag – Image tag defined in parameter images

virttest.storage.``file_exists(params, filename_path)
Check if image_filename exists.

Parameters:

  • params – Dictionary containing the test parameters.
  • filename_path (str) – path to file
  • root_dir (str) – Base directory for relative filenames.

Returns:

True if image file exists else False

virttest.storage.``file_remove(params, filename_path)
Remove the image :param params: Dictionary containing the test parameters. :param filename_path: path to file

virttest.storage.``get_image_blkdebug_filename(params, root_dir)
Generate an blkdebug file path from params and root_dir.

blkdebug files allow error injection in the block subsystem.

Parameters:

  • params – Dictionary containing the test parameters.
  • root_dir – Base directory for relative filenames.

Note:

params should contain: blkdebug – the name of the debug file.

virttest.storage.``get_image_filename(params, root_dir)
Generate an image path from params and root_dir.

Parameters:

  • params – Dictionary containing the test parameters.
  • root_dir – Base directory for relative filenames.
  • image_name – Force name of image.
  • image_format – Format for image.

Note:

params should contain: image_name – the name of the image file, without extension image_format – the format of the image (qcow2, raw etc)

Raises:

VMDeviceError – When no matching disk found (in indirect method).

virttest.storage.``get_image_filename_filesytem(params, root_dir)
Generate an image path from params and root_dir.

Parameters:

  • params – Dictionary containing the test parameters.
  • root_dir – Base directory for relative filenames.

Note:

params should contain: image_name – the name of the image file, without extension image_format – the format of the image (qcow2, raw etc)

Raises:

VMDeviceError – When no matching disk found (in indirect method).

virttest.storage.``postprocess_images(bindir, params)

virttest.storage.``preprocess_image_backend(bindir, params, env)

virttest.storage.``preprocess_images(bindir, params, env)

virttest.syslog_server module

classvirttest.syslog_server.``RequestHandler(request, client_address, server)
Bases: SocketServer.BaseRequestHandler

A request handler that relays all received messages as DEBUG

FACILITY_NAMES= {0: 'kern', 1: 'user', 2: 'mail', 3: 'daemon', 4: 'security', 5: 'syslog', 6: 'lpr', 7: 'news', 8: 'uucp', 9: 'cron', 10: 'authpriv', 11: 'ftp', 16: 'local0', 17: 'local1', 18: 'local2', 19: 'local3', 20: 'local4', 21: 'local5', 22: 'local6', 23: 'local7'}

LOG_ALERT= 1

LOG_AUTH= 4

LOG_AUTHPRIV= 10

LOG_CRIT= 2

LOG_CRON= 9

LOG_DAEMON= 3

LOG_DEBUG= 7

LOG_EMERG= 0

LOG_ERR= 3

LOG_FTP= 11

LOG_INFO= 6

LOG_KERN= 0

LOG_LOCAL0= 16

LOG_LOCAL1= 17

LOG_LOCAL2= 18

LOG_LOCAL3= 19

LOG_LOCAL4= 20

LOG_LOCAL5= 21

LOG_LOCAL6= 22

LOG_LOCAL7= 23

LOG_LPR= 6

LOG_MAIL= 2

LOG_NEWS= 7

LOG_NOTICE= 5

LOG_SYSLOG= 5

LOG_USER= 1

LOG_UUCP= 8

LOG_WARNING= 4

PRIORITY_NAMES= {0: 'emerg', 1: 'alert', 2: 'critical', 3: 'err', 4: 'warning', 5: 'notice', 6: 'info', 7: 'debug'}

RECORD_RE= <_sre.SRE_Pattern object at 0xcafc6c0>

decodeFacilityPriority(priority)
Decode both the facility and priority embedded in a syslog message

Parameters:

priority (integer) – an integer with facility and priority encoded

Returns:

a tuple with two strings

log(data, message_format=None)
Logs the received message as a DEBUG message

classvirttest.syslog_server.``RequestHandlerTcp(request, client_address, server)
Bases: virttest.syslog_server.RequestHandler

handle()
Handles a single request

classvirttest.syslog_server.``RequestHandlerUdp(request, client_address, server)
Bases: virttest.syslog_server.RequestHandler

handle()
Handles a single request

classvirttest.syslog_server.``SysLogServerTcp(address)
Bases: SocketServer.TCPServer

classvirttest.syslog_server.``SysLogServerUdp(address)
Bases: SocketServer.UDPServer

virttest.syslog_server.``get_default_format()
Returns the current default message format

virttest.syslog_server.``set_default_format(message_format)
Changes the default message format

Parameters:

message_format (string) – a message format string with 3 placeholders: facility, priority and message.

virttest.syslog_server.``syslog_server(address='', port=514, tcp=True, terminate_callable=None)

virttest.test_setup module

Library to perform pre/post test setup for virt test.

classvirttest.test_setup.``EGDConfig(params, env)
Bases: object

Setup egd.pl server on localhost, support startup with socket unix or tcp.

cleanup()

get_pid(socket)
Check egd.pl start at socket on localhost.

install()
Install egd.pl from source code

setup()

startup(socket)
Start egd.pl server with tcp or unix socket.

exceptionvirttest.test_setup.``EGDConfigError
Bases: exceptions.Exception

Raise when setup local egd.pl server failed.

exceptionvirttest.test_setup.``HPNotSupportedError
Bases: exceptions.Exception

Thrown when host does not support hugepages.

classvirttest.test_setup.``HugePageConfig(params)
Bases: object

Gets environment variable values and calculates the target number of huge memory pages.

Parameters:

params – Dict like object containing parameters for the test.

check_hugepage_size_as_expected(*args, **kwargs)
Check whether the hugepage size as expected

check_hugepage_support(*args, **kwargs)
Check whether the host support hugepage. Need check the cpu flag and kernel CML.

cleanup(*args, **kwargs)

get_hugepage_size()
Get the current system setting for huge memory page size.

get_multi_supported_hugepage_size()
As ‘/proc/meminfo’ only show default huge page size, this function is for get huge page size of multiple huge page pools.

For each huge page size supported by the running kernel, a subdirectory will exist, of the form:

hugepages-${size}kB

under /sys/kernel/mm/hugepages, get the support size and return a list.

Returns:

supported size list in kB unit

get_node_num_huge_pages(node, pagesize)
Get number of pages of certain page size under given numa node.

Parameters:

  • node – string or int, node number
  • pagesize – string or int, page size in kB

Returns:

int, node huge pages number of given page size

get_target_hugepages()
Calculate the target number of hugepages for testing purposes.

mount_hugepage_fs(*args, **kwargs)
Verify if there’s a hugetlbfs mount set. If there’s none, will set up a hugetlbfs mount using the class attribute that defines the mount point.

set_hugepages(*args, **kwargs)
Sets the hugepage limit to the target hugepage value calculated.

set_node_num_huge_pages(num, node, pagesize)
Set number of pages of certain page size under given numa node.

Parameters:

  • num – string or int, number of pages
  • node – string or int, node number
  • pagesize – string or int, page size in kB

setup()

classvirttest.test_setup.``KSMConfig(params, env)
Bases: object

Parameters:

params – Dict like object containing parameters for the test.

cleanup(env)

setup(env)

classvirttest.test_setup.``LibvirtPolkitConfig(params)
Bases: object

Enable polkit access driver for libvirtd and set polkit rules.

For setting JavaScript polkit rule, using template of rule to satisfy libvirt ACL API testing need, just replace keys in template.

Create a non-privileged user ‘testacl’ for test if given ‘unprivileged_user’ contains ‘EXAMPLE’, and delete the user at cleanup.

Multiple rules could be add into one config file while action_id string is offered space separated.

e.g. action_id = “org.libvirt.api.domain.start org.libvirt.api.domain.write”

then 2 actions “org.libvirt.api.domain.start” and “org.libvirt.api.domain.write” specified, which could be used to generate 2 rules in one config file.

Parameters:

params – Dict like object containing parameters for the test.

cleanup()
Cleanup polkit config

file_replace_append(fpath, pat, repl)
Replace pattern in file with replacement str if pattern found in file, else append the replacement str to file.

Parameters:

  • fpath – string, the file path
  • pat – string, the pattern string
  • repl – string, the string to replace

setup()
Enable polkit libvirt access driver and setup polkit ACL rules.

classvirttest.test_setup.``PciAssignable(driver=None, driver_option=None, host_set_flag=None, kvm_params=None, vf_filter_re=None, pf_filter_re=None, device_driver=None, nic_name_re=None, static_ip=None, net_mask=None, start_addr_PF=None)
Bases: object

Request PCI assignable devices on host. It will check whether to request PF (physical Functions) or VF (Virtual Functions).

Initialize parameter ‘type’ which could be: vf: Virtual Functions pf: Physical Function (actual hardware) mixed: Both includes VFs and PFs

If pass through Physical NIC cards, we need to specify which devices to be assigned, e.g. ‘eth1 eth2’.

If pass through Virtual Functions, we need to specify max vfs in driver e.g. max_vfs = 7 in config file.

Parameters:

  • type (string) – PCI device type.
  • driver (string) – Kernel module for the PCI assignable device.
  • driver_option (string) – Module option to specify the maximum number of VFs (eg ‘max_vfs=7’)
  • host_set_flag (string) – Flag for if the test should setup host env: 0: do nothing 1: do setup env 2: do cleanup env 3: setup and cleanup env
  • kvm_params (dict) – a dict for kvm module parameters default value
  • vf_filter_re (string) – Regex used to filter vf from lspci.
  • pf_filter_re (string) – Regex used to filter pf from lspci.
  • static_ip – Flag to be set if the test should assign static IP
  • start_addr_PF – Starting private IPv4 address for the PF interface

add_device(device_type='vf', name=None, mac=None)
Add device type and name to class.

Parameters:

  • device_type (string) – vf/pf device is added.
  • name (string) – Physical device interface name. eth1 or others
  • mac (string) – set mac address for vf.

check_vfs_count()
Check VFs count number according to the parameter driver_options.

get_devs(devices=None)
Get devices’ PCI IDs according to parameters set in self.devices.

Parameters:

devices (List of dict) – List of device dict that contain PF VF information.

Returns:

List of all available devices’ PCI IDs

Return type:

List of string

get_pf_devs(devices=None)
Get PFs PCI IDs requested by self.devices. It will try to get PF by device name. It will still return it, if device name you set already occupied. Please set unoccupied device name. If not sure, please just do not set device name. It will return unused PF list.

Parameters:

devices (List of dict) – List of device dict that contain PF VF information.

Returns:

List with all PCI IDs for the physical hardware requested

Return type:

List of string

get_pf_mlx()
Get the PF devices for mlx5_core driver

get_pf_vf_info()
Get pf and vf related information in this host that match self.pf_filter_re.

for every pf it will create following information:

pf_id:
The id of the pf device.

occupied:
Whether the pf device assigned or not

vf_ids:
Id list of related vf in this pf.

ethname:
eth device name in host for this pf.

Returns:

return a list contains pf vf information.

Return type:

builtin.list

get_same_group_devs(pci_id)
Get the device that in same iommu group.

Parameters:

pci_id (string) – Device’s pci_id

Returns:

Return the device’s pci id that in same group with pci_id.

Return type:

List of string.

get_vf_devs(devices=None)
Get all unused VFs PCI IDs.

Parameters:

devices (List of dict) – List of device dict that contain PF VF information.

Returns:

List of all available PCI IDs for Virtual Functions.

Return type:

List of string

get_vf_num_by_id(vf_id)
Return corresponding pf eth name and vf num according to vf id.

Parameters:

vf_id (string) – vf id to check.

Returns:

PF device name and vf num.

Return type:

string

get_vf_status(vf_id)
Check whether one vf is assigned to VM.

Parameters:

vf_id (string) – vf id to check.

Returns:

Return True if vf has already assigned to VM. Else return false.

Return type:

bool

get_vfs_count()
Get VFs count number according to lspci.

is_binded_to_stub(full_id)
Verify whether the device with full_id is already binded to driver.

Parameters:

full_id (String) – Full ID for the given PCI device

release_devs(*args, **kwargs)
Release all PCI devices currently assigned to VMs back to the virtualization host.

request_devs(devices=None)
Implement setup process: unbind the PCI device and then bind it to the device driver.

Parameters:

devices (List of dict) – List of device dict

Returns:

List of successfully requested devices’ PCI IDs.

Return type:

List of string

sr_iov_cleanup()
Clean up the sriov setup

Check if the PCI hardware device drive is loaded with the appropriate, parameters (none of VFs), and if it’s not, perform cleanup.

Returns:

True, if the setup was completed successfully, False otherwise.

Return type:

bool

sr_iov_setup(*args, **kwargs)
Ensure the PCI device is working in sr_iov mode.

Check if the PCI hardware device drive is loaded with the appropriate, parameters (number of VFs), and if it’s not, perform setup.

Returns:

True, if the setup was completed successfully, False otherwise.

Return type:

bool

exceptionvirttest.test_setup.``PolkitConfigCleanupError
Bases: virttest.test_setup.PolkitConfigError

Thrown when polkit config cleanup is not behaving as expected.

exceptionvirttest.test_setup.``PolkitConfigError
Bases: exceptions.Exception

Base exception for Polkit Config setup.

exceptionvirttest.test_setup.``PolkitRulesSetupError
Bases: virttest.test_setup.PolkitConfigError

Thrown when setup polkit rules is not behaving as expected.

exceptionvirttest.test_setup.``PolkitWriteLibvirtdConfigError
Bases: virttest.test_setup.PolkitConfigError

Thrown when setup libvirtd config file is not behaving as expected.

classvirttest.test_setup.``PrivateBridgeConfig(params=None)
Bases: object

cleanup()

setup()

exceptionvirttest.test_setup.``PrivateBridgeError(brname)
Bases: exceptions.Exception

classvirttest.test_setup.``PrivateOvsBridgeConfig(params=None)
Bases: virttest.test_setup.PrivateBridgeConfig

classvirttest.test_setup.``StraceQemu(test, params, env)
Bases: object

Attach strace to qemu VM processes, if enable_strace is ‘yes’. It’s useful to analyze qemu hang issue. But it will generate a large size logfile if it is enabled, so compressed original logfiles after strace process terminated to safe disk space.

log_tarball

root_dir

start(vms=None)
Attach strace to qemu VM process

stop()
Stop strace process and compress strace log file

exceptionvirttest.test_setup.``THPError
Bases: exceptions.Exception

Base exception for Transparent Hugepage setup.

exceptionvirttest.test_setup.``THPKhugepagedError
Bases: virttest.test_setup.THPError

Thrown when khugepaged is not behaving as expected.

exceptionvirttest.test_setup.``THPNotSupportedError
Bases: virttest.test_setup.THPError

Thrown when host does not support transparent hugepages.

exceptionvirttest.test_setup.``THPWriteConfigError
Bases: virttest.test_setup.THPError

Thrown when host does not support transparent hugepages.

classvirttest.test_setup.``TransparentHugePageConfig(test, params)
Bases: object

Find paths for transparent hugepages and kugepaged configuration. Also, back up original host configuration so it can be restored during cleanup.

cleanup()
: Restore the host’s original configuration after test

khugepaged_test()
Start, stop and frequency change test for khugepaged.

set_env()
Applies test configuration on the host.

setup()
Configure host for testing. Also, check that khugepaged is working as expected.

value_listed(value)
Get a parameters list from a string

virttest.test_setup.``disable_smt()
Checks whether smt is on, if so disables it in PowerPC system This function is used in env_process to check & disable smt in Power8

virttest.utils_config module

exceptionvirttest.utils_config.``ConfigError(msg)
Bases: exceptions.Exception

exceptionvirttest.utils_config.``ConfigNoOptionError(option, path)
Bases: virttest.utils_config.ConfigError

classvirttest.utils_config.``LibvirtConfigCommon(path='')
Bases: virttest.utils_config.SectionlessConfig

A abstract class to manipulate options of a libvirt related configure files in a property’s way.

Variables “__option_types__” and “conf_path” must be setup in the inherented classes before use.

“__option_types__” is a dict contains every possible option as keys and their type (“boolean”, “int”, “string”, “float” or “list”) as values.

Basic usage: 1) Create a config file object: >>> # LibvirtdConfig is a subclass of LibvirtConfigCommon. >>> config = LibvirtdConfig()

  1. Set or update an option: >>> config.listen_tcp = True >>> config.listen_tcp = 1 >>> config.listen_tcp = “1” # All three have the same effect.

    If the setting value don't meet the specified type.

    config.listen_tcp = "invalid"

    It'll thown an warning message and set a raw string instead.

    Use set_* methods when need to customize the result.

    config.set_raw("'1'")

  2. Get an option: >>> is_listening = config.listen_tcp >>> print is_listening True

  3. Delete an option from the config file: >>> del config.listen_tcp

  4. Make the changes take effect in libvirt by restart libvirt daemon. >>> from virttest import utils_libvirtd >>> utils_libvirtd.Libvirtd().restart()

  5. Restore the content of the config file. >>> config.restore()

conf_path= ''

exceptionvirttest.utils_config.``LibvirtConfigUnknownKeyError(key)
Bases: virttest.utils_config.ConfigError

exceptionvirttest.utils_config.``LibvirtConfigUnknownKeyTypeError(key, key_type)
Bases: virttest.utils_config.ConfigError

classvirttest.utils_config.``LibvirtGuestsConfig(path='')
Bases: virttest.utils_config.LibvirtConfigCommon

Class for sysconfig libvirt-guests config file.

conf_path= '/etc/sysconfig/libvirt-guests'

classvirttest.utils_config.``LibvirtQemuConfig(path='')
Bases: virttest.utils_config.LibvirtConfigCommon

Class for libvirt qemu config file.

conf_path= '/etc/libvirt/qemu.conf'

classvirttest.utils_config.``LibvirtdConfig(path='')
Bases: virttest.utils_config.LibvirtConfigCommon

Class for libvirt daemon config file.

conf_path= '/etc/libvirt/libvirtd.conf'

classvirttest.utils_config.``LibvirtdSysConfig(path='')
Bases: virttest.utils_config.LibvirtConfigCommon

Class for sysconfig libvirtd config file.

conf_path= '/etc/sysconfig/libvirtd'

classvirttest.utils_config.``SectionlessConfig(path)
Bases: object

This is a wrapper class for python’s internal library ConfigParser except allows manipulating sectionless configuration file with a dict-like way.

Example config file test.conf:

># This is a comment line. >a = 1 >b = [hi, there] >c = hello >d = “hi, there” >e = [hi, > there]

Example script using try...finally... statement:

>>> from virttest import utils_config
>>> config = utils_config.SectionlessConfig('test.conf')
>>> try:
...     print len(config)
...     print config
...     print config['a']
...     del config['a']
...     config['f'] = 'test'
...     print config
... finally:
...     config.restore()

Example script using with statement:

>>> from virttest import utils_config
>>> with utils_config.SectionlessConfig('test.conf') as config:
...     print len(config)
...     print config
...     print config['a']
...     del config['a']
...     config['f'] = 'test'
...     print config

get_boolean(option)

get_float(option)

get_int(option)

get_list(option)

get_raw(option)

get_string(option)

restore()

set_boolean(option, value)

set_float(option, value)

set_int(option, value)

set_list(option, value)

set_raw(option, value)

set_string(option, value)

virttest.utils_conn module

connection tools to manage kinds of connection.

exceptionvirttest.utils_conn.``ConnCertError(cert, output)
Bases: virttest.utils_conn.ConnectionError

Error in building certificate file with certtool command.

exceptionvirttest.utils_conn.``ConnCmdClientError(cmd, output)
Bases: virttest.utils_conn.ConnectionError

Error in executing cmd on client.

exceptionvirttest.utils_conn.``ConnCopyError(src_path, dest_path)
Bases: virttest.utils_conn.ConnectionError

Error in coping file.

exceptionvirttest.utils_conn.``ConnForbiddenError(detail)
Bases: virttest.utils_conn.ConnectionError

Error in forbidden operation.

exceptionvirttest.utils_conn.``ConnLoginError(dest, detail)
Bases: virttest.utils_conn.ConnectionError

Error in login.

exceptionvirttest.utils_conn.``ConnMkdirError(directory, output)
Bases: virttest.utils_conn.ConnectionError

Error in making directory.

exceptionvirttest.utils_conn.``ConnNotImplementedError(method_type, class_type)
Bases: virttest.utils_conn.ConnectionError

Error in calling unimplemented method

exceptionvirttest.utils_conn.``ConnPrivKeyError(key, output)
Bases: virttest.utils_conn.ConnectionError

Error in building private key with certtool command.

exceptionvirttest.utils_conn.``ConnRmCertError(cert, output)
Bases: virttest.utils_conn.ConnectionError

Error in removing certificate file with rm command.

exceptionvirttest.utils_conn.``ConnSCPError(src_ip, src_path, dest_ip, dest_path, detail)
Bases: virttest.utils_conn.ConnectionError

Error in SCP.

exceptionvirttest.utils_conn.``ConnServerRestartError(output)
Bases: virttest.utils_conn.ConnectionError

Error in restarting libvirtd on server.

exceptionvirttest.utils_conn.``ConnToolNotFoundError(tool, detail)
Bases: virttest.utils_conn.ConnectionError

Error in not found tools.

classvirttest.utils_conn.``ConnectionBase(*args, **dargs)
Bases: virttest.propcan.PropCanBase

Base class of a connection between server and client.

Connection is build to from client to server. And there are some information for server and client in ConnectionBase.

Initialize instance with server info and client info.

Parameters:

  • server_ip – Ip of server.
  • server_user – Username to login server.
  • server_pwd – Password for server_user.
  • client_ip – IP of client.
  • client_user – Username to login client.
  • client_pwd – Password for client_user.
  • server_session – Session to server and execute command on server.
  • client_session – Session to client and execute command on client.
  • tmp_dir – A tmp dir to store some tmp file.
  • auto_recover – If it is False same as the default, conn_recover() will not called by __del__() If it is True, Connection class will call conn_recover() in __del__(), then user need not call it manually. But the errors in conn_recover() will be ignored.

Example:

connection = ConnectionBase(server_ip=server_ip,
                            server_user=server_user,
                            server_pwd=server_pwd,
                            client_ip=client_ip,
                            client_user=client_user,
                            client_pwd=client_pwd)
connection.conn_setup()
virsh.connect(URI)
connection.conn_recover()

We suggest not to pass auto_recover=True to __init__(), and call conn_recover() manually when you don’t need this connection any more.

auto_recover

client_ip

client_pwd

client_session

client_user

close_session()
If some session exists, close it down.

conn_check()
waiting for implemented by subclass.

conn_recover()
waiting for implemented by subclass.

conn_setup()
waiting for implemented by subclass.

del_client_session()
Delete client session.

del_server_session()
Delete server session.

get_client_session()
If the client session exists,return it. else create a session to client and set client_session.

get_server_session()
If the server session exists,return it. else create a session to server and set server_session.

server_ip

server_pwd

server_session

server_user

set_client_session(value)
Set client session to value.

set_server_session(value=None)
Set server session to value.

tmp_dir

exceptionvirttest.utils_conn.``ConnectionError
Bases: exceptions.Exception

The base error in connection.

exceptionvirttest.utils_conn.``SSHCheckError(server_ip, output)
Bases: virttest.utils_conn.ConnectionError

Base Error in check of SSH connection.

classvirttest.utils_conn.``SSHConnection(*args, **dargs)
Bases: virttest.utils_conn.ConnectionBase

Connection of SSH transport.

Some specific variables in SSHConnection class.

ssh_rsa_pub_path: Path of id_rsa.pub, default is /root/.ssh/id_rsa.pub. ssh_id_rsa_path: Path of id_rsa, default is /root/.ssh/id_rsa. SSH_KEYGEN, SSH_ADD, SSH_COPY_ID, SSH_AGENT, SHELL, SSH: tools to build a non-pwd connection.

Initialization of SSH connection.

(1). Call __init__ of class ConnectionBase. (2). Initialize tools will be used in conn setup.

SHELL

SSH

SSH_ADD

SSH_AGENT

SSH_COPY_ID

SSH_KEYGEN

conn_check()
Check the SSH connection.

(1).Initialize some variables. (2).execute ssh command to check conn.

conn_recover()
Clean up authentication host.

conn_setup(timeout=10)
Setup of SSH connection.

(1).Initialization of some variables. (2).Check tools. (3).Initialization of id_rsa. (4).set a ssh_agent. (5).copy pub key to server.

Parameters:

timeout – The time duration (in seconds) to wait for prompts

ssh_id_rsa_path

ssh_rsa_pub_path

exceptionvirttest.utils_conn.``SSHRmAuthKeysError(auth_keys, output)
Bases: virttest.utils_conn.ConnectionError

Error in removing authorized_keys file.

classvirttest.utils_conn.``TCPConnection(*args, **dargs)
Bases: virttest.utils_conn.ConnectionBase

Connection class for TCP transport.

Some specific variables for TCPConnection class.

init params for TCP connection and init tmp_dir.

Parameters:

  • tcp_port – Port of tcp connection, default is 16509.
  • sysconfig_libvirtd_path – Path of libvirtd file, default is /etc/sysconfig/libvirtd.
  • libvirtd_conf_path – Path of libvirtd.conf, default is /etc/libvirt/libvirtd.conf.

auth_tcp

conn_recover()
Clean up for TCP connection.

(1).initialize variables. (2).Delete the RemoteFile. (3).restart libvirtd on server.

conn_setup()
Enable tcp connect of libvirtd on server.

(1).initialization for variables. (2).edit /etc/sysconfig/libvirtd on server. (3).edit /etc/libvirt/libvirtd.conf on server. (4).restart libvirtd service on server.

listen_addr

remote_libvirtdconf

remote_syslibvirtd

sasl_allowed_users

tcp_port

classvirttest.utils_conn.``TLSConnection(*args, **dargs)
Bases: virttest.utils_conn.ConnectionBase

Connection of TLS transport.

Some specific variables for TLSConnection class.

server_cn, client_cn, ca_cn: Info to build pki key. CERTOOL: tool to build key for TLS connection. pki_CA_dir: Dir to store CA key. libvirt_pki_dir, libvirt_pki_private_dir: Dir to store pki in libvirt. sysconfig_libvirtd_path, libvirtd_conf_path: Path of libvirt config file. hosts_path: /etc/hosts auth_tls, tls_port, listen_addr: custom TLS Auth, port and listen address tls_allowed_dn_list: DN’s list are checked tls_verify_cert: disable verification, default is to always verify tls_sanity_cert: disable checks, default is to always run sanity checks custom_pki_path: custom pki path ca_cakey_path: CA certification path, sometimes need to reuse previous cert scp_new_cacert: copy new CA certification, default is to always copy restart_libvirtd: default is to restart libvirtd

Initialization of TLSConnection.

(1).call the init func in ConnectionBase. (2).check and set CERTTOOL. (3).make a tmp directory as a workspace. (4).set values of pki related.

CERTTOOL

auth_tls

ca_cakey_path

ca_cn

cert_recover()
Do the clean up certifications work.

(1).initialize variables. (2).Delete local and remote generated certifications file.

client_cn

client_hosts

client_setup()
setup private key and certificate file for client.

(1).initialization for variables. (2).build a key for client. (3).copy files to client. (4).edit /etc/hosts on client.

conn_recover()
Do the clean up work.

(1).initialize variables. (2).Delete remote file. (3).Restart libvirtd on server.

conn_setup(server_setup=True, client_setup=True)
setup a TLS connection between server and client. At first check the certtool needed to setup. Then call some setup functions to complete connection setup.

custom_pki_path

libvirt_pki_dir

libvirt_pki_private_dir

listen_addr

pki_CA_dir

restart_libvirtd

scp_new_cacert

server_cn

server_libvirtdconf

server_setup()
setup private key and certificate file for server.

(1).initialization for variables. (2).build server key. (3).copy files to server. (4).edit /etc/sysconfig/libvirtd on server. (5).edit /etc/libvirt/libvirtd.conf on server. (6).restart libvirtd service on server.

server_syslibvirtd

tls_allowed_dn_list

tls_port

tls_sanity_cert

tls_verify_cert

classvirttest.utils_conn.``UNIXConnection(*args, **dargs)
Bases: virttest.utils_conn.ConnectionBase

Connection class for UNIX transport.

Some specific variables for UNIXConnection class.

init params for UNIX connection.

Parameters:

  • auth_unix_ro – UNIX R/O sockets, default is ‘none’.
  • auth_unix_rw – UNIX R/W sockets, default is ‘none’.
  • unix_sock_group – UNIX domain socket group ownership, default is ‘libvirt’.
  • access_drivers – access control restrictions, default is ‘[“polkit”]’.
  • unix_sock_ro_perms – UNIX socket permissions for the R/O socket, default is ‘0777’.
  • unix_sock_rw_perms – UNIX socket permissions for the R/W socket, default is ‘0770’.
  • client_libvirtdconf – Path of client libvirtd.conf, default is ‘/etc/libvirt/libvirtd.conf’.
  • restart_libvirtd – default is to restart libvirtd.

access_drivers

auth_unix_ro

auth_unix_rw

client_ip

client_libvirtdconf

client_pwd

client_user

conn_recover()
Do the clean up work.

(1).Delete remote file. (2).Restart libvirtd on server.

conn_setup()
Setup a UNIX connection.

(1).Initialize variables. (2).Update libvirtd.conf configuration. (3).Restart libvirtd on client.

restart_libvirtd

unix_sock_dir

unix_sock_group

unix_sock_ro_perms

unix_sock_rw_perms

virttest.utils_conn.``build_CA(tmp_dir, cn='AUTOTEST.VIRT', ca_cakey_path=None, certtool='certtool')
setup private key and certificate file which are needed to build. certificate file for client and server.

(1).initialization for variables. (2).make a private key with certtool command. (3).prepare a info file. (4).make a certificate file with certtool command.

virttest.utils_conn.``build_client_key(tmp_dir, client_cn='TLSClient', certtool='certtool')
(1).initialization for variables. (2).make a private key with certtool command. (3).prepare a info file. (4).make a certificate file with certtool command.

virttest.utils_conn.``build_server_key(tmp_dir, ca_cakey_path=None, server_cn='TLSServer', certtool='certtool')
(1).initialization for variables. (2).make a private key with certtool command. (3).prepare a info file. (4).make a certificate file with certtool command.

virttest.utils_disk module

Virtualization test - Virtual disk related utility functions

copyright:

Red Hat Inc.

classvirttest.utils_disk.``CdromDisk(path, tmpdir)
Bases: virttest.utils_disk.Disk

Represents a CDROM disk that we can master according to our needs.

close(*args, **kwargs)

setup_virtio_win2008(virtio_floppy, cdrom_virtio)
Setup the install cdrom with the virtio storage drivers, win2008 style.

Win2008, Vista and 7 require people to point out the path to the drivers on the unattended file, so we just need to copy the drivers to the extra cdrom disk. Important to note that it’s possible to specify drivers from a CDROM, so the floppy driver copy is optional. Process:

  1. Copy the virtio drivers on the virtio floppy to the install cdrom, if there is one available

classvirttest.utils_disk.``CdromInstallDisk(path, tmpdir, source_cdrom, extra_params)
Bases: virttest.utils_disk.Disk

Represents a install CDROM disk that we can master according to our needs.

close(*args, **kwargs)

get_answer_file_path(filename)

classvirttest.utils_disk.``Disk
Bases: object

Abstract class for Disk objects, with the common methods implemented.

close()

copy_to(src)

get_answer_file_path(filename)

classvirttest.utils_disk.``FloppyDisk(*args, **kwargs)
Bases: virttest.utils_disk.Disk

Represents a floppy disk. We can copy files to it, and setup it in convenient ways.

close()
Copy everything that is in the mountpoint to the floppy.

copy_to(src)

setup_virtio_win2003(virtio_floppy, virtio_oemsetup_id)
Setup the install floppy with the virtio storage drivers, win2003 style.

Win2003 and WinXP depend on the file txtsetup.oem file to install the virtio drivers from the floppy, which is a .ini file. Process:

  1. Copy the virtio drivers on the virtio floppy to the install floppy
  2. Parse the ini file with config parser
  3. Modify the identifier of the default session that is going to be executed on the config parser object
  4. Re-write the config file to the disk

setup_virtio_win2008(virtio_floppy)
Setup the install floppy with the virtio storage drivers, win2008 style.

Win2008, Vista and 7 require people to point out the path to the drivers on the unattended file, so we just need to copy the drivers to the driver floppy disk. Important to note that it’s possible to specify drivers from a CDROM, so the floppy driver copy is optional. Process:

  1. Copy the virtio drivers on the virtio floppy to the install floppy, if there is one available

classvirttest.utils_disk.``GuestFSModiDisk(disk)
Bases: object

class of guest disk using guestfs lib to do some operation(like read/write) on guest disk:

mount_all()

mounts()

os_inspects()

read_file(file_name)
read file from the guest disk, return the content of the file

Parameters:

file_name – the file you want to read.

replace_image_file_content(file_name, find_con, rep_con)
replace file content matches in the file with rep_con. support using Regular expression

Parameters:

  • file_name – the file you want to replace
  • find_con – the original content you want to replace.
  • rep_con – the replace content you want.

umount_all()

write_to_image_file(file_name, content, w_append=False)
Write content to the file on the guest disk.

When using this method all the original content will be overriding. if you don’t hope your original data be override set w_append=True.

Parameters:

  • file_name – the file you want to write
  • content – the content you want to write.
  • w_append – append the content or override

virttest.utils_disk.``copytree(src, dst, overwrite=True, ignore='')
Copy dirs from source to target.

Parameters:

  • src – source directory
  • dst – destination directory
  • overwrite – overwrite file if exist or not
  • ignore – files want to ignore

virttest.utils_disk.``is_mount(src, dst)
Check is src or dst mounted.

Parameters:

  • src – source device or directory, if None will skip to check
  • dst – mountpoint, if None will skip to check

Returns:

if mounted mountpoint or device, else return False

virttest.utils_disk.``mount(src, dst, fstype=None, options=None, verbose=False)
Mount src under dst if it’s really mounted, then remout with options.

Parameters:

  • src – source device or directory, if None will skip to check
  • dst – mountpoint, if None will skip to check
  • fstype – filesystem type need to mount

Returns:

if mounted return True else return False

virttest.utils_disk.``umount(src, dst, verbose=False)
Umount src from dst, if src really mounted under dst.

Parameters:

  • src – source device or directory, if None will skip to check
  • dst – mountpoint, if None will skip to check

Returns:

if unmounted return True else return False

virttest.utils_env module

classvirttest.utils_env.``Env(filename=None, version=0)
Bases: UserDict.IterableUserDict

A dict-like object containing global objects used by tests.

Create an empty Env object or load an existing one from a file.

If the version recorded in the file is lower than version, or if some error occurs during unpickling, or if filename is not supplied, create an empty Env object.

Parameters:

  • filename – Path to an env file.
  • version – Required env version (int).

clean_objects()
Destroy all objects registered in this Env object.

create_vm(vm_type, target, name, params, bindir)
Create and register a VM in this Env object

destroy()
Destroy all objects stored in Env and remove the backing file.

get_all_vms()
Return a list of all VM objects in this Env object.

get_lvmdev(name)
Get lvm device object by name from env;

Parameters:

name – lvm device object name;

Returns:

lvmdev object

get_syncserver(port)
Return a Sync Server object by its port.

Parameters:

port – Sync Server port.

get_vm(name)
Return a VM object by its name.

Parameters:

name – VM name.

register_lvmdev(*args, **kwargs)
Register lvm device object into env;

Parameters:

  • name – name of register lvmdev object
  • lvmdev – lvmdev object;

register_syncserver(*args, **kwargs)
Register a Sync Server in this Env object.

Parameters:

  • port – Sync Server port.
  • server – Sync Server object.

register_vm(*args, **kwargs)
Register a VM in this Env object.

Parameters:

  • name – VM name.
  • vm – VM object.

save(filename=None)
Pickle the contents of the Env object into a file.

Parameters:

filename – Filename to pickle the dict into. If not supplied, use the filename from which the dict was loaded.

start_tcpdump(params)

stop_tcpdump()

unregister_lvmdev(*args, **kwargs)
Remove lvm device object from env;

Parameters:

name – name of lvm device object;

unregister_syncserver(*args, **kwargs)
Remove a given Sync Server.

Parameters:

port – Sync Server port.

unregister_vm(*args, **kwargs)
Remove a given VM.

Parameters:

name – VM name.

exceptionvirttest.utils_env.``EnvSaveError
Bases: exceptions.Exception

virttest.utils_env.``get_env_version()

virttest.utils_env.``lock_safe(function)
Get the environment safe lock, run the function, then release the lock.

Unfortunately, it only works if the 1st argument of the function is an Env instance. This is mostly to save up code.

Parameters:

function – Function to wrap.

virttest.utils_gdb module

classvirttest.utils_gdb.``GDB(command=None)
Bases: aexpect.client.Expect

Class to manipulate a inferior process in gdb.

back_trace()
Get current backtrace stack as a list of lines.

cmd(command, cont=True)
Call a gdb of GDB/MI command.

Parameters:

  • command – Command line to be called
  • cont – Whether continue the inferior after calling the command

cont()
Continue a stopped inferior.

exit()
Exit the gdb session.

insert_break(break_func)
Insert a function breakpoint.

Parameters:

break_func – Function at which breakpoint inserted

kill()
Kill inferior by sending a SIGTERM signal.

run(arg_str='')
Start the inferior with an optional argument string.

Parameters:

arg_str – Argument the inferior to be called with

send_signal(signal_name)
Send a signal to the inferior.

Parameters:

signal_name – Signal name as a string or integer

set_callback(callback_type, func, params=None)
Set a callback function to a customized function.

Parameters:

  • callback_type – Could be one of “stop”, “start”, “termination”, “break” or “signal”
  • func – Function to be set as callback
  • params – Parameters to be passed to callback function

stop()
Stop inferior by sending a SIGINT signal.

wait_for_start(timeout=60)
Wait the inferior to start.

Parameters:

timeout – Max time to wait

wait_for_stop(timeout=60)
Wait the inferior to be stopped.

Parameters:

timeout – Max time to wait

wait_for_termination(timeout=60)
Wait the gdb session to be exited.

Parameters:

timeout – Max time to wait

exceptionvirttest.utils_gdb.``GDBCmdError(command, msg)
Bases: virttest.utils_gdb.GDBError

Exception raised when calling an gdb command.

exceptionvirttest.utils_gdb.``GDBError
Bases: exceptions.Exception

General module exception class

virttest.utils_libguestfs module

libguestfs tools test utility functions.

classvirttest.utils_libguestfs.``Guestfish(disk_img=None, ro_mode=False, libvirt_domain=None, inspector=False, uri=None, mount_options=None, run_mode='interactive')
Bases: virttest.utils_libguestfs.LibguestfsBase

Execute guestfish, using a new guestfish shell each time.

Initialize guestfish command with options.

Parameters:

  • disk_img – if it is not None, use option ‘-a disk’.
  • ro_mode – only for disk_img. add option ‘–ro’ if it is True.
  • libvirt_domain – if it is not None, use option ‘-d domain’.
  • inspector – guestfish mounts vm’s disks automatically
  • uri – guestfish’s connect uri
  • mount_options – Mount the named partition or logical volume on the given mountpoint.

complete_cmd(command)
Execute built-in command in a complete guestfish command (Not a guestfish session). command: guestfish [–options] [commands]

classvirttest.utils_libguestfs.``GuestfishPersistent(disk_img=None, ro_mode=False, libvirt_domain=None, inspector=False, uri=None, mount_options=None, run_mode='interactive')
Bases: virttest.utils_libguestfs.Guestfish

Execute operations using persistent guestfish session.

SESSION_COUNTER= 0

add_domain(domain, libvirturi=None, readonly=False, iface=None, live=False, allowuuid=False, readonlydisk=None)
domain/add-domain - add the disk(s) from a named libvirt domain

This function adds the disk(s) attached to the named libvirt domain “dom”. It works by connecting to libvirt, requesting the domain and domain XML from libvirt, parsing it for disks, and calling “add_drive_opts” on each one.

add_drive(filename)
add-drive - add an image to examine or modify

This function is the equivalent of calling “add_drive_opts” with no optional parameters, so the disk is added writable, with the format being detected automatically.

add_drive_opts(filename, readonly=False, format=None, iface=None, name=None, label=None, protocol=None, server=None, username=None, secret=None, cachemode=None, discard=None, copyonread=False)
add-drive-opts - add an image to examine or modify.

This function adds a disk image called “filename” to the handle. “filename” may be a regular host file or a host device.

add_drive_ro(filename)
add-ro/add-drive-ro - add a drive in snapshot mode (read-only)

This function is the equivalent of calling “add_drive_opts” with the optional parameter “GUESTFS_ADD_DRIVE_OPTS_READONLY” set to 1, so the disk is added read-only, with the format being detected automatically.

add_drive_ro_with_if(filename, iface)
add-drive-ro-with-if - add a drive read-only specifying the QEMU block emulation to use

This is the same as “add_drive_ro” but it allows you to specify the QEMU interface emulation to use at run time.

add_drive_scratch(size, name=None, label=None)
add-drive-scratch - add a temporary scratch drive

This command adds a temporary scratch drive to the handle. The “size” parameter is the virtual size (in bytes). The scratch drive is blank initially (all reads return zeroes until you start writing to it). The drive is deleted when the handle is closed.

add_drive_with_if(filename, iface)
add-drive-with-if - add a drive specifying the QEMU block emulation to use

This is the same as “add_drive” but it allows you to specify the QEMU interface emulation to use at run time.

alloc(filename, size)
alloc - allocate and add a disk file

This creates an empty (zeroed) file of the given size, and then adds so it can be further examined.

aug_clear(augpath)
aug-clear - clear Augeas path

Set the value associated with “path” to “NULL”. This is the same as the augtool(1) “clear” command.

aug_close()
aug-close - close the current Augeas handle and free up any resources used by it.

After calling this, you have to call “aug_init” again before you can use any other Augeas functions.

aug_defnode(node, expr, value)
aug-defnode - defines a variable “name” whose value is the result of evaluating “expr”.

If “expr” evaluates to an empty nodeset, a node is created, equivalent to calling “aug_set” “expr”, “value”. “name” will be the nodeset containing that single node.

On success this returns a pair containing the number of nodes in the nodeset, and a boolean flag if a node was created.

aug_defvar(name, expr)
aug-defvar - define an Augeas variable

Defines an Augeas variable “name” whose value is the result of evaluating “expr”. If “expr” is NULL, then “name” is undefined.

On success this returns the number of nodes in “expr”, or 0 if “expr” evaluates to something which is not a nodeset.

aug_get(augpath)
aug-get - look up the value of an Augeas path

Look up the value associated with “path”. If “path” matches exactly one node, the “value” is returned.

aug_init(root, flags)
aug-init - create a new Augeas handle

Create a new Augeas handle for editing configuration files. If there was any previous Augeas handle associated with this guestfs session, then it is closed.

aug_insert(augpath, label, before)
aug-insert - insert a sibling Augeas node

Create a new sibling “label” for “path”, inserting it into the tree before or after “path” (depending on the boolean flag “before”).

“path” must match exactly one existing node in the tree, and “label” must be a label, ie. not contain “/”, “*” or end with a bracketed index “[N]”.

aug_label(augpath)
aug-label - return the label from an Augeas path expression

The label (name of the last element) of the Augeas path expression “augpath” is returned. “augpath” must match exactly one node, else this function returns an error.

aug_load()
aug-load - load files into the tree

Load files into the tree. See “aug_load” in the Augeas documentation for the full gory details.

aug_ls(augpath)
aug-ls - list Augeas nodes under augpath

This is just a shortcut for listing “aug_match” “path/*” and sorting the resulting nodes into alphabetical order.

aug_match(augpath)
aug-match - return Augeas nodes which match augpath

Returns a list of paths which match the path expression “path”. The returned paths are sufficiently qualified so that they match exactly one node in the current tree.

aug_mv(src, dest)
aug-mv - move Augeas node

Move the node “src” to “dest”. “src” must match exactly one node. “dest” is overwritten if it exists.

aug_rm(augpath)
aug-rm - remove an Augeas path

Remove “path” and all of its children. On success this returns the number of entries which were removed.

aug_save()
aug-save - write all pending Augeas changes to disk

This writes all pending changes to disk. The flags which were passed to “aug_init” affect exactly how files are saved.

aug_set(augpath, val)
aug-set - set Augeas path to value

Set the value associated with “path” to “val”.

In the Augeas API, it is possible to clear a node by setting the value to NULL. Due to an oversight in the libguestfs API you cannot do that with this call. Instead you must use the “aug_clear” call.

aug_setm(base, sub, val)
aug-setm - set multiple Augeas nodes

available(groups)
available - test availability of some parts of the API

This command is used to check the availability of some groups of functionality in the appliance, which not all builds of the libguestfs appliance will be able to provide.

available_all_groups()
available-all-groups - return a list of all optional groups

This command returns a list of all optional groups that this daemon knows about. Note this returns both supported and unsupported groups. To find out which ones the daemon can actually support you have to call “available” / “feature_available” on each member of the returned list.

blkid(device)
blkid - print block device attributes

This command returns block device attributes for “device”. The following fields are usually present in the returned hash. Other fields may also be present.

blockdev_flushbufs(device)
blockdev-flushbufs - flush device buffers

This tells the kernel to flush internal buffers associated with “device”.

blockdev_getbsz(device)
blockdev-getbsz - get blocksize of block device

This returns the block size of a device.

blockdev_getro(device)
blockdev-getro - is block device set to read-only

Returns a boolean indicating if the block device is read-only (true if read-only, false if not).

blockdev_getsize64(device)
blockdev-getsize64 - get total size of device in bytes

This returns the size of the device in bytes

blockdev_getss(device)
blockdev-getss - get sectorsize of block device

This returns the size of sectors on a block device. Usually 512, but can be larger for modern devices.

blockdev_getsz(device)
blockdev-getsz - get total size of device in 512-byte sectors

This returns the size of the device in units of 512-byte sectors (even if the sectorsize isn’t 512 bytes ... weird).

blockdev_rereadpt(device)
blockdev-rereadpt - reread partition table

Reread the partition table on “device”.

blockdev_setbsz(device, blocksize)
blockdev-setbsz - set blocksize of block device

This sets the block size of a device.

blockdev_setro(device)
blockdev-setro - set block device to read-only

Sets the block device named “device” to read-only.

blockdev_setrw(device)
blockdev-setrw - set block device to read-write

Sets the block device named “device” to read-write.

canonical_device_name(device)
canonical-device-name - return canonical device name

This utility function is useful when displaying device names to the user.

case_sensitive_path(path)
case-sensitive-path - return true path on case-insensitive filesystem

The “drop-caches” command can be used to resolve case insensitive paths on a filesystem which is case sensitive. The use case is to resolve paths which you have read from Windows configuration files or the Windows Registry, to the true path.

cat(path)
cat - list the contents of a file

Return the contents of the file named “path”.

checksum(csumtype, path)
checksum - compute MD5, SHAx or CRC checksum of file

This call computes the MD5, SHAx or CRC checksum of the file named “path”.

checksum_device(csumtype, device)
checksum-device - compute MD5, SHAx or CRC checksum of the contents of a device

This call computes the MD5, SHAx or CRC checksum of the contents of the device named “device”. For the types of checksums supported see the “checksum” command.

checksums_out(csumtype, directory, sumsfile)
checksums-out - compute MD5, SHAx or CRC checksum of files in a directory

This command computes the checksums of all regular files in “directory” and then emits a list of those checksums to the local output file “sumsfile”.

chmod(mode, path)
chmod - change file mode

Change the mode (permissions) of “path” to “mode”. Only numeric modes are supported.

chown(owner, group, path)
chown - change file owner and group

Change the file owner to “owner” and group to “group”.

close_session()
If a persistent session exists, close it down.

command(cmd)
command - run a command from the guest filesystem

This call runs a command from the guest filesystem. The filesystem must be mounted, and must contain a compatible operating system (ie. something Linux, with the same or compatible processor architecture).

command_lines(cmd)
command-lines - run a command, returning lines

This is the same as “command”, but splits the result into a list of lines.

compress_device_out(ctype, device, zdevice)
compress-device-out - output compressed device

This command compresses “device” and writes it out to the local file “zdevice”.

The “ctype” and optional “level” parameters have the same meaning as in “compress_out”.

compress_out(ctype, file, zfile)
compress-out - output compressed file

This command compresses “file” and writes it out to the local file “zfile”.

The compression program used is controlled by the “ctype” parameter. Currently this includes: “compress”, “gzip”, “bzip2”, “xz” or “lzop”. Some compression types may not be supported by particular builds of libguestfs, in which case you will get an error containing the substring “not supported”.

The optional “level” parameter controls compression level. The meaning and default for this parameter depends on the compression program being used.

config(hvparam, hvvalue)
config - add hypervisor parameters

This can be used to add arbitrary hypervisor parameters of the form -param value. Actually it’s not quite arbitrary - we prevent you from setting some parameters which would interfere with parameters that we use.

copy_in(local, remotedir)
copy-in - copy local files or directories into an image

“copy-in” copies local files or directories recursively into the disk image, placing them in the directory called “/remotedir” (which must exist).

copy_out(remote, localdir)
copy-out - copy remote files or directories out of an image

“copy-out” copies remote files or directories recursively out of the disk image, placing them on the host disk in a local directory called “localdir” (which must exist).

copy_size(src, dest, size)
copy-size - copy size bytes from source to destination using dd

This command copies exactly “size” bytes from one source device or file “src” to another destination device or file “dest”.

cp(src, dest)
cp - copy a file

This copies a file from “src” to “dest” where “dest” is either a destination filename or destination directory.

cp_a(src, dest)
cp-a - copy a file or directory recursively

This copies a file or directory from “src” to “dest” recursively using the “cp -a” command.

dd(src, dest)
dd - copy from source to destination using dd

This command copies from one source device or file “src” to another destination device or file “dest”.Normally you would use this to copy to or from a device or partition,for example to duplicate a filesystem

debug(subcmd, extraargs)
debug - debugging and internals

The “debug” command exposes some internals of “guestfsd” (the guestfs daemon) that runs inside the hypervisor.

delete_event(name)
delete-event - delete a previously registered event handler

Delete the event handler which was previously registered as “name”. If multiple event handlers were registered with the same name, they are all deleted.

device_index(device)
device-index - convert device to index

This function takes a device name (eg. “/dev/sdb”) and returns the index of the device in the list of devices

df()
df - report file system disk space usage

This command runs the “df” command to report disk space used.

df_h()
df-h - report file system disk space usage (human readable)

This command runs the “df -h” command to report disk space used in human-readable format.

disk_format(filename)
disk-format - detect the disk format of a disk image

Detect and return the format of the disk image called “filename”, “filename” can also be a host device, etc

disk_has_backing_file(filename)
disk-has-backing-file - return whether disk has a backing file

Detect and return whether the disk image “filename” has a backing file

disk_virtual_size(filename)
disk-virtual-size - return virtual size of a disk

Detect and return the virtual size in bytes of the disk image”

dmesg()
dmesg - return kernel messages

This returns the kernel messages (“dmesg” output) from the guest kernel. This is sometimes useful for extended debugging of problems.

do_mount(mountpoint)
do_mount - Automaticly mount

Mount a lvm or physical partation to ‘/’

download(remotefilename, filename)
download - download a file to the local machine

Download file “remotefilename” and save it as “filename” on the local machine.

download_offset(remotefilename, filename, offset, size)
download-offset - download a file to the local machine with offset and size

Download file “remotefilename” and save it as “filename” on the local machine.

drop_caches(whattodrop)
drop-caches - drop kernel page cache, dentries and inodes

The “drop-caches” command instructs the guest kernel to drop its page cache, and/or dentries and inode caches. The parameter “whattodrop” tells the kernel what precisely to drop.

du(path)
du - estimate file space usage

This command runs the “du -s” command to estimate file space usage for “path”.

e2fsck(device, correct=None, forceall=None)
e2fsck - check an ext2/ext3 filesystem

This runs the ext2/ext3 filesystem checker on “device”. It can take the following optional arguments:

e2fsck_f(device)
e2fsck-f - check an ext2/ext3 filesystem

This runs “e2fsck -p -f device”, ie. runs the ext2/ext3 filesystem checker on “device”, noninteractively (-p), even if the filesystem appears to be clean (-f).

echo(params=None)
echo - display a line of text

This echos the parameters to the terminal.

echo_daemon(words)
echo-daemon - echo arguments back to the client

This command concatenates the list of “words” passed with single spaces between them and returns the resulting string.

egrep(regex, path)
egrep - return lines matching a pattern

This calls the external “egrep” program and returns the matching lines.

egrepi(regex, path)
egrepi - return lines matching a pattern

This calls the external “egrep -i” program and returns the matching lines.

equal(file1, file2)
equal - test if two files have equal contents

This compares the two files “file1” and “file2” and returns true if their content is exactly equal, or false otherwise.

event(name, eventset, script)
event - register a handler for an event or events

Register a shell script fragment which is executed when an event is raised. See “guestfs_set_event_callback” in guestfs(3) for a discussion of the event API in libguestfs.

exists(path)
exists - test if file or directory exists

This returns “true” if and only if there is a file, directory (or anything) with the given “path” name

extlinux(directory)
extlinux - install the SYSLINUX bootloader on an ext2/3/4 or btrfs filesystem

Install the SYSLINUX bootloader on the device mounted at “directory”. Unlike “syslinux” which requires a FAT filesystem, this can be used on an ext2/3/4 or btrfs filesystem.

fallocate(path, len)
fallocate - preallocate a file in the guest filesystem

This command preallocates a file (containing zero bytes) named “path” of size “len” bytes. If the file exists already, it is overwritten.

fallocate64(path, len)
fallocate - preallocate a file in the guest filesystem

This command preallocates a file (containing zero bytes) named “path” of size “len” bytes. If the file exists already, it is overwritten.

feature_available(groups)
feature-available - test availability of some parts of the API

This is the same as “available”, but unlike that call it returns a simple true/false boolean result, instead of throwing an exception if a feature is not found. For other documentation see “available”.

fgrep(pattern, path)
fgrep - return lines matching a pattern

This calls the external “fgrep” program and returns the matching lines.

fgrepi(pattern, path)
fgrepi - return lines matching a pattern

This calls the external “fgrep -i” program and returns the matching lines.

file(path)
file - determine file type

This call uses the standard file(1) command to determine the type or contents of the file.

file_architecture(filename)
file-architecture - detect the architecture of a binary file

This detects the architecture of the binary “filename”, and returns it if known.

filesize(file)
filesize - return the size of the file in bytes

This command returns the size of “file” in bytes.

filesystem_available(filesystem)
filesystem-available - check if filesystem is available

Check whether libguestfs supports the named filesystem. The argument “filesystem” is a filesystem name, such as “ext3”.

fill(c, len, path)
fill - fill a file with octets

This command creates a new file called “path”. The initial content of the file is “len” octets of “c”, where “c” must be a number in the range “[0..255]”.

fill_dir(dir, nr)
fill-dir - fill a directory with empty files

This function, useful for testing filesystems, creates “nr” empty files in the directory “dir” with names 00000000 through “nr-1” (ie. each file name is 8 digits long padded with zeroes).

fill_pattern(pattern, len, path)
fill-pattern - fill a file with a repeating pattern of bytes

This function is like “fill” except that it creates a new file of length “len” containing the repeating pattern of bytes in “pattern”. The pattern is truncated if necessary to ensure the length of the file is exactly “len” bytes.

findfs_label(label)
findfs-label - find a filesystem by label

This command searches the filesystems and returns the one which has the given label. An error is returned if no such filesystem can be found.

findfs_uuid(uuid)
findfs-uuid - find a filesystem by UUID

This command searches the filesystems and returns the one which has the given UUID. An error is returned if no such filesystem can be found.

fsck(fstype, device)
fsck - run the filesystem checker

This runs the filesystem checker (fsck) on “device” which should have filesystem type “fstype”.

get_append()
get-append - get the additional kernel options

Return the additional kernel options which are added to the libguestfs appliance kernel command line.

get_attach_method()
get-attach-method - get the backend

Return the current backend.

get_autosync()
get-autosync - get autosync mode

Get the autosync flag.

get_backend()
get-backend - get the backend

Return the current backend.

get_direct()
get-direct - get direct appliance mode flag

Return the direct appliance mode flag.

get_e2attrs(file)
get-e2attrs - get ext2 file attributes of a file

This returns the file attributes associated with “file”.

get_e2generation(file)
get-e2generation - get ext2 file generation of a file

This returns the ext2 file generation of a file. The generation (which used to be called the “version”) is a number associated with an inode. This is most commonly used by NFS servers.

get_e2label(device)
get-e2label - get the ext2/3/4 filesystem label

This returns the ext2/3/4 filesystem label of the filesystem on “device”.

get_e2uuid(device)
get-e2uuid - get the ext2/3/4 filesystem UUID

This returns the ext2/3/4 filesystem UUID of the filesystem on “device”.

get_memsize()
get-memsize - get memory allocated to the hypervisor

This gets the memory size in megabytes allocated to the hypervisor.

get_network()
get-network - get enable network flag

This returns the enable network flag.

get_path()
get-path - get the search path

Return the current search path.

get_pgroup()
get-pgroup - get process group flag

This returns the process group flag.

get_pid()
get-pid - get PID of hypervisor

Return the process ID of the hypervisor. If there is no hypervisor running, then this will return an error.

get_program()
get-program - get the program name

Get the program name. See “set_program”.

get_qemu()
get-qemu - get the hypervisor binary (usually qemu)

Return the current hypervisor binary (usually qemu).

get_recovery_proc()
get-recovery-proc - get recovery process enabled flag

Return the recovery process enabled flag.

get_smp()
get-smp - get number of virtual CPUs in appliance

This returns the number of virtual CPUs assigned to the appliance.

get_trace()
get-trace - get command trace enabled flag

Return the command trace flag.

get_umask()
get-umask - get the current umask

Return the current umask. By default the umask is 022 unless it has been set by calling “umask”.

get_verbose()
get-verbose - get verbose mode

This returns the verbose messages flag.

glob(command, args)
glob - expand wildcards in command

Expand wildcards in any paths in the args list, and run “command” repeatedly on each matching path.

glob_expand(path)
glob-expand - expand a wildcard path

This command searches for all the pathnames matching “pattern” according to the wildcard expansion rules used by the shell.

grep(regex, path)
grep - return lines matching a pattern

This calls the external “grep” program and returns the matching lines.

grepi(regex, path)
grepi - return lines matching a pattern

This calls the external “grep -i” program and returns the matching lines.

grub_install(root, device)
grub-install root device

This command installs GRUB 1 (the Grand Unified Bootloader) on “device”, with the root directory being “root”.

head(path)
head - return first 10 lines of a file

This command returns up to the first 10 lines of a file as a list of strings.

head_n(nrlines, path)
head-n - return first N lines of a file

If the parameter “nrlines” is a positive number, this returns the first “nrlines” lines of the file “path”.

help(orcmd=None)
help - display a list of commands or help on a command

hexdump(path)
hexdump - dump a file in hexadecimal

This runs “hexdump -C” on the given “path”. The result is the human-readable, canonical hex dump of the file.

initrd_cat(initrdpath, filename)
initrd-cat - list the contents of a single file in an initrd

This command unpacks the file “filename” from the initrd file called “initrdpath”. The filename must be given without the initial “/” character.

initrd_list(path)
initrd-list - list files in an initrd

This command lists out files contained in an initrd.

inner_cmd(command)
Execute inner command of guestfish in a pesistent session.

Parameters:

command – inner command to be executed.

inspect_get_arch(root)
inspect-get-arch - get architecture of inspected operating system

This returns the architecture of the inspected operating system.

inspect_get_distro(root)
inspect-get-distro - get distro of inspected operating system

This returns the distro (distribution) of the inspected operating system.

inspect_get_filesystems(root)
inspect-get-filesystems - get filesystems associated with inspected operating system

This returns a list of all the filesystems that we think are associated with this operating system.

inspect_get_hostname(root)
inspect-get-hostname - get hostname of the operating system

This function returns the hostname of the operating system as found by inspection of the guest’s configuration files.

inspect_get_major_version(root)
inspect-get-major-version - get major version of inspected operating system

This returns the major version number of the inspected operating system.

inspect_get_minor_version(root)
inspect-get-minor-version - get minor version of inspected operating system

This returns the minor version number of the inspected operating system

inspect_get_mountpoints(root)
inspect-get-mountpoints - get mountpoints of inspected operating system

This returns a hash of where we think the filesystems associated with this operating system should be mounted.

inspect_get_roots()
inspect-get-roots - return list of operating sy

Clone this wiki locally