virttest package

Subpackages

Submodules

virttest.RFBDes module

class virttest.RFBDes.Des(key)[source]

Bases: object

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

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()[source]

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

crypt(data, crypt_type=0)[source]

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)[source]

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)[source]

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()[source]

Just get the crypting key.

get_sub_list(table, block)[source]

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)[source]

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.aexpect module

A class and functions used for running and controlling child processes.

copyright:2008-2009 Red Hat Inc.
class virttest.aexpect.Expect(command=None, a_id=None, auto_close=True, echo=False, linesep='n', termination_func=None, termination_params=(), output_func=None, output_params=(), output_prefix='', thread_name=None)[source]

Bases: virttest.aexpect.Tail

This class runs a child process in the background and provides expect-like services.

It also provides all of Tail’s functionality.

match_patterns(cont, patterns)[source]

Match cont against a list of patterns.

Return the index of the first pattern that matches a substring of cont. None and empty strings in patterns are ignored. If no match is found, return None.

Parameters:
  • cont – input string
  • patterns – List of strings (regular expression patterns).
match_patterns_multiline(cont, patterns)[source]

Match list of lines against a list of patterns.

Return the index of the first pattern that matches a substring of cont. None and empty strings in patterns are ignored. If no match is found, return None.

Parameters:
  • cont – List of strings (input strings)
  • patterns – List of strings (regular expression patterns). The pattern priority is from the last to first.
read_nonblocking(internal_timeout=None, timeout=None)[source]

Read from child until there is nothing to read for timeout seconds.

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.
read_until_any_line_matches(patterns, timeout=60, internal_timeout=None, print_func=None)[source]

Read using read_nonblocking until any line matches a pattern.

Read using read_nonblocking until any line of the output matches one of the patterns (using match_patterns_multiline), or until timeout expires. Return a tuple containing the match index (or None if no match was found) and the data read so far.

Parameters:
  • patterns – A list of strings (regular expression patterns) Consider using ‘^’ in the beginning.
  • timeout – The duration (in seconds) to wait until a match is found
  • internal_timeout – The timeout to pass to read_nonblocking
  • print_func – A function to be used to print the data being read (should take a string parameter)
Returns:

A tuple containing the match index and the data read so far

Raises:
  • ExpectTimeoutError – Raised if timeout expires
  • ExpectProcessTerminatedError – Raised if the child process terminates while waiting for output
  • ExpectError – Raised if an unknown error occurs
read_until_last_line_matches(patterns, timeout=60, internal_timeout=None, print_func=None)[source]

Read using read_nonblocking until the last non-empty line matches a pattern.

Read using read_nonblocking until the last non-empty line of the output matches one of the patterns (using match_patterns), or until timeout expires. Return a tuple containing the match index (or None if no match was found) and the data read so far.

Parameters:
  • patterns – A list of strings (regular expression patterns)
  • timeout – The duration (in seconds) to wait until a match is found
  • internal_timeout – The timeout to pass to read_nonblocking
  • print_func – A function to be used to print the data being read (should take a string parameter)
Returns:

A tuple containing the match index and the data read so far

Raises:
  • ExpectTimeoutError – Raised if timeout expires
  • ExpectProcessTerminatedError – Raised if the child process terminates while waiting for output
  • ExpectError – Raised if an unknown error occurs
read_until_last_word_matches(patterns, timeout=60, internal_timeout=None, print_func=None)[source]

Read using read_nonblocking until the last word of the output matches one of the patterns (using match_patterns), or until timeout expires.

Parameters:
  • patterns – A list of strings (regular expression patterns)
  • timeout – The duration (in seconds) to wait until a match is found
  • internal_timeout – The timeout to pass to read_nonblocking
  • print_func – A function to be used to print the data being read (should take a string parameter)
Returns:

A tuple containing the match index and the data read so far

Raises:
  • ExpectTimeoutError – Raised if timeout expires
  • ExpectProcessTerminatedError – Raised if the child process terminates while waiting for output
  • ExpectError – Raised if an unknown error occurs
read_until_output_matches(patterns, filter_func=<function <lambda>>, timeout=60, internal_timeout=None, print_func=None, match_func=None)[source]

Read from child using read_nonblocking until a pattern matches.

Read using read_nonblocking until a match is found using match_patterns, or until timeout expires. Before attempting to search for a match, the data is filtered using the filter_func function provided.

Parameters:
  • patterns – List of strings (regular expression patterns)
  • filter_func – Function to apply to the data read from the child before attempting to match it against the patterns (should take and return a string)
  • timeout – The duration (in seconds) to wait until a match is found
  • internal_timeout – The timeout to pass to read_nonblocking
  • print_func – A function to be used to print the data being read (should take a string parameter)
  • match_func – Function to compare the output and patterns.
Returns:

Tuple containing the match index and the data read so far

Raises:
  • ExpectTimeoutError – Raised if timeout expires
  • ExpectProcessTerminatedError – Raised if the child process terminates while waiting for output
  • ExpectError – Raised if an unknown error occurs
exception virttest.aexpect.ExpectError(patterns, output)[source]

Bases: exceptions.Exception

exception virttest.aexpect.ExpectProcessTerminatedError(patterns, status, output)[source]

Bases: virttest.aexpect.ExpectError

exception virttest.aexpect.ExpectTimeoutError(patterns, output)[source]

Bases: virttest.aexpect.ExpectError

exception virttest.aexpect.ShellCmdError(cmd, status, output)[source]

Bases: virttest.aexpect.ShellError

exception virttest.aexpect.ShellError(cmd, output)[source]

Bases: exceptions.Exception

exception virttest.aexpect.ShellProcessTerminatedError(cmd, status, output)[source]

Bases: virttest.aexpect.ShellError

class virttest.aexpect.ShellSession(command=None, a_id=None, auto_close=True, echo=False, linesep='n', termination_func=None, termination_params=(), output_func=None, output_params=(), output_prefix='', thread_name=None, prompt='[\#\$]\s*$', status_test_command='echo $?')[source]

Bases: virttest.aexpect.Expect

This class runs a child process in the background. It it suited for processes that provide an interactive shell, such as SSH and Telnet.

It provides all services of Expect and Tail. In addition, it provides command running services, and a utility function to test the process for responsiveness.

cmd(cmd, timeout=60, internal_timeout=None, print_func=None, ok_status=[0], ignore_all_errors=False)[source]

Send a command and return its output. If the command’s exit status is nonzero, raise an exception.

Parameters:
  • cmd – Command to send (must not contain newline characters)
  • timeout – The duration (in seconds) to wait for the prompt to return
  • internal_timeout – The timeout to pass to read_nonblocking
  • print_func – A function to be used to print the data being read (should take a string parameter)
  • ok_status – do not raise ShellCmdError in case that exit status is one of ok_status. (default is [0,])
  • ignore_all_errors – toggles whether or not an exception should be raised on any error.
Returns:

The output of cmd

Raises:
  • ShellTimeoutError – Raised if timeout expires
  • ShellProcessTerminatedError – Raised if the shell process terminates while waiting for output
  • ShellError – Raised if the exit status cannot be obtained or if an unknown error occurs
  • ShellStatusError – Raised if the exit status cannot be obtained
  • ShellError – Raised if an unknown error occurs
  • ShellCmdError – Raised if the exit status is nonzero
cmd_output(cmd, timeout=60, internal_timeout=None, print_func=None)[source]

Send a command and return its output.

Parameters:
  • cmd – Command to send (must not contain newline characters)
  • timeout – The duration (in seconds) to wait for the prompt to return
  • internal_timeout – The timeout to pass to read_nonblocking
  • print_func – A function to be used to print the data being read (should take a string parameter)
Returns:

The output of cmd

Raises:
  • ShellTimeoutError – Raised if timeout expires
  • ShellProcessTerminatedError – Raised if the shell process terminates while waiting for output
  • ShellError – Raised if an unknown error occurs
cmd_output_safe(cmd, timeout=60, internal_timeout=None, print_func=None)[source]

Send a command and return its output (serial sessions).

In serial sessions, frequently the kernel might print debug or error messages that make read_up_to_prompt to timeout. Let’s try to be a little more robust and send a carriage return, to see if we can get to the prompt.

Parameters:
  • cmd – Command to send (must not contain newline characters)
  • timeout – The duration (in seconds) to wait for the prompt to return
  • internal_timeout – The timeout to pass to read_nonblocking
  • print_func – A function to be used to print the data being read (should take a string parameter)
Returns:

The output of cmd

Raises:
  • ShellTimeoutError – Raised if timeout expires
  • ShellProcessTerminatedError – Raised if the shell process terminates while waiting for output
  • ShellError – Raised if an unknown error occurs
cmd_status(cmd, timeout=60, internal_timeout=None, print_func=None)[source]

Send a command and return its exit status.

Parameters:
  • cmd – Command to send (must not contain newline characters)
  • timeout – The duration (in seconds) to wait for the prompt to return
  • internal_timeout – The timeout to pass to read_nonblocking
  • print_func – A function to be used to print the data being read (should take a string parameter)
Returns:

The exit status of cmd

Raises:
  • ShellTimeoutError – Raised if timeout expires
  • ShellProcessTerminatedError – Raised if the shell process terminates while waiting for output
  • ShellStatusError – Raised if the exit status cannot be obtained
  • ShellError – Raised if an unknown error occurs
cmd_status_output(cmd, timeout=60, internal_timeout=None, print_func=None)[source]

Send a command and return its exit status and output.

Parameters:
  • cmd – Command to send (must not contain newline characters)
  • timeout – The duration (in seconds) to wait for the prompt to return
  • internal_timeout – The timeout to pass to read_nonblocking
  • print_func – A function to be used to print the data being read (should take a string parameter)
Returns:

A tuple (status, output) where status is the exit status and output is the output of cmd

Raises:
  • ShellTimeoutError – Raised if timeout expires
  • ShellProcessTerminatedError – Raised if the shell process terminates while waiting for output
  • ShellStatusError – Raised if the exit status cannot be obtained
  • ShellError – Raised if an unknown error occurs
get_command_output(cmd, timeout=60, internal_timeout=None, print_func=None)[source]

Alias for cmd_output() for backward compatibility.

get_command_status(cmd, timeout=60, internal_timeout=None, print_func=None)[source]

Alias for cmd_status() for backward compatibility.

get_command_status_output(cmd, timeout=60, internal_timeout=None, print_func=None)[source]

Alias for cmd_status_output() for backward compatibility.

is_responsive(timeout=5.0)[source]

Return True if the process responds to STDIN/terminal input.

Send a newline to the child process (e.g. SSH or Telnet) and read some output using read_nonblocking(). If all is OK, some output should be available (e.g. the shell prompt). In that case return True. Otherwise return False.

Parameters:timeout – Time duration to wait before the process is considered unresponsive.
read_up_to_prompt(timeout=60, internal_timeout=None, print_func=None)[source]

Read using read_nonblocking until the last non-empty line matches the prompt.

Read using read_nonblocking until the last non-empty line of the output matches the prompt regular expression set by set_prompt, or until timeout expires.

Parameters:
  • timeout – The duration (in seconds) to wait until a match is found
  • internal_timeout – The timeout to pass to read_nonblocking
  • print_func – A function to be used to print the data being read (should take a string parameter)
Returns:

The data read so far

Raises:
  • ExpectTimeoutError – Raised if timeout expires
  • ExpectProcessTerminatedError – Raised if the shell process terminates while waiting for output
  • ExpectError – Raised if an unknown error occurs
classmethod remove_command_echo(cont, cmd)[source]
classmethod remove_last_nonempty_line(cont)[source]
set_prompt(prompt)[source]

Set the prompt attribute for later use by read_up_to_prompt.

:param String that describes the prompt contents.

set_status_test_command(status_test_command)[source]

Set the command to be sent in order to get the last exit status.

Parameters:status_test_command – Command that will be sent to get the last exit status.
exception virttest.aexpect.ShellStatusError(cmd, output)[source]

Bases: virttest.aexpect.ShellError

exception virttest.aexpect.ShellTimeoutError(cmd, output)[source]

Bases: virttest.aexpect.ShellError

class virttest.aexpect.Spawn(command=None, a_id=None, auto_close=False, echo=False, linesep='n')[source]

Bases: object

This class is used for spawning and controlling a child process.

A new instance of this class can either run a new server (a small Python program that reads output from the child process and reports it to the client and to a text file) or attach to an already running server. When a server is started it runs the child process. The server writes output from the child’s STDOUT and STDERR to a text file. The text file can be accessed at any time using get_output(). In addition, the server opens as many pipes as requested by the client and writes the output to them. The pipes are requested and accessed by classes derived from Spawn. These pipes are referred to as “readers”. The server also receives input from the client and sends it to the child process. An instance of this class can be pickled. Every derived class is responsible for restoring its own state by properly defining __getinitargs__().

The first named pipe is used by _tail(), a function that runs in the background and reports new output from the child as it is produced. The second named pipe is used by a set of functions that read and parse output as requested by the user in an interactive manner, similar to pexpect. When unpickled it automatically resumes _tail() if needed.

close(sig=9)[source]

Kill the child process if it’s alive and remove temporary files.

Parameters:sig – The signal to send the process when attempting to kill it.
get_id()[source]

Return the instance’s a_id attribute, which may be used to access the process in the future.

get_output()[source]

Return the STDOUT and STDERR output of the process so far.

get_pid()[source]

Return the PID of the process.

Note: this may be the PID of the shell process running the user given command.

get_status()[source]

Wait for the process to exit and return its exit status, or None if the exit status is not available.

get_stripped_output()[source]

Return the STDOUT and STDERR output without the console codes escape and sequences of the process so far.

is_alive()[source]

Return True if the process is running.

is_defunct()[source]

Return True if the process is defunct (zombie).

kill(sig=9)[source]

Kill the child process if alive

send(cont='')[source]

Send a string to the child process.

Parameters:cont – String to send to the child process.
send_ctrl(control_str='')[source]

Send a control string to the aexpect process.

Parameters:control_str – Control string to send to the child process container.
sendline(cont='')[source]

Send a string followed by a line separator to the child process.

Parameters:cont – String to send to the child process.
set_linesep(linesep)[source]

Sets the line separator string (usually “n”).

Parameters:linesep – Line separator string.
class virttest.aexpect.Tail(command=None, a_id=None, auto_close=False, echo=False, linesep='n', termination_func=None, termination_params=(), output_func=None, output_params=(), output_prefix='', thread_name=None)[source]

Bases: virttest.aexpect.Spawn

This class runs a child process in the background and sends its output in real time, line-by-line, to a callback function.

See Spawn’s docstring.

This class uses a single pipe reader to read data in real time from the child process and report it to a given callback function. When the child process exits, its exit status is reported to an additional callback function.

When this class is unpickled, it automatically resumes reporting output.

set_log_file(filename)[source]

Set a log file name for this tail instance.

Parameters:filename – Base name of the log.
set_output_func(output_func)[source]

Set the output_func attribute. See __init__() for details.

Parameters:output_func – Function to call for each line of STDOUT/STDERR output from the process. Must take a single string parameter.
set_output_params(output_params)[source]

Set the output_params attribute. See __init__() for details.

Parameters:output_params – Parameters to send to output_func before the output line.
set_output_prefix(output_prefix)[source]

Set the output_prefix attribute. See __init__() for details.

Parameters:output_prefix – String to pre-pend to each line sent to output_func (see set_output_callback()).
set_termination_func(termination_func)[source]

Set the termination_func attribute. See __init__() for details.

Parameters:termination_func – Function to call when the process terminates. Must take a single parameter – the exit status.
set_termination_params(termination_params)[source]

Set the termination_params attribute. See __init__() for details.

Parameters:termination_params – Parameters to send to termination_func before the exit status.
virttest.aexpect.clean_tmp_files()[source]

Remove all aexpect temporary files.

virttest.aexpect.kill_tail_threads()[source]

Kill all Tail threads.

After calling this function no new threads should be started.

virttest.aexpect.run_bg(command, termination_func=None, output_func=None, output_prefix='', timeout=1.0, auto_close=True)[source]

Run a subprocess in the background and collect its output and exit status.

Run command as a subprocess. Call output_func with each line of output from the subprocess (prefixed by output_prefix). Call termination_func when the subprocess terminates. Return when timeout expires or when the subprocess exits – whichever occurs first.

Parameters:
  • command – The shell command to execute
  • termination_func – A function to call when the process terminates (should take an integer exit status parameter)
  • output_func – A function to call with each line of output from the subprocess (should take a string parameter)
  • output_prefix – A string to pre-pend to each line of the output, before passing it to stdout_func
  • timeout – Time duration (in seconds) to wait for the subprocess to terminate before returning
  • auto_close – If True, close() the instance automatically when its reference count drops to zero (default False).
Returns:

A Expect object.

virttest.aexpect.run_fg(command, output_func=None, output_prefix='', timeout=1.0)[source]

Run a subprocess in the foreground and collect its output and exit status.

Run command as a subprocess. Call output_func with each line of output from the subprocess (prefixed by prefix). Return when timeout expires or when the subprocess exits – whichever occurs first. If timeout expires and the subprocess is still running, kill it before returning.

Parameters:
  • command – The shell command to execute
  • output_func – A function to call with each line of output from the subprocess (should take a string parameter)
  • output_prefix – A string to pre-pend to each line of the output, before passing it to stdout_func
  • timeout – Time duration (in seconds) to wait for the subprocess to terminate before killing it and returning
Returns:

A 2-tuple containing the exit status of the process and its STDOUT/STDERR output. If timeout expires before the process terminates, the returned status is None.

virttest.aexpect.run_tail(command, termination_func=None, output_func=None, output_prefix='', timeout=1.0, auto_close=True)[source]

Run a subprocess in the background and collect its output and exit status.

Run command as a subprocess. Call output_func with each line of output from the subprocess (prefixed by output_prefix). Call termination_func when the subprocess terminates. Return when timeout expires or when the subprocess exits – whichever occurs first.

Parameters:
  • command – The shell command to execute
  • termination_func – A function to call when the process terminates (should take an integer exit status parameter)
  • output_func – A function to call with each line of output from the subprocess (should take a string parameter)
  • output_prefix – A string to pre-pend to each line of the output, before passing it to stdout_func
  • timeout – Time duration (in seconds) to wait for the subprocess to terminate before returning
  • auto_close – If True, close() the instance automatically when its reference count drops to zero (default False).
Returns:

A Expect object.

virttest.arch module

virttest.arch.get_kvm_module_list()[source]

virttest.asset module

virttest.asset.download_all_test_providers(update=False)[source]

Download all available test providers.

virttest.asset.download_asset(asset, interactive=True, restore_image=False)[source]

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)[source]

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)[source]

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()[source]
virttest.asset.get_asset_info(asset)[source]
virttest.asset.get_file_asset(title, src_path, destination)[source]
virttest.asset.get_known_backends()[source]

Return virtualization backends supported by virt-test.

virttest.asset.get_test_provider_info(provider)[source]

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)[source]

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)[source]

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)[source]

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.

class virttest.base_installer.BaseInstaller(mode, name, test=None, params=None)[source]

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.

install(cleanup=True, download=True, prepare=True, build=True, install=True, init=True)[source]

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)[source]

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 (list) – list of kernel modules names to load
reload_modules()[source]

Reload the kernel modules (unload, then load)

reload_modules_if_needed()[source]
set_install_params(test=None, params=None)[source]

Called by test to setup parameters from the configuration file

uninstall()[source]

Performs the uninstallations of the virtualization software

Note: This replaces old qemu_installer._clean_previous_install()

unload_modules(module_list=None)[source]

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)[source]
class virttest.base_installer.BaseLocalSourceInstaller(mode, name, test=None, params=None)[source]

Bases: virttest.base_installer.BaseInstaller

set_install_params(test, params)[source]
class virttest.base_installer.FailedInstaller(msg='Virtualization software install failed')[source]

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()[source]

Will refuse to load the kerkel modules as install failed

class virttest.base_installer.GitRepoInstaller(mode, name, test=None, params=None)[source]

Bases: virttest.base_installer.BaseLocalSourceInstaller

get_version()[source]
set_install_params(test, params)[source]
class virttest.base_installer.KojiInstaller(mode, name, test=None, params=None)[source]

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.

get_version()[source]
set_install_params(test, params)[source]
class virttest.base_installer.LocalSourceDirInstaller(mode, name, test=None, params=None)[source]

Bases: virttest.base_installer.BaseLocalSourceInstaller

Handles software installation by building/installing from a source dir

set_install_params(test, params)[source]
class virttest.base_installer.LocalSourceTarInstaller(mode, name, test=None, params=None)[source]

Bases: virttest.base_installer.BaseLocalSourceInstaller

Handles software installation by building/installing from a tarball

set_install_params(test, params)[source]
exception virttest.base_installer.NoModuleError[source]

Bases: exceptions.Exception

Error raised when no suitable modules were found to load

class virttest.base_installer.NoopInstaller(mode, name, test=None, params=None)[source]

Bases: virttest.base_installer.BaseInstaller

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

install()[source]
class virttest.base_installer.RemoteSourceTarInstaller(mode, name, test=None, params=None)[source]

Bases: virttest.base_installer.BaseLocalSourceInstaller

Handles software installation by building/installing from a remote tarball

set_install_params(test, params)[source]
exception virttest.base_installer.VirtInstallException[source]

Bases: exceptions.Exception

Base virtualization software components installation exception

exception virttest.base_installer.VirtInstallFailed[source]

Bases: virttest.base_installer.VirtInstallException

Installation of virtualization software components failed

exception virttest.base_installer.VirtInstallNotInstalled[source]

Bases: virttest.base_installer.VirtInstallException

Virtualization software components are not installed

class virttest.base_installer.YumInstaller(mode, name, test=None, params=None)[source]

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.

get_version()[source]
set_install_params(test, params)[source]

virttest.bootstrap module

virttest.bootstrap.bootstrap(options, interactive=False)[source]

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, step=None, force_update=False)[source]
virttest.bootstrap.create_guest_os_cfg(t_type)[source]
virttest.bootstrap.create_subtests_cfg(t_type)[source]
virttest.bootstrap.get_directory_structure(rootdir, guest_file)[source]
virttest.bootstrap.get_guest_os_info_list(test_name, guest_os)[source]

Returns a list of matching assets compatible with the specified test name and guest OS

virttest.bootstrap.haz_defcon(datadir, imagesdir, isosdir, tmpdir)[source]

Compare current types from Defaults, or if default, compare on-disk type

virttest.bootstrap.set_defcon(datadir, imagesdir, isosdir, tmpdir)[source]

Tries to set datadir default contexts returns True if changed

virttest.bootstrap.setup(options)[source]

Run pre tests setup (Uncompress test image(s), such as the JeOS image).

Parameters:
  • test_name – Test name, such as “qemu”.
  • guest_os – Specify the guest image used for bootstrapping. By default the JeOS image is used.
virttest.bootstrap.verify_mandatory_programs(t_type, guest_os)[source]
virttest.bootstrap.verify_selinux(datadir, imagesdir, isosdir, tmpdir, interactive, selinux=False)[source]

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 virt-test 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)[source]

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

class virttest.build_helper.GitRepoParamHelper(params, name, destination_dir)[source]

Bases: autotest.client.shared.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

execute()[source]
class virttest.build_helper.GnuSourceBuildHelper(source, build_dir, prefix, configure_options=[])[source]

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

configure()[source]

Runs the “configure” script passing appropriate command line options

enable_debug_symbols()[source]

Enables option that leaves debug symbols on compiled software

This makes debugging a lot easier.

execute()[source]

Runs appropriate steps for building this source code tree

get_available_configure_options()[source]

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()[source]

Formats configure script with all options set

Returns:string with all configure options, including prefix
get_configure_path()[source]

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

include_pkg_config_path()[source]

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)[source]

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()[source]

Runs “make clean”

make_install()[source]

Runs “make install”

make_non_parallel()[source]

Runs “make”, using a single job

make_parallel()[source]

Runs “make” using the correct number of parallel jobs

exception virttest.build_helper.GnuSourceBuildInvalidSource[source]

Bases: exceptions.Exception

Exception raised when build source dir/file is not valid

class virttest.build_helper.GnuSourceBuildParamHelper(params, name, destination_dir, install_prefix)[source]

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

class virttest.build_helper.LinuxKernelBuildHelper(params, prefix, source)[source]

Bases: object

Handles Building Linux Kernel.

cp_linux_kernel()[source]

Copying Linux kernel to target path

execute()[source]

Runs appropriate steps for building this source code tree

install()

Copying Linux kernel to target path

make(failure_feedback=True)[source]

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()[source]

Runs “make clean”

make_guest_kernel()[source]

Runs “make”, using a single job

class virttest.build_helper.LocalSourceDirHelper(source_dir, destination_dir)[source]

Bases: object

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

execute()[source]

Copies the source directory to the destination directory

class virttest.build_helper.LocalSourceDirParamHelper(params, name, destination_dir)[source]

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

class virttest.build_helper.LocalTarHelper(source, destination_dir)[source]

Bases: object

Helper class to deal with source code in a local tarball

execute()[source]

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()[source]

Extracts the tarball into the destination directory

class virttest.build_helper.LocalTarParamHelper(params, name, destination_dir)[source]

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

class virttest.build_helper.PatchHelper(source_dir, patches)[source]

Bases: object

Helper that encapsulates the patching of source code with patch files

download()[source]

Copies patch files from remote locations to the source directory

execute()[source]

Performs all steps necessary to download patches and apply them

patch()[source]

Patches the source dir with all patch files

class virttest.build_helper.PatchParamHelper(params, prefix, source_dir)[source]

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‘]

class virttest.build_helper.RemoteTarHelper(source_uri, destination_dir)[source]

Bases: virttest.build_helper.LocalTarHelper

Helper that fetches a tarball and extracts it locally

execute()[source]

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.

class virttest.build_helper.RemoteTarParamHelper(params, name, destination_dir)[source]

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

exception virttest.build_helper.SourceBuildFailed[source]

Bases: exceptions.Exception

Exception raised when building with parallel jobs fails

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

exception virttest.build_helper.SourceBuildParallelFailed[source]

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
class virttest.cartesian_config.BlockFilter(blocked)[source]

Bases: object

apply_to_dict(d)[source]
blocked
class virttest.cartesian_config.Condition(lfilter, line)[source]

Bases: virttest.cartesian_config.NoFilter

content
class virttest.cartesian_config.FileReader(filename)[source]

Bases: virttest.cartesian_config.StrReader

Preprocess an input file for easy reading.

class virttest.cartesian_config.Filter(lfilter)[source]

Bases: object

filter
match(ctx, ctx_set)[source]
might_match(ctx, ctx_set, descendant_labels)[source]
class virttest.cartesian_config.LAnd[source]

Bases: virttest.cartesian_config.Token

identifier = '..'
class virttest.cartesian_config.LAppend[source]

Bases: virttest.cartesian_config.LOperators

apply_to_dict(d)[source]
identifier = '+='
class virttest.cartesian_config.LApplyPreDict[source]

Bases: virttest.cartesian_config.LOperators

apply_to_dict(d)[source]
identifier = 'apply_pre_dict'
set_operands(name, value)[source]
class virttest.cartesian_config.LCoc[source]

Bases: virttest.cartesian_config.Token

identifier = '.'
class virttest.cartesian_config.LColon[source]

Bases: virttest.cartesian_config.Token

identifier = ':'
class virttest.cartesian_config.LComa[source]

Bases: virttest.cartesian_config.Token

identifier = ','
class virttest.cartesian_config.LCond[source]

Bases: virttest.cartesian_config.Token

identifier = ''
class virttest.cartesian_config.LDefault[source]

Bases: virttest.cartesian_config.Token

identifier = '@'
class virttest.cartesian_config.LDel[source]

Bases: virttest.cartesian_config.LOperators

apply_to_dict(d)[source]
identifier = 'del'
class virttest.cartesian_config.LDot[source]

Bases: virttest.cartesian_config.Token

identifier = '.'
class virttest.cartesian_config.LEndBlock(length)[source]

Bases: virttest.cartesian_config.LIndent

class virttest.cartesian_config.LEndL[source]

Bases: virttest.cartesian_config.Token

identifier = 'endl'
class virttest.cartesian_config.LIdentifier[source]

Bases: str

checkAlpha()[source]

Check if string contain only chars

checkChar(chars)[source]
checkCharAlpha(chars)[source]

Check if string contain only chars

checkCharAlphaNum(chars)[source]

Check if string contain only chars

checkCharNumeric(chars)[source]

Check if string contain only chars

checkNumbers()[source]

Check if string contain only chars

identifier = 'Identifier re([A-Za-z0-9][A-Za-z0-9_-]*)'
class virttest.cartesian_config.LInclude[source]

Bases: virttest.cartesian_config.Token

identifier = 'include'
class virttest.cartesian_config.LIndent(length)[source]

Bases: virttest.cartesian_config.Token

identifier = 'indent'
length
class virttest.cartesian_config.LLBracket[source]

Bases: virttest.cartesian_config.Token

identifier = '['
class virttest.cartesian_config.LLRBracket[source]

Bases: virttest.cartesian_config.Token

identifier = '('
class virttest.cartesian_config.LNo[source]

Bases: virttest.cartesian_config.Token

identifier = 'no'
class virttest.cartesian_config.LNotCond[source]

Bases: virttest.cartesian_config.Token

identifier = '!'
class virttest.cartesian_config.LOnly[source]

Bases: virttest.cartesian_config.Token

identifier = 'only'
class virttest.cartesian_config.LOperators[source]

Bases: virttest.cartesian_config.Token

function = None
identifier = ''
name
set_operands(name, value)[source]
value
class virttest.cartesian_config.LOr[source]

Bases: virttest.cartesian_config.Token

identifier = ','
class virttest.cartesian_config.LPrepend[source]

Bases: virttest.cartesian_config.LOperators

apply_to_dict(d)[source]
identifier = '<='
class virttest.cartesian_config.LRBracket[source]

Bases: virttest.cartesian_config.Token

identifier = ']'
class virttest.cartesian_config.LRRBracket[source]

Bases: virttest.cartesian_config.Token

identifier = ')'
class virttest.cartesian_config.LRegExpAppend[source]

Bases: virttest.cartesian_config.LOperators

apply_to_dict(d)[source]
identifier = '?+='
class virttest.cartesian_config.LRegExpPrepend[source]

Bases: virttest.cartesian_config.LOperators

apply_to_dict(d)[source]
identifier = '?<='
class virttest.cartesian_config.LRegExpSet[source]

Bases: virttest.cartesian_config.LOperators

apply_to_dict(d)[source]
identifier = '?='
class virttest.cartesian_config.LRegExpStart[source]

Bases: virttest.cartesian_config.Token

identifier = '${'
class virttest.cartesian_config.LRegExpStop[source]

Bases: virttest.cartesian_config.Token

identifier = '}'
class virttest.cartesian_config.LSet[source]

Bases: virttest.cartesian_config.LOperators

apply_to_dict(d)[source]
Parameters:d – Dictionary for apply value
identifier = '='
class virttest.cartesian_config.LString[source]

Bases: virttest.cartesian_config.LIdentifier

identifier = 'String re(.+)'
class virttest.cartesian_config.LUpdateFileMap[source]

Bases: virttest.cartesian_config.LOperators

apply_to_dict(d)[source]
dest
identifier = 'update_file_map'
set_operands(filename, name, dest='_name_map_file')[source]
shortname
class virttest.cartesian_config.LVariant[source]

Bases: virttest.cartesian_config.Token

identifier = '-'
class virttest.cartesian_config.LVariants[source]

Bases: virttest.cartesian_config.Token

identifier = 'variants'
class virttest.cartesian_config.LWhite[source]

Bases: virttest.cartesian_config.LIdentifier

identifier = 'WhiteSpace re(\\s)'
class virttest.cartesian_config.Label(name, next_name=None)[source]

Bases: object

hash_name()[source]
hash_val
hash_var
hash_variant()[source]
long_name
name
var_name
class virttest.cartesian_config.Lexer(reader)[source]

Bases: object

check_token(token, lType)[source]
flush_until(end_tokens=None)[source]
get_lexer()[source]
get_next_check(lType)[source]
get_next_check_nw(lType)[source]
get_until(end_tokens=None)[source]
get_until_check(lType, end_tokens=None)[source]

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)[source]
get_until_no_white(end_tokens=None)[source]

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)[source]
rest_line()[source]
rest_line_as_LString()[source]
rest_line_gen()[source]
rest_line_no_white()[source]
set_fast()[source]
set_prev_indent(prev_indent)[source]
set_strict()[source]
exception virttest.cartesian_config.LexerError(msg, line=None, filename=None, linenum=None)[source]

Bases: virttest.cartesian_config.ParserError

exception virttest.cartesian_config.MissingIncludeError(line, filename, linenum)[source]

Bases: exceptions.Exception

class virttest.cartesian_config.NegativeCondition(lfilter, line)[source]

Bases: virttest.cartesian_config.OnlyFilter

content
class virttest.cartesian_config.NoFilter(lfilter, line)[source]

Bases: virttest.cartesian_config.NoOnlyFilter

is_irrelevant(ctx, ctx_set, descendant_labels)[source]
might_pass(failed_ctx, failed_ctx_set, ctx, ctx_set, descendant_labels)[source]
requires_action(ctx, ctx_set, descendant_labels)[source]
class virttest.cartesian_config.NoOnlyFilter(lfilter, line)[source]

Bases: virttest.cartesian_config.Filter

line
class virttest.cartesian_config.Node[source]

Bases: object

append_to_shortname
children
content
default
dep
dump(indent, recurse=False)[source]
failed_cases
filename
labels
name
q_dict
var_name
class virttest.cartesian_config.OnlyFilter(lfilter, line)[source]

Bases: virttest.cartesian_config.NoOnlyFilter

is_irrelevant(ctx, ctx_set, descendant_labels)[source]
might_pass(failed_ctx, failed_ctx_set, ctx, ctx_set, descendant_labels)[source]
requires_action(ctx, ctx_set, descendant_labels)[source]
class virttest.cartesian_config.Parser(filename=None, defaults=False, expand_defaults=[], debug=False)[source]

Bases: object

assign(key, value)[source]

Apply a only filter programatically and keep track of it.

Equivalent to parse a “key = value” line.

Parameters:variant – String with the variant name.
get_dicts(node=None, ctx=[], content=[], shortname=[], dep=[])[source]

Generate dictionaries from the code parsed so far. This should be called after parsing something.

Returns:A dict generator.
no_filter(variant)[source]

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)[source]

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)[source]

Parse a file.

Parameters:filename – Path of the configuration file.
parse_string(s)[source]

Parse a string.

Parameters:s – String to parse.
exception virttest.cartesian_config.ParserError(msg, line=None, filename=None, linenum=None)[source]

Bases: exceptions.Exception

class virttest.cartesian_config.StrReader(s)[source]

Bases: object

Preprocess an input string for easy reading.

get_next_line(prev_indent)[source]

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)[source]

Make the next call to get_next_line() return the given line instead of the real next line.

class virttest.cartesian_config.Token[source]

Bases: object

identifier = ''
virttest.cartesian_config.apply_predict(lexer, node, pre_dict)[source]
virttest.cartesian_config.cmd_tokens(tokens1, tokens2)[source]
virttest.cartesian_config.compare_string(str1, str2)[source]

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')[source]

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)[source]
virttest.cartesian_config.parse_filter(lexer, tokens)[source]
Returns:Parsed filter
virttest.cartesian_config.postfix_parse(dic)[source]
virttest.cartesian_config.print_dicts(options, dicts)[source]
virttest.cartesian_config.print_dicts_default(options, dicts)[source]

Print dictionaries in the default mode

virttest.cartesian_config.print_dicts_repr(options, dicts)[source]

virttest.cartesian_config_unittest module

class virttest.cartesian_config_unittest.CartesianConfigTest(methodName='runTest')[source]

Bases: unittest.case.TestCase

testComplicatedFilter()[source]
testCondition()[source]
testDefaults()[source]
testDel()[source]
testError1()[source]
testFilterMixing()[source]
testHugeTest1()[source]
testMissingInclude()[source]
testNameVariant()[source]
testNegativeCondition()[source]
testSimpleVariant()[source]
testSyntaxErrors()[source]
testVariableAssignment()[source]

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.

exception virttest.ceph.CephError[source]

Bases: exceptions.Exception

virttest.common module

virttest.common.load_setup_modules(client_dir)[source]

virttest.data_dir module

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

exception virttest.data_dir.MissingDepsDirError[source]

Bases: exceptions.Exception

class virttest.data_dir.SubdirGlobList(basedir, globstr, filterlist=None)[source]

Bases: virttest.data_dir.SubdirList

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

class virttest.data_dir.SubdirList(basedir, filterlist=None)[source]

Bases: list

List of all non-hidden subdirectories beneath basedir

exception virttest.data_dir.UnknownBackendError(backend)[source]

Bases: exceptions.Exception

virttest.data_dir.clean_tmp_files()[source]
virttest.data_dir.get_backend_cfg_path(backend_type, cfg_basename)[source]
virttest.data_dir.get_backend_dir(backend_type)[source]
virttest.data_dir.get_backing_data_dir()[source]
virttest.data_dir.get_data_dir()[source]
virttest.data_dir.get_deps_dir(target=None)[source]

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()[source]
virttest.data_dir.get_root_dir()[source]
virttest.data_dir.get_test_provider_dir(provider)[source]

Return a specific test providers dir, inside the base dir.

virttest.data_dir.get_test_providers_dir()[source]

Return the base test providers dir (at the moment, test-providers.d).

virttest.data_dir.get_tmp_dir()[source]
virttest.data_dir.set_backing_data_dir(backing_data_dir)[source]

virttest.defaults module

virttest.defaults.get_default_guest_os_info()[source]

Gets the default asset and variant information depending on host OS

virttest.element_path module

class virttest.element_path.Path(path)[source]
find(element)[source]
findall(element)[source]
findtext(element, default=None)[source]
virttest.element_path.find(element, path)[source]
virttest.element_path.findall(element, path)[source]
virttest.element_path.findtext(element, path, default=None)[source]
class virttest.element_path.xpath_descendant_or_self[source]
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)[source]
virttest.element_tree.dump(elem)[source]
virttest.element_tree.Element(tag, attrib={}, **extra)[source]
class virttest.element_tree.ElementTree(element=None, file=None)[source]

Bases: object

find(path)[source]
findall(path)[source]
findtext(path, default=None)[source]
getiterator(tag=None)[source]
getroot()[source]
parse(source, parser=None)[source]
write(file, encoding='us-ascii')[source]
virttest.element_tree.fromstring(text)
virttest.element_tree.iselement(element)[source]
class virttest.element_tree.iterparse(source, events=None)[source]

Bases: object

next()[source]
virttest.element_tree.parse(source, parser=None)[source]
virttest.element_tree.PI(target, text=None)
virttest.element_tree.ProcessingInstruction(target, text=None)[source]
class virttest.element_tree.QName(text_or_uri, tag=None)[source]

Bases: object

virttest.element_tree.SubElement(parent, tag, attrib={}, text=None, **extra)[source]
virttest.element_tree.tostring(element, encoding=None)[source]
class virttest.element_tree.TreeBuilder(element_factory=None)[source]

Bases: object

close()[source]
data(data)[source]
end(tag)[source]
start(tag, attrs)[source]
virttest.element_tree.XML(text)[source]
virttest.element_tree.XMLParser

alias of XMLTreeBuilder

class virttest.element_tree.XMLTreeBuilder(html=0, target=None)[source]

Bases: object

close()[source]
doctype(name, pubid, system)[source]
feed(data)[source]

virttest.env_process module

virttest.env_process.postprocess_image(test, params, image_name, vm_process_status=None)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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.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)[source]

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)[source]

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)[source]

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.

exception virttest.gluster.GlusterBrickError(error_mgs)[source]

Bases: virttest.gluster.GlusterError

exception virttest.gluster.GlusterError[source]

Bases: exceptions.Exception

virttest.gluster.add_rpc_insecure(filepath)[source]

Allow glusterd RPC authority insecure

virttest.gluster.file_exists(params, filename_path)[source]
virttest.gluster.get_image_filename(params, image_name, image_format)[source]

Form the image file name using gluster uri

virttest.gluster.gluster_brick_create(brick_path, force=False)[source]

Creates brick

virttest.gluster.gluster_brick_delete(brick_path)[source]

Creates brick

virttest.gluster.glusterfs_mount(g_uri, mount_point)[source]

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.
class virttest.guest_agent.QemuAgent(vm, name, serial_type, serial_filename, get_supported_cmds=False, suppress_exceptions=False)[source]

Bases: virttest.qemu_monitor.Monitor

Wraps qemu guest agent commands.

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'
cmd(cmd, args=None, timeout=20, debug=True, success_resp=True)[source]

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:
  • VAgentLockError – Raised if the lock cannot be acquired
  • VAgentSocketError – Raised if a socket error occurs
  • VAgentProtocolError – Raised if no response is received
  • VAgentCmdError – Raised if the response is an error message
cmd_obj(obj, timeout=20)[source]

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:
  • VAgentLockError – Raised if the lock cannot be acquired
  • VAgentSocketError – Raised if a socket error occurs
  • VAgentProtocolError – Raised if no response is received
cmd_raw(data, timeout=20, success_resp=True)[source]

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:
  • VAgentLockError – Raised if the lock cannot be acquired
  • VAgentSocketError – Raised if a socket error occurs
  • VAgentProtocolError – Raised if no response is received
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.
get_fsfreeze_status()[source]

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

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’.

verify_fsfreeze_status(expected)[source]

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()[source]

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

exception virttest.guest_agent.VAgentCmdError(cmd, args, data)[source]

Bases: virttest.guest_agent.VAgentError

exception virttest.guest_agent.VAgentConnectError[source]

Bases: virttest.guest_agent.VAgentError

exception virttest.guest_agent.VAgentError[source]

Bases: virttest.qemu_monitor.MonitorError

exception virttest.guest_agent.VAgentFreezeStatusError(vm_name, status, expected)[source]

Bases: virttest.guest_agent.VAgentError

exception virttest.guest_agent.VAgentLockError[source]

Bases: virttest.guest_agent.VAgentError

exception virttest.guest_agent.VAgentNotSupportedError[source]

Bases: virttest.guest_agent.VAgentError

exception virttest.guest_agent.VAgentProtocolError[source]

Bases: virttest.guest_agent.VAgentError

exception virttest.guest_agent.VAgentSocketError(msg, e)[source]

Bases: virttest.guest_agent.VAgentError

exception virttest.guest_agent.VAgentSuspendError[source]

Bases: virttest.guest_agent.VAgentError

exception virttest.guest_agent.VAgentSuspendUnknownModeError(mode)[source]

Bases: virttest.guest_agent.VAgentSuspendError

exception virttest.guest_agent.VAgentSyncError(vm_name)[source]

Bases: virttest.guest_agent.VAgentError

virttest.http_server module

class virttest.http_server.HTTPRequestHandler(request, client_address, server)[source]

Bases: SimpleHTTPServer.SimpleHTTPRequestHandler

address_string()[source]

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)[source]

Copies a range of a file to destination.

do_GET()[source]

Serve a GET request.

log_message(fmt, *args)[source]
parse_header_byte_range()[source]
send_head_range(range_begin, range_end)[source]
translate_path(path)[source]

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)[source]

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.

class virttest.installer.InstallerRegistry(**kwargs)[source]

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)[source]

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)[source]

Returns a list of all registered installer modes

register(mode, klass, virt=None)[source]

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)[source]

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)[source]

Runs the installation routines for all installers, one at a time

This is usually the main entry point for tests

virttest.installer_unittest module

class virttest.installer_unittest.installer_test(methodName='runTest')[source]

Bases: unittest.case.TestCase

setUp()[source]
test_make_installer()[source]
test_register_get_installer()[source]
test_register_get_installer_default()[source]

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.

class virttest.iscsi.Iscsi[source]

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.

static create_iSCSI(params, root_dir='/tmp')[source]
class virttest.iscsi.IscsiLIO(params, root_dir)[source]

Bases: virttest.iscsi._IscsiComm

iscsi support class for LIO backend used in RHEL7.

delete_target()[source]

Delete target from host.

export_target()[source]

Export target in localhost for emulated iscsi

get_target_id()[source]

Get target id from image name.

set_chap_acls_target()[source]

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()[source]

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

class virttest.iscsi.IscsiTGT(params, root_dir)[source]

Bases: virttest.iscsi._IscsiComm

iscsi support TGT backend used in RHEL6.

add_chap_account()[source]

Add CHAP authentication account

delete_chap_account()[source]

Delete the CHAP authentication account

delete_target()[source]

Delete target from host.

export_target()[source]

Export target in localhost for emulated iscsi

get_chap_accounts()[source]

Get all CHAP authentication accounts

get_target_account_info()[source]

Get the target account information

get_target_id()[source]

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

set_chap_auth_target()[source]

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)[source]

Query from iscsi server for available targets

Parameters:portal_ip – Ip for iscsi server
virttest.iscsi.iscsi_get_nodes()[source]

Get the iscsi nodes

virttest.iscsi.iscsi_get_sessions()[source]

Get the iscsi sessions activated

virttest.iscsi.iscsi_login(target_name, portal)[source]

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)[source]

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)[source]

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_unittest module

class virttest.iscsi_unittest.iscsi_test(methodName='runTest')[source]

Bases: unittest.case.TestCase

setUp()[source]
setup_stubs_add_chap_account(iscsi_obj)[source]
setup_stubs_cleanup(iscsi_obj, fname='')[source]
setup_stubs_delete_chap_account(iscsi_obj)[source]
setup_stubs_export_target(iscsi_obj)[source]
setup_stubs_get_chap_accounts(result='')[source]
setup_stubs_get_device_name(iscsi_obj)[source]
setup_stubs_get_target_account_info()[source]
setup_stubs_get_target_id()[source]
setup_stubs_init()[source]
setup_stubs_logged_in(result='')[source]
setup_stubs_login(iscsi_obj)[source]
setup_stubs_portal_visible(iscsi_obj, result='')[source]
setup_stubs_set_chap_auth_initiator(iscsi_obj)[source]
setup_stubs_set_chap_auth_target(iscsi_obj)[source]
setup_stubs_set_initiatorName(iscsi_obj)[source]
tearDown()[source]
test_iscsi_get_device_name()[source]
test_iscsi_login()[source]
test_iscsi_target_id()[source]
test_iscsi_visible()[source]

virttest.libvirt_network_unittest module

Unit tests for Manipulator classes in libvirt_xml module.

class virttest.libvirt_network_unittest.NetworkTestBase(methodName='runTest')[source]

Bases: unittest.case.TestCase

Base class for NetworkXML test providing fake virsh commands.

setUp()[source]
class virttest.libvirt_network_unittest.NetworkXMLTest(methodName='runTest')[source]

Bases: virttest.libvirt_network_unittest.NetworkTestBase

Unit test class for manipulator methods in NetworkXML class.

test_sync_and_state_dict()[source]

Unit test for sync and state_dict methods of NetworkXML class.

Traverse all possible state and call sync using the state.

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
class virttest.libvirt_storage.PoolVolume(pool_name, virsh_instance=<module 'virttest.virsh' from '/home/docs/checkouts/readthedocs.org/user_builds/virt-test/checkouts/latest/virttest/virsh.py'>)[source]

Bases: object

Volume Manager for libvirt storage pool.

clone_volume(old_name, new_name)[source]

Clone a volume

create_volume(name, capability, allocation=None, frmt=None)[source]

Create a volume in pool.

delete_volume(name)[source]

Remove a volume.

list_volumes()[source]

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

volume_exists(name)[source]
volume_info(name)[source]

Get volume’s information with command vol-info.

class virttest.libvirt_storage.QemuImg(params, root_dir, tag)[source]

Bases: virttest.storage.QemuImg

libvirt class for handling operations of disk/block images.

check_image(params, root_dir)[source]

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()[source]

Commit image to it’s base file

convert(params, root_dir)[source]

Convert image

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

params should contain:

create(params)[source]

Create an image.

Parameters:params – Dictionary containing the test parameters.
Note:params should contain:
rebase(params)[source]

Rebase image

Parameters:params – A dict
Note:params should contain:
remove()[source]

Remove an image file.

Note:params should contain:
snapshot_create()[source]

Create a snapshot image.

Note:params should contain:
snapshot_del(blkdebug_cfg='')[source]

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
class virttest.libvirt_storage.StoragePool(virsh_instance=<module 'virttest.virsh' from '/home/docs/checkouts/readthedocs.org/user_builds/virt-test/checkouts/latest/virttest/virsh.py'>)[source]

Bases: object

Pool Manager for libvirt storage with virsh commands

build_pool(name)[source]

Build pool.

define_dir_pool(name, target_path)[source]

Define a directory type pool.

define_disk_pool(name, block_device, target_path)[source]

Define a disk type pool.

define_fs_pool(name, block_device, target_path)[source]

Define a filesystem type pool.

define_iscsi_pool(name, source_host, source_dev, target_path)[source]

Define a iscsi type pool.

define_lvm_pool(name, block_device, vg_name, target_path)[source]

Define a lvm type pool.

define_netfs_pool(name, source_host, source_path, target_path)[source]

Define a netfs type pool.

define_rbd_pool(name, source_host, source_name, extra='')[source]

Define a rbd type pool.

delete_pool(name)[source]

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)[source]

Destroy pool if it is active.

get_pool_uuid(name)[source]

Get pool’s uuid.

Returns:Pool uuid.
is_pool_active(name)[source]

Check whether pool is active on given libvirt

is_pool_persistent(name)[source]

Check whether pool is persistent

list_pools()[source]
Return a dict include pools’ information with structure:
pool_name ==> pool_details(a dict: feature ==> value)
pool_exists(name)[source]

Check whether pool exists on given libvirt

pool_info(name)[source]

Get pool’s information.

Returns:A dict include pool’s information: Name ==> value UUID ==> value ...
pool_state(name)[source]

Get pool’s state.

Returns:active/inactive, and None when something wrong.
set_pool_autostart(name, extra='')[source]

Set given pool as autostart

start_pool(name)[source]

Start pool if it is inactive.

virttest.libvirt_storage_unittest module

class virttest.libvirt_storage_unittest.ExistPoolTest(methodName='runTest')[source]

Bases: virttest.libvirt_storage_unittest.PoolTestBase

test_exist_pool()[source]
class virttest.libvirt_storage_unittest.NewPoolTest(methodName='runTest')[source]

Bases: virttest.libvirt_storage_unittest.PoolTestBase

tearDown()[source]
test_dir_pool()[source]
class virttest.libvirt_storage_unittest.NotExpectedPoolTest(methodName='runTest')[source]

Bases: virttest.libvirt_storage_unittest.PoolTestBase

test_not_exist_pool()[source]
class virttest.libvirt_storage_unittest.PoolTestBase(methodName='runTest')[source]

Bases: unittest.case.TestCase

setUp()[source]

virttest.libvirt_vm module

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

copyright:2011 Red Hat Inc.
class virttest.libvirt_vm.VM(name, params, root_dir, address_cache, state=None)[source]

Bases: virttest.virt_vm.BaseVM

This class handles all basic VM operations for libvirt.

activate_nic(nic_index_or_name)[source]
attach_disk(source, target=None, prefix='vd', extra='', ignore_status=False, debug=False)[source]

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 successed

attach_interface(option='', ignore_status=False, debug=False)[source]

Attach a NIC to VM.

backup_xml(active=False)[source]

Backup the guest’s xmlfile.

cleanup_serial_console()[source]

Close serial console and associated log file

cleanup_swap()[source]

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)[source]

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:
  • VMCreateError – If qemu terminates unexpectedly
  • VMKVMInitError – If KVM initialization fails
  • VMHugePageError – If hugepage initialization fails
  • VMImageMissingError – If a CD image is missing
  • VMHashMismatchError – If a CD image hash has doesn’t match the expected hash
  • VMBadPATypeError – If an unsupported PCI assignment type is requested
  • VMPAError – If no PCI assignable devices could be assigned
create_serial_console()[source]

Establish a session with the serial console.

The libvirt version uses virsh console to manage it.

create_swap_file(swapfile='/swapfile')[source]

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)[source]

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)[source]
define(xml_file)[source]

Define the VM.

destroy(gracefully=True, free_mac_addresses=True)[source]

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)[source]

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)[source]

Detach a NIC from VM.

dominfo()[source]

Return a dict include vm’s information.

domjobabort()[source]

Abort job for vm.

dump(path, option='')[source]

Dump self to path.

Raise:error.TestFail if dump fail.
exists()[source]

Return True if VM exists.

get_blk_devices()[source]

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()[source]

Return the VM’s cpu topology in VM cmdline.

Returns:A dirt of cpu topology
get_cpu_topology_in_vm()[source]
get_device_details(device_target)[source]
get_device_size(device_target)[source]
get_disk_devices()[source]

Get vm’s disk type block devices.

get_disks(diskname=None)[source]

Get disks in vm.

Parameters:diskname – Specify disk to be listed, used for checking given disk.
get_first_disk_devices()[source]

Get vm’s first disk type block devices.

get_id()[source]

Return VM’s ID.

get_ifname(nic_index=0)[source]
get_interface_mac(interface)[source]

Get mac address of interface by given name.

get_interfaces()[source]

Get available interfaces in vm.

get_job_type()[source]
get_max_mem()[source]

Get vm’s maximum memory(kilobytes).

get_pci_devices(device_str=None)[source]

Get PCI devices in vm accroding to given device character.

Parameters:device_str – a string to identify device.
get_pid()[source]

Return the VM’s PID.

Returns:int with PID. If VM is not alive, returns None.
get_serial_console_filename(name)[source]

Return the serial console filename.

Parameters:name – The serial port name.
get_serial_console_filenames()[source]

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

get_shared_meminfo()[source]

Returns the VM’s shared memory information.

Returns:Shared memory used by VM (MB)
get_shell_pid()[source]

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()[source]

Get vm’s current memory(kilobytes).

get_uuid()[source]

Return VM’s UUID.

get_vcpus_pid()[source]

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)[source]

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()[source]

Return VM’s xml file.

getenforce()[source]

Set SELinux mode in the VM.

Returns:SELinux mode [Enforcing|Permissive|Disabled]
has_swap()[source]

Check if there is any active swap partition/file.

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

install_package(name)[source]

Install a package on VM. ToDo: Support multiple package manager.

Parameters:name – Name of package to be installed
is_alive()[source]

Return True if VM is alive.

is_autostart()[source]

Return True if VM is autostart.

is_dead()[source]

Return True if VM is dead.

is_esx()[source]

Return True if VM is a esx guest.

is_lxc()[source]

Return True if VM is linux container.

is_paused()[source]

Return True if VM is paused.

is_persistent()[source]

Return True if VM is persistent.

is_qemu()[source]

Return True if VM is a qemu guest.

is_xen()[source]

Return True if VM is a xen guest.

make_create_command(name=None, params=None, root_dir=None)[source]

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()[source]

Managed save of VM’s state

migrate(dest_uri='', option='--live --timeout 60', extra='', ignore_status=False, debug=False)[source]

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()[source]
pmsuspend(target='mem', duration=0)[source]

Suspend a domain gracefully using power management functions

pmwakeup()[source]

Wakeup a domain from pmsuspended state

prepare_guest_agent(prepare_xml=True, channel=True, start=True)[source]

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()[source]
remove_package(name)[source]

Remove a package from VM. ToDo: Support multiple package manager.

Parameters:name – Name of package to be removed
remove_with_storage()[source]

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)[source]

Override BaseVM restore_from_file method

resume()[source]
save_to_file(path)[source]

Override BaseVM save_to_file method

screendump(filename, debug=False)[source]
set_console_getty(device, getty='mgetty', remove=False)[source]

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)[source]

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)[source]

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)[source]

Allow or ban root to login through serial console.

Parameters:
  • device – device to set root login
  • allow_root – do remove operation
setenforce(mode)[source]

Set SELinux mode in the VM.

Parameters:mode – SELinux mode [Enforcing|Permissive|1|0]
shutdown()[source]

Shuts down this VM.

start(autoconsole=True)[source]

Starts this VM.

state()[source]

Return domain state.

undefine()[source]

Undefine the VM.

vcpuinfo()[source]

Return a dict’s list include vm’s vcpu information.

vcpupin(vcpu, cpu_list, options='')[source]

To pin vcpu to cpu_list

verify_alive()[source]

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)[source]

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)[source]

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)[source]

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
Returns:a complete uri
virttest.libvirt_vm.get_uri_with_transport(uri_type='qemu', transport='', dest_ip='')[source]

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)[source]

Processes connect_uri Cartesian into something virsh can use

Parameters:connect_uri – Cartesian Params setting
Returns:Normalized connect_uri

virttest.libvirt_xml_unittest module

class virttest.libvirt_xml_unittest.AccessorsTest(methodName='runTest')[source]

Bases: virttest.libvirt_xml_unittest.LibvirtXMLTestBase

test_AllForbidden()[source]
test_XMLElementBool_deep()[source]
test_XMLElementBool_simple()[source]
test_XMLElementInt()[source]
test_XMLElementList()[source]
test_XMLElementList_Text()[source]
test_XMLElementNest()[source]
test_accessor_base()[source]
test_create_by_xpath()[source]
test_not_enuf_dargs()[source]
test_required_slots()[source]
test_too_many_dargs()[source]
test_type_check()[source]
class virttest.libvirt_xml_unittest.Bar(parent, virsh_instance)[source]

Bases: virttest.libvirt_xml.base.LibvirtXMLBase

baz
class virttest.libvirt_xml_unittest.Baz(parent, virsh_instance)[source]

Bases: virttest.libvirt_xml.base.LibvirtXMLBase

foobar
class virttest.libvirt_xml_unittest.LibvirtXMLTestBase(methodName='runTest')[source]

Bases: unittest.case.TestCase

setUp()[source]
tearDown()[source]
class virttest.libvirt_xml_unittest.TestLibvirtXML(methodName='runTest')[source]

Bases: virttest.libvirt_xml_unittest.LibvirtXMLTestBase

test_guest_capabilities()[source]
test_uuid()[source]
class virttest.libvirt_xml_unittest.TestVMXML(methodName='runTest')[source]

Bases: virttest.libvirt_xml_unittest.LibvirtXMLTestBase

test_getters()[source]
test_new_from_dumpxml()[source]
test_restore()[source]
test_seclabel()[source]
test_valid_xml()[source]
class virttest.libvirt_xml_unittest.testAddressXML(methodName='runTest')[source]

Bases: virttest.libvirt_xml_unittest.LibvirtXMLTestBase

test_required()[source]
class virttest.libvirt_xml_unittest.testCAPXML(methodName='runTest')[source]

Bases: virttest.libvirt_xml_unittest.LibvirtXMLTestBase

test_capxmlbase()[source]
class virttest.libvirt_xml_unittest.testCharacterXML(methodName='runTest')[source]

Bases: virttest.libvirt_xml_unittest.LibvirtXMLTestBase

test_arbitrart_attributes()[source]
class virttest.libvirt_xml_unittest.testDiskXML(methodName='runTest')[source]

Bases: virttest.libvirt_xml_unittest.LibvirtXMLTestBase

test_vm_get()[source]
test_vm_get_by_class()[source]
class virttest.libvirt_xml_unittest.testLibrarian(methodName='runTest')[source]

Bases: virttest.libvirt_xml_unittest.LibvirtXMLTestBase

test_bad_names()[source]
test_no_module()[source]
test_serial_class()[source]
class virttest.libvirt_xml_unittest.testNetworkXML(methodName='runTest')[source]

Bases: virttest.libvirt_xml_unittest.LibvirtXMLTestBase

test_getters()[source]
test_ip_getter()[source]
test_valid_xml()[source]
class virttest.libvirt_xml_unittest.testNodedevXML(methodName='runTest')[source]

Bases: virttest.libvirt_xml_unittest.LibvirtXMLTestBase

test_get_key2syspath_dict()[source]
test_get_key2value_dict()[source]
test_new_from_dumpxml()[source]
class virttest.libvirt_xml_unittest.testNodedevXMLBase(methodName='runTest')[source]

Bases: virttest.libvirt_xml_unittest.LibvirtXMLTestBase

test_getter()[source]
test_static()[source]
class virttest.libvirt_xml_unittest.testPCIXML(methodName='runTest')[source]

Bases: virttest.libvirt_xml_unittest.LibvirtXMLTestBase

test_get_key2filename_dict()[source]
test_get_key2value_dict()[source]
test_get_path()[source]
test_static()[source]
class virttest.libvirt_xml_unittest.testSerialXML(methodName='runTest')[source]

Bases: virttest.libvirt_xml_unittest.LibvirtXMLTestBase

XML = u"<serial type='pty'><source path='/dev/null'/> <target port='-1'/></serial>"
test_from_element()[source]
test_getters()[source]
test_vm_get_by_class()[source]
test_vm_get_modify()[source]
class virttest.libvirt_xml_unittest.testStubXML(methodName='runTest')[source]

Bases: virttest.libvirt_xml_unittest.LibvirtXMLTestBase

TypedFoobar[source]
UntypedFoobar[source]
setUp()[source]
test_typed_device_stub()[source]
test_untyped_device_stub()[source]
class virttest.libvirt_xml_unittest.testVMCPUTuneXML(methodName='runTest')[source]

Bases: virttest.libvirt_xml_unittest.LibvirtXMLTestBase

test_get_set_del()[source]
class virttest.libvirt_xml_unittest.testVMXMLDevices(methodName='runTest')[source]

Bases: virttest.libvirt_xml_unittest.LibvirtXMLTestBase

test_channels()[source]
test_graphics()[source]

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;
class virttest.lvm.EmulatedLVM(params, root_dir='/tmp')[source]

Bases: virttest.lvm.LVM

cleanup()[source]

Cleanup created logical volumes;

get_emulate_image_name()[source]
make_emulate_image()[source]

Create emulate image via dd with 8M block size;

make_volume(img_file, extra_args='')[source]

Map a file to loop back device;

Parameters:img_file – image file path;
Returns:loop back device name;
setup()[source]

Main function to setup a lvm environments;

Returns:LogicalVolume path
setup_pv(vg)[source]

Setup physical volume device if exists return it directly;

class virttest.lvm.LVM(params)[source]

Bases: object

cleanup()[source]

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

generate_id(params)[source]

Create prefix with image_name;

get_vol(vname, vtype)[source]

Get a exists volume object;

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

Volume object or None;

register(vol)[source]

Register new volume;

Parameters:vol – Volume object or VolumeGroup objects
rescan()[source]

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

setup()[source]

Main function to setup a lvm environments;

Returns:LogicalVolume path
setup_lv()[source]

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)[source]

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)[source]

Setup logical volumegroup which specify on volumegroup specify by params[“vg_name”];

Parameters:params["vg_name"] – volumegroup name;
Returns:volumegroup object;
unregister(vol)[source]

Unregister volume or VolumeGroup;

Parameters:vol – Volume object or VolumeGroup objects
class virttest.lvm.LogicalVolume(name, size, vg)[source]

Bases: virttest.lvm.Volume

create()[source]

Create LogicalVolume device;

Returns:path of logical volume;
display(extra_args='')[source]

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)[source]

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')[source]

Remove LogicalVolume device;

Parameters:extra_args – extra argurments pass to lvm command;
resize(size, extra_args='-ff')[source]

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;

class virttest.lvm.PhysicalVolume(name, size)[source]

Bases: virttest.lvm.Volume

create(extra_args='-ff --yes')[source]

Create physical volume on specify physical volume;

Parameters:extra_args – extra argurments for pvcreate command;
Raise:CmdError or TestError;
Returns:physical volume abspath
display()[source]

Show physical volume detials

Raise:CmdError
get_attr(attr)[source]

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')[source]

Remove a physical volume

Parameters:extra_args – extra argurments for pvremove command
Raise:CmdError
resize(size, extra_args='-ff --yes')[source]

Resize a physical volume;

Parameters:
  • size – new size of the physical volume device;
  • extra_args – extra argurments for pvresize command;
set_vg(vg)[source]

Set VolumeGroup of the physical volume device;

Parameters:vg – VolumeGroup object
class virttest.lvm.Volume(name, size)[source]

Bases: object

exists()[source]

Check is the volume really exists or not;

get_attr(cmd, attr, res='[\\w/]+')[source]

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')[source]

Unmount volume;

class virttest.lvm.VolumeGroup(name, size, pvs)[source]

Bases: object

append_lv(lv)[source]

Collect Logical Volumes on the VolumeGroup;

Parameters:lv – LogicalVolume Object
create(extra_args='-ff --yes')[source]

Create volume group with specify physical volumes;

Parameters:extra_args – extra argurments for lvm command;
Raise:CmdError or TestError;
Returns:volume group name;
exists()[source]

Check VolumeGroup exists or not;

Returns:bool type, if exists True else False;
extend_pv(pv, extra_args='')[source]

Add PhysicalVolume into VolumeGroup;

Parameters:
  • pv – PhysicalVolume object
  • extra_args – extra argurments used for vgextend command
get_attr(attr)[source]

Get VolumeGroup attribue;

Parameters:attr – attribue name;
Returns:string or None;
reduce_pv(pv, extra_args='-ff --yes')[source]

Reduce a PhysicalVolume from VolumeGroup;

Parameters:
  • pv – PhysicalVolume object;
  • extra_args – extra argurments pass to lvm command;
remove(extra_args='-ff --yes')[source]

Remove the VolumeGroup;

Parameters:extra_args – extra argurments for lvm command;
virttest.lvm.cmd_output(cmd, res='[\\w/]+')[source]
virttest.lvm.normalize_data_size(size)[source]

virttest.lvsb module

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

copyright:2013 Red Hat Inc.
class virttest.lvsb.TestBaseSandboxes(params, env)[source]

Bases: virttest.lvsb_base.TestSandboxes

Simplistic sandbox aggregate manager

command_suffixes()[source]

Append command after a –

results(each_timeout=5)[source]

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

class virttest.lvsb.TestComplexSandboxes(params, env)[source]

Bases: virttest.lvsb.TestBaseSandboxes

Executes a command with complex options

class virttest.lvsb.TestSimpleSandboxes(params, env)[source]

Bases: virttest.lvsb.TestBaseSandboxes

Executes a command with simple options

virttest.lvsb.make_sandboxes(params, env, extra_ns=None)[source]

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.
class virttest.lvsb_base.SandboxBase(params)[source]

Bases: object

Base operations for sandboxed command

auto_clean(boolean)[source]

Change behavior of asynchronous background sandbox process on __del__

exit_code()[source]

Block until asynchronous background sandbox process ends, returning code

fini()[source]

Finalize asynchronous background sandbox process (destroys state!)

instances = None
make_sandbox_command_line(extra=None)[source]

Return the fully formed command-line for the sandbox using self.options

recv()[source]

Return stdout and stderr from asynchronous background sandbox process

recverr()[source]

return only stderr from asynchronous background sandbox process

recvout()[source]

Return only stdout from asynchronous background sandbox process

run(extra=None)[source]

Launch new sandbox as asynchronous background sandbox process

Parameters:extra – String of extra command-line to use but not store
running()[source]

Return True/False if asynchronous background sandbox process executing

send(data)[source]

Send data to asynchronous background sandbox process

stop()[source]

Destroy but don’t finalize asynchronous background sandbox process

class virttest.lvsb_base.SandboxCommandBase(params, name=None)[source]

Bases: virttest.lvsb_base.SandboxBase

Connection to a single new or existing sandboxed command

BINARY_PATH_PARAM = 'virt_sandbox_binary'
add_flag(option)[source]

Add a flag into the list of command line options

add_mm()[source]

Append a – to the end of the current option list

add_optarg(option, argument)[source]

Add an option with an argument into the list of command line options

add_pos(argument)[source]

Add a positional option into the list of command line options

static flaten_options(options)[source]

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

list_flags()[source]

Return a list of all flags (options without arguments)

list_long_options()[source]

Return a list of all long options with an argument

list_pos()[source]

Return a list of all positional arguments

list_short_options()[source]

Return a list of all short options with an argument

make_sandbox_command_line(extra=None)[source]

Return entire command-line string needed to start sandbox

name

Represent a unique sandbox name generated from class and identifier

exception virttest.lvsb_base.SandboxException(message)[source]

Bases: exceptions.Exception

Basic exception class for problems occurring in SandboxBase or subclasses

class virttest.lvsb_base.SandboxSession[source]

Bases: object

Connection instance to asynchronous I/O redirector process

auto_clean(boolean)[source]

Make session cleanup on GC if True

close_session(warn_if_nonexist=True)[source]

Finalize assigned opaque session object

connected

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

exit_code()[source]

Block, and return exit code from session

is_running()[source]

Return True if exit_code() would block

kill_session(sig=15)[source]

Send a signal to the opaque session object

new_session(command)[source]

Create and set new opaque session object

open_session(a_id)[source]

Restore connection to existing session identified by a_id

recv()[source]

Return combined stdout/stderr output received so far

recverr()[source]

Return just stderr output

recvout()[source]

Return just stdout output

send(a_string)[source]

Send a_string to session

session_id

Returns unique & persistent identifier for the background process

used = False
class virttest.lvsb_base.TestSandboxes(params, env)[source]

Bases: object

Aggregate manager class of SandboxCommandBase or subclass instances

SANDBOX_TYPE

alias of SandboxCommandBase

are_failed()[source]

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

are_running()[source]

Return the number of sandbox processes still running

for_each(do_something, *args, **dargs)[source]

Iterate over all sandboxes, calling do_something on each

Parameters:do_sometihng – Called with the item and *args, **dargs
init_sandboxes()[source]

Create self.count Sandbox instances

virttest.lvsbs module

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

class virttest.lvsbs.SandboxService(params, service_name, uri='lxc:///')[source]

Bases: object

Management for a single new/existing sandboxed service

create()[source]
destroy()[source]
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.

class virttest.nfs.Exportfs(path, client='*', options='', ori_exported=None)[source]

Bases: object

Add or remove one entry to exported nfs file system.

export()[source]

Export one directory if it is not in exported list.

Returns:Export nfs file system succeed or not
is_exported()[source]

Check if the directory is already exported.

Returns:If the entry is exported
Return type:Boolean
need_reexport()[source]

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()[source]

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

unexport()[source]

Unexport an entry.

class virttest.nfs.NFSClient(params)[source]

Bases: object

NFSClient class for handle nfs remotely mount and umount.

cleanup()[source]

Cleanup NFS client.

is_mounted()[source]

Check the NFS is mounted or not.

Returns:If the src is mounted as expect
Return type:Boolean
setup()[source]

Setup NFS client.

setup_remote()[source]

Mount sharing directory to remote host.

class virttest.nfs.Nfs(params)[source]

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()[source]

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()[source]

Check the NFS is mounted or not.

Returns:If the src is mounted as expect
Return type:Boolean
mount()[source]

Mount source into given mount point.

setup()[source]

Setup NFS in host.

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

umount()[source]

Umount the given mount point.

virttest.nfs.nfs_exported()[source]

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.nfs_unittest module

class virttest.nfs_unittest.FakeService(service_name)[source]

Bases: object

get_stdout(cmd)[source]
restart()[source]
status()[source]
class virttest.nfs_unittest.nfs_test(methodName='runTest')[source]

Bases: unittest.case.TestCase

setUp()[source]
setup_stubs_cleanup(nfs_obj)[source]
setup_stubs_init()[source]
setup_stubs_is_mounted(nfs_obj)[source]
setup_stubs_setup(nfs_obj)[source]
tearDown()[source]
test_nfs_setup()[source]

virttest.openvswitch module

Wrapper around module.

Necessary for pickling of dynamic class.

class virttest.openvswitch.OpenVSwitch(tmpdir, db_path=None, db_socket=None, db_pidfile=None, ovs_pidfile=None, dbschema=None, install_prefix=None)[source]

Bases: virttest.openvswitch.OpenVSwitchSystem

OpenVSwtich class.

clean()[source]
init_db()[source]
init_new()[source]

Create new dbfile without any configuration.

start_ovs_vswitchd()[source]
class virttest.openvswitch.OpenVSwitchControl[source]

Bases: object

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

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

add_br(br_name)[source]
add_port(br_name, port_name)[source]
add_port_tag(port_name, tag)[source]
add_port_trunk(port_name, trunk)[source]
br_exist(br_name)[source]
check_port_in_br(br_name, port_name)[source]
static convert_version_to_int(version)[source]
Parameters:version – (int) Converted from version string 1.4.0 => int 140
del_br(br_name)[source]
del_port(br_name, port_name)[source]
classmethod get_version()[source]

Get version of installed OpenVSwtich.

Returns:Version of OpenVSwtich.
list_br()[source]
set_vlanmode(port_name, vlan_mode)[source]
status()[source]
class virttest.openvswitch.OpenVSwitchControlCli_140[source]

Bases: virttest.openvswitch.OpenVSwitchControl

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

add_br(br_name)[source]
add_fake_br(br_name, parent, vlan)[source]
add_port(br_name, port_name)[source]
add_port_tag(port_name, tag)[source]
add_port_trunk(port_name, trunk)[source]
Parameters:trunk – list of vlans id.
br_exist(br_name)[source]
del_br(br_name)[source]
del_port(br_name, port_name)[source]
list_br()[source]
list_ports(br_name)[source]
ovs_vsctl(parmas, ignore_status=False)[source]
port_to_br(port_name)[source]

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)[source]
status()[source]
class virttest.openvswitch.OpenVSwitchControlCli_CNT[source]

Bases: virttest.versionable_class.VersionableClass

class virttest.openvswitch.OpenVSwitchControlDB_140[source]

Bases: virttest.openvswitch.OpenVSwitchControl

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

class virttest.openvswitch.OpenVSwitchControlDB_CNT[source]

Bases: virttest.versionable_class.VersionableClass

class virttest.openvswitch.OpenVSwitchSystem(db_path=None, db_socket=None, db_pidfile=None, ovs_pidfile=None, dbschema=None, install_prefix=None)[source]

Bases: virttest.openvswitch.OpenVSwitchControlCli_CNT, virttest.openvswitch.OpenVSwitchControlDB_CNT

OpenVSwtich class.

check()[source]
check_db_daemon()[source]

Check if OVS daemon is started correctly.

check_db_file()[source]

Check if db_file exists.

check_db_socket()[source]

Check if db socket exists.

check_switch_daemon()[source]

Check if OVS daemon is started correctly.

clean()[source]

Empty cleanup function

init_system()[source]

Create new dbfile without any configuration.

is_installed()[source]

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

Returns:Version of OpenVSwtich.
class virttest.openvswitch.ServiceManager[source]

Bases: virttest.versionable_class.VersionableClass

class virttest.openvswitch.ServiceManagerInterface[source]

Bases: object

classmethod get_version()[source]

Get version of ServiceManager. :return: Version of ServiceManager.

restart(service_name)[source]
start(service_name)[source]
status(service_name)[source]
stop(service_name)[source]
class virttest.openvswitch.ServiceManagerSystemD[source]

Bases: virttest.openvswitch.ServiceManagerSysvinit

restart(service_name)[source]
start(service_name)[source]
status(service_name)[source]
stop(service_name)[source]
class virttest.openvswitch.ServiceManagerSysvinit[source]

Bases: virttest.openvswitch.ServiceManagerInterface

restart(service_name)[source]
start(service_name)[source]
stop(service_name)[source]

virttest.ovirt module

oVirt SDK wrapper module.

copyright:2008-2012 Red Hat Inc.
class virttest.ovirt.ClusterManager(params)[source]

Bases: object

This class handles all basic cluster operations.

add(dc_name, cpu_type='Intel Nehalem Family')[source]

Add a new cluster into data center.

list()[source]

List all of clusters.

class virttest.ovirt.DataCenterManager(params)[source]

Bases: object

This class handles all basic datacenter operations.

add(storage_type)[source]

Add a new data center.

list()[source]

List all of datacenters.

class virttest.ovirt.HostManager(params)[source]

Bases: object

This class handles all basic host operations.

add(host_address, host_password, cluster_name, timeout=300)[source]

Register a host into specified cluster.

get_address()[source]

Return host IP address.

list()[source]

List all of hosts.

state()[source]

Return host state.

class virttest.ovirt.StorageDomainManager(params)[source]

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')[source]

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()[source]

List all of storagedomains.

class virttest.ovirt.VMManager(params, root_dir, address_cache=None, state=None)[source]

Bases: virttest.virt_vm.BaseVM

This class handles all basic VM operations for oVirt.

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)[source]

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)[source]

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)[source]

Create a template from VM.

Parameters:
  • cluster_name – cluster name.
  • template_name – ‘my_template’ is default template name.
  • timeout – Time out
delete(timeout=300)[source]

Delete a VM.

delete_from_export_domain(export_name)[source]

Remove a VM from specified export domain.

Parameters:export_name – export domain name.
destroy(gracefully=False)[source]

Destroy a VM.

export_from_export_domain(export_name, timeout=300)[source]

Export a VM from storage domain to export domain.

Parameters:export_name – Export domain name.
get_address(index=0)[source]

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='*')[source]

Return MAC address of a VM.

import_from_export_domain(export_name, storage_name, cluster_name, timeout=300)[source]

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()[source]

Judge if a VM is alive.

is_dead()[source]

Judge if a VM is dead.

is_paused()[source]

Return if VM is suspend.

list()[source]

List all of VMs.

lookup_by_storagedomains(storage_name)[source]

Lookup VM object in storage domain according to VM name.

resume(timeout)[source]

Resume a suspended VM.

shutdown(gracefully=True, timeout=300)[source]

Shut down a running VM.

snapshot(snapshot_name='my_snapshot', timeout=300)[source]

Create a snapshot to VM.

Parameters:
  • snapshot_name – ‘my_snapshot’ is default snapshot name.
  • timeout – Time out
start(wait_for_up=True, timeout=300)[source]

Start a VM.

state()[source]

Return VM state.

suspend(timeout)[source]

Suspend a VM.

update_instance()[source]
exception virttest.ovirt.WaitHostStateTimeoutError(msg, output)[source]

Bases: virttest.ovirt.WaitStateTimeoutError

exception virttest.ovirt.WaitStateTimeoutError(msg, output)[source]

Bases: exceptions.Exception

exception virttest.ovirt.WaitVMStateTimeoutError(msg, output)[source]

Bases: virttest.ovirt.WaitStateTimeoutError

virttest.ovirt.connect(params)[source]

Connect ovirt manager API.

virttest.ovirt.disconnect()[source]

Disconnect ovirt manager connection.

virttest.ovs_utils module

class virttest.ovs_utils.Machine(vm=None, src=None)[source]

Bases: object

add_vlan_iface(iface, vlan_id)[source]

Add vlan link for interface

Parameters:
  • iface – Interface on which should be added vlan.
  • vlan_id – Id of vlan.
bring_iface_down(iface)[source]

Bring interface up

bring_iface_up(iface)[source]

Bring interface up

cmd(cmd, timeout=60)[source]

Return outpu of command.

cmd_in_src(cmd, timeout=60)[source]
cmd_state(cmd, timeout=60)[source]

Return status of command.

compile_autotools_app_tar(path, package_name)[source]

Compile app on machine in src dir.

Parameters:
  • path – Path where shoule be program compiled.
  • dst_dir – Installation path.
copy_to(src, dst)[source]
del_vlan_iface(iface, vlan_id)[source]

Del vlan link for interface

Parameters:
  • iface – Interface from which should be deleted vlan.
  • vlan_id – Id of vlan.
fill_addrs()[source]
get_if_vlan_name(ifname, vlan_id=0)[source]
get_linkv6_addr(ifname)[source]

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()[source]

Return vlans interface name.

Returns:dict of {“ifname”: [(vlanid, ifname),(...)],...}
is_virtual()[source]
Returns:True when Machine is virtual.
ping(dst, iface=None, count=1, vlan=0, ipv=None)[source]

Ping destination.

prepare_directory(path, cleanup=False)[source]

Prepare dest directory. Create if directory not exist.

Parameters:
  • path – Path to directory
  • cleanup – It true clears the contents of directory.
virttest.ovs_utils.ping4(iface, dst_ip, count=1, runner=None)[source]

Format command for ipv4.

virttest.ovs_utils.ping6(iface, dst_ip, count=1, runner=None)[source]

Format command for ipv6.

virttest.passfd module

virttest.passfd_setup module

virttest.passfd_setup.import_passfd()[source]

Imports and lazily sets up the passfd module

Returns:passfd module
virttest.passfd_setup.passfd_setup(output_dir='/home/docs/checkouts/readthedocs.org/user_builds/virt-test/checkouts/latest/virttest')[source]

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
class virttest.postprocess_iozone.AnalyzerLoggingConfig(use_console=True)[source]

Bases: autotest.client.shared.logging_config.LoggingConfig

configure_logging(results_dir=None, verbose=False)[source]
class virttest.postprocess_iozone.IOzoneAnalyzer(list_files, output_dir)[source]

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()[source]

Analyzes and eventually compares sets of IOzone data.

average_performance(results, size=None)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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.
class virttest.postprocess_iozone.IOzonePlotter(results_file, output_dir)[source]

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()[source]

Creates data file without headers for gnuplot consumption.

plot_2d_graphs()[source]

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()[source]

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()[source]

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

virttest.postprocess_iozone.compare_matrices(matrix1, matrix2, treshold=0.05)[source]

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)[source]

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)[source]

Calculate the hamming distance

virttest.ppm_utils.find_id_for_screendump(md5sum, data_dir)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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))[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

Calculate two images hamming distance

virttest.ppm_utils.img_similar(base_img, comp_img, threshold=10)[source]

check whether two images are similar by hamming distance

virttest.ppm_utils.md5eval(data)[source]

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__()
class virttest.propcan.PropCan(*args, **dargs)[source]

Bases: virttest.propcan.PropCanBase

Special value handling on retrieval of None values

has_key(key)
items()[source]
keys()[source]
set_if_none(key, value)[source]

Set the value of key, only if it’s not set or None

set_if_value_not_none(key, value)[source]

Set the value of key, only if value is not None

values()[source]
class virttest.propcan.PropCanBase(*args, **dargs)[source]

Bases: dict, virttest.propcan.PropCanInternal

Objects with optional accessor methods and dict-like access to fixed set of keys

INITIALIZED = False
copy()[source]

Copy properties by value, not by reference.

update(other=None, excpt=<type 'exceptions.AttributeError'>, **kwargs)[source]

Update properties in __all_slots__ with another dict.

class virttest.propcan.PropCanInternal[source]

Bases: object

Semi-private methods for use only by PropCanBase subclasses (NOT instances)

class virttest.propcan.classproperty[source]

Bases: property

virttest.propcan_unittest module

class virttest.propcan_unittest.TestPropCan(methodName='runTest')[source]

Bases: unittest.case.TestCase

setUp()[source]
test_compare()[source]
test_extranious_init()[source]
test_init_None_value()[source]
test_odd_values()[source]
test_printables()[source]
class virttest.propcan_unittest.TestPropCanBase(methodName='runTest')[source]

Bases: unittest.case.TestCase

test_dict_methods_1()[source]
test_dict_methods_2()[source]
test_double_init()[source]
test_empty_init()[source]
test_empty_params_init()[source]
test_mixed_init()[source]
test_single_init()[source]
test_slots_restrict()[source]
test_subclass_no_mask_attributeerror()[source]
test_subclass_single_init_delter()[source]
test_subclass_single_init_getter()[source]
test_subclass_single_init_setter()[source]
test_update()[source]

virttest.qemu_devices_unittest module

This is a unittest for qemu_devices library.

author:Lukas Doktor <ldoktor@redhat.com>
copyright:2012 Red Hat, Inc.
class virttest.qemu_devices_unittest.Buses(methodName='runTest')[source]

Bases: unittest.case.TestCase

Set of bus-representation tests

test_q_pci_bus()[source]

PCI bus tests

test_q_pci_bus_strict()[source]

PCI bus tests in strict_mode (enforce additional options)

test_q_sparse_bus()[source]

Sparse bus tests (general bus testing)

test_usb_bus()[source]

Tests the specific handlings of QUSBBus

class virttest.qemu_devices_unittest.Container(methodName='runTest')[source]

Bases: unittest.case.TestCase

Tests related to the abstract representation of qemu machine

create_qdev(vm_name='vm1', strict_mode='no', allow_hotplugged_vm='yes')[source]
Returns:Initialized qcontainer.DevContainer object
setUp()[source]
tearDown()[source]
test_pci()[source]
test_qdev_equal()[source]
test_qdev_functional()[source]

Test basic qdev workflow

test_qdev_hotplug()[source]

Test the hotplug/unplug functionality

test_qdev_low_level()[source]

Test low level functions

class virttest.qemu_devices_unittest.Devices(methodName='runTest')[source]

Bases: unittest.case.TestCase

set of qemu devices tests

test_q_base_device()[source]

QBaseDevice tests

test_q_device()[source]

QDevice tests

test_q_string_device()[source]

QStringDevice tests

class virttest.qemu_devices_unittest.MockHMPMonitor[source]

Bases: virttest.qemu_monitor.HumanMonitor

Dummy class inherited from qemu_monitor.HumanMonitor

class virttest.qemu_devices_unittest.ParamsDict[source]

Bases: dict

params like dictionary

object_params(obj)[source]
objects(item)[source]

virttest.qemu_installer module

Installer code that implement KVM specific bits.

See BaseInstaller class in base_installer.py for interface details.

class virttest.qemu_installer.GitRepoInstaller(mode, name, test=None, params=None)[source]

Bases: virttest.qemu_installer.QEMUBaseInstaller, virttest.base_installer.GitRepoInstaller

Installer that deals with source code on Git repositories

class virttest.qemu_installer.LocalSourceDirInstaller(mode, name, test=None, params=None)[source]

Bases: virttest.qemu_installer.QEMUBaseInstaller, virttest.base_installer.LocalSourceDirInstaller

Installer that deals with source code on local directories

class virttest.qemu_installer.LocalSourceTarInstaller(mode, name, test=None, params=None)[source]

Bases: virttest.qemu_installer.QEMUBaseInstaller, virttest.base_installer.LocalSourceTarInstaller

Installer that deals with source code on local tarballs

class virttest.qemu_installer.RemoteSourceTarInstaller(mode, name, test=None, params=None)[source]

Bases: virttest.qemu_installer.QEMUBaseInstaller, virttest.base_installer.RemoteSourceTarInstaller

Installer that deals with source code on remote tarballs

virttest.qemu_io module

class virttest.qemu_io.QemuIO(test, params, image_name, blkdebug_cfg='', prompt='qemu-io>\s*$', log_filename=None, io_options='', log_func=None)[source]

Bases: object

A class for execute qemu-io command

close()[source]

Clean up

cmd_output(command)[source]

Run a command in qemu-io

get_cmd_line(ignore_option=[], essential_option=[], forbid_option=[])[source]

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

exception virttest.qemu_io.QemuIOParamError[source]

Bases: exceptions.Exception

Parameter Error for qemu-io command

class virttest.qemu_io.QemuIOShellSession(test, params, image_name, blkdebug_cfg='', prompt='qemu+-io>\s*$', log_filename=None, io_options='', log_func=None)[source]

Bases: virttest.qemu_io.QemuIO

Use a shell session to execute qemu-io command

close()[source]

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

class virttest.qemu_io.QemuIOSystem(test, params, image_name, blkdebug_cfg='', prompt='qemu-io>\s*$', log_filename=None, io_options='', log_func=None)[source]

Bases: virttest.qemu_io.QemuIO

Run qemu-io with a command line which will return immediately

close()[source]

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.
class virttest.qemu_monitor.HumanMonitor(vm, name, filename, suppress_exceptions=False)[source]

Bases: virttest.qemu_monitor.Monitor

Wraps “human monitor” commands.

CMD_TIMEOUT = 120
PROMPT_TIMEOUT = 60
block_mirror(device, target, speed, sync, format, mode, cmd='drive_mirror', correct=True)[source]

Start mirror type block device copy job

Parameters:
  • device – device ID
  • target – target image
  • speed – limited speed, unit is B/s
  • sync – full copy to target image(unsupport in human monitor)
  • mode – target image create mode, ‘absolute-paths’ or ‘existing’
  • format – target image format
  • cmd – block mirror command
  • correct – auto correct command, correct by default
Returns:

The command’s output

block_reopen(device, new_image_file, image_format, cmd='block_job_complete', correct=True)[source]

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)[source]

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)[source]

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)[source]

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)[source]

Change media of cdrom of drive;

cmd(cmd, timeout=120, debug=True, fd=None)[source]

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:
  • MonitorLockError – Raised if the lock cannot be acquired
  • MonitorSocketError – Raised if a socket error occurs
  • MonitorProtocolError – Raised if the (qemu) prompt cannot be found after sending the command
eject_cdrom(device, force=False)[source]

Eject media of cdrom and open cdrom door;

get_backingfile(device)[source]

Return “backing_file” path of the device

Parameters:device – device ID
Returns:string, backing_file path
get_status()[source]
getfd(fd, name)[source]

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)[source]

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)[source]

Request info about something and return the output. :param debug: Whether to print the commands being sent and responses

live_snapshot(device, snapshot_file, snapshot_format='qcow2')[source]

Take a live disk snapshot.

Parameters:
  • device – device id of base image
  • snapshot_file – image file name of snapshot
  • snapshot_format – image format of snapshot
Returns:

The response to the command

migrate(uri, full_copy=False, incremental_copy=False, wait=False)[source]

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)[source]

Set maximum tolerated downtime (in seconds) for migration.

Parameters:value – maximum downtime (in seconds)
Returns:The command’s output
migrate_set_speed(value)[source]

Set maximum speed (in bytes/sec) for migrations.

Parameters:value – Speed in bytes/sec
Returns:The command’s output
mouse_button(state)[source]

Set mouse button state.

Parameters:state – Button state (1=L, 2=M, 4=R)
Returns:The command’s output
mouse_move(dx, dy)[source]

Move mouse.

Parameters:
  • dx – X amount
  • dy – Y amount
Returns:

The command’s output

nmi()[source]

Inject a NMI on all guest’s CPUs.

query(what)[source]

Alias for info.

query_block_job(device)[source]

Get block job status on the device

Parameters:device – device ID
Returns:dict about job info, return empty dict if no active job
quit()[source]

Send “quit” without waiting for output.

screendump(filename, debug=True)[source]

Request a screendump.

Parameters:filename – Location for the screendump
Returns:The command’s output
send_args_cmd(cmdlines, timeout=120, convert=True)[source]

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)[source]

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)[source]

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 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

system_wakeup()[source]

Wakeup suspended guest.

verify_responsive()[source]

Make sure the monitor is responsive by sending a command.

verify_status(status)[source]

Verify VM status

Parameters:status – Optional VM status, ‘running’ or ‘paused’
Returns:return True if VM status is same as we expected
class virttest.qemu_monitor.Monitor(vm, name, filename)[source]

Common code for monitor classes.

ACQUIRE_LOCK_TIMEOUT = 20
CONNECT_TIMEOUT = 30
DATA_AVAILABLE_TIMEOUT = 0
close()[source]

Close the connection to the monitor and its log file.

correct(cmd)[source]

Automatic conversion “-” and “_” in commands if the translate command is supported commands;

human_monitor_cmd(cmd='', timeout=None, debug=True, fd=None)[source]

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)[source]

Request info about something and return the response.

info_block(debug=True)[source]

Request info about blocks and return dict of parsed results :return: Dict of disk parameters

info_numa()[source]

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()[source]

Return True iff the monitor is responsive.

classmethod parse_info_numa(r)[source]

Parse ‘info numa’ output

See info_numa() for information about the return value.

re_numa_node_info = <_sre.SRE_Pattern object>
re_numa_nodes = <_sre.SRE_Pattern object>
verify_supported_cmd(cmd)[source]

Verify whether cmd is supported by monitor. If not, raise a MonitorNotSupportedCmdError Exception.

Parameters:cmd – The cmd string need to verify.
exception virttest.qemu_monitor.MonitorConnectError(monitor_name)[source]

Bases: virttest.qemu_monitor.MonitorError

exception virttest.qemu_monitor.MonitorError[source]

Bases: exceptions.Exception

exception virttest.qemu_monitor.MonitorLockError[source]

Bases: virttest.qemu_monitor.MonitorError

exception virttest.qemu_monitor.MonitorNotSupportedCmdError(monitor, cmd)[source]

Bases: virttest.qemu_monitor.MonitorNotSupportedError

exception virttest.qemu_monitor.MonitorNotSupportedError[source]

Bases: virttest.qemu_monitor.MonitorError

exception virttest.qemu_monitor.MonitorProtocolError[source]

Bases: virttest.qemu_monitor.MonitorError

exception virttest.qemu_monitor.MonitorSocketError(msg, e)[source]

Bases: virttest.qemu_monitor.MonitorError

exception virttest.qemu_monitor.QMPCmdError(cmd, qmp_args, data)[source]

Bases: virttest.qemu_monitor.MonitorError

class virttest.qemu_monitor.QMPMonitor(vm, name, filename, suppress_exceptions=False)[source]

Bases: virttest.qemu_monitor.Monitor

Wraps QMP monitor commands.

CMD_TIMEOUT = 120
PROMPT_TIMEOUT = 60
READ_OBJECTS_TIMEOUT = 5
RESPONSE_TIMEOUT = 120
block_mirror(device, target, speed, sync, format, mode, cmd='drive-mirror', correct=True)[source]

Start mirror type block device copy job

Parameters:
  • device – device ID
  • target – target image
  • speed – limited speed, unit is B/s
  • sync – what parts of the disk image should be copied to the destination;
  • mode – ‘absolute-paths’ or ‘existing’
  • format – target image format
  • cmd – block mirror command
  • correct – auto correct command, correct by default
Returns:

The command’s output

block_reopen(device, new_image_file, image_format, cmd='block-job-complete', correct=True)[source]

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)[source]

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)[source]

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)[source]

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)[source]

Change media of cdrom of drive;

clear_event(name)[source]

Clear a kinds of events in events list only.

Raises:MonitorLockError – Raised if the lock cannot be acquired
clear_events()[source]

Clear the list of asynchronous events.

Raises:MonitorLockError – Raised if the lock cannot be acquired
cmd(cmd, args=None, timeout=120, debug=True, fd=None)[source]

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:
  • MonitorLockError – Raised if the lock cannot be acquired
  • MonitorSocketError – Raised if a socket error occurs
  • MonitorProtocolError – Raised if no response is received
  • QMPCmdError – Raised if the response is an error message (the exception’s args are (cmd, args, data) where data is the error data)
cmd_obj(obj, timeout=120)[source]

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:
  • MonitorLockError – Raised if the lock cannot be acquired
  • MonitorSocketError – Raised if a socket error occurs
  • MonitorProtocolError – Raised if no response is received
cmd_qmp(cmd, args=None, q_id=None, timeout=120)[source]

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:
  • MonitorLockError – Raised if the lock cannot be acquired
  • MonitorSocketError – Raised if a socket error occurs
  • MonitorProtocolError – Raised if no response is received
cmd_raw(data, timeout=120)[source]

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:
  • MonitorLockError – Raised if the lock cannot be acquired
  • MonitorSocketError – Raised if a socket error occurs
  • MonitorProtocolError – Raised if no response is received
eject_cdrom(device, force=False)[source]

Eject media of cdrom and open cdrom door;

get_backingfile(device)[source]

Return “backing_file” path of the device

Parameters:device – device ID
Returns:string, backing_file path
get_event(name)[source]

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()[source]

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()[source]

Return QMP greeting message.

get_status()[source]

Get VM status.

Returns:return VM status
getfd(fd, name)[source]

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=120, debug=True, fd=None)[source]

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)[source]

Request info about something and return the response.

live_snapshot(device, snapshot_file, snapshot_format='qcow2')[source]

Take a live disk snapshot.

Parameters:
  • device – device id of base image
  • snapshot_file – image file name of snapshot
  • snapshot_format – image format of snapshot
Returns:

The response to the command

migrate(uri, full_copy=False, incremental_copy=False, wait=False)[source]

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)[source]

Set maximum tolerated downtime (in seconds) for migration.

Parameters:value – maximum downtime (in seconds)
Returns:The command’s output
migrate_set_speed(value)[source]

Set maximum speed (in bytes/sec) for migrations.

Parameters:value – Speed in bytes/sec
Returns:The response to the command
nmi()[source]

Inject a NMI on all guest’s CPUs.

query(what, debug=True)[source]

Alias for info.

query_block_job(device)[source]

Get block job status on the device

Parameters:device – device ID
Returns:dict about job info, return empty dict if no active job
quit()[source]

Send “quit” and return the response.

screendump(filename, debug=True)[source]

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=120, convert=True)[source]

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:
  • MonitorLockError – Raised if the lock cannot be acquired
  • MonitorSendError – Raised if the command cannot be sent
  • MonitorProtocolError – Raised if no response is received
sendkey(keystr, hold_time=1)[source]

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)[source]

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 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

system_wakeup()[source]

Wakeup suspended guest.

verify_responsive()[source]

Make sure the monitor is responsive by sending a command.

verify_status(status)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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_monitor_unittest module

class virttest.qemu_monitor_unittest.InfoBlocks(methodName='runTest')[source]

Bases: unittest.case.TestCase

testParseBlocks()[source]
class virttest.qemu_monitor_unittest.InfoNumaTests(methodName='runTest')[source]

Bases: unittest.case.TestCase

testTwoNodes()[source]
testZeroNodes()[source]
class virttest.qemu_monitor_unittest.MockMonitor[source]

Bases: virttest.qemu_monitor.Monitor

Dummy class inherited from qemu_monitor.HumanMonitor

virttest.qemu_qtree module

Utility classes and functions to handle KVM Qtree parsing and verification.

author:Lukas Doktor <ldoktor@redhat.com>
copyright:2012 Red Hat Inc.
exception virttest.qemu_qtree.IncompatibleTypeError(prop, desired_type, value)[source]

Bases: exceptions.TypeError

class virttest.qemu_qtree.QtreeBus[source]

Bases: virttest.qemu_qtree.QtreeNode

bus: qtree object

add_child(child)[source]
guess_type()[source]
class virttest.qemu_qtree.QtreeContainer[source]

Bases: object

Container for Qtree

get_nodes()[source]
Returns:flat list of all qtree nodes (last one is main-system-bus)
get_qtree()[source]
Returns:root of qtree
parse_info_qtree(info)[source]

Parses ‘info qtree’ output. Creates list of self.nodes. Last node is the main-system-bus (whole qtree)

class virttest.qemu_qtree.QtreeDev[source]

Bases: virttest.qemu_qtree.QtreeNode

dev: qtree object

add_child(child)[source]
guess_type()[source]
class virttest.qemu_qtree.QtreeDisk[source]

Bases: virttest.qemu_qtree.QtreeDev

qtree disk object

generate_params()[source]
get_block()[source]
get_qname()[source]
set_block_prop(prop, value)[source]
update_block_prop(prop, value)[source]
class virttest.qemu_qtree.QtreeDisksContainer(nodes)[source]

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.

check_disk_params(params)[source]

Check gathered info from qtree/block with params :param params: autotest params :return: number of errors

check_guests_proc_scsi(info)[source]

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()[source]

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)[source]

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
class virttest.qemu_qtree.QtreeNode[source]

Bases: object

Generic Qtree node

add_child(child)[source]
generate_params()[source]
get_children()[source]
get_params()[source]
get_parent()[source]
get_qtree()[source]
guess_type()[source]

Detect type of this object from qtree props

replace_child(oldchild, newchild)[source]
set_parent(parent)[source]
set_qtree(qtree)[source]
set_qtree_prop(prop, value)[source]
str_qtree()[source]
str_short()[source]
update_params(param, value)[source]
update_qtree_prop(prop, value)[source]
verify()[source]

virttest.qemu_qtree_unittest module

This is a unittest for qemu_qtree library.

author:Lukas Doktor <ldoktor@redhat.com>
copyright:2012 Red Hat, Inc.
class virttest.qemu_qtree_unittest.KvmQtreeClassTest(methodName='runTest')[source]

Bases: unittest.case.TestCase

Additional tests for qemu_qtree classes

test_qtree_bus_bus()[source]

Bus’ child can’t be Bus()

test_qtree_dev_dev()[source]

Dev’s child can’t be Dev()

test_qtree_disk_missing_filename()[source]

in info_block must contain info about file or backing_file

class virttest.qemu_qtree_unittest.ParamsDict[source]

Bases: dict

params like dictionary

object_params(obj)[source]
objects(item)[source]
class virttest.qemu_qtree_unittest.QtreeContainerTest(methodName='runTest')[source]

Bases: unittest.case.TestCase

QtreeContainer tests

test_bad_qtree()[source]

Incorrect qtree

test_qtree()[source]

Correct workflow

class virttest.qemu_qtree_unittest.QtreeDiskContainerTest(methodName='runTest')[source]

Bases: unittest.case.TestCase

QtreeDiskContainer tests

setUp()[source]
tearDown()[source]
test_check_params()[source]

Correct workflow

test_check_params_bad()[source]

Whole workflow with bad data

virttest.qemu_qtree_unittest.combine(first, second, offset)[source]

Add string line-by-line with offset*OFFSET_PER_LEVEL

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
class virttest.qemu_storage.Iscsidev(params, root_dir, tag)[source]

Bases: virttest.storage.Iscsidev

Class for handle iscsi devices for VM

cleanup()[source]

Logout the iscsi target and clean up the config and image.

setup()[source]

Access the iscsi target. And return the local raw device name.

class virttest.qemu_storage.LVMdev(params, root_dir, tag)[source]

Bases: virttest.storage.LVMdev

Class for handle lvm devices for VM

cleanup()[source]

Cleanup useless volumes;

setup()[source]

Get logical volume path;

class virttest.qemu_storage.QemuImg(params, root_dir, tag)[source]

Bases: virttest.storage.QemuImg

KVM class for handling operations of disk/block images.

check_image(params, root_dir)[source]

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)[source]

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, verbose=True)[source]

Compare 2 images using the appropriate tools for each virt backend.

Parameters:
  • image1 – image path of first image
  • image2 – image path of second image
  • verbose – Record output in debug file or not
convert(params, root_dir, cache_mode=None)[source]

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, utils.CmdResult object containing the result of the creation command).

get_format()[source]

Get the fimage file format.

info()[source]

Run qemu-img info command on image file and return its output.

rebase(params, cache_mode=None)[source]

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()[source]

Remove an image file.

snapshot_apply()[source]

Apply a snapshot image.

Note:params should contain: snapshot_image_name – the name of snapshot image file
snapshot_create()[source]

Create a snapshot image.

Note:params should contain: snapshot_image_name – the name of snapshot image file
snapshot_del(blkdebug_cfg='')[source]

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()[source]

List all snapshots in the given image

support_cmd(cmd)[source]

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.
class virttest.qemu_virtio_port.GuestWorker(vm)[source]

Bases: object

Class for executing “virtio_console_guest” script on guest

cleanup()[source]

Cleanup ports and quit the worker

cleanup_ports()[source]

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)[source]

Wrapper around the self.cmd command which executes the command on guest. Unlike self._cmd command when the command fails it raises the test error. :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)[source]

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)[source]

Reconnect to guest_worker (eg. after migration) :param vm: New VM object

safe_exit_loopback_threads(send_pts, recv_pts)[source]

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.

class virttest.qemu_virtio_port.ThRecv(port, event, blocklen=1024, quiet=False)[source]

Bases: threading.Thread

Receives data and throws it away.

run()[source]
class virttest.qemu_virtio_port.ThRecvCheck(port, buff, exit_event, blocklen=1024, sendlen=0, migrate_event=None, debug=None)[source]

Bases: threading.Thread

Random data receiver/checker thread.

reload_loss_idx()[source]

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()[source]

Pick the right mode and execute it

run_debug()[source]

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()[source]

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.

class virttest.qemu_virtio_port.ThSend(port, data, exit_event, quiet=False)[source]

Bases: threading.Thread

Random data sender thread.

run()[source]
class virttest.qemu_virtio_port.ThSendCheck(port, exit_event, queues, blocklen=1024, migrate_event=None, reduced_set=False)[source]

Bases: threading.Thread

Random data sender thread.

run()[source]
class virttest.qemu_virtio_port.VirtioConsole(qemu_id, name, hostfile)[source]

Bases: virttest.qemu_virtio_port._VirtioPort

Class for handling virtio-console

exception virttest.qemu_virtio_port.VirtioPortException[source]

Bases: exceptions.Exception

General virtio_port exception

exception virttest.qemu_virtio_port.VirtioPortFatalException[source]

Bases: virttest.qemu_virtio_port.VirtioPortException

Fatal virtio_port exception

class virttest.qemu_virtio_port.VirtioSerial(qemu_id, name, hostfile)[source]

Bases: virttest.qemu_virtio_port._VirtioPort

Class for handling virtio-serialport

virttest.qemu_vm module

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

copyright:2008-2009, 2014 Red Hat Inc.
exception virttest.qemu_vm.ImageUnbootableError(name)[source]

Bases: virttest.virt_vm.VMError

exception virttest.qemu_vm.KVMInternalError(*args)[source]

Bases: virttest.virt_vm.VMError

exception virttest.qemu_vm.QemuSegFaultError(crash_message)[source]

Bases: virttest.virt_vm.VMError

class virttest.qemu_vm.VM(name, params, root_dir, address_cache, state=None)[source]

Bases: virttest.virt_vm.BaseVM

This class handles all basic VM operations.

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)[source]

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.
block_mirror(device, target, speed, sync, format, mode='absolute-paths', correct=True)[source]

Mirror block device to target file;

Parameters:
  • device – device ID
  • target – destination image file name;
  • speed – max limited speed, default unit is B/s;
  • sync – what parts of the disk image should be copied to the destination;
  • mode – new image open mode
  • format – target image format
  • correct – auto correct cmd, correct by default
block_reopen(device, new_image, format='qcow2', correct=True)[source]

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)[source]

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)[source]

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)[source]

Change media of cdrom;

Parameters:
  • device – Device ID;
  • target – new media file;
check_block_locked(value)[source]

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()[source]

Close serial console and associated log file

clone(name=None, params=None, root_dir=None, address_cache=None, copy_state=False)[source]

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_qemu_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:
  • VMCreateError – If qemu terminates unexpectedly
  • VMKVMInitError – If KVM initialization fails
  • VMHugePageError – If hugepage initialization fails
  • VMImageMissingError – If a CD image is missing
  • VMHashMismatchError – If a CD image hash has doesn’t match the expected hash
  • VMBadPATypeError – If an unsupported PCI assignment type is requested
  • VMPAError – If no PCI assignable devices could be assigned
  • TAPCreationError – If fail to create tap fd
  • BRAddIfError – If fail to add a tap to a bridge
  • TAPBringUpError – If fail to bring up a tap
  • PrivateBridgeError – If fail to bring the private bridge
create_serial_console()[source]

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()[source]

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)[source]

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)[source]

Eject cdrom and open door of the CDROM;

Parameters:
  • device – device ID;
  • force – force eject or not;
get_block(p_dict={})[source]

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={})[source]

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)[source]

Return the ifname of a bridge/tap device associated with a NIC.

Parameters:nic_index – Index of the NIC
get_job_status(device)[source]

get block job info;

Parameters:device – device ID
get_monitors_by_type(mon_type)[source]

Return list of monitors of mon_type type. :param mon_type: desired monitor type (qmp, human)

get_peer(netid)[source]

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()[source]

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_serial_console_filename(name=None)[source]

Return the serial console filename.

Parameters:name – The serial port name.
get_serial_console_filenames()[source]

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

get_shared_meminfo()[source]

Returns the VM’s shared memory information.

Returns:Shared memory used by VM (MB)
get_shell_pid()[source]

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)[source]

Returns string value of spice variable of choice or None :param spice_var - spice related variable ‘spice_port’, ...

get_vcpu_pids(vcpu_thread_pattern)[source]

Return the list of vcpu PIDs

Returns:the list of vcpu PIDs
get_vhost_threads(vhost_thread_pattern)[source]

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:list of integer
get_virtio_port_filenames()[source]

Get socket file of virtio ports

get_vnc_port()[source]

Return self.vnc_port.

graceful_shutdown(timeout=60)[source]

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()[source]

Return True if the VM is alive and its monitor is responsive.

is_dead()[source]

Return True if the qemu process is dead.

is_paused()[source]

Return True if the qemu process is paused (‘stop’ed)

live_snapshot(base_file, snapshot_file, snapshot_format='qcow2')[source]

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)[source]

Override BaseVM loadvm method

make_create_command(name=None, params=None, root_dir=None)[source]

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()[source]
mig_failed()[source]
mig_finished()[source]
mig_succeeded()[source]
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
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()[source]

Pause the VM operation.

process_info_block(blocks_info)[source]

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)[source]

Override BaseVM restore_from_file method

resume()[source]

Resume the VM operation in case it’s stopped.

save_to_file(path)[source]

Override BaseVM save_to_file method

savevm(tag_name)[source]

Override BaseVM savevm method

screendump(filename, debug=True)[source]
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)[source]

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)[source]

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 up/down.

Parameters:
  • name – Link name
  • up – Bool value, True=set up this link, False=Set down this link
update_system_dependent_devs()[source]
update_vga_global_default(params, migrate=None)[source]

Update VGA global default settings

Parameters:
  • params – dict for create vm
  • migrate – is vm create for migration
verify_alive()[source]

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()[source]
verify_kvm_internal_error()[source]

Verify KVM internal error.

verify_status(status)[source]

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()[source]

Verify if the userspace component (qemu) crashed.

wait_for_migration(timeout)[source]
wait_for_shutdown(timeout=60)[source]

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)[source]

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)[source]

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)[source]

Wait until the VM is paused.

Parameters:timeout – Timeout in seconds.
Returns:True in case the VM is paused before timeout, otherwise return None.
exception virttest.qemu_vm.VMMigrateProtoUnsupportedError(protocol, output)[source]

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()[source]

virttest.remote module

Functions and classes used for logging into guests and transferring files.

class virttest.remote.AexpectIOWrapperOut(obj)[source]

Bases: virttest.remote_commander.messenger.StdIOWrapperOutBase64

Basic implementation of IOWrapper for stdout

close()[source]
fileno()[source]
write(data)[source]
exception virttest.remote.LoginAuthenticationError(msg, output)[source]

Bases: virttest.remote.LoginError

exception virttest.remote.LoginBadClientError(client)[source]

Bases: virttest.remote.LoginError

exception virttest.remote.LoginError(msg, output)[source]

Bases: exceptions.Exception

exception virttest.remote.LoginProcessTerminatedError(status, output)[source]

Bases: virttest.remote.LoginError

exception virttest.remote.LoginTimeoutError(output)[source]

Bases: virttest.remote.LoginError

class virttest.remote.RemoteFile(address, client, username, password, port, remote_path, limit='', log_filename=None, verbose=False, timeout=600)[source]

Bases: object

Class to handle the operations of file on remote host or guest.

add(line_list)[source]

Append lines in line_list into file on remote.

remove(pattern_list)[source]

Remove the lines in remote file which matchs a pattern in pattern_list.

sub(pattern2repl_dict)[source]

Replace the string which match the pattern to the value contained in pattern2repl_dict.

sub_else_add(pattern2repl_dict)[source]

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)[source]

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
class virttest.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)[source]

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.

run(command, timeout=60, ignore_status=False)[source]

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.
class virttest.remote.Remote_Package(address, client, username, password, port, remote_path)[source]

Bases: object

pull_file(local_path, timeout=600)[source]

Copy file from remote to local.

push_file(local_path, timeout=600)[source]

Copy file from local to remote.

exception virttest.remote.SCPAuthenticationError(msg, output)[source]

Bases: virttest.remote.SCPError

exception virttest.remote.SCPAuthenticationTimeoutError(output)[source]

Bases: virttest.remote.SCPAuthenticationError

exception virttest.remote.SCPError(msg, output)[source]

Bases: exceptions.Exception

exception virttest.remote.SCPTransferFailedError(status, output)[source]

Bases: virttest.remote.SCPError

exception virttest.remote.SCPTransferTimeoutError(output)[source]

Bases: virttest.remote.SCPError

virttest.remote.copy_files_from(address, client, username, password, port, remote_path, local_path, limit='', log_filename=None, verbose=False, timeout=600, interface=None)[source]

Copy files from a remote host (guest) using the selected client.

Parameters:
  • client – Type of transfer client
  • username – Username (if required)
  • password – Password (if requried)
  • remote_path – Path on the remote machine where we are copying from
  • local_path – Path on the local machine where we are copying to
  • address – Address of remote host(guest)
  • 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 to complete.
Interface:

The interface the neighbours attach to (only use when using ipv6 linklocal address.)

Raise:

Whatever remote_scp() raises

virttest.remote.copy_files_to(address, client, username, password, port, local_path, remote_path, limit='', log_filename=None, verbose=False, timeout=600, interface=None)[source]

Copy files to a remote host (guest) using the selected client.

Parameters:
  • client – Type of transfer client
  • username – Username (if required)
  • password – Password (if requried)
  • local_path – Path on the local machine where we are copying from
  • remote_path – Path on the remote machine where we are copying to
  • address – Address of remote host(guest)
  • 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 to complete.
Interface:

The interface the neighbours attach to (only use when using ipv6 linklocal address.)

Raise:

Whatever remote_scp() raises

virttest.remote.handle_prompts(session, username, password, prompt, timeout=10, debug=False)[source]

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:
  • LoginTimeoutError – If timeout expires
  • LoginAuthenticationError – If authentication fails
  • LoginProcessTerminatedError – If the client terminates during login
  • LoginError – If some other error occurs
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='udp', timeout=10, check_sum=True)[source]

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.
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)[source]

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 $?')[source]

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)[source]

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)[source]

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)[source]

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)[source]

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.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)[source]

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)[source]

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

exception virttest.remote_build.BuildError(error_info)[source]

Bases: exceptions.Exception

class virttest.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)[source]

Bases: object

build()[source]

Synchronize all files and execute ‘make’ on the remote system if needed. :returns: The path to the build directory on the remote machine

make()[source]

Execute make on the remote system

sync_directories()[source]

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.remote_unittest module

class virttest.remote_unittest.RemoteFileTest(methodName='runTest')[source]

Bases: unittest.case.TestCase

default_data = ['RemoteFile Test.\n', 'Pattern Line.']
testAdd()[source]
testRemove()[source]
testSEEA()[source]
testSub()[source]
test_file_path = '/home/docs/checkouts/readthedocs.org/user_builds/virt-test/checkouts/latest/tmp/remote_file'
tmp_dir = '/home/docs/checkouts/readthedocs.org/user_builds/virt-test/checkouts/latest/tmp'

virttest.rss_client module

Client for file transfer services offered by RSS (Remote Shell Server).

author:Michael Goldish (mgoldish@redhat.com)
copyright:2008-2010 Red Hat Inc.
class virttest.rss_client.FileDownloadClient(address, port, log_func=None, timeout=20)[source]

Bases: virttest.rss_client.FileTransferClient

Connect to a RSS (remote shell server) and download files or directory trees.

download(src_pattern, dst_path, timeout=600)[source]

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:
  • FileTransferTimeoutError – Raised if timeout expires
  • FileTransferServerError – Raised if something goes wrong and the server sends an informative error message to the client
Note:

Other exceptions can be raised.

class virttest.rss_client.FileTransferClient(address, port, log_func=None, timeout=20)[source]

Bases: object

Connect to a RSS (remote shell server) and transfer files.

close()[source]

Close the connection.

exception virttest.rss_client.FileTransferConnectError(msg, e=None, filename=None)[source]

Bases: virttest.rss_client.FileTransferError

exception virttest.rss_client.FileTransferError(msg, e=None, filename=None)[source]

Bases: exceptions.Exception

exception virttest.rss_client.FileTransferNotFoundError(msg, e=None, filename=None)[source]

Bases: virttest.rss_client.FileTransferError

exception virttest.rss_client.FileTransferProtocolError(msg, e=None, filename=None)[source]

Bases: virttest.rss_client.FileTransferError

exception virttest.rss_client.FileTransferServerError(errmsg)[source]

Bases: virttest.rss_client.FileTransferError

exception virttest.rss_client.FileTransferSocketError(msg, e=None, filename=None)[source]

Bases: virttest.rss_client.FileTransferError

exception virttest.rss_client.FileTransferTimeoutError(msg, e=None, filename=None)[source]

Bases: virttest.rss_client.FileTransferError

class virttest.rss_client.FileUploadClient(address, port, log_func=None, timeout=20)[source]

Bases: virttest.rss_client.FileTransferClient

Connect to a RSS (remote shell server) and upload files or directory trees.

upload(src_pattern, dst_path, timeout=600)[source]

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:
  • FileTransferTimeoutError – Raised if timeout expires
  • FileTransferServerError – Raised if something goes wrong and the server sends an informative error message to the client
Note:

Other exceptions can be raised.

virttest.rss_client.download(address, port, src_pattern, dst_path, log_func=None, timeout=60, connect_timeout=20)[source]

Connect to server and upload files.

:see:: FileDownloadClient

virttest.rss_client.main()[source]
virttest.rss_client.upload(address, port, src_pattern, dst_path, log_func=None, timeout=60, connect_timeout=20)[source]

Connect to server and upload files.

:see:: FileUploadClient

virttest.scheduler module

class virttest.scheduler.scheduler(tests, num_workers, total_cpus, total_mem, bindir)[source]

A scheduler that manages several parallel test execution pipelines on a single host.

scheduler()[source]

The scheduler function.

Sends commands to workers, telling them to run tests, clean up or terminate execution.

worker(index, run_test_func)[source]

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.service_unittest module

class virttest.service_unittest.ConstantsTest(methodName='runTest')[source]

Bases: unittest.case.TestCase

test_ModuleLoad()[source]
class virttest.service_unittest.ResultParserTest(methodName='runTest')[source]

Bases: unittest.case.TestCase

test_systemd_result_parser()[source]
test_sysvinit_result_parser()[source]
class virttest.service_unittest.SysVInitGeneratorTest(methodName='runTest')[source]

Bases: unittest.case.TestCase

setUp()[source]
test_all_command()[source]
test_set_target()[source]
class virttest.service_unittest.SystemdGeneratorTest(methodName='runTest')[source]

Bases: unittest.case.TestCase

setUp()[source]
test_all_command()[source]
test_list()[source]
test_set_target()[source]
class virttest.service_unittest.TestServiceManager(init_name, run_mock)[source]

Bases: object

get_service_manager()[source]
class virttest.service_unittest.TestSysVInitServiceManager(methodName='runTest')[source]

Bases: unittest.case.TestCase

setUp()[source]
test_enable()[source]
test_list()[source]
test_runlevels()[source]
test_unknown_runlevel()[source]
class virttest.service_unittest.TestSystemdServiceManager(methodName='runTest')[source]

Bases: unittest.case.TestCase

setUp()[source]
test_list()[source]
test_start()[source]

virttest.standalone_test module

class virttest.standalone_test.Bcolors[source]

Bases: object

Very simple class with color support.

disable()[source]
class virttest.standalone_test.Test(params, options)[source]

Bases: object

Mininal test class used to run a virt test.

env_version = 1
run_once()[source]
set_debugdir(debugdir)[source]
start_file_logging()[source]
stop_file_logging()[source]
verify_background_errors()[source]

Verify if there are any errors that happened on background threads.

Raises:Exception – Any exception stored on the background_errors queue.
write_test_keyval(d)[source]
virttest.standalone_test.bootstrap_tests(options)[source]

Bootstrap process (download the appropriate JeOS file to data dir).

This function will check whether the JeOS is in the right location of the data dir, if not, it will download it non interactively.

Parameters:options – OptParse object with program command line options.
virttest.standalone_test.cleanup_env(parser, options)[source]

Clean up virt-test temporary files.

Parameters:
  • parser – Cartesian parser with run parameters.
  • options – Test runner options object.
virttest.standalone_test.configure_console_logging(loglevel=10)[source]

Simple helper for adding a file logger to the root logger.

virttest.standalone_test.configure_file_logging(logfile, loglevel=10)[source]

Simple helper for adding a file logger to the root logger.

virttest.standalone_test.create_config_files(options)[source]

Check if the appropriate configuration files are present.

If the files are not present, create them.

Parameters:options – OptParser object with options.
virttest.standalone_test.find_default_qemu_paths(options_qemu=None, options_dst_qemu=None)[source]
virttest.standalone_test.get_cartesian_parser_details(cartesian_parser)[source]

Print detailed information about filters applied to the cartesian cfg.

Parameters:cartesian_parser – Cartesian parser object.
virttest.standalone_test.get_guest_name_list(options)[source]
virttest.standalone_test.get_guest_name_parser(options)[source]
virttest.standalone_test.get_paginator()[source]
virttest.standalone_test.print_error(t_elapsed, open_fd=False)[source]

Print ERROR to stdout with ERROR (red) color.

virttest.standalone_test.print_fail(t_elapsed, open_fd=False)[source]

Print FAIL to stdout with FAIL (red) color.

virttest.standalone_test.print_guest_list(options)[source]

Helper function to pretty print the guest list.

This function uses a paginator, if possible (inspired on git).

Parameters:
  • options – OptParse object with cmdline options.
  • cartesian_parser – Cartesian parser object with test options.
virttest.standalone_test.print_header(sr)[source]

Print a string to stdout with HEADER (blue) color.

virttest.standalone_test.print_pass(t_elapsed, open_fd=False)[source]

Print PASS to stdout with PASS (green) color.

virttest.standalone_test.print_skip(open_fd=False)[source]

Print SKIP to stdout with SKIP (yellow) color.

virttest.standalone_test.print_stdout(sr, end=True)[source]
virttest.standalone_test.print_test_list(options, cartesian_parser)[source]

Helper function to pretty print the test list.

This function uses a paginator, if possible (inspired on git).

Parameters:
  • options – OptParse object with cmdline options.
  • cartesian_parser – Cartesian parser object with test options.
virttest.standalone_test.print_warn(t_elapsed, open_fd=False)[source]

Print WARN to stdout with WARN (yellow) color.

virttest.standalone_test.reset_logging()[source]

Remove all the handlers and unset the log level on the root logger.

virttest.standalone_test.run_tests(parser, options)[source]

Runs the sequence of KVM tests based on the list of dctionaries generated by the configuration system, handling dependencies.

Parameters:
  • parser – Config parser object.
  • options – Test runner options object.
Returns:

True, if all tests ran passed, False if any of them failed.

virttest.step_editor module

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
class virttest.storage.Iscsidev(params, root_dir, tag)[source]

Bases: virttest.storage.Rawdev

Class for handle iscsi devices for VM

class virttest.storage.LVMdev(params, root_dir, tag)[source]

Bases: virttest.storage.Rawdev

Class for handle LVM devices for VM

exception virttest.storage.OptionMissing(option)[source]

Bases: exceptions.Exception

Option not found in the odbject

class virttest.storage.QemuImg(params, root_dir, tag)[source]

Bases: object

A basic class for handling operations of disk/block images.

backup_image(params, root_dir, action, good=True, skip_existing=False)[source]

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)[source]

Check if object has the option required.

Parameters:option – option should be checked
static clone_image(params, vm_name, image_name, root_dir)[source]

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()[source]

Check if image is from a remote server or not

static rm_cloned_image(params, vm_name, image_name, root_dir)[source]

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.
class virttest.storage.Rawdev(params, root_dir, tag)[source]

Bases: object

Base class for raw storage devices such as iscsi and local disks

virttest.storage.file_exists(params, filename_path)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]
virttest.storage.preprocess_image_backend(bindir, params, env)[source]
virttest.storage.preprocess_images(bindir, params, env)[source]

virttest.syslog_server module

class virttest.syslog_server.RequestHandler(request, client_address, server)[source]

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>
decodeFacilityPriority(priority)[source]

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)[source]

Logs the received message as a DEBUG message

class virttest.syslog_server.RequestHandlerTcp(request, client_address, server)[source]

Bases: virttest.syslog_server.RequestHandler

handle()[source]

Handles a single request

class virttest.syslog_server.RequestHandlerUdp(request, client_address, server)[source]

Bases: virttest.syslog_server.RequestHandler

handle()[source]

Handles a single request

class virttest.syslog_server.SysLogServerTcp(address)[source]

Bases: SocketServer.TCPServer

class virttest.syslog_server.SysLogServerUdp(address)[source]

Bases: SocketServer.UDPServer

virttest.syslog_server.get_default_format()[source]

Returns the current default message format

virttest.syslog_server.set_default_format(message_format)[source]

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)[source]

virttest.test_setup module

Library to perform pre/post test setup for virt test.

class virttest.test_setup.EGDConfig(params, env)[source]

Bases: object

Setup egd.pl server on localhost, support startup with socket unix or tcp.

cleanup()[source]
get_pid(socket)[source]

Check egd.pl start at socket on localhost.

install()[source]

Install egd.pl from source code

setup()[source]
startup(socket)[source]

Start egd.pl server with tcp or unix socket.

exception virttest.test_setup.EGDConfigError[source]

Bases: exceptions.Exception

Raise when setup local egd.pl server failed.

exception virttest.test_setup.HPNotSupportedError[source]

Bases: exceptions.Exception

Thrown when host does not support hugepages.

class virttest.test_setup.HugePageConfig(params)[source]

Bases: object

cleanup(*args, **kwargs)
get_hugepage_size()[source]

Get the current system setting for huge memory page size.

get_multi_supported_hugepage_size()[source]

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)[source]

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()[source]

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)[source]

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()[source]
class virttest.test_setup.KSMConfig(params, env)[source]

Bases: object

cleanup(env)[source]
setup(env)[source]
class virttest.test_setup.LibvirtPolkitConfig(params)[source]

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.

cleanup()[source]

Cleanup polkit config

file_replace_append(fpath, pat, repl)[source]

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()[source]

Enable polkit libvirt access driver and setup polkit ACL rules.

class virttest.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)[source]

Bases: object

Request PCI assignable devices on host. It will check whether to request PF (physical Functions) or VF (Virtual Functions).

add_device(device_type='vf', name=None, mac=None)[source]

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()[source]

Check VFs count number according to the parameter driver_options.

get_devs(devices=None)[source]

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)[source]

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_vf_info()[source]

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:list of dict
get_same_group_devs(pci_id)[source]

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)[source]

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)[source]

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)[source]

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()[source]

Get VFs count number according to lspci.

is_binded_to_stub(full_id)[source]

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)[source]

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()[source]

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
exception virttest.test_setup.PolkitConfigCleanupError[source]

Bases: virttest.test_setup.PolkitConfigError

Thrown when polkit config cleanup is not behaving as expected.

exception virttest.test_setup.PolkitConfigError[source]

Bases: exceptions.Exception

Base exception for Polkit Config setup.

exception virttest.test_setup.PolkitRulesSetupError[source]

Bases: virttest.test_setup.PolkitConfigError

Thrown when setup polkit rules is not behaving as expected.

exception virttest.test_setup.PolkitWriteLibvirtdConfigError[source]

Bases: virttest.test_setup.PolkitConfigError

Thrown when setup libvirtd config file is not behaving as expected.

class virttest.test_setup.PrivateBridgeConfig(params=None)[source]

Bases: object

cleanup()[source]
setup()[source]
exception virttest.test_setup.PrivateBridgeError(brname)[source]

Bases: exceptions.Exception

class virttest.test_setup.PrivateOvsBridgeConfig(params=None)[source]

Bases: virttest.test_setup.PrivateBridgeConfig

exception virttest.test_setup.THPError[source]

Bases: exceptions.Exception

Base exception for Transparent Hugepage setup.

exception virttest.test_setup.THPKhugepagedError[source]

Bases: virttest.test_setup.THPError

Thrown when khugepaged is not behaving as expected.

exception virttest.test_setup.THPNotSupportedError[source]

Bases: virttest.test_setup.THPError

Thrown when host does not support transparent hugepages.

exception virttest.test_setup.THPWriteConfigError[source]

Bases: virttest.test_setup.THPError

Thrown when host does not support transparent hugepages.

class virttest.test_setup.TransparentHugePageConfig(test, params)[source]

Bases: object

cleanup()[source]

: Restore the host’s original configuration after test

khugepaged_test()[source]

Start, stop and frequency change test for khugepaged.

set_env()[source]

Applies test configuration on the host.

setup()[source]

Configure host for testing. Also, check that khugepaged is working as expected.

value_listed(value)[source]

Get a parameters list from a string

virttest.utils_cgroup_unittest module

class virttest.utils_cgroup_unittest.CgroupTest(methodName='runTest')[source]

Bases: unittest.case.TestCase

test_get_cgroup_mountpoint()[source]

virttest.utils_config module

exception virttest.utils_config.ConfigError(msg)[source]

Bases: exceptions.Exception

exception virttest.utils_config.ConfigNoOptionError(option, path)[source]

Bases: virttest.utils_config.ConfigError

class virttest.utils_config.LibvirtConfigCommon(path='')[source]

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()

2) 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'")

3) Get an option: >>> is_listening = config.listen_tcp >>> print is_listening True

4) Delete an option from the config file: >>> del config.listen_tcp

5) Make the changes take effect in libvirt by restart libvirt daemon. >>> from virttest import utils_libvirtd >>> utils_libvirtd.Libvirtd().restart()

6) Restore the content of the config file. >>> config.restore()

conf_path = ''
exception virttest.utils_config.LibvirtConfigUnknownKeyError(key)[source]

Bases: virttest.utils_config.ConfigError

exception virttest.utils_config.LibvirtConfigUnknownKeyTypeError(key, key_type)[source]

Bases: virttest.utils_config.ConfigError

class virttest.utils_config.LibvirtGuestsConfig(path='')[source]

Bases: virttest.utils_config.LibvirtConfigCommon

Class for sysconfig libvirt-guests config file.

conf_path = '/etc/sysconfig/libvirt-guests'
class virttest.utils_config.LibvirtQemuConfig(path='')[source]

Bases: virttest.utils_config.LibvirtConfigCommon

Class for libvirt qemu config file.

conf_path = '/etc/libvirt/qemu.conf'
class virttest.utils_config.LibvirtdConfig(path='')[source]

Bases: virttest.utils_config.LibvirtConfigCommon

Class for libvirt daemon config file.

conf_path = '/etc/libvirt/libvirtd.conf'
class virttest.utils_config.LibvirtdSysConfig(path='')[source]

Bases: virttest.utils_config.LibvirtConfigCommon

Class for sysconfig libvirtd config file.

conf_path = '/etc/sysconfig/libvirtd'
class virttest.utils_config.SectionlessConfig(path)[source]

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)[source]
get_float(option)[source]
get_int(option)[source]
get_list(option)[source]
get_raw(option)[source]
get_string(option)[source]
restore()[source]
set_boolean(option, value)[source]
set_float(option, value)[source]
set_int(option, value)[source]
set_list(option, value)[source]
set_raw(option, value)[source]
set_string(option, value)[source]

virttest.utils_config_unittest module

class virttest.utils_config_unittest.LibvirtConfigCommonTest(methodName='runTest')[source]

Bases: unittest.case.TestCase

class NoTypesConfig(path='')[source]

Bases: virttest.utils_config.LibvirtConfigCommon

conf_path = '/tmp/config_unittest.conf'
class LibvirtConfigCommonTest.UndefinedTypeConfig(path='')[source]

Bases: virttest.utils_config.LibvirtConfigCommon

conf_path = '/tmp/config_unittest.conf'
class LibvirtConfigCommonTest.UnimplementedConfig(path='')[source]

Bases: virttest.utils_config.LibvirtConfigCommon

LibvirtConfigCommonTest.test_no_path()[source]
LibvirtConfigCommonTest.test_undefined_type()[source]
LibvirtConfigCommonTest.test_unimplemented()[source]
class virttest.utils_config_unittest.LibvirtConfigTest(methodName='runTest')[source]

Bases: unittest.case.TestCase

test_accessers()[source]
class virttest.utils_config_unittest.SectionlessConfigTest(methodName='runTest')[source]

Bases: unittest.case.TestCase

test_accessers()[source]
test_restore()[source]
test_specific_accessers()[source]
test_sync_file()[source]

virttest.utils_conn module

connection tools to manage kinds of connection.

exception virttest.utils_conn.ConnCertError(cert, output)[source]

Bases: virttest.utils_conn.ConnectionError

Error in building certificate file with certtool command.

exception virttest.utils_conn.ConnCmdClientError(cmd, output)[source]

Bases: virttest.utils_conn.ConnectionError

Error in executing cmd on client.

exception virttest.utils_conn.ConnCopyError(src_path, dest_path)[source]

Bases: virttest.utils_conn.ConnectionError

Error in coping file.

exception virttest.utils_conn.ConnForbiddenError(detail)[source]

Bases: virttest.utils_conn.ConnectionError

Error in forbidden operation.

exception virttest.utils_conn.ConnLoginError(dest, detail)[source]

Bases: virttest.utils_conn.ConnectionError

Error in login.

exception virttest.utils_conn.ConnMkdirError(directory, output)[source]

Bases: virttest.utils_conn.ConnectionError

Error in making directory.

exception virttest.utils_conn.ConnNotImplementedError(method_type, class_type)[source]

Bases: virttest.utils_conn.ConnectionError

Error in calling unimplemented method

exception virttest.utils_conn.ConnPrivKeyError(key, output)[source]

Bases: virttest.utils_conn.ConnectionError

Error in building private key with certtool command.

exception virttest.utils_conn.ConnRmCertError(cert, output)[source]

Bases: virttest.utils_conn.ConnectionError

Error in removing certificate file with rm command.

exception virttest.utils_conn.ConnSCPError(src_ip, src_path, dest_ip, dest_path, detail)[source]

Bases: virttest.utils_conn.ConnectionError

Error in SCP.

exception virttest.utils_conn.ConnServerRestartError(output)[source]

Bases: virttest.utils_conn.ConnectionError

Error in restarting libvirtd on server.

exception virttest.utils_conn.ConnToolNotFoundError(tool, detail)[source]

Bases: virttest.utils_conn.ConnectionError

Error in not found tools.

class virttest.utils_conn.ConnectionBase(*args, **dargs)[source]

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.

auto_recover
client_ip
client_pwd
client_session
client_user
close_session()[source]

If some session exists, close it down.

conn_check()[source]

waiting for implemented by subclass.

conn_recover()[source]

waiting for implemented by subclass.

conn_setup()[source]

waiting for implemented by subclass.

del_client_session()[source]

Delete client session.

del_server_session()[source]

Delete server session.

get_client_session()[source]

If the client session exists,return it. else create a session to client and set client_session.

get_server_session()[source]

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)[source]

Set client session to value.

set_server_session(value=None)[source]

Set server session to value.

tmp_dir
exception virttest.utils_conn.ConnectionError[source]

Bases: exceptions.Exception

The base error in connection.

exception virttest.utils_conn.SSHCheckError(server_ip, output)[source]

Bases: virttest.utils_conn.ConnectionError

Base Error in check of SSH connection.

class virttest.utils_conn.SSHConnection(*args, **dargs)[source]

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.

SHELL
SSH
SSH_ADD
SSH_AGENT
SSH_COPY_ID
SSH_KEYGEN
conn_check()[source]

Check the SSH connection.

(1).Initialize some variables. (2).execute ssh command to check conn.

conn_recover()[source]

Clean up authentication host.

conn_setup()[source]

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.

ssh_id_rsa_path
ssh_rsa_pub_path
exception virttest.utils_conn.SSHRmAuthKeysError(auth_keys, output)[source]

Bases: virttest.utils_conn.ConnectionError

Error in removing authorized_keys file.

class virttest.utils_conn.TCPConnection(*args, **dargs)[source]

Bases: virttest.utils_conn.ConnectionBase

Connection class for TCP transport.

Some specific variables for TCPConnection class.

auth_tcp
conn_recover()[source]

Clean up for TCP connection.

(1).initialize variables. (2).Delete the RemoteFile. (3).restart libvirtd on server.

conn_setup()[source]

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
class virttest.utils_conn.TLSConnection(*args, **dargs)[source]

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

CERTTOOL
auth_tls
ca_cakey_path
ca_cn
cert_recover()[source]

Do the clean up certifications work.

(1).initialize variables. (2).Delete local and remote generated certifications file.

client_cn
client_hosts
client_setup()[source]

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()[source]

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)[source]

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()[source]

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
class virttest.utils_conn.UNIXConnection(*args, **dargs)[source]

Bases: virttest.utils_conn.ConnectionBase

Connection class for UNIX transport.

Some specific variables for UNIXConnection class.

access_drivers
auth_unix_ro
auth_unix_rw
client_ip
client_libvirtdconf
client_pwd
client_user
conn_recover()[source]

Do the clean up work.

(1).Delete remote file. (2).Restart libvirtd on server.

conn_setup()[source]

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')[source]

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')[source]

(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')[source]

(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.
class virttest.utils_disk.CdromDisk(path, tmpdir)[source]

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)[source]

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
class virttest.utils_disk.CdromInstallDisk(path, tmpdir, source_cdrom, extra_params)[source]

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)[source]
class virttest.utils_disk.Disk[source]

Bases: object

Abstract class for Disk objects, with the common methods implemented.

close()[source]
copy_to(src)[source]
get_answer_file_path(filename)[source]
class virttest.utils_disk.FloppyDisk(*args, **kwargs)[source]

Bases: virttest.utils_disk.Disk

Represents a floppy disk. We can copy files to it, and setup it in convenient ways.

close()[source]

Copy everything that is in the mountpoint to the floppy.

copy_to(src)[source]
setup_virtio_win2003(virtio_floppy, virtio_oemsetup_id)[source]

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)[source]

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
class virttest.utils_disk.GuestFSModiDisk(disk)[source]

Bases: object

class of guest disk using guestfs lib to do some operation(like read/write) on guest disk:

mount_all()[source]
mounts()[source]
os_inspects()[source]
read_file(file_name)[source]

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)[source]

replace file content matchs in the file with rep_con. suport using Regular expression

Parameters:
  • file_name – the file you want to replace
  • find_con – the orign content you want to replace.
  • rep_con – the replace content you want.
umount_all()[source]
write_to_image_file(file_name, content, w_append=False)[source]

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='')[source]

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)[source]

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)[source]

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)[source]

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

class virttest.utils_env.Env(filename=None, version=0)[source]

Bases: UserDict.IterableUserDict

A dict-like object containing global objects used by tests.

clean_objects()[source]

Destroy all objects registered in this Env object.

create_vm(vm_type, target, name, params, bindir)[source]

Create and register a VM in this Env object

destroy()[source]

Destroy all objects stored in Env and remove the backing file.

get_all_vms()[source]

Return a list of all VM objects in this Env object.

get_lvmdev(name)[source]

Get lvm device object by name from env;

Parameters:name – lvm device object name;
Returns:lvmdev object
get_syncserver(port)[source]

Return a Sync Server object by its port.

Parameters:port – Sync Server port.
get_vm(name)[source]

Return a VM object by its name.

Parameters:name – VM name.
register_lvmdev(*args, **kwargs)[source]

Register lvm device object into env;

Parameters:
  • name – name of register lvmdev object
  • lvmdev – lvmdev object;
register_syncserver(*args, **kwargs)[source]

Register a Sync Server in this Env object.

Parameters:
  • port – Sync Server port.
  • server – Sync Server object.
register_vm(*args, **kwargs)[source]

Register a VM in this Env object.

Parameters:
  • name – VM name.
  • vm – VM object.
save(filename=None)[source]

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)[source]
stop_tcpdump()[source]
unregister_lvmdev(*args, **kwargs)[source]

Remove lvm device object from env;

Parameters:name – name of lvm device object;
unregister_syncserver(*args, **kwargs)[source]

Remove a given Sync Server.

Parameters:port – Sync Server port.
unregister_vm(*args, **kwargs)[source]

Remove a given VM.

Parameters:name – VM name.
exception virttest.utils_env.EnvSaveError[source]

Bases: exceptions.Exception

virttest.utils_env.get_env_version()[source]
virttest.utils_env.lock_safe(function)[source]

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_env_unittest module

class virttest.utils_env_unittest.FakeSyncListenServer(address='', port=123, tmpdir=None)[source]

Bases: object

close()[source]
class virttest.utils_env_unittest.FakeVm(vm_name, params)[source]

Bases: object

get_params()[source]
is_alive()[source]
class virttest.utils_env_unittest.TestEnv(methodName='runTest')[source]

Bases: unittest.case.TestCase

setUp()[source]
tearDown()[source]
test_get_all_vms()[source]
  1. Create an env object.
  2. Create 2 vms and register them in the env.
  3. Create a SyncListenServer and register it in the env.
  4. Verify that the 2 vms are in the output of get_all_vms.
  5. Verify that the sync server is not in the output of get_all_vms.
test_locking()[source]
  1. Create an env file.
  2. Create a thread that creates a dict as one of env’s elements, and keeps updating it, using the env save_lock attribute.
  3. Try to save the environment.
test_register_syncserver()[source]
  1. Create an env file.
  2. Create a SyncListenServer object and register it in the env.
  3. Get that SyncListenServer with get_syncserver.
  4. Verify that both objects are the same.
test_register_vm()[source]
  1. Create an env object.
  2. Create a VM and register it from env.
  3. Get the vm back from the env.
  4. Verify that the 2 objects are the same.
test_save()[source]
  1. Verify that calling env.save() with no filename where env doesn’t specify a filename will throw an EnvSaveError.
  2. Register a VM in environment, save env to a file, recover env from that file, get the vm and verify that the instance attribute of the 2 objects is the same.
  3. Register a SyncListenServer and don’t save env. Restore env from file and try to get the syncserver, verify it doesn’t work.
  4. Now save env to a file, restore env from file and verify that the syncserver can be found there, and that the sync server instance attribute is equal to the initial sync server instance.
test_unregister_syncserver()[source]

Unregister a sync server.

  1. Create an env file.
  2. Create and register 2 SyncListenServers in the env.
  3. Get one of the SyncListenServers in the env.
  4. Unregister one of the SyncListenServers.
  5. Verify that the SyncListenServer unregistered can’t be retrieved anymore with get_syncserver().
test_unregister_vm()[source]
  1. Create an env object.
  2. Register 2 vms to the env.
  3. Verify both vms are in the env.
  4. Remove one of those vms.
  5. Verify that the removed vm is no longer in env.

virttest.utils_gdb module

class virttest.utils_gdb.GDB(command=None)[source]

Bases: virttest.aexpect.Expect

Class to manipulate a inferior process in gdb.

back_trace()[source]

Get current backtrace stack as a list of lines.

cmd(command, cont=True)[source]

Call a gdb of GDB/MI command.

Parameters:
  • command – Command line to be called
  • cont – Whether continue the inferior after calling the command
cont()[source]

Continue a stopped inferior.

exit()[source]

Exit the gdb session.

insert_break(break_func)[source]

Insert a function breakpoint.

Parameters:break_func – Function at which breakpoint inserted
kill()[source]

Kill inferior by sending a SIGTERM signal.

run(arg_str='')[source]

Start the inferior with an optional argument string.

Parameters:arg_str – Argument the inferior to be called with
send_signal(signal_name)[source]

Send a signal to the inferior.

Parameters:signal_name – Signal name as a string or integer
set_callback(callback_type, func, params=None)[source]

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()[source]

Stop inferior by sending a SIGINT signal.

wait_for_start(timeout=60)[source]

Wait the inferior to start.

Parameters:timeout – Max time to wait
wait_for_stop(timeout=60)[source]

Wait the inferior to be stopped.

Parameters:timeout – Max time to wait
wait_for_termination(timeout=60)[source]

Wait the gdb session to be exited.

Parameters:timeout – Max time to wait
exception virttest.utils_gdb.GDBCmdError(command, msg)[source]

Bases: virttest.utils_gdb.GDBError

Exception raised when calling an gdb command.

exception virttest.utils_gdb.GDBError[source]

Bases: exceptions.Exception

General module exception class

virttest.utils_libguestfs module

libguestfs tools test utility functions.

class virttest.utils_libguestfs.Guestfish(disk_img=None, ro_mode=False, libvirt_domain=None, inspector=False, uri=None, mount_options=None, run_mode='interactive')[source]

Bases: virttest.utils_libguestfs.LibguestfsBase

Execute guestfish, using a new guestfish shell each time.

complete_cmd(command)[source]

Execute built-in command in a complete guestfish command (Not a guestfish session). command: guestfish [–options] [commands]

class virttest.utils_libguestfs.GuestfishPersistent(disk_img=None, ro_mode=False, libvirt_domain=None, inspector=False, uri=None, mount_options=None, run_mode='interactive')[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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()[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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()[source]

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)[source]

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)[source]

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)[source]

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)[source]

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()[source]

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)[source]

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)[source]

aug-setm - set multiple Augeas nodes

available(groups)[source]

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()[source]

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)[source]

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)[source]

blockdev-flushbufs - flush device buffers

This tells the kernel to flush internal buffers associated with “device”.

blockdev_getbsz(device)[source]

blockdev-getbsz - get blocksize of block device

This returns the block size of a device.

blockdev_getro(device)[source]

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)[source]

blockdev-getsize64 - get total size of device in bytes

This returns the size of the device in bytes

blockdev_getss(device)[source]

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)[source]

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)[source]

blockdev-rereadpt - reread partition table

Reread the partition table on “device”.

blockdev_setbsz(device, blocksize)[source]

blockdev-setbsz - set blocksize of block device

This sets the block size of a device.

blockdev_setro(device)[source]

blockdev-setro - set block device to read-only

Sets the block device named “device” to read-only.

blockdev_setrw(device)[source]

blockdev-setrw - set block device to read-write

Sets the block device named “device” to read-write.

canonical_device_name(device)[source]

canonical-device-name - return canonical device name

This utility function is useful when displaying device names to the user.

case_sensitive_path(path)[source]

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)[source]

cat - list the contents of a file

Return the contents of the file named “path”.

checksum(csumtype, path)[source]

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)[source]

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)[source]

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)[source]

chmod - change file mode

Change the mode (permissions) of “path” to “mode”. Only numeric modes are supported.

chown(owner, group, path)[source]

chown - change file owner and group

Change the file owner to “owner” and group to “group”.

close_session()[source]

If a persistent session exists, close it down.

command(cmd)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

debug - debugging and internals

The “debug” command exposes some internals of “guestfsd” (the guestfs daemon) that runs inside the hypervisor.

delete_event(name)[source]

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)[source]

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()[source]

df - report file system disk space usage

This command runs the “df” command to report disk space used.

df_h()[source]

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)[source]

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)[source]

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)[source]

disk-virtual-size - return virtual size of a disk

Detect and return the virtual size in bytes of the disk image”

dmesg()[source]

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)[source]

do_mount - Automaticly mount

Mount a lvm or physical partation to ‘/’

download(remotefilename, filename)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

echo - display a line of text

This echos the parameters to the terminal.

echo_daemon(words)[source]

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)[source]

egrep - return lines matching a pattern

This calls the external “egrep” program and returns the matching lines.

egrepi(regex, path)[source]

egrepi - return lines matching a pattern

This calls the external “egrep -i” program and returns the matching lines.

equal(file1, file2)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

fgrep - return lines matching a pattern

This calls the external “fgrep” program and returns the matching lines.

fgrepi(pattern, path)[source]

fgrepi - return lines matching a pattern

This calls the external “fgrep -i” program and returns the matching lines.

file(path)[source]

file - determine file type

This call uses the standard file(1) command to determine the type or contents of the file.

file_architecture(filename)[source]

file-architecture - detect the architecture of a binary file

This detects the architecture of the binary “filename”, and returns it if known.

filesize(file)[source]

filesize - return the size of the file in bytes

This command returns the size of “file” in bytes.

filesystem_available(filesystem)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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)[source]

fsck - run the filesystem checker

This runs the filesystem checker (fsck) on “device” which should have filesystem type “fstype”.

get_append()[source]

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()[source]

get-attach-method - get the backend

Return the current backend.

get_autosync()[source]

get-autosync - get autosync mode

Get the autosync flag.

get_backend()[source]

get-backend - get the backend

Return the current backend.

get_direct()[source]

get-direct - get direct appliance mode flag

Return the direct appliance mode flag.

get_e2attrs(file)[source]

get-e2attrs - get ext2 file attributes of a file

This returns the file attributes associated with “file”.

get_e2generation(file)[source]

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)[source]

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)[source]

get-e2uuid - get the ext2/3/4 filesystem UUID

This returns the ext2/3/4 filesystem UUID of the filesystem on “device”.

get_memsize()[source]

get-memsize - get memory allocated to the hypervisor

This gets the memory size in megabytes allocated to the hypervisor.

get_network()[source]

get-network - get enable network flag

This returns the enable network flag.

get_path()[source]

get-path - get the search path

Return the current search path.

get_pgroup()[source]

get-pgroup - get process group flag

This returns the process group flag.

get_pid()[source]

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()[source]

get-program - get the program name

Get the program name. See “set_program”.

get_qemu()[source]

get-qemu - get the hypervisor binary (usually qemu)

Return the current hypervisor binary (usually qemu).

get_recovery_proc()[source]

get-recovery-proc - get recovery process enabled flag

Return the recovery process enabled flag.

get_smp()[source]

get-smp - get number of virtual CPUs in appliance

This returns the number of virtual CPUs assigned to the appliance.

get_trace()[source]

get-trace - get command trace enabled flag

Return the command trace flag.

get_umask()[source]

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()[source]

get-verbose - get verbose mode

This returns the verbose messages flag.

glob(command, args)[source]

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)[source]

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)[source]

grep - return lines matching a pattern

This calls the external “grep” program and returns the matching lines.

grepi(regex, path)[source]

grepi - return lines matching a pattern

This calls the external “grep -i” program and returns the matching lines.

grub_install(root, device)[source]

grub-install root device

This command installs GRUB 1 (the Grand Unified Bootloader) on “device”, with the root directory being “root”.

head(path)[source]

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)[source]

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)[source]

help - display a list of commands or help on a command

hexdump(path)[source]

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)[source]

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)[source]

initrd-list - list files in an initrd

This command lists out files contained in an initrd.

inner_cmd(command)[source]

Execute inner command of guestfish in a pesistent session.

Parameters:command – inner command to be executed.
inspect_get_arch(root)[source]

inspect-get-arch - get architecture of inspected operating system

This returns the architecture of the inspected operating system.

inspect_get_distro(root)[source]

inspect-get-distro - get distro of inspected operating system

This returns the distro (distribution) of the inspected operating system.

inspect_get_filesystems(root)[source]

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)[source]

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)[source]

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)[source]

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)[source]

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()[source]

inspect-get-roots - return list of operating systems found by last inspection

This function is a convenient way to get the list of root devices

inspect_os()[source]

inspect-os - inspect disk and return list of operating systems found

This function uses other libguestfs functions and certain heuristics to inspect the disk(s) (usually disks belonging to a virtual machine), looking for operating systems.

is_blockdev(path, followsymlinks=None)[source]

is-blockdev - test if block device

This returns “true” if and only if there is a block device with the given “path” name

is_blockdev_opts(path, followsymlinks=None)[source]

is-blockdev_opts - test if block device

This returns “true” if and only if there is a block device with the given “path” name

An alias of command is-blockdev

is_chardev(path, followsymlinks=None)[source]

is-chardev - test if character device

This returns “true” if and only if there is a character device with the given “path” name.

is_chardev_opts(path, followsymlinks=None)[source]

is-chardev_opts - test if character device

This returns “true” if and only if there is a character device with the given “path” name.

An alias of command is-chardev

is_config()[source]

is-config - is ready to accept commands

This returns true if this handle is in the “CONFIG” state

is_dir(path, followsymlinks=None)[source]

is-dir - test if a directory

This returns “true” if and only if there is a directory with the given “path” name. Note that it returns false for other objects like files.

is_dir_opts(path, followsymlinks=None)[source]

is-dir-opts - test if character device

This returns “true” if and only if there is a character device with the given “path” name.

An alias of command is-dir

is_fifo(path, followsymlinks=None)[source]

is-fifo - test if FIFO (named pipe)

This returns “true” if and only if there is a FIFO (named pipe) with the given “path” name.

is_fifo_opts(path, followsymlinks=None)[source]

is-fifo-opts - test if FIFO (named pipe)

This returns “true” if and only if there is a FIFO (named pipe) with the given “path” name.

An alias of command is-fifo

is_file(path, followsymlinks=None)[source]

is-file - test if a regular file

This returns “true” if and only if there is a regular file with the given “path” name.

is_file_opts(path, followsymlinks=None)[source]

is-file_opts - test if a regular file

This returns “true” if and only if there is a regular file with the given “path” name.

An alias of command is-file

is_lv(device)[source]

is-lv - test if device is a logical volume

This command tests whether “device” is a logical volume, and returns true iff this is the case.

is_ready()[source]

is-ready - is ready to accept commands

This returns true if this handle is ready to accept commands (in the “READY” state).

is_socket(path, followsymlinks=None)[source]

is-socket - test if socket

This returns “true” if and only if there is a Unix domain socket with the given “path” name.

is_socket_opts(path, followsymlinks=None)[source]

is-socket-opts - test if socket

This returns “true” if and only if there is a Unix domain socket with the given “path” name.

An alias of command is-socket

is-symlink - test if symbolic link

This returns “true” if and only if there is a symbolic link with the given “path” name.

is_whole_device(device)[source]

is_whole_device - test if a device is a whole device

This returns “true” if and only if “device” refers to a whole block device. That is, not a partition or a logical device.

is_zero(path)[source]

is-zero - test if a file contains all zero bytes

This returns true iff the file exists and the file is empty or it contains all zero bytes.

is_zero_device(device)[source]

is-zero-device - test if a device contains all zero bytes

This returns true iff the device exists and contains all zero bytes. Note that for large devices this can take a long time to run.

kill_subprocess()[source]

kill-subprocess - kill the hypervisor

This kills the hypervisor.

launch()[source]

launch - launch the backend

You should call this after configuring the handle (eg. adding drives) but before performing any actions.

lcd(directory)[source]

lcd - change working directory

Change the local directory, ie. the current directory of guestfish itself.

lchown(owner, group, path)[source]

lchown - change file owner and group

Change the file owner to “owner” and group to “group”. This is like “chown” but if “path” is a symlink then the link itself is changed, not the target.

list_devices()[source]

list-devices - list the block devices

List all the block devices.

list_disk_labels()[source]

list-disk-labels - mapping of disk labels to devices

If you add drives using the optional “label” parameter of “add_drive_opts”, you can use this call to map between disk labels, and raw block device and partition names (like “/dev/sda” and “/dev/sda1”).

list_events()[source]

list-events - list event handlers

List the event handlers registered using the guestfish “event” command.

list_filesystems()[source]

list-filesystems - list filesystems

This inspection command looks for filesystems on partitions, block devices and logical volumes, returning a list of devices containing filesystems and their type.

list_md_devices()[source]

list-md-devices - list Linux md (RAID) devices

List all Linux md devices.

list_partitions()[source]

list-partitions - list the partitions

List all the partitions detected on all block devices.

ll(directory)[source]

ll - list the files in a directory (long format)

List the files in “directory” (relative to the root directory, there is no cwd) in the format of ‘ls -la’.

ls(directory)[source]

ls - list the files in a directory

List the files in “directory” (relative to the root directory, there is no cwd). The ‘.’ and ‘..’ entries are not returned, but hidden files are shown.

lstat(path)[source]

lstat - get file information for a symbolic link

Returns file information for the given “path”.

lstatlist(path, names)[source]

lstatlist - lstat on multiple files

This call allows you to perform the “lstat” operation on multiple files, where all files are in the directory “path”. “names” is the list of files from this directory.

lvcreate(logvol, volgroup, mbytes)[source]

lvcreate - create an LVM logical volume

This creates an LVM logical volume called “logvol” on the volume group “volgroup”, with “size” megabytes.

lvm_canonical_lv_name(lvname)[source]

lvm-canonical-lv-name - get canonical name of an LV

This converts alternative naming schemes for LVs that you might find to the canonical name.

lvm_clear_filter()[source]

lvm-clear-filter - clear LVM device filter

This undoes the effect of “lvm_set_filter”. LVM will be able to see every block device. This command also clears the LVM cache and performs a volume group scan.

lvm_remove_all()[source]

lvm-remove-all - remove all LVM LVs, VGs and PVs

This command removes all LVM logical volumes, volume groups and physical volumes.

lvm_set_filter(device)[source]

lvm-set-filter - set LVM device filter

This sets the LVM device filter so that LVM will only be able to “see” the block devices in the list “devices”, and will ignore all other attached block devices.

lvremove(device)[source]

lvremove - remove an LVM logical volume

Remove an LVM logical volume “device”, where “device” is the path to the LV, such as “/dev/VG/LV”.

lvrename(logvol, newlogvol)[source]

lvrename - rename an LVM logical volume

Rename a logical volume “logvol” with the new name “newlogvol”

lvresize(device, mbytes)[source]

lvresize - resize an LVM logical volume

This resizes (expands or shrinks) an existing LVM logical volume to “mbytes”.

lvresize_free(lv, percent)[source]

lvresize-free - expand an LV to fill free space

This expands an existing logical volume “lv” so that it fills “pc”% of the remaining free space in the volume group. Commonly you would call this with pc = 100 which expands the logical volume as much as possible, using all remaining free space in the volume group.

lvs()[source]

lvs - list the LVM logical volumes (LVs)

List all the logical volumes detected.

lvs_full()[source]

lvs-full - list the LVM logical volumes (LVs)

List all the logical volumes detected. This is the equivalent of the lvs(8) command. The “full” version includes all fields.

lvuuid(device)[source]

lvuuid - get the UUID of a logical volume

This command returns the UUID of the LVM LV “device”.

man()[source]

man - open the manual

Opens the manual page for guestfish.

max_disks()[source]

max-disks - maximum number of disks that may be added

Return the maximum number of disks that may be added to a handle

md_create(name, device, missingbitmap=None, nrdevices=None, spare=None, chunk=None, level=None)[source]

md-create - create a Linux md (RAID) device

Create a Linux md (RAID) device named “name” on the devices in the list “devices”.

md_detail(md)[source]

md-detail - obtain metadata for an MD device

This command exposes the output of ‘mdadm -DY <md>’. The following fields are usually present in the returned hash. Other fields may also be present.

md_stat(md)[source]

md-stat - get underlying devices from an MD device

This call returns a list of the underlying devices which make up the single software RAID array device “md”.

md_stop(md)[source]

md-stop - stop a Linux md (RAID) device

This command deactivates the MD array named “md”. The device is stopped, but it is not destroyed or zeroed.

mkdir(path)[source]

mkdir - create a directory

Create a directory named “path”.

mkdir_mode(path, mode)[source]

mkdir-mode - create a directory with a particular mode

This command creates a directory, setting the initial permissions of the directory to “mode”.

mkdir_p(path)[source]

mkdir-p - create a directory and parents

Create a directory named “path”, creating any parent directories as necessary. This is like the “mkdir -p” shell command.

mkfifo(mode, path)[source]

mkfifo - make FIFO (named pipe)

This call creates a FIFO (named pipe) called “path” with mode “mode”. It is just a convenient wrapper around “mknod”.

mkfs(fstype, device, blocksize=None, features=None, inode=None, sectorsize=None)[source]

mkfs - make a filesystem This function creates a filesystem on “device”. The filesystem type is “fstype”, for example “ext3”.

mkfs_opts(fstype, device, blocksize=None, features=None, inode=None, sectorsize=None)[source]

same with mkfs

mklost_and_found(mountpoint)[source]

mklost-and-found - make lost+found directory on an ext2/3/4 filesystem

Make the “lost+found” directory, normally in the root directory of an ext2/3/4 filesystem. “mountpoint” is the directory under which we try to create the “lost+found” directory.

mkmountpoint(exemptpath)[source]

mkmountpoint - create a mountpoint

“mkmountpoint” and “rmmountpoint” are specialized calls that can be used to create extra mountpoints before mounting the first filesystem.

mknod(mode, devmajor, devminor, path)[source]

mknod - make block, character or FIFO devices

This call creates block or character special devices, or named pipes (FIFOs).

mknod_b(mode, devmajor, devminor, path)[source]

mknod-b - make block device node

This call creates a block device node called “path” with mode “mode” and device major/minor “devmajor” and “devminor”. It is just a convenient wrapper around “mknod”.

mknod_c(mode, devmajor, devminor, path)[source]

mknod-c - make char device node

This call creates a char device node called “path” with mode “mode” and device major/minor “devmajor” and “devminor”. It is just a convenient wrapper around “mknod”.

mkswap(device, label=None, uuid=None)[source]

mkswap - create a swap partition

Create a Linux swap partition on “device”

mkswap_L(label, device)[source]

mkswap-L - create a swap partition with a label

Create a swap partition on “device” with label “label”.

mkswap_U(uuid, device)[source]

mkswap-U - create a swap partition with an explicit UUID

Create a swap partition on “device” with UUID “uuid”.

mkswap_file(file)[source]

mkswap-file - create a swap file

Create a swap file.

modprobe(modulename)[source]

modprobe - load a kernel module

This loads a kernel module in the appliance.

more(filename)[source]

more - view a file

This is used to view a file.

mount(device, mountpoint)[source]

mount - mount a guest disk at a position in the filesystem

Mount a guest disk at a position in the filesystem.

mount_loop(file, mountpoint)[source]

mount-loop - mount a file using the loop device

This command lets you mount “file” (a filesystem image in a file) on a mount point. It is entirely equivalent to the command “mount -o loop file mountpoint”.

mount_options(options, device, mountpoint)[source]

mount - mount a guest disk at a position in the filesystem

Mount a guest disk at a position in the filesystem.

mount_ro(device, mountpoint)[source]

mount-ro - mount a guest disk, read-only

This is the same as the “mount” command, but it mounts the filesystem with the read-only (-o ro) flag.

mount_vfs(options, vfstype, mountable, mountpoint)[source]

mount-vfs - mount a guest disk with mount options and vfstype

This is the same as the “mount” command, but it allows you to set both the mount options and the vfstype as for the mount(8) -o and -t flags.

mountpoints()[source]

mountpoints - show mountpoints

This call is similar to “mounts”. That call returns a list of devices.

mounts()[source]

mounts - show mounted filesystems

This returns the list of currently mounted filesystems.

new_session()[source]

Open new session, closing any existing

nr_devices()[source]

nr-devices - return number of whole block devices (disks) added

This returns the number of whole block devices that were added

ntfs_3g_probe(rw, device)[source]

ntfs-3g-probe - probe NTFS volume

This command runs the ntfs-3g.probe(8) command which probes an NTFS “device” for mountability. (Not all NTFS volumes can be mounted read-write, and some cannot be mounted at all).

ntfsresize_opts(device, size=None, force=None)[source]

ntfsresize - resize an NTFS filesystem

This command resizes an NTFS filesystem, expanding or shrinking it to the size of the underlying device.

open_session()[source]

Return session with session_id in this class.

parse_environment()[source]

parse-environment - parse the environment and set handle flags accordingly

Parse the program’s environment and set flags in the handle accordingly. For example if “LIBGUESTFS_DEBUG=1” then the ‘verbose’ flag is set in the handle.

parse_environment_list(environment)[source]

parse-environment-list - parse the environment and set handle flags accordingly

Parse the list of strings in the argument “environment” and set flags in the handle accordingly. For example if “LIBGUESTFS_DEBUG=1” is a string in the list, then the ‘verbose’ flag is set in the handle.

part_add(device, prlogex, startsect, endsect)[source]

part-add - add a partition to the device

This command adds a partition to “device”. If there is no partition table on the device, call “part_init” first.

part_del(device, partnum)[source]

part-del device partnum

This command deletes the partition numbered “partnum” on “device”.

Note that in the case of MBR partitioning, deleting an extended partition also deletes any logical partitions it contains.

part_disk(device, parttype)[source]

part-disk - partition whole disk with a single primary partition

This command is simply a combination of “part_init” followed by “part_add” to create a single primary partition covering the whole disk.

part_get_bootable(device, partnum)[source]

part-get-bootable - return true if a partition is bootable

This command returns true if the partition “partnum” on “device” has the bootable flag set.

part_get_mbr_id(device, partnum)[source]

part-get-mbr-id - get the MBR type byte (ID byte) from a partition

Returns the MBR type byte (also known as the ID byte) from the numbered partition “partnum”.

part_get_parttype(device)[source]

part-get-parttype - get the partition table type

This command examines the partition table on “device” and returns the partition table type (format) being used.

part_init(device, parttype)[source]

part-init - create an empty partition table

This creates an empty partition table on “device” of one of the partition types listed below. Usually “parttype” should be either “msdos” or “gpt” (for large disks).

part_list(device)[source]

part-list - list partitions on a device

This command parses the partition table on “device” and returns the list of partitions found.

part_set_bootable(device, partnum, bootable)[source]

part-set-bootable device partnum bootable

This sets the bootable flag on partition numbered “partnum” on device “device”. Note that partitions are numbered from 1.

part_set_mbr_id(device, partnum, idbyte)[source]

part-set-mbr-id - set the MBR type byte (ID byte) of a partition

Sets the MBR type byte (also known as the ID byte) of the numbered partition “partnum” to “idbyte”. Note that the type bytes quoted in most documentation are in fact hexadecimal numbers, but usually documented without any leading “0x” which might be confusing.

part_set_name(device, partnum, name)[source]

part-set-name - set partition name

This sets the partition name on partition numbered “partnum” on device “device”. Note that partitions are numbered from 1.

part_to_dev(partition)[source]

part-to-dev - convert partition name to device name

This function takes a partition name (eg. “/dev/sdb1”) and removes the partition number, returning the device name (eg. “/dev/sdb”).

The named partition must exist, for example as a string returned from “list_partitions”.

part_to_partnum(partition)[source]

part-to-partnum - convert partition name to partition number

This function takes a partition name (eg. “/dev/sdb1”) and returns the partition number (eg. 1).

The named partition must exist, for example as a string returned from “list_partitions”.

ping_daemon()[source]

ping-daemon - ping the guest daemon

This is a test probe into the guestfs daemon running inside the hypervisor. Calling this function checks that the daemon responds to the ping message, without affecting the daemon or attached block device(s) in any other way.

pread(path, count, offset)[source]

pread - read part of a file

This command lets you read part of a file. It reads “count” bytes of the file, starting at “offset”, from file “path”.

pvcreate(physvols)[source]

pvcreate - create an LVM physical volume

This creates an LVM physical volume called “physvols”.

pvremove(device)[source]

pvremove - remove an LVM physical volume

This wipes a physical volume “device” so that LVM will no longer recognise it.

The implementation uses the “pvremove” command which refuses to wipe physical volumes that contain any volume groups, so you have to remove those first.

pvresize(device)[source]

pvresize - resize an LVM physical volume

This resizes (expands or shrinks) an existing LVM physical volume to match the new size of the underlying device

pvresize_size(device, size)[source]

pvresize-size - resize an LVM physical volume (with size)

This command is the same as “pvresize” except that it allows you to specify the new size (in bytes) explicitly.

pvs()[source]

pvs - list the LVM physical volumes (PVs)

List all the physical volumes detected. This is the equivalent of the pvs(8) command.

pvs_full()[source]

pvs-full - list the LVM physical volumes (PVs)

List all the physical volumes detected. This is the equivalent of the pvs(8) command. The “full” version includes all fields.

pvuuid(device)[source]

pvuuid - get the UUID of a physical volume

This command returns the UUID of the LVM PV “device”.

quit()[source]

quit - quit guestfish

read_file(path)[source]

read-file - read a file

This calls returns the contents of the file “path” as a buffer.

readdir(dir)[source]

readdir - read directories entries

This returns the list of directory entries in directory “dir”

reopen()[source]

reopen - close and reopen libguestfs handle

Close and reopen the libguestfs handle. It is not necessary to use this normally, because the handle is closed properly when guestfish exits. However this is occasionally useful for testing.

resize2fs(device)[source]

resize2fs - resize an ext2, ext3 or ext4 filesystem

This resizes an ext2, ext3 or ext4 filesystem to match the size of the underlying device.

resize2fs_M(device)[source]

resize2fs-M - resize an ext2, ext3 or ext4 filesystem to the minimum size

This command is the same as “resize2fs”, but the filesystem is resized to its minimum size. This works like the -M option to the “resize2fs” command.

resize2fs_size(device, size)[source]

resize2fs-size - resize an ext2, ext3 or ext4 filesystem (with size)

This command is the same as “resize2fs” except that it allows you to specify the new size (in bytes) explicitly.

rm(path)[source]

rm - remove a file

Remove the single file “path”.

rm_rf(path)[source]

rm-rf - remove a file or directory recursively

Remove the file or directory “path”, recursively removing the contents if its a directory. This is like the “rm -rf” shell command.

rmmountpoint(exemptpath)[source]

rmmountpoint - remove a mountpoint

This calls removes a mountpoint that was previously created with “mkmountpoint”. See “mkmountpoint” for full details.

rsync(src, dest, args)[source]

rsync - synchronize the contents of two directories

This call may be used to copy or synchronize two directories under the same libguestfs handle. This uses the rsync(1) program which uses a fast algorithm that avoids copying files unnecessarily.

rsync_in(src, dest, args)[source]

rsync-in - synchronize host or remote filesystem with filesystem

This call may be used to copy or synchronize the filesystem on the host or on a remote computer with the filesystem within libguestfs. This uses the rsync(1) program which uses a fast algorithm that avoids copying files unnecessarily.

rsync_out(src, dest, args)[source]

rsync-out - synchronize filesystem with host or remote filesystem

This call may be used to copy or synchronize the filesystem within libguestfs with a filesystem on the host or on a remote computer. This uses the rsync(1) program which uses a fast algorithm that avoids copying files unnecessarily.

run()[source]

run/launch - launch the qemu subprocess

Internally libguestfs is implemented by running a virtual machine using qemu.

run_mode
scrub_device(device)[source]

scrub-device - scrub (securely wipe) a device

This command writes patterns over “device” to make data retrieval more difficult

scrub_file(file)[source]

scrub-file - scrub (securely wipe) a file

This command writes patterns over a file to make data retrieval more difficult

scrub_freespace(dir)[source]

scrub-freespace - scrub (securely wipe) free space

This command creates the directory “dir” and then fills it with files until the filesystem is full,and scrubs the files as for “scrub_file”, and deletes them. The intention is to scrub any free space on the partition containing “dir”

session_id
set_append(append)[source]

set-append - add options to kernel command line

This function is used to add additional options to the libguestfs appliance kernel command line.

set_attach_method(backend)[source]

set-attach-method - set the backend

Set the method that libguestfs uses to connect to the backend guestfsd daemon.

set_autosync(autosync)[source]

set-autosync autosync

If “autosync” is true, this enables autosync. Libguestfs will make a best effort attempt to make filesystems consistent and synchronized when the handle is closed (also if the program exits without closing handles).

set_backend(backend)[source]

set-backend - set the backend

Set the method that libguestfs uses to connect to the backend guestfsd daemon.

set_direct(direct)[source]

set-direct - enable or disable direct appliance mode

If the direct appliance mode flag is enabled, then stdin and stdout are passed directly through to the appliance once it is launched.

set_e2attrs(file, attrs, clear=None)[source]

set-e2attrs - set ext2 file attributes of a file

This sets or clears the file attributes “attrs” associated with the inode “file”.

set_e2generation(file, generation)[source]

set-e2generation - set ext2 file generation of a file

This sets the ext2 file generation of a file.

set_e2label(device, label)[source]

set-e2label - set the ext2/3/4 filesystem label

This sets the ext2/3/4 filesystem label of the filesystem on “device” to “label”. Filesystem labels are limited to 16 characters.

set_e2uuid(device, uuid)[source]

set-e2uuid - set the ext2/3/4 filesystem UUID

This sets the ext2/3/4 filesystem UUID of the filesystem on “device” to “uuid”. The format of the UUID and alternatives such as “clear”, “random” and “time” are described in the tune2fs(8) manpage.

set_label(mountable, label)[source]

set-label - set filesystem label

Set the filesystem label on “mountable” to “label”.

set_memsize(memsize)[source]

set-memsize - set memory allocated to the hypervisor

This sets the memory size in megabytes allocated to the hypervisor. This only has any effect if called before “launch”.

set_network(network)[source]

set-network - set enable network flag

If “network” is true, then the network is enabled in the libguestfs appliance. The default is false.

set_path(searchpath)[source]

set-path - set the search path

Set the path that libguestfs searches for kernel and initrd.img.

set_pgroup(pgroup)[source]

set-pgroup - set process group flag

If “pgroup” is true, child processes are placed into their own process group.

set_program(program)[source]

set-program - set the program name

Set the program name. This is an informative string which the main program may optionally set in the handle.

set_qemu(hv)[source]

set-qemu - set the hypervisor binary (usually qemu)

Set the hypervisor binary (usually qemu) that we will use.

set_recovery_proc(recoveryproc)[source]

set-recovery-proc - enable or disable the recovery process

If this is called with the parameter “false” then “launch” does not create a recovery process. The purpose of the recovery process is to stop runaway hypervisor processes in the case where the main program aborts abruptly.

set_smp(smp)[source]

set-smp - set number of virtual CPUs in appliance

Change the number of virtual CPUs assigned to the appliance. The default is 1. Increasing this may improve performance, though often it has no effect.

set_trace(trace)[source]

set-trace - enable or disable command traces

If the command trace flag is set to 1, then libguestfs calls, parameters and return values are traced.

set_uuid(device, uuid)[source]

set-uuid - set the filesystem UUID

Set the filesystem UUID on “device” to “uuid”.

set_verbose(verbose)[source]

set-verbose - set verbose mode

If “verbose” is true, this turns on verbose messages.

setenv(VAR, value)[source]

setenv - set an environment variable

Set the environment variable “VAR” to the string “value”.

sfdisk(device, cyls, heads, sectors, lines)[source]

sfdisk - create partitions on a block device

This is a direct interface to the sfdisk(8) program for creating partitions on block devices.

This function is deprecated. In new code, use the “part-add” call instead.

Deprecated functions will not be removed from the API, but the fact that they are deprecated indicates that there are problems with correct use of these functions.

sfdiskM(device, lines)[source]

sfdiskM - create partitions on a block device

This is a simplified interface to the “sfdisk” command, where partition sizes are specified in megabytes only (rounded to the nearest cylinder) and you don’t need to specify the cyls, heads and sectors parameters which were rarely if ever used anyway.

This function is deprecated. In new code, use the “part-add” call instead.

sfdisk_N(device, partnum, cyls, heads, sectors, line)[source]

sfdisk-N - modify a single partition on a block device

This runs sfdisk(8) option to modify just the single partition “n” (note: “n” counts from 1).

For other parameters, see “sfdisk”. You should usually pass 0 for the cyls/heads/sectors parameters.

This function is deprecated. In new code, use the “part-add” call instead.

sfdisk_disk_geometry(device)[source]

sfdisk-disk-geometry - display the disk geometry from the partition table

This displays the disk geometry of “device” read from the partition table. Especially in the case where the underlying block device has been resized, this can be different from the kernel’s idea of the geometry

sfdisk_kernel_geometry(device)[source]

sfdisk-kernel-geometry - display the kernel geometry

This displays the kernel’s idea of the geometry of “device”.

sfdisk_l(device)[source]

sfdisk-l - display the partition table

This displays the partition table on “device”, in the human-readable output of the sfdisk(8) command. It is not intended to be parsed.

This function is deprecated. In new code, use the “part-list” call instead.

sh(cmd)[source]

sh - run a command via the shell

This call runs a command from the guest filesystem via the guest’s “/bin/sh”.

sh_lines(cmd)[source]

sh-lines - run a command via the shell returning lines

This is the same as “sh”, but splits the result into a list of lines.

shutdown()[source]

shutdown - shutdown the hypervisor

This is the opposite of “launch”. It performs an orderly shutdown of the backend process(es). If the autosync flag is set (which is the default) then the disk image is synchronized.

sleep(secs)[source]

sleep - sleep for some seconds

Sleep for “secs” seconds.

sparse(filename, size)[source]

sparse - create a sparse disk image and add

This creates an empty sparse file of the given size, and then adds so it can be further examined.

stat(path)[source]

stat - get file information

Returns file information for the given “path”.

statvfs(path)[source]

statvfs - get file system statistics

Returns file system statistics for any mounted file system. “path” should be a file or directory in the mounted file system (typically it is the mount point itself, but it doesn’t need to be).

strings(path)[source]

strings - print the printable strings in a file

This runs the strings(1) command on a file and returns the list of printable strings found.

supported()[source]

supported - list supported groups of commands

This command returns a list of the optional groups known to the daemon, and indicates which ones are supported by this build of the libguestfs appliance.

swapoff_device(device)[source]

swapoff-device - disable swap on device

This command disables the libguestfs appliance swap device or partition named “device”. See “swapon_device”.

swapoff_file(file)[source]

swapoff-file - disable swap on file

This command disables the libguestfs appliance swap on file.

swapoff_label(label)[source]

swapoff-label - disable swap on labeled swap partition

This command disables the libguestfs appliance swap on labeled swap partition.

swapoff_uuid(uuid)[source]

swapoff-uuid - disable swap on swap partition by UUID

This command disables the libguestfs appliance swap partition with the given UUID.

swapon_device(device)[source]

swapon-device - enable swap on device

This command enables the libguestfs appliance to use the swap device or partition named “device”. The increased memory is made available for all commands, for example those run using “command” or “sh”.

swapon_file(file)[source]

swapon-file - enable swap on file

This command enables swap to a file. See “swapon_device” for other notes.

swapon_label(label)[source]

swapon-label - enable swap on labeled swap partition

This command enables swap to a labeled swap partition. See “swapon_device” for other notes.

swapon_uuid(uuid)[source]

swapon-uuid - enable swap on swap partition by UUID

This command enables swap to a swap partition with the given UUID. See “swapon_device” for other notes.

sync()[source]

lsync - sync disks, writes are flushed through to the disk image

This syncs the disk, so that any writes are flushed through to the underlying disk image.

syslinux(device, directory=None)[source]

syslinux - install the SYSLINUX bootloader

Install the SYSLINUX bootloader on “device”.

tail(path)[source]

tail - return last 10 lines of a file

This command returns up to the last 10 lines of a file as a list of strings.

tar_in(tarfile, directory)[source]

tar-in - unpack tarfile to directory

This command uploads and unpacks local file “tarfile” (an uncompressed tar file) into “directory”.

tar_in_opts(tarfile, directory, compress=None)[source]

tar-in-opts - unpack tarfile to directory

This command uploads and unpacks local file “tarfile” (an compressed tar file) into “directory”.

tar_out(directory, tarfile)[source]

tar-out - pack directory into tarfile

This command packs the contents of “directory” and downloads it to local file “tarfile”.

time(command, args=None)[source]

time - print elapsed time taken to run a command

Run the command as usual, but print the elapsed time afterwards. This can be useful for benchmarking operations.

touch(path)[source]

touch - update file timestamps or create a new file

Touch acts like the touch(1) command. It can be used to update the timestamps on a file, or, if the file does not exist, to create a new zero-length file.

tune2fs(device, force=None, maxmountcount=None, mountcount=None, errorbehavior=None, group=None, intervalbetweenchecks=None, reservedblockspercentage=None, lastmounteddirectory=None, reservedblockscount=None, user=None)[source]

tune2fs - adjust ext2/ext3/ext4 filesystem parameters

This call allows you to adjust various filesystem parameters of an ext2/ext3/ext4 filesystem called “device”.

tune2fs_l(device)[source]

tune2fs-l - get ext2/ext3/ext4 superblock details

This returns the contents of the ext2, ext3 or ext4 filesystem superblock on “device”.

umask(mask)[source]

umask - set file mode creation mask (umask)

This function sets the mask used for creating new files and device nodes to “mask & 0777”.

umount(pathordevice, force=None, lazyunmount=None)[source]

umount - unmount a filesystem

This unmounts the given filesystem. The filesystem may be specified either by its mountpoint (path) or the device which contains the filesystem.

umount_all()[source]

umount-all - unmount all filesystems

This unmounts all mounted filesystems. Some internal mounts are not unmounted by this call.

unsetenv(VAR)[source]

unsetenv - unset an environment variable

Remove “VAR” from the environment.

upload(filename, remotefilename)[source]

upload - upload a file from the local machine

Upload local file “filename” to “remotefilename” on the filesystem.

upload_offset(filename, remotefilename, offset)[source]

upload - upload a file from the local machine with offset

Upload local file “filename” to “remotefilename” on the filesystem.

utimens(path, atsecs, atnsecs, mtsecs, mtnsecs)[source]

utimens - set timestamp of a file with nanosecond precision

This command sets the timestamps of a file with nanosecond precision.

utsname()[source]

utsname - appliance kernel version

This returns the kernel version of the appliance, where this is available. This information is only useful for debugging. Nothing in the returned structure is defined by the API.

version()[source]

version - get the library version number

Return the libguestfs version number that the program is linked against.

vfs_label(mountable)[source]

vfs-label - get the filesystem label

This returns the label of the filesystem on “mountable”.

vfs_type(mountable)[source]

vfs-type - get the Linux VFS type corresponding to a mounted device

Gets the filesystem type corresponding to the filesystem on “mountable”

vfs_uuid(mountable)[source]

vfs-uuid - get the filesystem UUID

This returns the filesystem UUID of the filesystem on “mountable”.

vg_activate(activate, volgroups)[source]

vg-activate - activate or deactivate some volume groups

This command activates or (if “activate” is false) deactivates all logical volumes in the listed volume groups “volgroups”

vg_activate_all(activate)[source]

vg-activate-all - activate or deactivate all volume groups

This command activates or (if “activate” is false) deactivates all logical volumes in all volume groups.

vgcreate(volgroup, physvols)[source]

vgcreate - create an LVM volume group

This creates an LVM volume group called “volgroup” from the non-empty list of physical volumes “physvols”.

vglvuuids(vgname)[source]

vglvuuids - get the LV UUIDs of all LVs in the volume group

Given a VG called “vgname”, this returns the UUIDs of all the logical volumes created in this volume group.

vgpvuuids(vgname)[source]

vgpvuuids - get the PV UUIDs containing the volume group

Given a VG called “vgname”, this returns the UUIDs of all the physical volumes that this volume group resides on.

vgremove(vgname)[source]

vgremove - remove an LVM volume group

Remove an LVM volume group “vgname”, (for example “VG”).

vgrename(volgroup, newvolgroup)[source]

vgrename - rename an LVM volume group

Rename a volume group “volgroup” with the new name “newvolgroup”.

vgs()[source]

vgs - list the LVM volume groups (VGs)

List all the volumes groups detected.

vgs_full()[source]

vgs-full - list the LVM volume groups (VGs)

List all the volumes groups detected. This is the equivalent of the vgs(8) command. The “full” version includes all fields.

vgscan()[source]

vgscan - rescan for LVM physical volumes, volume groups and logical volumes

This rescans all block devices and rebuilds the list of LVM physical volumes, volume groups and logical volumes.

vguuid(vgname)[source]

vguuid - get the UUID of a volume group

This command returns the UUID of the LVM VG named “vgname”

write(path, content)[source]

write - create a new file

This call creates a file called “path”. The content of the file is the string “content” (which can contain any 8 bit data).

write_append(path, content)[source]

write-append - append content to end of file

This call appends “content” to the end of file “path”. If “path” does not exist, then a new file is created.

zegrep(regex, path)[source]

zegrep - return lines matching a pattern

This calls the external “zegrep” program and returns the matching lines.

zegrepi(regex, path)[source]

zegrepi - return lines matching a pattern

This calls the external “zegrep -i” program and returns the matching lines.

zero(device)[source]

zero - write zeroes to the device

This command writes zeroes over the first few blocks of “device”.

zero_device(device)[source]

zero-device - write zeroes to an entire device

This command writes zeroes over the entire “device”. Compare with “zero” which just zeroes the first few blocks of a device.

zfgrep(pattern, path)[source]

zfgrep - return lines matching a pattern

This calls the external “zfgrep” program and returns the matching lines.

zfgrepi(pattern, path)[source]

zfgrepi - return lines matching a pattern

This calls the external “zfgrep -i” program and returns the matching lines.

zgrep(regex, path)[source]

zgrep - return lines matching a pattern

This calls the external “zgrep” program and returns the matching lines.

zgrepi(regex, path)[source]

zgrepi - return lines matching a pattern

This calls the external “zgrep -i” program and returns the matching lines.

class virttest.utils_libguestfs.GuestfishRemote(guestfs_exec=None, a_id=None)[source]

Bases: object

Remote control of guestfish.

ERROR_REGEX_LIST = ['libguestfs: error:\\s*']
cmd(cmd, ignore_status=False)[source]

Mimic utils.run()

cmd_result(cmd, ignore_status=False)[source]

Mimic utils.run()

cmd_status_output(cmd, ignore_status=None, verbose=None, timeout=60)[source]

Send a guestfish command and return its exit status and output.

Parameters:
  • cmd – guestfish command to send(must not contain newline characters)
  • timeout – The duration (in seconds) to wait for the prompt to return
Returns:

A tuple (status, output) where status is the exit status and output is the output of cmd

Raises:

LibguestfsCmdError – Raised if commands execute failed

get_id()[source]
class virttest.utils_libguestfs.GuestfishSession(guestfs_exec=None, a_id=None, prompt='><fs>\s*')[source]

Bases: virttest.aexpect.ShellSession

A shell session of guestfish.

ERROR_REGEX_LIST = ['libguestfs: error:\\s*']
cmd_result(cmd, ignore_status=False)[source]

Mimic utils.run()

cmd_status_output(cmd, timeout=60, internal_timeout=None, print_func=None)[source]

Send a guestfish command and return its exit status and output.

Parameters:
  • cmd – guestfish command to send (must not contain newline characters)
  • timeout – The duration (in seconds) to wait for the prompt to return
  • internal_timeout – The timeout to pass to read_nonblocking
  • print_func – A function to be used to print the data being read (should take a string parameter)
Returns:

A tuple (status, output) where status is the exit status and output is the output of cmd

Raises:
  • ShellTimeoutError – Raised if timeout expires
  • ShellProcessTerminatedError – Raised if the shell process terminates while waiting for output
  • ShellStatusError – Raised if the exit status cannot be obtained
  • ShellError – Raised if an unknown error occurs
class virttest.utils_libguestfs.LibguestfsBase(lgf_exec='/bin/true', ignore_status=True, debug=False, timeout=60, uri=None)[source]

Bases: virttest.propcan.PropCanBase

Base class of libguestfs tools.

debug
get_uri()[source]

Accessor method for ‘uri’ property that must exist

ignore_status
lgf_exec
set_debug(debug)[source]

Accessor method for ‘debug’ property that logs message on change

set_ignore_status(ignore_status)[source]

Enforce setting ignore_status as a boolean.

set_timeout(timeout)[source]

Accessor method for ‘timeout’ property, timeout should be digit

timeout
uri
exception virttest.utils_libguestfs.LibguestfsCmdError(details='')[source]

Bases: exceptions.Exception

Error of libguestfs-tool command.

virttest.utils_libguestfs.guestmount(disk_or_domain, mountpoint, inspector=False, readonly=False, **dargs)[source]
guestmount - Mount a guest filesystem on the host using
FUSE and libguestfs.
Parameters:
  • disk_or_domain – a disk or a domain to be mounted If you need to mount a disk, set is_disk to True in dargs
  • mountpoint – the mountpoint of filesystems
  • inspector – mount all filesystems automatically
  • readonly – if mount filesystem with readonly option
virttest.utils_libguestfs.lgf_cmd_check(cmd)[source]

To check whether the cmd is supported on this host.

Parameters:cmd – the cmd to use a libguest tool.
Returns:None if the cmd is not exist, otherwise return its path.
virttest.utils_libguestfs.lgf_command(cmd, ignore_status=True, debug=False, timeout=60)[source]

Interface of libguestfs tools’ commands.

Parameters:cmd – Command line to execute.
Returns:CmdResult object.
Raise:LibguestfsCmdError if non-zero exit status and ignore_status=False
virttest.utils_libguestfs.libguest_test_tool_cmd(qemuarg=None, qemudirarg=None, timeoutarg=None, ignore_status=True, debug=False, timeout=60)[source]

Execute libguest-test-tool command.

Parameters:
  • qemuarg – the qemu option
  • qemudirarg – the qemudir option
  • timeoutarg – the timeout option
Returns:

a CmdResult object

Raise:

raise LibguestfsCmdError

virttest.utils_libguestfs.virt_cat_cmd(disk_or_domain, file_path, options=None, ignore_status=True, debug=False, timeout=60)[source]

Execute virt-cat command to print guest’s file detail.

Parameters:
  • disk_or_domain – a img path or a domain name.
  • file_path – the file to print detail
  • options – the options of virt-cat.
Returns:

a CmdResult object.

virttest.utils_libguestfs.virt_clone_cmd(original, newname=None, autoclone=False, **dargs)[source]

Clone existing virtual machine images.

Parameters:
  • original – Name of the original guest to be cloned.
  • newname – Name of the new guest virtual machine instance.
  • autoclone – Generate a new guest name, and paths for new storage.
  • dargs – Standardized function API keywords. There are many options not listed, they can be passed in dargs.
virttest.utils_libguestfs.virt_cmd_contain_opt(virt_cmd, opt)[source]

Check if opt is supported by virt-command

virttest.utils_libguestfs.virt_copy_in(disk_or_domain, file, destination, is_disk=False, ignore_status=True, debug=False, timeout=60)[source]

“virt-copy-in” copies files and directories from the local disk into a virtual machine disk image or named libvirt domain. #TODO: expand file to files

virttest.utils_libguestfs.virt_copy_out(disk_or_domain, file_path, localdir, is_disk=False, ignore_status=True, debug=False, timeout=60)[source]

“virt-copy-out” copies files and directories out of a virtual machine disk image or named libvirt domain.

virttest.utils_libguestfs.virt_df(disk_or_domain, ignore_status=True, debug=False, timeout=60)[source]

“virt-df” is a command line tool to display free space on virtual machine filesystems.

virttest.utils_libguestfs.virt_edit_cmd(disk_or_domain, file_path, is_disk=False, disk_format=None, options=None, extra=None, expr=None, connect_uri=None, ignore_status=True, debug=False, timeout=60)[source]

Execute virt-edit command to check whether it is ok.

Since virt-edit will need uses’ interact, maintain and return a session if there is no raise after command has been executed.

Parameters:
  • disk_or_domain – a img path or a domain name.
  • file_path – the file need to be edited in img file.
  • is_disk – whether disk_or_domain is disk or domain
  • disk_format – when is_disk is true, add a format if it is set.
  • options – the options of virt-edit.
  • extra – additional suffix of command.
Returns:

a session of executing virt-edit command.

virttest.utils_libguestfs.virt_filesystems(disk_or_domain, **dargs)[source]

virt-filesystems - List filesystems, partitions, block devices, LVM in a virtual machine or disk image

Parameters:disk_or_domain – a disk or a domain to be mounted If you need to mount a disk, set is_disk to True in dargs
virttest.utils_libguestfs.virt_format(disk, filesystem=None, image_format=None, lvm=None, partition=None, wipe=False, ignore_status=False, debug=False, timeout=60)[source]

Virt-format takes an existing disk file (or it can be a host partition, LV etc), erases all data on it, and formats it as a blank disk.

virttest.utils_libguestfs.virt_inspector(disk_or_domain, is_disk=False, ignore_status=True, debug=False, timeout=60)[source]

virt-inspector2 examines a virtual machine or disk image and tries to determine the version of the operating system and other information about the virtual machine.

virttest.utils_libguestfs.virt_list_filesystems(disk_or_domain, format=None, long=False, all=False, ignore_status=True, debug=False, timeout=60)[source]

“virt-list-filesystems” is a command line tool to list the filesystems that are contained in a virtual machine or disk image.

Parameters:disk_or_domain – a disk or a domain to be mounted
virttest.utils_libguestfs.virt_list_partitions(disk_or_domain, long=False, total=False, human_readable=False, ignore_status=True, debug=False, timeout=60)[source]

“virt-list-partitions” is a command line tool to list the partitions that are contained in a virtual machine or disk image.

Parameters:disk_or_domain – a disk or a domain to be mounted
virttest.utils_libguestfs.virt_list_partitions_cmd(disk_or_domain, long=False, total=False, human_readable=False, ignore_status=True, debug=False, timeout=60)[source]

“virt-list-partitions” is a command line tool to list the partitions that are contained in a virtual machine or disk image.

Parameters:disk_or_domain – a disk or a domain to be mounted
virttest.utils_libguestfs.virt_ls_cmd(disk_or_domain, file_dir_path, is_disk=False, options=None, extra=None, connect_uri=None, ignore_status=True, debug=False, timeout=60)[source]

Execute virt-ls command to check whether file exists.

Parameters:
  • disk_or_domain – a img path or a domain name.
  • file_dir_path – the file or directory need to check.
virttest.utils_libguestfs.virt_resize_cmd(indisk, outdisk, **dargs)[source]

Resize a virtual machine disk.

Parameters:
  • indisk – The source disk to be resized
  • outdisk – The destination disk.
virttest.utils_libguestfs.virt_sparsify_cmd(indisk, outdisk, compress=False, convert=None, format=None, ignore_status=True, debug=False, timeout=60)[source]

Make a virtual machine disk sparse.

Parameters:
  • indisk – The source disk to be sparsified.
  • outdisk – The destination disk.
virttest.utils_libguestfs.virt_sysprep_cmd(disk_or_domain, options=None, extra=None, ignore_status=True, debug=False, timeout=600)[source]

Execute virt-sysprep command to reset or unconfigure a virtual machine.

Parameters:
  • disk_or_domain – a img path or a domain name.
  • options – the options of virt-sysprep.
Returns:

a CmdResult object.

virttest.utils_libguestfs.virt_sysprep_operations()[source]

Get virt-sysprep support operation

virttest.utils_libguestfs.virt_tar_in(disk_or_domain, tar_file, destination, is_disk=False, ignore_status=True, debug=False, timeout=60)[source]

“virt-tar-in” unpacks an uncompressed tarball into a virtual machine disk image or named libvirt domain.

virttest.utils_libguestfs.virt_tar_out(disk_or_domain, directory, tar_file, is_disk=False, ignore_status=True, debug=False, timeout=60)[source]

“virt-tar-out” packs a virtual machine disk image directory into a tarball.

virttest.utils_libguestfs_unittest module

class virttest.utils_libguestfs_unittest.LibguestfsTest(methodName='runTest')[source]

Bases: unittest.case.TestCase

test_lgf_cmd()[source]
test_lgf_cmd_check()[source]
test_lgf_cmd_check_raises()[source]
class virttest.utils_libguestfs_unittest.SlotsCheckTest(methodName='runTest')[source]

Bases: unittest.case.TestCase

test_Guestfish_slots()[source]

Test Guestfish slots

test_LibguestfsBase_default_slots()[source]

Default slots’ value check

test_LibguestfsBase_update_slots()[source]

Update slots

virttest.utils_libvirtd module

Module to control libvirtd service.

class virttest.utils_libvirtd.Libvirtd(session=None)[source]

Bases: object

Class to manage libvirtd service on host or guest.

is_running()[source]
restart(reset_failed=True)[source]
start(reset_failed=True)[source]
stop()[source]
class virttest.utils_libvirtd.LibvirtdSession(gdb=False, logging_handler=None, logging_pattern='.*')[source]

Bases: object

Interaction libvirt daemon session by directly call the libvirtd command. With gdb debugging feature can be optionally started.

back_trace()[source]

Get the backtrace from gdb session.

cont()[source]

Continue a stopped libvirtd session.

exit()[source]

Exit the libvirtd session.

insert_break(break_func)[source]

Insert a function breakpoint.

Parameters:break_func – Function at which breakpoint inserted
is_working()[source]

Check if libvirtd is start by return status of ‘virsh list’

kill()[source]

Kill the libvirtd session.

restart(arg_str='', wait_for_working=True)[source]

Restart the libvirtd session.

Parameters:
  • arg_str – Argument passing to the session
  • wait_for_working – Whether wait for libvirtd finish loading
set_callback(callback_type, callback_func, callback_params=None)[source]

Set a customized gdb callback function.

start(arg_str='', wait_for_working=True)[source]

Start libvirtd session.

Parameters:
  • arg_str – Argument passing to the session
  • wait_for_working – Whether wait for libvirtd finish loading
wait_for_stop(timeout=60, step=0.1)[source]

Wait for libvirtd to stop.

Parameters:
  • timeout – Max wait time
  • step – Checking interval
wait_for_termination(timeout=60)[source]

Wait for libvirtd gdb session to exit.

Parameters:timeout – Max wait time
wait_for_working(timeout=60)[source]

Wait for libvirtd to work.

Parameters:timeout – Max wait time
virttest.utils_libvirtd.deprecation_warning()[source]

As the utils_libvirtd.libvirtd_xxx interfaces are deprecated, this function are printing the warning to user.

virttest.utils_libvirtd.libvirtd_is_running()[source]
virttest.utils_libvirtd.libvirtd_restart()[source]
virttest.utils_libvirtd.libvirtd_start()[source]
virttest.utils_libvirtd.libvirtd_stop()[source]
virttest.utils_libvirtd.service_libvirtd_control(action, session=None)[source]

virttest.utils_misc module

Virtualization test utility functions.

copyright:2008-2009 Red Hat Inc.
class virttest.utils_misc.Flag[source]

Bases: str

Class for easy merge cpuflags.

aliases = {}
class virttest.utils_misc.ForAll[source]

Bases: list

class virttest.utils_misc.ForAllP[source]

Bases: list

Parallel version of ForAll

class virttest.utils_misc.ForAllPSE[source]

Bases: list

Parallel version of and suppress exception.

class virttest.utils_misc.KSMController[source]

Bases: object

KSM Manager

get_ksm_feature(feature)[source]

Get ksm feature’s value.

get_ksmtuned_pid()[source]

Return ksmtuned process id(0 means not running).

get_writable_features()[source]

Get writable features for setting

is_ksm_running()[source]

Verify whether ksm is running.

is_module_loaded()[source]

Check whether ksm module has been loaded.

load_ksm_module()[source]

Try to load ksm module.

restart_ksm(pages_to_scan=None, sleep_ms=None)[source]

Restart ksm service

restart_ksmtuned()[source]

Restart ksmtuned service

set_ksm_feature(feature_args)[source]

Set ksm features.

Parameters:feature_args – a dict include features and their’s value.
start_ksm(pages_to_scan=None, sleep_ms=None)[source]

Start ksm function.

start_ksmtuned()[source]

Start ksmtuned service

stop_ksm()[source]

Stop ksm function.

stop_ksmtuned()[source]

Stop ksmtuned service

unload_ksm_module()[source]

Try to unload ksm module.

exception virttest.utils_misc.KSMError[source]

Bases: exceptions.Exception

Base exception for KSM setup

exception virttest.utils_misc.KSMNotSupportedError[source]

Bases: virttest.utils_misc.KSMError

Thrown when host does not support KSM.

exception virttest.utils_misc.KSMTunedError[source]

Bases: virttest.utils_misc.KSMError

Thrown when KSMTuned Error happen.

exception virttest.utils_misc.KSMTunedNotSupportedError[source]

Bases: virttest.utils_misc.KSMTunedError

Thrown when host does not support KSMTune.

exception virttest.utils_misc.LogLockError[source]

Bases: exceptions.Exception

class virttest.utils_misc.NumaInfo(all_nodes_path=None, online_nodes_path=None)[source]

Bases: object

Numa topology for host. Also provide the function for check the memory status of the node.

get_all_nodes(all_nodes_path=None)[source]

Get all node ids in host.

Returns:All node ids in host
Return type:list
get_node_distance(node_id)[source]

Get the distance from the give node to other nodes include itself.

Parameters:node_id (string) – Node that you want to check
Returns:A list in of distance for the node in positive-sequence
Return type:list
get_online_nodes(online_nodes_path=None)[source]

Get node ids online in host

Returns:The ids of node which is online
Return type:list
read_from_node_meminfo(node_id, key)[source]

Get specific value of a given node from memoinfo file

Parameters:
  • node_id (string) – The node you want to check
  • key (string) – The value you want to check such as MemTotal etc.
Returns:

The value in KB

Return type:

string

class virttest.utils_misc.NumaNode(i=-1, all_nodes_path=None, online_nodes_path=None)[source]

Bases: object

Numa node to control processes and shared memory.

free_cpu(i, thread=None)[source]

Release pin of one node.

Parameters:
  • i – Index of the node.
  • thread – Thread ID, remove all threads if thread ID isn’t set
get_cpu_topology(cpu_id)[source]

Return cpu info dict get from sysfs.

Parameters:cpu_id – integer, cpu id number
Returns:topology dict of certain cpu
get_node_cpus(i)[source]

Get cpus of a specific node

Parameters:i – Index of the CPU inside the node.
pin_cpu(*args, **kwargs)

Pin one process to a single cpu.

Parameters:
  • process – Process ID.
  • cpu – CPU ID, pin thread to free CPU if cpu ID isn’t set
show()[source]

Display the record dict in a convenient way.

class virttest.utils_misc.SELinuxBoolean(params)[source]

Bases: object

SELinuxBoolean class for managing SELinux boolean value.

cleanup(keep_authorized_keys=False)[source]

Cleanup SELinux boolean value.

get_sebool_local()[source]

Get SELinux boolean value from local host.

get_sebool_remote()[source]

Get SELinux boolean value from remote host.

setup()[source]

Set SELinux boolean value.

setup_local()[source]

Set SELinux boolean value on the local

setup_remote()[source]

Set SELinux boolean value on remote host.

exception virttest.utils_misc.UnsupportedCPU[source]

Bases: autotest.client.shared.error.TestError

class virttest.utils_misc.VFIOController(load_modules=True, allow_unsafe_interrupts=True)[source]

Bases: object

Control Virtual Function for testing

add_device_to_iommu_group(pci_id)[source]

Add one single device to iommu group.

bind_device_to_iommu_group(pci_id)[source]

Bind device to iommu group.

check_iommu()[source]

Check whether iommu group is available.

check_vfio_id(group_id)[source]

Check whether given vfio group has been established.

get_iommu_group_devices(group_id)[source]

Get all devices in one group by its id.

get_pci_iommu_group_id(pci_id, device_type='')[source]

Get pci devices iommu group id

exception virttest.utils_misc.VFIOError(err)[source]

Bases: exceptions.Exception

class virttest.utils_misc.VirtLoggingConfig(use_console=True)[source]

Bases: autotest.client.shared.logging_config.LoggingConfig

Used with the sole purpose of providing convenient logging setup for the KVM test auxiliary programs.

configure_logging(results_dir=None, verbose=False)[source]
virttest.utils_misc.add_identities_into_ssh_agent()[source]

Adds RSA or DSA identities to the authentication agent

virttest.utils_misc.add_ker_cmd(kernel_cmdline, kernel_param, remove_similar=False)[source]

Add a parameter to kernel command line content

Parameters:
  • kernel_cmdline (string) – Original kernel command line.
  • kernel_param (string) – parameter want to change include the value.
  • remove_similar (bool) – remove the value of the parameter that already in kernel cmd line or not.
Returns:

kernel command line

Return type:

string

virttest.utils_misc.archive_as_tarball(source_dir, dest_dir, tarball_name=None, compression='bz2', verbose=True)[source]

Saves the given source directory to the given destination as a tarball

If the name of the archive is omitted, it will be taken from the source_dir. If it is an absolute path, dest_dir will be ignored. But, if both the destination directory and tarball anem is given, and the latter is not an absolute path, they will be combined.

For archiving directory ‘/tmp’ in ‘/net/server/backup’ as file ‘tmp.tar.bz2’, simply use:

>>> utils_misc.archive_as_tarball('/tmp', '/net/server/backup')

To save the file it with a different name, say ‘host1-tmp.tar.bz2’ and save it under ‘/net/server/backup’, use:

>>> utils_misc.archive_as_tarball('/tmp', '/net/server/backup',
                                  'host1-tmp')

To save with gzip compression instead (resulting in the file ‘/net/server/backup/host1-tmp.tar.gz’), use:

>>> utils_misc.archive_as_tarball('/tmp', '/net/server/backup',
                                  'host1-tmp', 'gz')
virttest.utils_misc.aton(sr)[source]

Transform a string to a number(include float and int). If the string is not in the form of number, just return false.

Parameters:sr – string to transfrom
Returns:float, int or False for failed transform
virttest.utils_misc.bind_device_driver(pci_id, driver_type)[source]

Bind device driver.

Parameters:driver_type – Supported drivers: igb, lpfc, vfio-pci
virttest.utils_misc.bitlist_to_string(data)[source]

Transform from bit list to ASCII string.

Parameters:data – Bit list to be transformed
virttest.utils_misc.check_device_driver(pci_id, driver_type)[source]

Check whether device’s driver is same as expected.

virttest.utils_misc.check_if_vm_vcpu_match(vcpu_desire, vm)[source]

This checks whether the VM vCPU quantity matches the value desired.

virttest.utils_misc.check_module(module_name, submodules=[])[source]

Check whether module and its submodules work.

virttest.utils_misc.close_log_file(filename)[source]
virttest.utils_misc.convert_ipv4_to_ipv6(ipv4)[source]

Translates a passed in string of an ipv4 address to an ipv6 address.

Parameters:ipv4 – a string of an ipv4 address
virttest.utils_misc.cpu_str_to_list(origin_str)[source]

Convert the cpu string to a list. The string may include comma and hyphen.

Parameters:origin_str (string) – the cpu info string read from system
Returns:A list of the cpu ids
Return type:list
virttest.utils_misc.create_x509_dir(path, cacert_subj, server_subj, passphrase, secure=False, bits=1024, days=1095)[source]

Creates directory with freshly generated: ca-cart.pem, ca-key.pem, server-cert.pem, server-key.pem,

Parameters:
  • path – defines path to directory which will be created
  • cacert_subj – ca-cert.pem subject
  • server_key.csr – subject
  • passphrase – passphrase to ca-key.pem
  • secure – defines if the server-key.pem will use a passphrase
  • bits – bit length of keys
  • days – cert expiration
Raises:
  • ValueError – openssl not found or rc != 0
  • OSError – if os.makedirs() fails
virttest.utils_misc.delete_pid_file_if_exists(program_name, pid_files_dir=None)[source]

Tries to remove <program_name>.pid from the main autotest directory.

virttest.utils_misc.display_attributes(instance)[source]

Inspects a given class instance attributes and displays them, convenient for debugging.

virttest.utils_misc.extract_qemu_cpu_models(qemu_cpu_help_text)[source]

Get all cpu models from qemu -cpu help text.

Parameters:qemu_cpu_help_text – text produced by <qemu> -cpu ‘?’
Returns:list of cpu models
virttest.utils_misc.find_command(cmd)[source]

Try to find a command in the PATH, paranoid version.

Parameters:cmd – Command to be found.
Raise:ValueError in case the command was not found.
virttest.utils_misc.find_free_port(start_port, end_port, address='localhost')[source]

Return a host free port in the range [start_port, end_port].

Parameters:
  • start_port – First port that will be checked.
  • end_port – Port immediately after the last one that will be checked.
virttest.utils_misc.find_free_ports(start_port, end_port, count, address='localhost')[source]

Return count of host free ports in the range [start_port, end_port].

Parameters:
  • count – Initial number of ports known to be free in the range.
  • start_port – First port that will be checked.
  • end_port – Port immediately after the last one that will be checked.
virttest.utils_misc.find_substring(string, pattern1, pattern2=None)[source]

Return the match of pattern1 in string. Or return the match of pattern2 if pattern is not matched.

Parameters:
  • string – string
  • pattern1 – first pattern want to match in string, must set.
  • pattern2 – second pattern, it will be used if pattern1 not match, optional.
Returns:

Match substring or None

virttest.utils_misc.format_guest_disk(session, did, mountpoint, size, fstype, ostype)[source]

Create a partition on disk in guest and format and mount it.

Parameters:
  • session – session object to guest.
  • did – disk ID in guest.
  • mountpoint – mount point for the disk.
  • fstype – filesystem type for the disk.
  • ostype – guest os type ‘windows’ or ‘linux’.
Return Boolean:

disk usable or not.

virttest.utils_misc.format_linux_disk(session, did, mountpoint, size, fstype='ext3')[source]

Create a partition on disk in linux guest and format and mount it.

Parameters:
  • session – session object to guest.
  • did – disk serial, kname or wwn.
  • mountpoint – mount point for the disk.
  • fstype – filesystem type for the disk.
  • ostype – guest os type ‘windows’ or ‘linux’.
Return Boolean:

disk usable or not.

virttest.utils_misc.format_str_for_message(sr)[source]

Format str so that it can be appended to a message. If str consists of one line, prefix it with a space. If str consists of multiple lines, prefix it with a newline.

Parameters:str – string that will be formatted.
virttest.utils_misc.format_windows_disk(session, did, mountpoint=None, size=None, fstype='ntfs')[source]

Create a partition on disk in windows guest and format it.

Parameters:
  • session – session object to guest.
  • did – disk index which show in ‘diskpart list disk’.
  • mountpoint – mount point for the disk.
  • fstype – filesystem type for the disk.
  • ostype – guest os type ‘windows’ or ‘linux’.
Return Boolean:

disk usable or not.

virttest.utils_misc.generate_random_id()[source]

Return a random string suitable for use as a qemu id.

virttest.utils_misc.generate_random_string(length, ignore_str='!"#$%&\'()*+, -./:;<=>?@[\\]^_`{|}~', convert_str='')[source]

Return a random string using alphanumeric characters.

Parameters:
  • length – Length of the string that will be generated.
  • ignore_str – Characters that will not include in generated string.
  • convert_str – Characters that need to be escaped (prepend “”).
Returns:

The generated random string.

virttest.utils_misc.generate_tmp_file_name(file_name, ext=None, directory='/tmp/')[source]

Returns a temporary file name. The file is not created.

virttest.utils_misc.get_archive_tarball_name(source_dir, tarball_name, compression)[source]

Get the name for a tarball file, based on source, name and compression

virttest.utils_misc.get_cpu_flags(cpu_info='')[source]

Returns a list of the CPU flags

virttest.utils_misc.get_cpu_info(session=None)[source]

Return information about the CPU architecture

Parameters:session – session Object
Returns:A dirt of cpu information
virttest.utils_misc.get_cpu_status(cpu_num)[source]

Get cpu status to check it’s enable or disable

virttest.utils_misc.get_cpu_vendor(cpu_info='', verbose=True)[source]

Returns the name of the CPU vendor

virttest.utils_misc.get_dev_major_minor(dev)[source]

Get the major and minor numbers of the device @return: Tuple(major, minor) numbers of the device

virttest.utils_misc.get_dev_pts_max_id()[source]

Get the maxi ID of pseudoterminal interfaces for /dev/pts

:param None

virttest.utils_misc.get_free_disk(session, mount)[source]

Get FreeSpace for given mount point.

Parm session:shell Object.
Parm mount:mount point(eg. C:, /mnt)
Return string:freespace M-bytes
virttest.utils_misc.get_free_mem(session, os_type)[source]

Get Free memory for given OS.

Parm session:shell Object.
Parm os_type:os type (eg. linux or windows)
Return string:freespace M-bytes
virttest.utils_misc.get_full_pci_id(pci_id)[source]

Get full PCI ID of pci_id.

Parameters:pci_id – PCI ID of a device.
virttest.utils_misc.get_hash_from_file(hash_path, dvd_basename)[source]

Get the a hash from a given DVD image from a hash file (Hash files are usually named MD5SUM or SHA1SUM and are located inside the download directories of the DVDs)

Parameters:
  • hash_path – Local path to a hash file.
  • cd_image – Basename of a CD image
virttest.utils_misc.get_host_cpu_models()[source]

Get cpu model from host cpuinfo

virttest.utils_misc.get_image_info(image_file)[source]

Get image information and put it into a dict. Image information like this:

*******************************
image: /path/vm1_6.3.img
file format: raw
virtual size: 10G (10737418240 bytes)
disk size: 888M
....
image: /path/vm2_6.3.img
file format: raw
virtual size: 1.0M (1024000 bytes)
disk size: 196M
....
*******************************

And the image info dict will be like this

image_info_dict = {'format':'raw',
                   'vsize' : '10737418240',
                   'dsize' : '931135488',
                   'csize' : '65536'}
virttest.utils_misc.get_log_file_dir()[source]

get the base directory for log files created by log_line().

virttest.utils_misc.get_module_params(sys_path, module_name)[source]

Get the kvm module params :param sys_path: sysfs path for modules info :param module_name: module to check

virttest.utils_misc.get_node_cpus(i=0)[source]

Get cpu ids of one node

Returns:the cpu lists
Return type:list
virttest.utils_misc.get_open_fds(pid)[source]
virttest.utils_misc.get_path(base_path, user_path)[source]

Translate a user specified path to a real path. If user_path is relative, append it to base_path. If user_path is absolute, return it as is.

Parameters:
  • base_path – The base path of relative user specified paths.
  • user_path – The user specified path.
virttest.utils_misc.get_pci_devices_in_group(str_flag='')[source]

Get PCI Devices. Classify pci devices accroding its bus and slot, devices with same bus and slot will be put together. The format will be {‘domain:bus:slot’: ‘device_function’,...}

Parameters:str_flag – the match string to filter devices.
virttest.utils_misc.get_pci_group_by_id(pci_id, device_type='')[source]

Fit pci_id to a group list which has same domain:bus:slot.

Parameters:
  • pci_id – pci id of a device: domain:bus:slot.function or domain:bus:slot even bus:slot
  • device_type – string which can stand device like ‘Ethernet’, ‘Fibre’
virttest.utils_misc.get_pci_vendor_device(pci_id)[source]

Get vendor and device number by pci id.

Returns:a ‘vendor device’ list include all matched devices
virttest.utils_misc.get_pid_cpu(pid)[source]

Get the process used cpus.

Parameters:pid – process id
Returns:A list include all cpus the process used
Return type:list
virttest.utils_misc.get_pid_from_file(program_name, pid_files_dir=None)[source]

Reads the pid from <program_name>.pid in the autotest directory.

:param program_name the name of the program :return: the pid if the file exists, None otherwise.

virttest.utils_misc.get_pid_path(program_name, pid_files_dir=None)[source]
virttest.utils_misc.get_qemu_best_cpu_model(params)[source]

Try to find out the best CPU model available for qemu.

This function can’t be in qemu_vm, because it is used in env_process, where there’s no vm object available yet, and env content is synchronized in multi host testing.

  1. Get host CPU model

  2. Verify if host CPU model is in the list of supported qemu cpu models

  3. If so, return host CPU model

  4. If not, return the default cpu model set in params, if none defined,

    return ‘qemu64’.

virttest.utils_misc.get_qemu_binary(params)[source]

Get the path to the qemu binary currently in use.

virttest.utils_misc.get_qemu_cpu_models(qemu_binary)[source]

Get listing of CPU models supported by QEMU

Get list of CPU models by parsing the output of <qemu> -cpu ‘?’

virttest.utils_misc.get_qemu_dst_binary(params)[source]

Get the path to the qemu dst binary currently in use.

virttest.utils_misc.get_qemu_img_binary(params)[source]

Get the path to the qemu-img binary currently in use.

virttest.utils_misc.get_qemu_io_binary(params)[source]

Get the path to the qemu-io binary currently in use.

virttest.utils_misc.get_support_machine_type(qemu_binary='/usr/libexec/qemu-kvm')[source]

Get the machine type the host support,return a list of machine type

virttest.utils_misc.get_test_entrypoint_func(name, module)[source]

Returns the test entry point function for a loaded module

Parameters:
  • name (str) – the name of the test. Usually supplied on a cartesian config file using the “type” key
  • module (module) – a loaded python module for containing the code for the test named on name
Raises:

ValueError if module does not have a suitable function

Returns:

the test entry point function

Return type:

func

virttest.utils_misc.get_thread_cpu(thread)[source]

Get the light weight process(thread) used cpus.

Parameters:thread (string) – thread checked
Returns:A list include all cpus the thread used
Return type:list
virttest.utils_misc.get_vendor_from_pci_id(pci_id)[source]

Check out the device vendor ID according to pci_id.

Parameters:pci_id – PCI ID of a device.
virttest.utils_misc.get_virt_test_open_fds()[source]
virttest.utils_misc.get_windows_drive_letters(session)[source]

Get drive letters has been assigned

Parameters:session – session object to guest
Return list:letters has been assigned
virttest.utils_misc.get_winutils_vol(session, label='WIN_UTILS')[source]

Return Volume ID of winutils CDROM ISO file should be create via command mkisofs -V $label -o winutils.iso.

Parameters:
  • session – session Object
  • label – volume ID of WIN_UTILS.iso
Returns:

volume ID

virttest.utils_misc.install_disktest_on_vm(test, vm, src_dir, dst_dir)[source]

Install stress to vm.

Parameters:
  • vm – virtual machine.
  • src_dir – Source path.
  • dst_dir – Instaltation path.
virttest.utils_misc.install_host_kernel(job, params)[source]

Install a host kernel, given the appropriate params.

Parameters:
  • job – Job object.
  • params – Dict with host kernel install params.
virttest.utils_misc.is_mounted(src, mount_point, fstype, perm=None, verbose=False, fstype_mtab=None)[source]

Check mount status from /etc/mtab

Parameters:
  • src (string) – mount source
  • mount_point (string) – mount point
  • fstype (string) – file system type
  • perm (string) – mount permission
  • verbose (Boolean) – if display mtab content
  • fstype_mtab (str) – file system type in mtab could be different
Returns:

if the src is mounted as expect

Return type:

Boolean

virttest.utils_misc.is_port_free(port, address)[source]

Return True if the given port is available for use.

Parameters:port – Port number
virttest.utils_misc.kill_process_by_pattern(pattern)[source]

Send SIGTERM signal to a process with matched pattern. :param pattern: normally only matched against the process name

virttest.utils_misc.kill_process_tree(pid, sig=9)[source]

Signal a process and all of its children.

If the process does not exist – return.

Parameters:
  • pid – The pid of the process to signal.
  • sig – The signal to send to the processes.
virttest.utils_misc.kvm_flags_to_stresstests(flags)[source]

Covert [cpu flags] to [tests]

Parameters:cpuflags – list of cpuflags
Returns:Return tests like string.
virttest.utils_misc.lock_file(filename, mode=2)[source]
virttest.utils_misc.log_last_traceback(msg=None, log=<function error>)[source]

Writes last traceback into specified log.

Warning:

This function is being moved into autotest and your code should use autotest.client.shared.base_utils function instead.

Parameters:
  • msg – Override the default message. [“Original traceback”]
  • log – Where to log the traceback [logging.error]
virttest.utils_misc.log_line(filename, line)[source]

Write a line to a file.

Parameters:
  • filename – Path of file to write to, either absolute or relative to the dir set by set_log_file_dir().
  • line – Line to write.
virttest.utils_misc.monotonic_time()[source]

Get monotonic time

virttest.utils_misc.mount(src, mount_point, fstype, perm=None, verbose=False, fstype_mtab=None)[source]

Mount the src into mount_point of the host.

Src:mount source
Mount_point:mount point
Fstype:file system type
Perm:mount permission
Parameters:fstype_mtab (str) – file system type in mtab could be different
virttest.utils_misc.normalize_data_size(value_str, order_magnitude='M', factor='1024')[source]

Normalize a data size in one order of magnitude to another (MB to GB, for example).

Parameters:
  • value_str – a string include the data and unit
  • order_magnitude – the magnitude order of result
  • factor – the factor between two relative order of magnitude. Normally could be 1024 or 1000
virttest.utils_misc.parallel(targets)[source]

Run multiple functions in parallel.

Parameters:targets – A sequence of tuples or functions. If it’s a sequence of tuples, each tuple will be interpreted as (target, args, kwargs) or (target, args) or (target,) depending on its length. If it’s a sequence of functions, the functions will be called without arguments.
Returns:A list of the values returned by the functions called.
virttest.utils_misc.pid_exists(pid)[source]

Return True if a given PID exists.

Parameters:pid – Process ID number.
virttest.utils_misc.process_or_children_is_defunct(ppid)[source]

Verify if any processes from PPID is defunct.

Attempt to verify if parent process and any children from PPID is defunct (zombie) or not. :param ppid: The parent PID of the process to verify.

virttest.utils_misc.program_is_alive(program_name, pid_files_dir=None)[source]

Checks if the process is alive and not in Zombie state.

:param program_name the name of the program :return: True if still alive, False otherwise

virttest.utils_misc.qemu_has_option(option, qemu_path='/usr/bin/qemu-kvm')[source]

Helper function for command line option wrappers

Parameters:
  • option – Option need check.
  • qemu_path – Path for qemu-kvm.
virttest.utils_misc.rm_ker_cmd(kernel_cmdline, kernel_param)[source]

Remove a parameter from kernel command line content

Parameters:
  • kernel_cmdline (string) – Original kernel command line.
  • kernel_param (string) – parameter want to change include the value.
Returns:

kernel command line

Return type:

string

virttest.utils_misc.run_tests(parser, job)[source]

Runs the sequence of KVM tests based on the list of dictionaries generated by the configuration system, handling dependencies.

Parameters:
  • parser – Config parser object.
  • job – Autotest job object.
Returns:

True, if all tests ran passed, False if any of them failed.

virttest.utils_misc.safe_kill(pid, signal)[source]

Attempt to send a signal to a given process that may or may not exist.

Parameters:signal – Signal number.
virttest.utils_misc.selinux_enforcing()[source]

Deprecated function

Returns True if SELinux is in enforcing mode, False if permissive/disabled

Alias to utils_selinux.is_enforcing()

virttest.utils_misc.set_cpu_status(cpu_num, enable=True)[source]

Set assigned cpu to be enable or disable

virttest.utils_misc.set_log_file_dir(directory)[source]

Set the base directory for log files created by log_line().

Parameters:dir – Directory for log files.
virttest.utils_misc.signal_program(program_name, sig=15, pid_files_dir=None)[source]

Sends a signal to the process listed in <program_name>.pid

:param program_name the name of the program :param sig signal to send

virttest.utils_misc.string_to_bitlist(data)[source]

Transform from ASCII string to bit list.

Parameters:data – String to be transformed
virttest.utils_misc.strip_console_codes(output, custom_codes=None)[source]

Remove the Linux console escape and control sequences from the console output. Make the output readable and can be used for result check. Now only remove some basic console codes using during boot up.

Parameters:
  • output (string) – The output from Linux console
  • custom_codes – The codes added to the console codes which is not covered in the default codes
Returns:

the string wihout any special codes

Return type:

string

virttest.utils_misc.umount(src, mount_point, fstype, verbose=False, fstype_mtab=None)[source]

Umount the src mounted in mount_point.

Src:mount source
Mount_point:mount point
Type:file system type
Parameters:fstype_mtab (str) – file system type in mtab could be different
virttest.utils_misc.unbind_device_driver(pci_id)[source]

Unbind device current driver.

virttest.utils_misc.unique(llist)[source]

Return a list of the elements in list, but without duplicates.

Parameters:list – List with values.
Returns:List with non duplicate elements.
virttest.utils_misc.unlock_file(lockfile)[source]
virttest.utils_misc.valued_option_dict(options, split_pattern, start_count=0, dict_split=None)[source]

Divide the valued options into key and value

Parameters:
  • options – the valued options get from cfg
  • split_pattern – patten used to split options
  • dict_split – patten used to split sub options and insert into dict
  • start_count – the start_count to insert option_dict
Returns:

dict include option and its value

virttest.utils_misc.verify_host_dmesg(dmesg_log_file=None, trace_re=None)[source]

Find host call trace in dmesg log.

Parameters:
  • dmesg_log_file – The file used to save host dmesg. If None, will save host dmesg to logging.debug.
  • trace_re – re string used to filter call trace.
virttest.utils_misc.verify_running_as_root()[source]

Verifies whether we’re running under UID 0 (root).

Raise:error.TestNAError
virttest.utils_misc.wait_for(func, timeout, first=0.0, step=1.0, text=None)[source]

Wait until func() evaluates to True.

If func() evaluates to True before timeout expires, return the value of func(). Otherwise return None.

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
virttest.utils_misc.write_pid(program_name, pid_files_dir=None)[source]

Try to drop <program_name>.pid in the main autotest directory.

Args:
program_name: prefix for file name
virttest.utils_misc.yum_install(pkg_list, session=None, timeout=300)[source]

Try to install packages on system

Parameters:pkg_list – list of packages
Session:session Object
Returns:True if all packages installed, False if any error

virttest.utils_misc_unittest module

class virttest.utils_misc_unittest.FakeCmd(cmd)[source]

Bases: object

get_stdout(cmd)[source]
class virttest.utils_misc_unittest.TestNumaNode(methodName='runTest')[source]

Bases: unittest.case.TestCase

setUp()[source]
tearDown()[source]
test_bitlist_to_string()[source]
test_free_cpu()[source]
test_get_node_cpus()[source]
test_pin_cpu()[source]
test_string_to_bitlist()[source]
class virttest.utils_misc_unittest.TestUtilsMisc(methodName='runTest')[source]

Bases: unittest.case.TestCase

test_cpu_vendor_amd()[source]
test_cpu_vendor_intel()[source]
test_get_archive_tarball_name()[source]
test_get_archive_tarball_name_absolute()[source]
test_get_archive_tarball_name_from_dir()[source]
test_git_repo_param_helper()[source]
test_normalize_data_size()[source]
test_vendor_unknown()[source]
virttest.utils_misc_unittest.utils_run(cmd)[source]

virttest.utils_net module

exception virttest.utils_net.BRAddIfError(ifname, brname, details)[source]

Bases: virttest.utils_net.NetError

exception virttest.utils_net.BRDelIfError(ifname, brname, details)[source]

Bases: virttest.utils_net.NetError

exception virttest.utils_net.BRIpError(brname)[source]

Bases: virttest.utils_net.NetError

exception virttest.utils_net.BRNotExistError(brname, details)[source]

Bases: virttest.utils_net.NetError

class virttest.utils_net.Bridge[source]

Bases: object

add_bridge(brname)[source]

Add a bridge in host

add_port(brname, ifname)[source]

Add a device to bridge

Parameters:
  • ifname – Name of TAP device
  • brname – Name of the bridge
del_bridge(brname)[source]

Delete a bridge in host

del_port(brname, ifname)[source]

Remove a TAP device from bridge

Parameters:
  • ifname – Name of TAP device
  • brname – Name of the bridge
get_stp_status(brname)[source]

get STP status

get_structure()[source]

Get bridge list.

list_br()[source]
list_iface()[source]

Return all interfaces used by bridge.

port_to_br(port_name)[source]

Return bridge which contain port.

Parameters:port_name – Name of port.
Returns:Bridge name or None if there is no bridge which contain port.
class virttest.utils_net.DbNet(params, vm_name, db_filename, db_key)[source]

Bases: virttest.utils_net.VMNet

Networking information from database

Database specification-
database values are python string-formatted lists of dictionaries
db_entry(db_key=None)[source]

Returns a python list of dictionaries from locked DB string-format entry

lock_db()[source]
mac_index()[source]

Generator of mac addresses found in database

save_to_db(db_key=None)[source]

Writes string representation out to database

unlock_db()[source]
update_db()[source]
exception virttest.utils_net.DbNoLockError(*args)[source]

Bases: virttest.utils_net.NetError

exception virttest.utils_net.DelLinkError(ifname, details=None)[source]

Bases: virttest.utils_net.NetError

exception virttest.utils_net.HwAddrGetError(ifname)[source]

Bases: virttest.utils_net.NetError

exception virttest.utils_net.HwAddrSetError(ifname, mac)[source]

Bases: virttest.utils_net.NetError

exception virttest.utils_net.HwOperstarteGetError(ifname, details=None)[source]

Bases: virttest.utils_net.NetError

exception virttest.utils_net.IPAddrGetError(mac_addr, details=None)[source]

Bases: virttest.utils_net.NetError

class virttest.utils_net.IPAddress(ip_str='', info='')[source]

Bases: object

Class to manipulate IPv4 or IPv6 address.

canonicalize(ip_str)[source]

Parse an IP string for listen to IPAddress content.

listening_on(port, max_retry=30)[source]

Check whether a port is used for listening.

class virttest.utils_net.IPv6Manager(*args, **dargs)[source]

Bases: virttest.propcan.PropCanBase

Setup and cleanup IPv6 environment.

auto_recover
static check_connectivity(client_ifname, server_ipv6, count=5)[source]

Check IPv6 network connectivity :param client_ifname: client network interface name :param server_ipv6: server IPv6 address ::param count: sending packets counts, default is 5

check_ipv6_connectivity
cleanup()[source]

Cleanup IPv6 network environment.

client
client_ifname
client_ipv6_addr
close_session()[source]

If the session exists then close it.

flush_ip6tables()[source]

Refresh IPv6 firewall rules

get_addr_list(runner=None)[source]

Get IPv6 address list from local and remote host.

get_session()[source]

Make sure the session is alive and available

port
prompt
runner
server_ifname
server_ip
server_ipv6_addr
server_pwd
server_user
session
setup()[source]

Setup IPv6 network environment.

exception virttest.utils_net.IfChangeAddrError(ifname, ipaddr, details)[source]

Bases: virttest.utils_net.NetError

exception virttest.utils_net.IfChangeBrError(ifname, old_brname, new_brname, details)[source]

Bases: virttest.utils_net.NetError

exception virttest.utils_net.IfNotInBridgeError(ifname, details)[source]

Bases: virttest.utils_net.NetError

class virttest.utils_net.Interface(name)[source]

Bases: object

Class representing a Linux network device.

Delete the interface. Equivalent to ‘ip link delete NAME’.

down(*args, **argkw)[source]
get_index(*args, **argkw)[source]
get_ip(*args, **argkw)[source]
get_mac(*args, **argkw)[source]
get_netmask(*args, **argkw)[source]
get_stats(*args, **argkw)[source]
is_brport()[source]

Check Whether this Interface is a bridge port_to_br

is_up(*args, **argkw)[source]
set_ip(*args, **argkw)[source]
set_mac(*args, **argkw)[source]
set_netmask(*args, **argkw)[source]
up(*args, **argkw)[source]
class virttest.utils_net.LibvirtIface(*args, **dargs)[source]

Bases: virttest.utils_net.VirtIface

Networking information specific to libvirt

class virttest.utils_net.Macvtap(tapname=None)[source]

Bases: virttest.utils_net.Interface

class of macvtap, base Interface

create(device, mode='vepa')[source]

Create a macvtap device, only when the device does not exist.

Parameters:
  • device – Macvtap device to be created.
  • mode – Creation mode.
delete()[source]
get_device()[source]
get_tapname()[source]
open()[source]
exception virttest.utils_net.MacvtapCreationError(ifname, base_interface, details=None)[source]

Bases: virttest.utils_net.NetError

exception virttest.utils_net.MacvtapGetBaseInterfaceError(ifname=None, details=None)[source]

Bases: virttest.utils_net.NetError

exception virttest.utils_net.NetError(*args)[source]

Bases: exceptions.Exception

exception virttest.utils_net.OpenflowSwitchError(brname)[source]

Bases: virttest.utils_net.NetError

class virttest.utils_net.ParamsNet(params, vm_name)[source]

Bases: virttest.utils_net.VMNet

Networking information from Params

Params contents specification-
vms = <vm names...> nics = <nic names...> nics_<vm name> = <nic names...> # attr: mac, ip, model, nettype, netdst, etc. <attr> = value <attr>_<nic name> = value
mac_index()[source]

Generator over mac addresses found in params

reset_ip(index_or_name)[source]

Reset to ip from params if defined and valid, or undefine.

reset_mac(index_or_name)[source]

Reset to mac from params if defined and valid, or undefine.

class virttest.utils_net.QemuIface(*args, **dargs)[source]

Bases: virttest.utils_net.VirtIface

Networking information specific to Qemu

device_id
ifname
netdev_extra_params
netdev_id
nic_extra_params
queues
romfile
tapfd_ids
tapfds
tftp
vectors
vhostfds
vlan
exception virttest.utils_net.TAPBringDownError(ifname)[source]

Bases: virttest.utils_net.NetError

exception virttest.utils_net.TAPBringUpError(ifname)[source]

Bases: virttest.utils_net.NetError

exception virttest.utils_net.TAPCreationError(ifname, details=None)[source]

Bases: virttest.utils_net.NetError

exception virttest.utils_net.TAPModuleError(devname, action='open', details=None)[source]

Bases: virttest.utils_net.NetError

exception virttest.utils_net.TAPNotExistError(ifname)[source]

Bases: virttest.utils_net.NetError

exception virttest.utils_net.VMIPV6AdressError(error_info)[source]

Bases: virttest.utils_net.NetError

exception virttest.utils_net.VMIPV6NeighNotFoundError(ipv6_address)[source]

Bases: virttest.utils_net.NetError

class virttest.utils_net.VMNet(container_class=<class 'virttest.utils_net.VirtIface'>, virtiface_list=[])[source]

Bases: list

Collection of networking information.

DISCARD_WARNINGS = 10
append(value)[source]
mac_list()[source]

Return a list of all mac addresses used by defined interfaces

nic_lookup(prop_name, prop_value)[source]

Return the first index with prop_name key matching prop_value or None

nic_name_index(name)[source]

Return the index number for name, or raise KeyError

nic_name_list()[source]

Obtain list of nic names from lookup of contents ‘nic_name’ key.

process_mac(value)[source]

Strips ‘mac’ key from value if it’s not valid

subclass_pre_init(params, vm_name)[source]

Subclasses must establish style before calling VMNet. __init__()

exception virttest.utils_net.VMNetError(*args)[source]

Bases: virttest.utils_net.NetError

class virttest.utils_net.VMNetStyle[source]

Bases: dict

Make decisions about needed info from vm_type and driver_type params.

VMNet_Style_Map = {'default': {'default': {'mac_prefix': '9a', 'container_class': <class 'virttest.utils_net.QemuIface'>}}, 'libvirt': {'default': {'mac_prefix': '9a', 'container_class': <class 'virttest.utils_net.LibvirtIface'>}, 'xen': {'mac_prefix': '00:16:3e', 'container_class': <class 'virttest.utils_net.LibvirtIface'>}, 'qemu': {'mac_prefix': '52:54:00', 'container_class': <class 'virttest.utils_net.LibvirtIface'>}}}
classmethod get_driver_type_map(vm_type_map, driver_type)[source]
classmethod get_style(vm_type, driver_type)[source]
classmethod get_vm_type_map(vm_type)[source]
class virttest.utils_net.VirtIface(*args, **dargs)[source]

Bases: virttest.propcan.PropCan, object

Networking information for single guest interface and host connection.

LASTBYTE = 100
classmethod complete_mac_address(mac)[source]

Append randomly generated byte strings to make mac complete

Parameters:mac – String or list of mac bytes (possibly incomplete)
Raise:TypeError if mac is not a string or a list
g_nic_name
classmethod generate_bytes()[source]

Return next byte from ring

classmethod int_list_to_mac_str(mac_bytes)[source]

Return string formatting of int mac_bytes

ip
mac
classmethod mac_is_valid(mac)[source]
classmethod mac_str_to_int_list(mac)[source]

Convert list of string bytes to int list

classmethod name_is_valid(nic_name)[source]

Corner-case prevention where nic_name is not a sane string value

netdst
nettype
nic_model
nic_name
class virttest.utils_net.VirtNet(params, vm_name, db_key, db_filename='/tmp/address_pool')[source]

Bases: virttest.utils_net.DbNet, virttest.utils_net.ParamsNet

Persistent collection of VM’s networking information.

free_mac_address(nic_index_or_name)[source]

Remove the mac value from nic_index_or_name and cache unless static

Parameters:nic_index_or_name – index number or name of NIC
generate_ifname(nic_index_or_name)[source]

Return and set network interface name

generate_mac_address(nic_index_or_name, attempts=1024)[source]

Set & return valid mac address for nic_index_or_name or raise NetError

Parameters:nic_index_or_name – index number or name of NIC
Returns:MAC address string
Raise:NetError if mac generation failed
get_mac_address(nic_index_or_name)[source]

Return a MAC address for nic_index_or_name

Parameters:nic_index_or_name – index number or name of NIC
Returns:MAC address string.
mac_index()[source]

Generator for all allocated mac addresses (requires db lock)

set_mac_address(nic_index_or_name, mac)[source]

Set a MAC address to value specified

Parameters:nic_index_or_name – index number or name of NIC
Raise:NetError if mac already assigned
exception virttest.utils_net.VlanError(ifname, details)[source]

Bases: virttest.utils_net.NetError

virttest.utils_net.add_ovs_bridge(*args, **kargs)[source]
virttest.utils_net.add_to_bridge(*args, **kargs)[source]
virttest.utils_net.bring_down_ifname(ifname)[source]

Bring down an interface

Parameters:ifname – Name of the interface
virttest.utils_net.bring_up_ifname(ifname)[source]

Bring up an interface

Parameters:ifname – Name of the interface
virttest.utils_net.change_iface_bridge(*args, **kargs)[source]
virttest.utils_net.check_add_dnsmasq_to_br(br_name, tmpdir)[source]

Add dnsmasq for bridge. dnsmasq could be added only if bridge has assigned ip address.

Parameters:
  • bridge_name – Name of bridge.
  • bridge_ip – Bridge ip.
  • tmpdir – Tmp dir for save pid file and ip range file.
Returns:

When new dnsmasq is started name of pidfile otherwise return None because system dnsmasq is already started on bridge.

virttest.utils_net.check_listening_port_by_service(service, port, listen_addr='0.0.0.0', runner=None)[source]

Check TCP/IP listening by service

virttest.utils_net.check_listening_port_remote_by_service(server_ip, server_user, server_pwd, service, port, listen_addr)[source]

Check remote TCP/IP listening by service

virttest.utils_net.clean_tmp_files()[source]

Remove the base address pool filename.

virttest.utils_net.create_and_open_macvtap(ifname, mode='vepa', queues=1, base_if=None, mac_addr=None)[source]

Create a new macvtap device, open it, and return the fds

Parameters:
  • ifname – macvtap interface name
  • mode – macvtap type mode (“vepa, bridge,..)
  • queues – Queue number
  • base_if – physical interface to create macvtap
  • mac_addr – macvtap mac address
virttest.utils_net.create_macvtap(ifname, mode='vepa', base_if=None, mac_addr=None)[source]

Create Macvtap device, return a object of Macvtap

Parameters:
  • ifname – macvtap interface name
  • mode – macvtap type mode (“vepa, bridge,..)
  • base_if – physical interface to create macvtap
  • mac_addr – macvtap mac address
virttest.utils_net.del_from_bridge(*args, **kargs)[source]
virttest.utils_net.del_net_if_ip(if_name, ip_addr, runner=None)[source]

Delete network device ip addresses.

Parameters:
  • if_name – Name of interface.
  • ip_addr – Interface ip addr in format “ip_address/mask”.
Raise:

IfChangeAddrError.

virttest.utils_net.del_ovs_bridge(*args, **kargs)[source]
virttest.utils_net.disable_windows_guest_network(session, connection_id, timeout=240)[source]
virttest.utils_net.enable_windows_guest_network(session, connection_id, timeout=240)[source]
virttest.utils_net.find_bridge_manager(*args, **kargs)[source]
virttest.utils_net.find_current_bridge(*args, **kargs)[source]
virttest.utils_net.find_dnsmasq_listen_address()[source]

Search all dnsmasq listen addresses.

Parameters:
  • bridge_name – Name of bridge.
  • bridge_ip – Bridge ip.
Returns:

List of ip where dnsmasq is listening.

virttest.utils_net.generate_mac_address_simple()[source]
virttest.utils_net.get_all_ips()[source]

Get all IPv4 and IPv6 addresses from all interfaces.

virttest.utils_net.get_correspond_ip(remote_ip)[source]

Get local ip address which is used to contact remote ip.

Parameters:remote_ip – Remote ip
Returns:Local corespond IP.
virttest.utils_net.get_guest_ip_addr(session, mac_addr, os_type='linux', ip_version='ipv4', linklocal=False)[source]

Get guest ip addresses by serial session

Parameters:
  • session – serial session
  • mac_addr – nic mac address of the nic that you want get
  • os_type – guest os type, windows or linux
  • ip_version – guest ip version, ipv4 or ipv6
  • linklocal – Wether ip address is local or remote
Returns:

ip addresses of network interface.

virttest.utils_net.get_host_default_gateway()[source]

Get the Default Gateway in host. :return: a string of the host’s default gateway. :rtype: string

virttest.utils_net.get_host_iface()[source]

List the nic interface in host. :return: a list of the interfaces in host :rtype: list

virttest.utils_net.get_host_ip_address(params)[source]

returns ip address of host specified in host_ip_addr parameter If provided otherwise ip address on interface specified in netdst parameter is returned :param params

virttest.utils_net.get_ip_address_by_interface(ifname)[source]

returns ip address by interface :param ifname - interface name :raise NetError - When failed to fetch IP address (ioctl raised IOError.).

Retrieves interface address from socket fd trough ioctl call and transforms it into string from 32-bit packed binary by using socket.inet_ntoa().

virttest.utils_net.get_linux_ifname(session, mac_address='')[source]

Get the interface name through the mac address.

Parameters:
  • session – session to the virtual machine
  • mac_address – the macaddress of nic
:raise error.TestError in case it was not possible to determine the
interface name.
virttest.utils_net.get_macvtap_base_iface(base_interface=None)[source]

Get physical interface to create macvtap, if you assigned base interface is valid(not belong to any bridge and is up), will use it; else use the first physical interface, which is not a brport and up.

virttest.utils_net.get_neigh_attch_interface(neigh_address)[source]

Get the interface wihch can reach the neigh_address

virttest.utils_net.get_neigh_mac(neigh_address)[source]

Get neighbour mac by his address

virttest.utils_net.get_neighbours_info(neigh_address='', interface_name=None)[source]

Get the neighbours infomation

virttest.utils_net.get_net_if(runner=None, state=None)[source]
Parameters:
  • runner – command runner.
  • div_phy_virt – if set true, will return a tuple division real physical interface and virtual interface
Returns:

List of network interfaces.

virttest.utils_net.get_net_if_addrs(if_name, runner=None)[source]

Get network device ip addresses. ioctl not used because it’s not compatible with ipv6 address.

Parameters:if_name – Name of interface.
Returns:List ip addresses of network interface.
virttest.utils_net.get_net_if_addrs_win(session, mac_addr)[source]

Try to get windows guest nic address by serial session

Parameters:
  • session – serial sesssion
  • mac_addr – guest nic mac address
Returns:

List ip addresses of network interface.

virttest.utils_net.get_net_if_and_addrs(runner=None)[source]
Returns:Dict of interfaces and their addresses {“ifname”: addrs}.
virttest.utils_net.get_net_if_operstate(ifname, runner=None)[source]

Get linux host/guest network device operstate.

Parameters:if_name – Name of the interface.
Raise:HwOperstarteGetError.
virttest.utils_net.get_sorted_net_if()[source]

Get all network interfaces, but sort them among physical and virtual if.

Returns:Tuple (physical interfaces, virtual interfaces)
virttest.utils_net.get_windows_nic_attribute(session, key, value, target, timeout=240, global_switch='nic')[source]

Get the windows nic attribute using wmic. All the support key you can using wmic to have a check.

Parameters:
  • session – session to the virtual machine
  • key – the key supported by wmic
  • value – the value of the key
  • target – which nic attribute you want to get.
virttest.utils_net.if_nametoindex(ifname)[source]

Map an interface name into its corresponding index. Returns 0 on error, as 0 is not a valid index

Parameters:ifname – interface name
virttest.utils_net.if_set_macaddress(ifname, mac)[source]

Set the mac address for an interface

Parameters:
  • ifname – Name of the interface
  • mac – Mac address
virttest.utils_net.ipv6_from_mac_addr(mac_addr)[source]
Returns:Ipv6 address for communication in link range.
virttest.utils_net.is_virtual_network_dev(dev_name)[source]
Parameters:dev_name – Device name.
Returns:True if dev_name is in virtual/net dir, else false.
virttest.utils_net.local_runner(cmd, timeout=None)[source]
virttest.utils_net.local_runner_status(cmd, timeout=None)[source]
virttest.utils_net.neigh_reachable(neigh_address, attach_if=None)[source]

Check the neighbour is reachable

virttest.utils_net.open_macvtap(macvtap_object, queues=1)[source]

Open a macvtap device and returns its file descriptors which are used by fds=<fd1:fd2:..> parameter of qemu

For single queue, only returns one file descriptor, it’s used by fd=<fd> legacy parameter of qemu

If you not have a switch support vepa in you env, run this type case you need at least two nic on you host [just workaround]

Parameters:
  • macvtap_object – macvtap object
  • queues – Queue number
virttest.utils_net.open_tap(devname, ifname, queues=1, vnet_hdr=True)[source]

Open a tap device and returns its file descriptors which are used by fds=<fd1:fd2:..> parameter of qemu

For single queue, only returns one file descriptor, it’s used by fd=<fd> legacy parameter of qemu

Parameters:
  • devname – TUN device path
  • ifname – TAP interface name
  • queues – Queue number
  • vnet_hdr – Whether enable the vnet header
virttest.utils_net.openflow_manager(*args, **kargs)[source]
virttest.utils_net.ovs_br_exists(*args, **kargs)[source]
virttest.utils_net.parse_arp()[source]

Read /proc/net/arp, return a mapping of MAC to IP

Returns:dict mapping MAC to IP
virttest.utils_net.refresh_neigh_table(interface_name=None, neigh_address='ff02::1')[source]

Refresh host neighbours table, if interface_name is assigned only refresh neighbours of this interface, else refresh the all the neighbours.

virttest.utils_net.restart_guest_network(session, mac_addr=None, os_type='linux', ip_version='ipv4', timeout=240)[source]

Restart guest network by serial session

Parameters:
  • session – serial session
  • mac_addr – nic mac address of the nic that you want restart
  • os_type – guest os type, windows or linux
  • ip_version – guest ip version, ipv4 or ipv6
  • timeout – timeout value for command.
virttest.utils_net.restart_windows_guest_network(session, connection_id, timeout=240, mode='netsh')[source]

Restart guest’s network via serial console. mode “netsh” can not works in winxp system

Parameters:
  • session – session to virtual machine
  • connection_id – windows nic connectionid,it means connection name, you Can get connection id string via wmic
virttest.utils_net.restart_windows_guest_network_by_devcon(session, netdevid, timeout=240)[source]
virttest.utils_net.restart_windows_guest_network_by_key(session, key, value, timeout=240, mode='netsh')[source]

Restart the guest network by nic Attribute like connectionid, interfaceindex, “netsh” can not work in winxp system. using devcon mode must download devcon.exe and put it under c: :param session: session to virtual machine :param key: the key supported by wmic nic :param value: the value of the key :param timeout: timeout :param mode: command mode netsh or devcon

virttest.utils_net.set_guest_network_status_by_devcon(session, status, netdevid, timeout=240)[source]

using devcon to enable/disable the network device. using it must download the devcon.exe, and put it under c:

virttest.utils_net.set_net_if_ip(if_name, ip_addr, runner=None)[source]

Set network device ip addresses. ioctl not used because there is incompatibility with ipv6.

Parameters:
  • if_name – Name of interface.
  • ip_addr – Interface ip addr in format “ip_address/mask”.
Raise:

IfChangeAddrError.

virttest.utils_net.set_win_guest_nic_status(session, connection_id, status, timeout=240)[source]

Set windows guest nic ENABLED/DISABLED

:param session : session to virtual machine :param connection_id : windows guest nic netconnectionid :param status : set nic ENABLED/DISABLED

virttest.utils_net.update_mac_ip_address(vm, params, timeout=None)[source]

Get mac and ip address from guest then update the mac pool and address cache

Parameters:
  • vm – VM object
  • params – Dictionary with the test parameters.
virttest.utils_net.verify_ip_address_ownership(ip, macs, timeout=60.0)[source]

Use arping and the ARP cache to make sure a given IP address belongs to one of the given MAC addresses.

Parameters:
  • ip – An IP address.
  • macs – A list or tuple of MAC addresses.
Returns:

True if ip is assigned to a MAC address in macs.

virttest.utils_net.vnet_hdr_probe(tapfd)[source]

Check if the IFF_VNET_HDR is support by tun.

Parameters:tapfd – the file descriptor of /dev/net/tun
virttest.utils_net.vnet_mq_probe(tapfd)[source]

Check if the IFF_MULTI_QUEUE is support by tun.

Parameters:tapfd – the file descriptor of /dev/net/tun
virttest.utils_net.warp_init_del(func)[source]

virttest.utils_net_unittest module

class virttest.utils_net_unittest.FakeVm(vm_name, params)[source]

Bases: object

get_params()[source]
is_alive()[source]
class virttest.utils_net_unittest.TestBridge(methodName='runTest')[source]

Bases: unittest.case.TestCase

class FakeCmd(*args, **kargs)[source]

Bases: object

get_stdout()[source]
iter = 0
TestBridge.setUp()[source]
TestBridge.tearDown()[source]
TestBridge.test_getstructure()[source]
class virttest.utils_net_unittest.TestLibvirtIface(methodName='runTest')[source]

Bases: virttest.utils_net_unittest.TestVirtIface

setUp()[source]
class virttest.utils_net_unittest.TestQemuIface(methodName='runTest')[source]

Bases: virttest.utils_net_unittest.TestVirtIface

setUp()[source]
class virttest.utils_net_unittest.TestVirtIface(methodName='runTest')[source]

Bases: unittest.case.TestCase

class VirtIface(*args, **dargs)

Bases: virttest.propcan.PropCan, object

Networking information for single guest interface and host connection.

LASTBYTE = 100
classmethod complete_mac_address(mac)

Append randomly generated byte strings to make mac complete

Parameters:mac – String or list of mac bytes (possibly incomplete)
Raise:TypeError if mac is not a string or a list
g_nic_name
classmethod generate_bytes()

Return next byte from ring

classmethod int_list_to_mac_str(mac_bytes)

Return string formatting of int mac_bytes

ip
mac
classmethod mac_is_valid(mac)
classmethod mac_str_to_int_list(mac)

Convert list of string bytes to int list

classmethod name_is_valid(nic_name)

Corner-case prevention where nic_name is not a sane string value

netdst
nettype
nic_model
nic_name
TestVirtIface.loop_assert(virtiface, test_keys, what_func)[source]
TestVirtIface.setUp()[source]
TestVirtIface.test_apendex_set()[source]

Verify container ignores unknown key names

TestVirtIface.test_full_set()[source]
TestVirtIface.test_half_set()[source]
TestVirtIface.test_mac_completer()[source]
class virttest.utils_net_unittest.TestVmNet(methodName='runTest')[source]

Bases: unittest.case.TestCase

setUp()[source]
test_VirtIface_container()[source]
test_string_container()[source]
class virttest.utils_net_unittest.TestVmNetStyle(methodName='runTest')[source]

Bases: unittest.case.TestCase

get_style(vm_type, driver_type)[source]
setUp()[source]
test_default_default()[source]
test_libvirt()[source]
class virttest.utils_net_unittest.TestVmNetSubclasses(methodName='runTest')[source]

Bases: unittest.case.TestCase

counter = 0
db_filename = '/dev/shm/UnitTest_AddressPool'
db_item_count = 0
fakevm_generator()[source]
mac_prefix = '01:02:03:04:05:'
nettests_cartesian = '\n variants:\n - onevm:\n vms=vm1\n - twovms:\n vms=vm1 vm2\n - threevms:\n vms=vm1 vm2 vm3\n\n variants:\n - typeundefined:\n - libvirt:\n vm_type = libvirt\n variants:\n - unsetdrivertype:\n - xen:\n driver_type = xen\n nics=nic1\n - qemu:\n driver_type = qemu\n nics=nic1 nic2\n - kvm:\n driver_type = kvm\n nics=nic1 nic2 nic3\n - lxc:\n driver_type = lxc\n nics=nic1 nic2 nic3 nic4\n - qemu:\n vm_type = qemu\n variants:\n - unsetdrivertype:\n - kvm:\n driver_type = kvm\n - qemu:\n driver_type = qemu\n\n variants:\n -propsundefined:\n -defaultprops:\n mac = 9a\n nic_model = virtio\n nettype = bridge\n netdst = virbr0\n vlan = 0\n -mixedpropsone:\n mac_nic1 = 9a:01\n nic_model_nic1 = rtl8139\n nettype_nic1 = bridge\n netdst_nic1 = virbr1\n vlan_nic1 = 1\n ip_nic1 = 192.168.122.101\n netdev_nic1 = foobar\n -mixedpropstwo:\n mac_nic2 = 9a:02\n nic_model_nic2 = e1000\n nettype_nic2 = network\n netdst_nic2 = eth2\n vlan_nic2 = 2\n ip_nic2 = 192.168.122.102\n netdev_nic2 = barfoo\n -mixedpropsthree:\n mac_nic1 = 01:02:03:04:05:06\n mac_nic2 = 07:08:09:0a:0b:0c\n mac_nic4 = 0d:0e:0f:10:11:12\n -mixedpropsthree:\n nettype_nic3 = bridge\n netdst_nic3 = virbr3\n netdev_nic3 = qwerty\n '
print_and_inc()[source]
setUp()[source]

Runs before every test

test_01_Params()[source]

Load Cartesian combinatorial result verifies against all styles of VM.

Note: There are some cases where the key should NOT be set, in this
case an exception is caught prior to verifying
test_02_db()[source]

Load Cartesian combinatorial result from params into database

test_03_db()[source]

Load from database created in test_02_db, verify data against params

test_04_VirtNet()[source]

Populate database with max - 1 mac addresses

test_05_VirtNet()[source]

Load max - 1 entries from db, overriding params.

DEPENDS ON test_04_VirtNet running first

test_06_VirtNet()[source]

Generate last possibly mac and verify value.

DEPENDS ON test_05_VirtNet running first

test_07_VirtNet()[source]

Release mac from beginning, midle, and end, re-generate + verify value

test_08_ifname()[source]
test_99_ifname()[source]
test_cmp_Virtnet()[source]
zero_counter(increment=100)[source]

virttest.utils_netperf module

class virttest.utils_netperf.Netperf(address, netperf_path, md5sum='', netperf_source='', client='ssh', port='22', username='root', password='redhat', compile_option='--enable-demo=yes', install=True)[source]

Bases: object

is_target_running(target)[source]
stop(target)[source]
class virttest.utils_netperf.NetperfClient(address, netperf_path, md5sum='', netperf_source='', client='ssh', port='22', username='root', password='redhat', compile_option='', install=True)[source]

Bases: virttest.utils_netperf.Netperf

bg_start(server_address, test_option='', session_num=1, cmd_prefix='', package_sizes='')[source]

Run netperf background, for stress test do not have output

Parameters:
  • server_address – Remote netserver address
  • netperf_path – netperf test option (global/test option)
  • timeout – Netperf test timeout(-l)
  • cmd_prefix – Prefix in netperf command
  • package_sizes – Package sizes test in netperf command.
is_netperf_running()[source]
start(server_address, test_option='', timeout=1200, cmd_prefix='', package_sizes='')[source]

Run netperf test

Parameters:
  • server_address – Remote netserver address
  • netperf_path – Netperf test option (global/test option)
  • timeout – Netperf test timeout(-l)
  • cmd_prefix – Prefix in netperf command
  • package_sizes – Package sizes test in netperf command.
Returns:

return test result

stop()[source]
exception virttest.utils_netperf.NetperfError[source]

Bases: exceptions.Exception

class virttest.utils_netperf.NetperfPackage(address, netperf_path, md5sum='', netperf_source='', client='ssh', port='22', username='root', password='123456')[source]

Bases: virttest.remote.Remote_Package

env_cleanup(clean_all=True)[source]
install(install, compile_option)[source]
pack_compile(compile_option='')[source]
pull_file(netperf_source=None)[source]

Copy file from remote to local.

exception virttest.utils_netperf.NetperfPackageError(error_info)[source]

Bases: virttest.utils_netperf.NetperfError

class virttest.utils_netperf.NetperfServer(address, netperf_path, md5sum='', netperf_source='', client='ssh', port='22', username='root', password='redhat', compile_option='--enable-demo=yes', install=True)[source]

Bases: virttest.utils_netperf.Netperf

is_server_running()[source]
start(restart=False)[source]

Start/Restart netserver

Parameters:restart – if restart=True, will restart the netserver
stop()[source]
exception virttest.utils_netperf.NetperfTestError(error_info)[source]

Bases: virttest.utils_netperf.NetperfError

exception virttest.utils_netperf.NetserverError(error_info)[source]

Bases: virttest.utils_netperf.NetperfError

virttest.utils_params module

exception virttest.utils_params.ParamNotFound[source]

Bases: autotest.client.shared.error.TestNAError

class virttest.utils_params.Params(*args, **kwargs)[source]

Bases: UserDict.IterableUserDict

A dict-like object passed to every test.

lock = <thread.lock object>
object_counts(count_key, base_name)[source]

This is a generator method: to give it the name of a count key and a base_name, and it returns an iterator over all the values from params

object_params(obj_name)[source]

Return a dict-like object containing the parameters of an individual object.

This method behaves as follows: the suffix ‘_’ + obj_name is removed from all key names that have it. Other key names are left unchanged. The values of keys with the suffix overwrite the values of their suffixless versions.

Parameters:obj_name – The name of the object (objects are listed by the objects() method).
objects(key)[source]

Return the names of objects defined using a given key.

Parameters:key – The name of the key whose value lists the objects (e.g. ‘nics’).

virttest.utils_params_unittest module

class virttest.utils_params_unittest.TestParams(methodName='runTest')[source]

Bases: unittest.case.TestCase

setUp()[source]
testGetItem()[source]
testGetItemMissing()[source]
testObjects()[source]
testObjectsParams()[source]

virttest.utils_sasl module

tools to manage sasl.

class virttest.utils_sasl.SASL(*args, **dargs)[source]

Bases: virttest.propcan.PropCanBase

Base class of a connection between server and client.

auto_recover
cleanup(remote=True)[source]

Clear created sasl users

client
close_session()[source]

If session exists then close it

get_session()[source]

Make sure the session is alive and available

linesep
list_users(remote=True, sasldb_path='/etc/libvirt/passwd.db')[source]

List users in sasldb

port
prompt
sasl_pwd_cmd
sasl_user_cmd
sasl_user_pwd
server_ip
server_pwd
server_user
session
setup(remote=True)[source]

Create sasl users with password

class virttest.utils_sasl.VirshSessionSASL(params)[source]

Bases: virttest.virsh.VirshSession

A wrap class for virsh session which used SASL infrastructure.

virttest.utils_selinux module

selinux test utility functions.

exception virttest.utils_selinux.RestoreconError[source]

Bases: virttest.utils_selinux.SelinuxError

exception virttest.utils_selinux.SeCmdError(cmd, detail)[source]

Bases: virttest.utils_selinux.SelinuxError

Error in executing cmd.

exception virttest.utils_selinux.SelinuxError[source]

Bases: exceptions.Exception

Error selinux utility functions.

exception virttest.utils_selinux.SemanageError[source]

Bases: virttest.utils_selinux.SelinuxError

Error when semanage binary is not found

virttest.utils_selinux.apply_defcon(pathname, dirdesc=False)[source]

Apply default contexts to pathname, possibly descending into sub-dirs also.

Parameters:
  • pathname – Absolute path to file, directory, or symlink
  • dirdesc – True to descend into sub-directories
Returns:

List of changes applied tuple(pathname, from context, to context)

virttest.utils_selinux.del_defcon(context_type, pathregex)[source]

Remove the default local SELinux policy type for a file/path

Parameters:

context – The selinux context (only type is used)

Pramm pathregex:
 

Pathname regex e.g. r”/foo/bar/baz(/.*)?”

Raises:
  • SelinuxError – if semanage command not found
  • SeCmdError – if semanage exits non-zero
virttest.utils_selinux.diff_defcon(pathname, dirdesc=False)[source]

Return a list of tuple(pathname, from, to) for current & default contexts

Parameters:
  • pathname – Absolute path to file, directory, or symlink
  • dirdesc – True to descend into sub-directories
Returns:

List of tuple(pathname, from context, to context)

virttest.utils_selinux.find_defcon(defcon, pathname)[source]

Returns the context type of first match to pathname or None

virttest.utils_selinux.find_defcon_idx(defcon, pathname)[source]

Returns the index into defcon where pathname matches or None

virttest.utils_selinux.find_pathregex(defcon, pathname)[source]

Returns the regular expression in defcon matching pathname

virttest.utils_selinux.get_context_from_str(context)[source]

Get the context in a context.

Parameters:context – SELinux context string
Raises:SelinuxError – if there is no context in context.
virttest.utils_selinux.get_context_of_file(filename)[source]

Get the context of file.

Raises:SeCmdError – if execute ‘getfattr’ failed.
virttest.utils_selinux.get_context_of_process(pid)[source]

Get context of process.

virttest.utils_selinux.get_defcon(local=False)[source]

Return list of dictionaries containing SELinux default file context types

Parameters:local – Only return locally modified default contexts
Returns:list of dictionaries of default context attributes
virttest.utils_selinux.get_status()[source]

Get the status of selinux.

Returns:

string of status in STATUS_LIST.

Raises:
  • SeCmdError – if execute ‘getenforce’ failed.
  • SelinuxError – if ‘getenforce’ command exit 0, but the output is not expected.
virttest.utils_selinux.get_type_from_context(context)[source]

Return just the type component of a full context string

Parameters:context – SELinux context string
Returns:Type component of SELinux context string
virttest.utils_selinux.is_disabled()[source]

Return True if the selinux is disabled.

virttest.utils_selinux.is_enforcing()[source]

Return true if the selinux is enforcing.

virttest.utils_selinux.is_not_disabled()[source]

Return True if the selinux is not disabled.

virttest.utils_selinux.is_permissive()[source]

Return true if the selinux is permissive.

virttest.utils_selinux.set_context_of_file(filename, context)[source]

Set context of file.

Raises:
  • SeCmdError – if failed to execute chcon.
  • SelinuxError – if command chcon execute normally, but the context of file is not setted to context.
virttest.utils_selinux.set_defcon(context_type, pathregex, context_range=None)[source]

Set the default context of a file/path in local SELinux policy

Parameters:
  • context_type – The selinux context (only type is used)
  • pathregex – Pathname regex e.g. r”/foo/bar/baz(/.*)?”
  • context_range – MLS/MCS Security Range e.g. s0:c87,c520
Raises:
  • SelinuxError – if semanage command not found
  • SeCmdError – if semanage exits non-zero
virttest.utils_selinux.set_status(status)[source]

Set status of selinux.

Parameters:

status – status want to set selinux.

Raises:
  • SelinuxError – status is not supported.
  • SelinuxError – need to reboot host.
  • SeCmdError – execute setenforce failed.
  • SelinuxError – cmd setenforce exit normally, but status of selinux is not set to expected.
virttest.utils_selinux.transmogrify_sub_dirs(pathregex)[source]

Append ‘(/.*)?’ regex to end of pathregex to optionally match all subdirs

virttest.utils_selinux.transmogrify_usr_local(pathregex)[source]

Replace usr/local/something with usr/(local/)?something

virttest.utils_selinux.verify_defcon(pathname, dirdesc=False, readonly=True, forcedesc=False)[source]

Verify contexts of pathspec (and/or below, if dirdesc) match default

Parameters:
  • pathname – Absolute path to file, directory, or symlink
  • dirdesc – True to descend into sub-directories
  • readonly – True to passive check and don’t change any file labels
  • forcedesc – True to force a replacement of the entire context
Returns:

True if all components match default contexts

Note:

By default DOES NOT follow symlinks

virttest.utils_spice module

Common spice test utility functions.

exception virttest.utils_spice.RVConnectError[source]

Bases: exceptions.Exception

Exception raised in case that remote-viewer fails to connect

virttest.utils_spice.clear_interface(vm, login_timeout=360, timeout=5)[source]

Clears user interface of a vm without reboot

Parameters:vm – VM where cleaning is required
virttest.utils_spice.clear_interface_linux(vm, login_timeout, timeout)[source]

Clears user interface of a vm without reboot

Parameters:vm – VM where cleaning is required
virttest.utils_spice.deploy_epel_repo(guest_session, params)[source]

Deploy epel repository to RHEL VM If It’s RHEL6 or 5.

:param guest_session - ssh session to guest VM :param params

virttest.utils_spice.gen_rv_file(params, guest_vm, host_subj=None, cacert=None)[source]

Generates vv file for remote-viewer

Parameters:
  • params – all parameters of the test
  • guest_vm – object of a guest VM
  • host_subj – subject of the host
  • cacert – location of certificate of host
virttest.utils_spice.get_vdagent_status(vm_session, test_timeout)[source]

Return the status of vdagent :param vm_session: ssh session of the VM :param test_timeout: timeout time for the cmd

virttest.utils_spice.install_rv_win(client, host_path, client_path='C:\\virt-viewer.msi')[source]

Install remote-viewer on a windows client

Parameters:
  • client – VM object
  • host_path – Location of installer on host
  • client_path – Location of installer after copying
virttest.utils_spice.install_usbclerk_win(client, host_path, client_path='C:\\usbclerk.msi')[source]

Install remote-viewer on a windows client

Parameters:
  • client – VM object
  • host_path – Location of installer on host
  • client_path – Location of installer after copying
virttest.utils_spice.kill_app(vm_name, app_name, params, env)[source]

Kill selected app on selected VM

:params vm_name - VM name in parameters :params app_name - name of application

virttest.utils_spice.restart_vdagent(guest_session, test_timeout)[source]

Sending commands to restart the spice-vdagentd service

Parameters:
  • guest_session – ssh session of the VM
  • test_timeout – timeout time for the cmds
virttest.utils_spice.start_vdagent(guest_session, test_timeout)[source]

Sending commands to start the spice-vdagentd service

Parameters:
  • guest_session – ssh session of the VM
  • test_timeout – timeout time for the cmds
virttest.utils_spice.stop_vdagent(guest_session, test_timeout)[source]

Sending commands to stop the spice-vdagentd service

Parameters:
  • guest_session – ssh session of the VM
  • test_timeout – timeout time for the cmds
virttest.utils_spice.verify_established(client_vm, host, port, rv_binary, tls_port=None, secure_channels=None)[source]

Parses netstat output for established connection on host:port :param client_session - vm.wait_for_login() :param host - host ip addr :param port - port for client to connect :param rv_binary - remote-viewer binary

virttest.utils_spice.verify_vdagent(guest_session, test_timeout)[source]

Verifying vdagent is installed on a VM

Parameters:
  • guest_session – ssh session of the VM
  • test_timeout – timeout time for the cmds
virttest.utils_spice.verify_virtio(guest_session, test_timeout)[source]

Verify Virtio linux driver is properly loaded.

Parameters:
  • guest_session – ssh session of the VM
  • test_timeout – timeout time for the cmds
virttest.utils_spice.wait_timeout(timeout=10)[source]

time.sleep(timeout) + logging.debug(timeout)

:param timeout=10

virttest.utils_v2v module

Virt-v2v test utility functions.

copyright:2008-2012 Red Hat Inc.
class virttest.utils_v2v.LinuxVMCheck(test, params, env)[source]

Bases: virttest.utils_v2v.VMCheck

This class handles all basic linux VM check operations.

get_grub_device(dev_map='/boot/grub2/device.map')[source]

Check whether vd[a-z] device is in device map.

get_vm_kernel()[source]

Get vm kernel info.

get_vm_modprobe_conf()[source]

Get /etc/modprobe.conf content.

get_vm_modules()[source]

Get vm modules list.

get_vm_os_info()[source]

Get vm os info.

get_vm_os_vendor()[source]

Get vm os vendor.

get_vm_parted()[source]

Get vm parted info.

get_vm_pci_list()[source]

Get vm pci list.

get_vm_rc_local()[source]

Get vm /etc/rc.local output.

get_vm_tty()[source]

Get vm tty config.

get_vm_video()[source]

Get vm video config.

has_vmware_tools()[source]

Check vmware tools.

is_disk_virtio(disk='/dev/vda')[source]

Check whether disk is virtio.

is_net_virtio()[source]

Check whether vm’s interface is virtio

class virttest.utils_v2v.Target(target, uri)[source]

Bases: object

This class is used for generating command options.

get_cmd_options(params)[source]

Target dispatcher.

class virttest.utils_v2v.Uri(hypervisor)[source]

Bases: object

This class is used for generating uri.

get_uri(hostname, vpx_dc=None, esx_ip=None)[source]

Uri dispatcher.

Parameters:hostname – String with host name.
class virttest.utils_v2v.VMCheck(test, params, env)[source]

Bases: object

This is VM check class dispatcher.

cleanup()[source]

Cleanup VM and remove all of storage files about guest

create_session(timeout=480)[source]
storage_cleanup()[source]

Cleanup storage pool and volume

class virttest.utils_v2v.WindowsVMCheck(test, params, env)[source]

Bases: virttest.utils_v2v.VMCheck

This class handles all basic Windows VM check operations.

click_install_driver()[source]

Move mouse and click button to install dirver for new device(Ethernet controller)

click_left_button()[source]

Click left button of VM mouse.

click_tab_enter()[source]

Send TAB and ENTER to VM.

copy_windows_file()[source]

Copy a widnows file

delete_windows_file()[source]

Delete a widnows file

get_driver_info(signed=True)[source]

Get windows signed driver info.

get_network_restart()[source]

Get windows network restart.

get_screenshot()[source]

Do virsh screenshot of the vm and fetch the image if the VM in remote host.

get_viostor_info()[source]

Get viostor info.

get_windows_event_info()[source]

Get windows event log info about WSH.

move_mouse(coordinate)[source]

Move VM mouse.

reboot_windows()[source]

Reboot Windows immediately

send_win32_key(keycode)[source]

Send key to Windows VM

wait_for_match(images, similar_degree=0.98, timeout=300)[source]

Compare VM screenshot with given images, if any image in the list matched, then return the image index, or return -1.

virttest.utils_v2v.import_vm_to_ovirt(params, address_cache, timeout=600)[source]

Import VM from export domain to oVirt Data Center

virttest.utils_v2v.v2v_cmd(params)[source]

Append ‘virt-v2v’ and execute it.

Parameters:params – A dictionary includes all of required parameters such as ‘target’, ‘hypervisor’ and ‘hostname’, etc.
Returns:A CmdResult object

virttest.utils_virtio_port module

class virttest.utils_virtio_port.VirtioPortTest(test, env, params)[source]

Bases: object

static cleanup(*args, **kwargs)

Cleanup function.

Parameters:
  • vm – VM whose ports should be cleaned
  • guest_worker – guest_worker which should be cleaned/exited
get_virtio_ports(*args, **kwargs)

Returns separated virtconsoles and virtserialports

Parameters:vm – VM object
Returns:tuple (all virtconsoles, all virtserialports)
get_vm_with_ports(*args, **kwargs)

Checks whether existing ‘main_vm’ fits the requirements, modifies it if needed and returns the VM object.

Parameters:
  • no_console – Number of desired virtconsoles.
  • no_serialport – Number of desired virtserialports.
  • spread – Spread consoles across multiple virtio-serial-pcis.
  • quiet – Notify user about VM recreation.
  • strict – Whether no_consoles have to match or just exceed.
Returns:

vm object matching the requirements.

get_vm_with_single_port(*args, **kwargs)

Wrapper which returns vm, guest_worker and virtio_ports with at lest one port of the type specified by fction parameter.

Parameters:port_type – type of the desired virtio port.
Returns:tuple (vm object with at least 1 port of the port_type, initialized GuestWorker of the vm, list of virtio_ports of the port_type type)
get_vm_with_worker(*args, **kwargs)

Checks whether existing ‘main_vm’ fits the requirements, modifies it if needed and returns the VM object and guest_worker.

Parameters:
  • no_console – Number of desired virtconsoles.
  • no_serialport – Number of desired virtserialports.
  • spread – Spread consoles across multiple virtio-serial-pcis.
  • quiet – Notify user about VM recreation.
  • strict – Whether no_consoles have to match or just exceed.
Returns:

tuple (vm object matching the requirements, initialized GuestWorker of the vm)

virttest.version module

Based on work from Douglas Creager <dcreager@dcreager.net>

Gets the current version number. If possible, this is the output of “git describe”, modified to conform to the versioning scheme that setuptools uses. If “git describe” returns an error (most likely because we’re in an unpacked copy of a release tarball, rather than in a git working copy), then we fall back on reading the contents of the RELEASE-VERSION file.

virttest.version.get_git_version(abbrev=4)[source]
virttest.version.get_version(abbrev=4)[source]
virttest.version.get_top_commit()[source]
virttest.version.get_current_branch()[source]
virttest.version.get_pretty_version_info()[source]

virttest.versionable_class module

class virttest.versionable_class.Manager(name, wrapper=None)[source]

Bases: object

factory(_class, *args, **kargs)[source]

Create new class with right version of subclasses.

Goes through class structure and search subclasses with right version.

Parameters:
  • _class (class.) – Class which should be prepared.
  • args – Params for _is_right_ver function.
Params kargs:

Params for _is_right_ver function.

getcls(cls, orig_class)[source]

Return class correspond class and original class.

Parameters:
  • cls (class) – class for which should be found derived alternative.
  • orig_class (class) – Original class
Returns:

Derived alternative class

Return type:

class

class virttest.versionable_class.ModuleWrapper(wrapped)[source]

Bases: object

Wrapper around module.

Necessary for pickling of dynamic class.

class virttest.versionable_class.VersionableClass[source]

Bases: object

Class used for marking of mutable class.

virttest.versionable_class.factory(orig_cls, *args, **kargs)[source]

Create class with specific version.

Parameters:
  • orig_class – Class from which should be derived good version.
  • args – list of parameters for _ir_right_ver
Params kargs:

dict of named parameters for _ir_right_ver

Returns:

params specific class.

Return type:

class

virttest.versionable_class.isclass(obj)[source]
Parameters:obj – Object for inspection if obj is class.
Returns:true if the object is a class.

virttest.versionable_class_unittest module

Wrapper around module.

Necessary for pickling of dynamic class.

class virttest.versionable_class_unittest.AA[source]

Bases: virttest.versionable_class_unittest.Sys_Container, virttest.versionable_class_unittest.BB, virttest.versionable_class_unittest.System_Container

class virttest.versionable_class_unittest.BB[source]

Bases: virttest.versionable_class_unittest.VM_container

func1()[source]
func2()[source]
test_class_bb = None
class virttest.versionable_class_unittest.Q(*args, **kargs)[source]

Bases: object

class virttest.versionable_class_unittest.Q1(*args, **kargs)[source]

Bases: virttest.versionable_class_unittest.Q

class virttest.versionable_class_unittest.Q_Container[source]

Bases: virttest.versionable_class.VersionableClass

class virttest.versionable_class_unittest.Sys(*args, **kargs)[source]

Bases: virttest.versionable_class_unittest.Q_Container

class virttest.versionable_class_unittest.Sys1(*args, **kargs)[source]

Bases: virttest.versionable_class_unittest.Sys

class virttest.versionable_class_unittest.Sys_Container[source]

Bases: virttest.versionable_class.VersionableClass

class virttest.versionable_class_unittest.System(*args, **kargs)[source]

Bases: object

class virttest.versionable_class_unittest.System1(*args, **kargs)[source]

Bases: virttest.versionable_class_unittest.System

class virttest.versionable_class_unittest.System_Container[source]

Bases: virttest.versionable_class.VersionableClass

class virttest.versionable_class_unittest.TestVersionableClass(methodName='runTest')[source]

Bases: unittest.case.TestCase

setUp()[source]
tearDown()[source]
test_complicated_multiple_create_params()[source]
test_complicated_versioning()[source]
test_pickleing()[source]

Test pickling for example save vm env.

test_sharing_data_in_same_version()[source]
test_simple_create_by_params_v0()[source]
test_simple_create_by_params_v1()[source]
test_simple_versioning()[source]
class virttest.versionable_class_unittest.VM(*args, **kargs)[source]

Bases: object

func1()[source]
func3()[source]
test_class_vm1 = None
class virttest.versionable_class_unittest.VM1(*args, **kargs)[source]

Bases: virttest.versionable_class_unittest.VM

func1()[source]
func2()[source]
func3()[source]
class virttest.versionable_class_unittest.VM_container[source]

Bases: virttest.versionable_class.VersionableClass

virttest.versionable_class_unittest.qemu_verison()[source]
virttest.versionable_class_unittest.system_version()[source]

virttest.video_maker module

Video Maker transforms screenshots taken during a test into a HTML 5 compatible video, so that one can watch the screen activity of the whole test from inside your own browser.

This relies on generally available multimedia libraries, frameworks and tools.

class virttest.video_maker.GstPythonVideoMaker(verbose=False)[source]

Bases: object

Makes a movie out of screendump images using gstreamer-python

CONTAINER_ENCODER_MAPPING = {'ogg': 'theora', 'webm': 'vp8'}
CONTAINER_MAPPING = {'ogg': 'oggmux', 'webm': 'webmmux'}
ENCODER_MAPPING = {'theora': 'theoraenc', 'vp8': 'vp8enc'}
get_container_name()[source]

Gets the video container available that is the best based on preference

get_element(name)[source]

Makes and returns and element from the gst factory interface

get_encoder_name()[source]

Gets the video encoder available that is the best based on preference

get_most_common_image_size(input_dir)[source]

Find the most common image size

has_element(kind)[source]

Returns True if a gstreamer element is available

normalize_images(input_dir)[source]

GStreamer requires all images to be the same size, so we do it here

start(input_dir, output_file)[source]

Process the input files and output the video file

virttest.video_maker.video_maker(input_dir, output_file)[source]

Instantiates and runs a video maker

virttest.virsh module

Utility classes and functions to handle connection to a libvirt host system

The entire contents of callables in this module (minus the names defined in NOCLOSE below), will become methods of the Virsh and VirshPersistent classes. A Closure class is used to wrap the module functions, lambda does not properly store instance state in this implementation.

Because none of the methods have a ‘self’ parameter defined, the classes are defined to be dict-like, and get passed in to the methods as a the special **dargs parameter. All virsh module functions _MUST_ include a special **dargs (variable keyword arguments) to accept non-default keyword arguments.

The standard set of keyword arguments to all functions/modules is declared in the VirshBase class. Only the ‘virsh_exec’ key is guaranteed to always be present, the remainder may or may not be provided. Therefor, virsh functions/methods should use the dict.get() method to retrieve with a default for non-existant keys.

copyright:2012 Red Hat Inc.
class virttest.virsh.Virsh(*args, **dargs)[source]

Bases: virttest.virsh.VirshBase

Execute libvirt operations, using a new virsh shell each time.

class virttest.virsh.VirshBase(*args, **dargs)[source]

Bases: virttest.propcan.PropCanBase

Base Class storing libvirt Connection & state to a host

debug
get_uri()[source]

Accessor method for ‘uri’ property that must exist

ignore_status
readonly
uri
virsh_exec
class virttest.virsh.VirshClosure(reference_function, dict_like_instance)[source]

Bases: object

Callable with weak ref. to override **dargs when calling reference_function

class virttest.virsh.VirshConnectBack(*args, **dargs)[source]

Bases: virttest.virsh.VirshPersistent

Persistent virsh session connected back from a remote host

static kosher_args(remote_ip, uri)[source]

Convenience static method to help validate argument sanity before use

Parameters:
  • remote_ip – ip/hostname of remote libvirt helper-system
  • uri – fully qualified libvirt uri of local system, from remote.
Returns:

True/False if checks pass or not

new_session()[source]

Open new remote session, closing any existing

remote_ip
class virttest.virsh.VirshPersistent(*args, **dargs)[source]

Bases: virttest.virsh.Virsh

Execute libvirt operations using persistent virsh session.

COUNTERS = {}
close_session()[source]

If a persistent session exists, close it down.

counter_decrease()[source]

Method to decrease the counter to self.a_id in COUNTERS. If the counter is less than 1, it means there is no more VirshSession instance referring to the session. So close this session, and return True. Else, decrease the counter in COUNTERS and return False.

counter_increase()[source]

Method to increase the counter to self.a_id in COUNTERS.

new_session()[source]

Open new session, closing any existing

readonly
remote_ip
remote_pwd
remote_user
session_id
set_uri(uri)[source]

Accessor method for ‘uri’ property, create new session on change

ssh_remote_auth
unprivileged_user
uri
class virttest.virsh.VirshSession(virsh_exec=None, uri=None, a_id=None, prompt='virsh\s*[\#\>]\s*', remote_ip=None, remote_user=None, remote_pwd=None, ssh_remote_auth=False, readonly=False, unprivileged_user=None, auto_close=False, check_libvirtd=True)[source]

Bases: virttest.aexpect.ShellSession

A virsh shell session, used with Virsh instances.

ERROR_REGEX_LIST = ['error:\\s*.+$', '.*failed.*']
cmd_result(cmd, ignore_status=False, debug=False, timeout=60)[source]

Mimic utils.run()

cmd_status_output(cmd, timeout=60, internal_timeout=None, print_func=None)[source]

Send a virsh command and return its exit status and output.

Parameters:
  • cmd – virsh command to send (must not contain newline characters)
  • timeout – The duration (in seconds) to wait for the prompt to return
  • internal_timeout – The timeout to pass to read_nonblocking
  • print_func – A function to be used to print the data being read (should take a string parameter)
Returns:

A tuple (status, output) where status is the exit status and output is the output of cmd

Raises:
  • ShellTimeoutError – Raised if timeout expires
  • ShellProcessTerminatedError – Raised if the shell process terminates while waiting for output
  • ShellStatusError – Raised if the exit status cannot be obtained
  • ShellError – Raised if an unknown error occurs
read_until_output_matches(patterns, filter_func=<function <lambda>>, timeout=60, internal_timeout=None, print_func=None, match_func=None)[source]

Read from child using read_nonblocking until a pattern matches.

Read using read_nonblocking until a match is found using match_patterns, or until timeout expires. Before attempting to search for a match, the data is filtered using the filter_func function provided.

Parameters:
  • patterns – List of strings (regular expression patterns)
  • filter_func – Function to apply to the data read from the child before attempting to match it against the patterns (should take and return a string)
  • timeout – The duration (in seconds) to wait until a match is found
  • internal_timeout – The timeout to pass to read_nonblocking
  • print_func – A function to be used to print the data being read (should take a string parameter)
  • match_func – Function to compare the output and patterns.
Returns:

Tuple containing the match index and the data read so far

Raises:
  • ExpectTimeoutError – Raised if timeout expires
  • ExpectProcessTerminatedError – Raised if the child process terminates while waiting for output
  • ExpectError – Raised if an unknown error occurs
virttest.virsh.attach_device(domainarg=None, filearg=None, domain_opt=None, file_opt=None, flagstr=None, **dargs)[source]

Attach a device using full parameter/argument set.

Parameters:
  • domainarg – Domain name (first pos. parameter)
  • filearg – File name (second pos. parameter)
  • domain_opt – Option to –domain parameter
  • file_opt – Option to –file parameter
  • flagstr – string of “–force, –persistent, etc.”
  • dargs – standardized virsh function API keywords
Returns:

CmdResult instance

virttest.virsh.attach_disk(name, source, target, extra='', **dargs)[source]

Attach a disk to VM.

Parameters:
  • name – name of guest
  • source – source of disk device
  • target – target of disk device
  • extra – additional arguments to command
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.attach_interface(name, option='', **dargs)[source]

Attach a NIC to VM.

Parameters:
  • name – name of guest
  • option – options to pass to command
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.autostart(name, options, **dargs)[source]

Autostart a domain

Returns:cmdresult object.
virttest.virsh.blkdeviotune(name, device=None, options=None, total_bytes_sec=None, read_bytes_sec=None, write_bytes_sec=None, total_iops_sec=None, read_iops_sec=None, write_iops_sec=None, **dargs)[source]

Set or get a domain’s blkio parameters :param name: name of domain :param options: options may be live, config and current :param dargs: standardized virsh function API keywords :return: CmdResult instance

virttest.virsh.blkiotune(name, weight=None, device_weights=None, options=None, **dargs)[source]

Set or get a domain’s blkio parameters :param name: name of domain :param options: options may be live, config and current :param dargs: standardized virsh function API keywords :return: CmdResult instance

virttest.virsh.blockcommit(name, path, options='', **dargs)[source]

Start a block commit operation.

Parameters:
  • name – name of domain
  • options – options of blockcommit
  • dargs – standardized virsh function API keywords
Returns:

CmdResult instance

virttest.virsh.blockcopy(name, path, dest, options='', **dargs)[source]

Start a block copy operation.

Parameters:
  • name – name of domain.
  • path – fully-qualified path or target of disk.
  • dest – path of the copy to create.
  • options – options of blockcopy.
  • dargs – standardized virsh function API keywords.
Returns:

CmdResult instance.

virttest.virsh.blockjob(name, path, options='', **dargs)[source]

Manage active block operations.

Parameters:
  • name – name of domain.
  • path – fully-qualified path or target of disk.
  • options – options of blockjob.
  • dargs – standardized virsh function API keywords.
Returns:

CmdResult instance.

virttest.virsh.blockpull(name, path, options='', **dargs)[source]

Start a block pull operation.

Parameters:
  • name – name of domain
  • options – options of blockpull
  • dargs – standardized virsh function API keywords
Returns:

CmdResult instance

virttest.virsh.blockresize(name, path, size, **dargs)[source]

Resize block device of domain.

Parameters:
  • name – name of domain
  • path – path of block device
  • dargs – standardized virsh function API keywords
Size:

new size of the block device

Returns:

CmdResult instance

virttest.virsh.canonical_uri(option='', **dargs)[source]

Return the hypervisor canonical URI.

Parameters:
  • option – additional option string to pass
  • dargs – standardized virsh function API keywords
Returns:

standard output from command

virttest.virsh.capabilities(option='', to_file=None, **dargs)[source]

Return output from virsh capabilities command

Parameters:
  • option – additional options (takes none)
  • dargs – standardized virsh function API keywords
virttest.virsh.cd(dir_path, options='', **dargs)[source]

Run cd command in virsh interactive session.

Parameters:
  • dir_path – dir path string
  • options – extra options
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.change_media(name, device, options, **dargs)[source]

Change media of CD or floppy drive.

Parameters:
  • name – VM’s name.
  • path – Fully-qualified path or target of disk device
  • options – command change_media options.
  • dargs – standardized virsh function API keywords
Returns:

CmdResult instance

virttest.virsh.click_button(name, left_button=True, **dargs)[source]

Click left/right button of VM mouse.

Parameters:
  • name – domain name
  • left_button – Click left or right button
virttest.virsh.command(cmd, **dargs)[source]

Interface to cmd function as ‘cmd’ symbol is polluted.

Parameters:
  • cmd – Command line to append to virsh command
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

Raise:

CmdError if non-zero exit status and ignore_status=False

virttest.virsh.connect(connect_uri='', options='', **dargs)[source]

Run a connect command to the uri.

Parameters:
  • connect_uri – target uri connect to.
  • options – options to pass to connect command
Returns:

CmdResult object.

virttest.virsh.cpu_baseline(xml_file, **dargs)[source]

Compute baseline CPU for a set of given CPUs.

Parameters:
  • xml_file – file containing an XML CPU description.
  • dargs – standardized virsh function API keywords
Returns:

CmdResult instance

virttest.virsh.cpu_compare(xml_file, **dargs)[source]

Compare host CPU with a CPU described by an XML file

Parameters:
  • xml_file – file containing an XML CPU description.
  • dargs – standardized virsh function API keywords
Returns:

CmdResult instance

virttest.virsh.cpu_models(arch, options='', **dargs)[source]

Get the CPU models for an arch.

Parameters:
  • arch – Architecture
  • options – Extra options
  • dargs – Standardized virsh function API keywords
Returns:

CmdResult instance

virttest.virsh.cpu_stats(name, options, **dargs)[source]

Display per-CPU and total statistics about domain’s CPUs

Parameters:
  • name – name of domain
  • options – options of cpu_stats
  • dargs – standardized virsh function API keywords
Returns:

CmdResult instance

virttest.virsh.create(xmlfile, options='', **dargs)[source]

Create guest from xml

Parameters:
  • xmlfile – domain xml file
  • options – –paused
Returns:

CmdResult object

virttest.virsh.define(xml_path, **dargs)[source]

Return cmd result of domain define.

Parameters:
  • xml_path – XML file path
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.desc(name, options, desc_str, **dargs)[source]

Show or modify description or title of a domain.

Parameters:
  • name – name of domain.
  • options – options for desc command.
  • desc_str – new desc message.
  • dargs – standardized virsh function API keywords.
Returns:

CmdResult object.

virttest.virsh.destroy(name, options='', **dargs)[source]

True on successful domain destruction

Parameters:
  • name – VM name
  • options – options for virsh destroy
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.detach_device(domainarg=None, filearg=None, domain_opt=None, file_opt=None, flagstr=None, **dargs)[source]

Detach a device using full parameter/argument set.

Parameters:
  • domainarg – Domain name (first pos. parameter)
  • filearg – File name (second pos. parameter)
  • domain_opt – Option to –domain parameter
  • file_opt – Option to –file parameter
  • flagstr – string of “–force, –persistent, etc.”
  • dargs – standardized virsh function API keywords
Returns:

CmdResult instance

virttest.virsh.detach_disk(name, target, extra='', **dargs)[source]

Detach a disk from VM.

Parameters:
  • name – name of guest
  • target – target of disk device
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.detach_interface(name, option='', **dargs)[source]

Detach a NIC to VM.

Parameters:
  • name – name of guest
  • option – options to pass to command
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.dom_list(options='', **dargs)[source]

Return the list of domains.

Parameters:options – options to pass to list command
Returns:CmdResult object
virttest.virsh.domain_exists(name, **dargs)[source]

Return True if a domain exits.

Parameters:
  • name – VM name
  • dargs – standardized virsh function API keywords
Returns:

True operation was successful

virttest.virsh.domblkerror(name, **dargs)[source]

Show errors on block devices

Parameters:name – name of domain
Returns:CmdResult object
virttest.virsh.domblkinfo(name, device, **dargs)[source]

Get block device size info for a domain.

Parameters:
  • name – VM’s name or id,uuid.
  • device – device of VM.
  • dargs – standardized virsh function API keywords.
Returns:

CmdResult object.

virttest.virsh.domblklist(name, options=None, **dargs)[source]

Get domain devices.

Parameters:
  • name – name of domain
  • options – options of domblklist.
  • dargs – standardized virsh function API keywords
Returns:

CmdResult instance

virttest.virsh.domblkstat(name, device, option, **dargs)[source]

Store state of VM into named file.

Parameters:
  • name – VM’s name.
  • device – VM’s device.
  • option – command domblkstat option.
  • dargs – standardized virsh function API keywords
Returns:

CmdResult instance

virttest.virsh.domcapabilities(virttype=None, emulatorbin=None, arch=None, machine=None, options='', **dargs)[source]

Capabilities of emulator with respect to host and libvirt

Parameters:
  • virttype – Virtualization type (/domain/@type)
  • emulatorbin – Path to emulator binary (/domain/devices/emulator)
  • arch – Domain architecture (/domain/os/type/@arch)
  • machine – machine type (/domain/os/type/@machine)
  • options – Extra options
  • dargs – Standardized virsh function API keywords
Returns:

CmdResult instance

virttest.virsh.domcontrol(name, options='', **dargs)[source]

Return domain control interface state.

Parameters:
  • name – name of domain
  • options – extra options
Returns:

CmdResult object

virttest.virsh.domdisplay(name, options='', **dargs)[source]

Get domain display connection URI

Parameters:
  • name – name of domain
  • options – options of domdisplay
Returns:

CmdResult object

virttest.virsh.domfsfreeze(name, mountpoint=None, options='', **dargs)[source]

Freeze domain’s mounted filesystems

Parameters:
  • name – name of domain
  • mountpoint – specific mountpoints to be frozen
  • options – extra options to domfsfreeze cmd.
Returns:

CmdResult object

virttest.virsh.domfsthaw(name, mountpoint=None, options='', **dargs)[source]

Thaw domain’s mounted filesystems

Parameters:
  • name – name of domain
  • mountpoint – specific mountpoints to be thawed
  • options – extra options to domfsfreeze cmd.
Returns:

CmdResult object

virttest.virsh.domfstrim(name, minimum=None, mountpoint=None, options='', **dargs)[source]

Do fstrim on domain’s mounted filesystems

Parameters:
  • name – name of domain
  • options – options maybe –minimum <number>, –mountpoint <string>
Returns:

CmdResult object

virttest.virsh.domid(name_or_uuid, **dargs)[source]

Return VM’s ID.

Parameters:
  • name_or_uuid – VM name or uuid
  • dargs – standardized virsh function API keywords
Returns:

CmdResult instance

Get network interface stats for a running domain.

Parameters:
  • name – Name of domain
  • interface – interface device
  • options – command options.
  • dargs – standardized virsh function API keywords
Returns:

domif state

Set network interface stats for a running domain.

Parameters:
  • name – Name of domain
  • interface – interface device
  • state – new state of the device up or down
  • options – command options.
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.domiflist(name, options='', extra='', **dargs)[source]

Get the domain network devices

Parameters:
  • name – name of domain
  • options – options of domiflist
  • dargs – standardized virsh function API keywords
Returns:

CmdResult instance

virttest.virsh.domifstat(name, interface, **dargs)[source]

Get network interface stats for a running domain.

Parameters:
  • name – Name of domain
  • interface – interface device
Returns:

CmdResult object

virttest.virsh.domiftune(name, interface, options=None, inbound=None, outbound=None, **dargs)[source]

Set/get parameters of a virtual interface.

Parameters:
  • name – name of domain.
  • interface – interface device (MAC Address).
  • inbound – control domain’s incoming traffics.
  • outbound – control domain’s outgoing traffics.
  • options – options may be live, config and current.
  • dargs – standardized virsh function API keywords.
Returns:

CmdResult instance.

virttest.virsh.dominfo(name, **dargs)[source]

Return the VM information.

Parameters:
  • name – VM’s name or id,uuid.
  • dargs – standardized virsh function API keywords
Returns:

CmdResult instance

virttest.virsh.domjobabort(name, **dargs)[source]

Aborts the currently running domain job.

Parameters:
  • name – VM’s name, id or uuid.
  • dargs – standardized virsh function API keywords
Returns:

result from command

virttest.virsh.domjobinfo(name, **dargs)[source]

Get domain job information.

Parameters:
  • name – VM name
  • dargs – standardized virsh function API keywords
Returns:

CmdResult instance

virttest.virsh.dommemstat(name, extra='', **dargs)[source]

Store state of VM into named file.

Parameters:
  • name – VM name
  • extra – extra options to pass to command
  • dargs – standardized virsh function API keywords
Returns:

CmdResult instance

virttest.virsh.domname(dom_id_or_uuid, **dargs)[source]

Convert a domain id or UUID to domain name

Parameters:
  • dom_id_or_uuid – a domain id or UUID.
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.dompmsuspend(name, target, duration=0, **dargs)[source]

Suspends a running domain using guest OS’s power management.

Parameters:
  • name – VM name
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.dompmwakeup(name, **dargs)[source]
Wakeup a domain that was previously suspended by power management.
Parameters:
  • name – VM name
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.domstate(name, extra='', **dargs)[source]

Return the state about a running domain.

Parameters:
  • name – VM name
  • extra – command options
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.domstats(domains='', options='', **dargs)[source]

Get statistics about one or multiple domains

Parameters:
  • domains – List of domains
  • options – Extra options
  • dargs – Standardized virsh function API keywords
Returns:

CmdResult instance

virttest.virsh.domtime(name, now=False, pretty=False, sync=False, time=None, options='', **dargs)[source]

Get/Set domain’s time

Parameters:
  • name – name of domain
  • now – set to the time of the host running virsh
  • pretty – print domain’s time in human readable form
  • sync – instead of setting given time, synchronize from domain’s RTC
  • time – integer time to set
Returns:

CmdResult object

virttest.virsh.domuuid(name_or_id, **dargs)[source]

Return the Converted domain name or id to the domain UUID.

Parameters:
  • name_or_id – VM name or id
  • dargs – standardized virsh function API keywords
Returns:

CmdResult instance

virttest.virsh.domxml_from_native(info_format, native_file, options=None, **dargs)[source]

Convert native guest configuration format to domain XML format.

:param info_format:The command’s options. For exmple:qemu-argv. :param native_file:Native information file. :param options:extra param. :param dargs: standardized virsh function API keywords. :return: result from command

virttest.virsh.domxml_to_native(info_format, xml_file, options, **dargs)[source]

Convert domain XML config to a native guest configuration format.

:param info_format:The command’s options. For exmple:qemu-argv. :param xml_file:XML config file. :param options:extra param. :param dargs: standardized virsh function API keywords :return: result from command

virttest.virsh.driver(**dargs)[source]

Return the driver by asking libvirt

Parameters:dargs – standardized virsh function API keywords
Returns:VM driver name
virttest.virsh.dump(name, path, option='', **dargs)[source]

Dump the core of a domain to a file for analysis.

Parameters:
  • name – VM name
  • path – absolute path to state file
  • option – command’s option.
  • dargs – standardized virsh function API keywords
Returns:

CmdResult instance

virttest.virsh.dumpxml(name, extra='', to_file='', **dargs)[source]

Return the domain information as an XML dump.

Parameters:
  • name – VM name
  • to_file – optional file to write XML output to
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object.

virttest.virsh.echo(echo_str, options='', **dargs)[source]

Run echo command in virsh session.

Parameters:
  • echo_str – the echo string
  • options – extra options
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.edit(options, **dargs)[source]

Edit the XML configuration for a domain.

Parameters:
  • options – virsh edit options string.
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.emulatorpin(name, cpulist=None, options=None, **dargs)[source]

Control or query domain emulator affinity :param name: name of domain :param cpulist: a list of physical CPU numbers :param options: options may be live, config and current :param dargs: standardized virsh function API keywords :return: CmdResult instance

virttest.virsh.event(domain=None, event=None, event_timeout=None, options='', **dargs)[source]

List event types, or wait for domain events to occur

Parameters:
  • domain – Domain name, id or UUID
  • event – Event type name
  • event_timeout – Timeout seconds
  • options – Extra options
  • dargs – Standardized virsh function API keywords
Returns:

CmdResult instance

virttest.virsh.exit(**dargs)[source]

Run exit command in virsh session.

Parameters:dargs – standardized virsh function API keywords
Returns:CmdResult object
virttest.virsh.find_storage_pool_sources(source_type, srcSpec, **dargs)[source]

Find potential storage pool sources

Parameters:
  • source_type – type of storage pool sources to find
  • srcSpec – file of source xml to qurey for pools
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.find_storage_pool_sources_as(source_type, options='', **dargs)[source]

Find potential storage pool sources

Parameters:
  • source_type – type of storage pool sources to find
  • options – cmd options
  • dargs – standardized virsh function API keywords
Returns:

returns the output of the command

virttest.virsh.freecell(cellno=None, options='', **dargs)[source]

Prints the available amount of memory on the machine or within a NUMA cell.

Parameters:
  • cellno – number of cell to show.
  • options – extra argument string to pass to command
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.freepages(cellno=None, pagesize=None, options='', **dargs)[source]

Display available free pages for the NUMA cell

Parameters:
  • cellno – NUMA cell number
  • pagesize – Page size (in kibibytes)
  • options – Extra options
  • dargs – Standardized virsh function API keywords
Returns:

CmdResult instance

virttest.virsh.has_command_help_match(virsh_cmd, regex, **dargs)[source]

Regex search on subcommand help output

Parameters:
  • virsh_cmd – Name of virsh command or group to match help output
  • regex – regular expression string to match
  • dargs – standardized virsh function API keywords
Returns:

re match object

virttest.virsh.has_help_command(virsh_cmd, options='', **dargs)[source]

String match on virsh command in help output command list

Parameters:
  • virsh_cmd – Name of virsh command or group to look for
  • options – Additional options to send to help command
  • dargs – standardized virsh function API keywords
Returns:

True/False

virttest.virsh.help(virsh_cmd='', **dargs)[source]

Prints global help, command specific help, or help for a group of related commands

Parameters:
  • virsh_cmd – Name of virsh command or group
  • dargs – standardized virsh function API keywords
Returns:

CmdResult instance

virttest.virsh.help_command(options='', cache=False, **dargs)[source]

Return list of commands and groups in help command output

Parameters:
  • options – additional options to pass to help command
  • cache – Return cached result if True, or refreshed cache if False
  • dargs – standardized virsh function API keywords
Returns:

List of command and group names

virttest.virsh.help_command_group(options='', cache=False, **dargs)[source]

Return list of groups in help command output

Parameters:
  • options – additional options to pass to help command
  • cache – Return cached result if True, or refreshed cache if False
  • dargs – standardized virsh function API keywords
Returns:

List of group names

virttest.virsh.help_command_only(options='', cache=False, **dargs)[source]

Return list of commands in help command output

Parameters:
  • options – additional options to pass to help command
  • cache – Return cached result if True, or refreshed cache if False
  • dargs – standardized virsh function API keywords
Returns:

List of command names

virttest.virsh.hostname(option='', **dargs)[source]

Return the hypervisor hostname.

Parameters:
  • option – additional option string to pass
  • dargs – standardized virsh function API keywords
Returns:

standard output from command

virttest.virsh.iface_begin(**dargs)[source]

Create a snapshot of current interfaces settings

Param:dargs: standardized virsh function API keywords
Returns:CmdResult instance
virttest.virsh.iface_bridge(iface, bridge, extra='', **dargs)[source]

Create a bridge device and attach an existing network device to it.

Parameters:
  • iface – Interface name or MAC address
  • bridge – New bridge device name
  • extra – Free-form string of options
  • dargs – Standardized virsh functiont API keywords
Returns:

CmdResult object

virttest.virsh.iface_commit(**dargs)[source]

Commit changes made since iface-begin and free restore point

Param:dargs: standardized virsh function API keywords
Returns:CmdResult instance
virttest.virsh.iface_define(xml_path, **dargs)[source]

Define (but don’t start) a physical host interface from an XML file.

Parameters:
  • xml_path – XML file path
  • dargs – Standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.iface_destroy(iface, **dargs)[source]

Destroy a physical host interface.

Parameters:
  • iface – Interface name or MAC address
  • dargs – Standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.iface_dumpxml(iface, extra='', to_file='', **dargs)[source]

Interface information in XML.

Parameters:
  • iface – Interface name or MAC address
  • extra – Free-form string of options
  • to_file – Optional file to write xml
  • dargs – standardized virsh function API keywords
Returns:

standard output from command

virttest.virsh.iface_edit(iface, **dargs)[source]

Edit XML configuration for a physical host interface.

Parameters:
  • iface – Interface name or MAC address
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.iface_list(extra='', **dargs)[source]

List physical host interfaces.

Parameters:
  • extra – Free-form string of options
  • dargs – Standardized virsh functiont API keywords
Returns:

CmdResult object

virttest.virsh.iface_mac(name, **dargs)[source]

Convert an interface name to interface MAC address.

Parameters:
  • name – Interface name
  • dargs – Standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.iface_name(mac, **dargs)[source]

Convert an interface MAC address to interface name.

Parameters:
  • mac – Interface MAC address
  • dargs – Standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.iface_rollback(**dargs)[source]

Rollback to previous saved configuration created via iface-begin

Param:dargs: standardized virsh function API keywords
Returns:CmdResult instance
virttest.virsh.iface_start(iface, **dargs)[source]

Start a physical host interface.

Parameters:
  • iface – Interface name or MAC address
  • dargs – Standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.iface_unbridge(bridge, extra='', **dargs)[source]

Undefine a bridge device after detaching its slave device.

Parameters:
  • bridge – Current bridge device name
  • extra – Free-form string of options
  • dargs – Standardized virsh functiont API keywords
Returns:

CmdResult object

virttest.virsh.iface_undefine(iface, **dargs)[source]

Undefine a physical host interface (remove it from configuration).

Parameters:
  • iface – Interface name or MAC address
  • dargs – Standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.inject_nmi(name, options='', **dargs)[source]

Inject NMI to the guest

Parameters:
  • name – domain name
  • options – extra options
virttest.virsh.is_alive(name, **dargs)[source]

Return True if the domain is started/alive.

Parameters:
  • name – VM name
  • dargs – standardized virsh function API keywords
Returns:

True operation was successful

virttest.virsh.is_dead(name, **dargs)[source]

Return True if the domain is undefined or not started/dead.

Parameters:
  • name – VM name
  • dargs – standardized virsh function API keywords
Returns:

True operation was successful

virttest.virsh.managedsave(name, options='', **dargs)[source]

Managed save of a domain state.

Parameters:
  • name – Name of domain to save
  • options – options: options to pass to list command
Returns:

CmdResult object

virttest.virsh.managedsave_remove(name, **dargs)[source]

Remove managed save of a domain

Parameters:name – name of managed-saved domain to remove
Returns:CmdResult object
virttest.virsh.maxvcpus(option='', **dargs)[source]

Return the connection vcpu maximum number.

Param:option: additional option string to pass
Param:dargs: standardized virsh function API keywords
Returns:CmdResult object
virttest.virsh.memtune_get(name, key)[source]

Get the specific memory controller value

Parameters:
  • domname – VM Name
  • key – memory controller limit for which the value needed
Returns:

the memory value of a key in Kbs

virttest.virsh.memtune_list(name, **dargs)[source]

List the memory controller value of a given domain

Parameters:domname – VM Name
virttest.virsh.memtune_set(name, options, **dargs)[source]

Set the memory controller parameters

Parameters:
  • domname – VM Name
  • options – contains the values limit, state and value
virttest.virsh.metadata(name, uri, options='', key=None, new_metadata=None, **dargs)[source]

Show or set domain’s custom XML Metadata

Parameters:
  • name – Domain name, id or uuid
  • uri – URI of the namespace
  • options – options may be live, config and current
  • key – Key to be used as a namespace identifier
  • new_metadata – new metadata to set
  • dargs – standardized virsh function API keywords
Returns:

CmdResult instance

virttest.virsh.migrate(name='', dest_uri='', option='', extra='', **dargs)[source]

Migrate a guest to another host.

Parameters:
  • name – name of guest on uri.
  • dest_uri – libvirt uri to send guest to
  • option – Free-form string of options to virsh migrate
  • extra – Free-form string of options to follow <domain> <desturi>
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.migrate_compcache(domain, size=None, **dargs)[source]

Get/set compression cache size for migration.

Parameters:
  • domain – name/uuid/id of guest
  • size – compression cache size to be set.
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.migrate_getspeed(domain, **dargs)[source]

Get the maximum migration bandwidth (in MiB/s) for a domain.

Parameters:
  • domain – name/uuid/id of guest
  • dargs – standardized virsh function API keywords
Returns:

standard output from command

virttest.virsh.migrate_setmaxdowntime(domain, downtime, extra=None, **dargs)[source]

Set maximum tolerable downtime of a domain which is being live-migrated to another host.

Parameters:
  • domain – name/uuid/id of guest
  • downtime – downtime number of live migration
virttest.virsh.migrate_setspeed(domain, bandwidth, extra=None, **dargs)[source]

Set the maximum migration bandwidth (in MiB/s) for a domain which is being migrated to another host.

Parameters:
  • domain – name/uuid/id of guest
  • bandwidth – migration bandwidth limit in MiB/s
  • dargs – standardized virsh function API keywords
virttest.virsh.move_mouse(name, coordinate, **dargs)[source]

Move VM mouse.

Parameters:
  • name – domain name
  • coordinate – Mouse coordinate
virttest.virsh.net_autostart(network, extra='', **dargs)[source]

Set/unset a network to autostart on host boot

Parameters:
  • network – name/parameter for network option/argument
  • extra – extra parameters to pass to command (e.g. –disable)
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.net_create(xml_file, extra='', **dargs)[source]

Create _transient_ network from a XML file.

Parameters:
  • xml_file – xml defining network
  • extra – extra parameters to pass to command
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.net_define(xml_file, extra='', **dargs)[source]

Define network from a XML file, do not start

Parameters:
  • xml_file – xml defining network
  • extra – extra parameters to pass to command
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.net_destroy(network, extra='', **dargs)[source]

Destroy (stop) an activated network on host.

Parameters:
  • network – name/parameter for network option/argument
  • extra – extra string to pass to command
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.net_dhcp_leases(network, mac=None, options='', **dargs)[source]

Print lease info for a given network

Parameters:
  • network – Network name or uuid
  • mac – Mac address
  • options – Extra options
  • dargs – Standardized virsh function API keywords
Returns:

CmdResult instance

virttest.virsh.net_dumpxml(name, extra='', to_file='', **dargs)[source]

Dump XML from network named param name.

Parameters:
  • name – Name of a network
  • extra – Extra parameters to pass to command
  • to_file – Send result to a file
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.net_event(network=None, event=None, event_timeout=None, options='', **dargs)[source]

List event types, or wait for network events to occur

Parameters:
  • network – Network name or uuid
  • event – Event type to wait for
  • event_timeout – Timeout seconds
  • options – Extra options
  • dargs – Standardized virsh function API keywords
Returns:

CmdResult instance

virttest.virsh.net_info(network, extra='', **dargs)[source]

Get network information

Parameters:
  • network – name/parameter for network option/argument
  • extra – extra parameters to pass to command.
  • dargs – standardized virsh function API keywords
Returns:

CmdResult instance

virttest.virsh.net_list(options, extra='', **dargs)[source]

List networks on host.

Parameters:
  • options – options to pass to command
  • extra – extra parameters to pass to command
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.net_name(uuid, extra='', **dargs)[source]

Get network name on host.

Parameters:
  • uuid – network UUID.
  • extra – extra parameters to pass to command.
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.net_start(network, extra='', **dargs)[source]

Start network on host.

Parameters:
  • network – name/parameter for network option/argument
  • extra – extra parameters to pass to command
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.net_state_dict(only_names=False, virsh_instance=None, **dargs)[source]

Return network name to state/autostart/persistent mapping

Parameters:
  • only_names – When true, return network names as keys and None values
  • virsh_instance – Call net_list() on this instance instead of module
  • dargs – standardized virsh function API keywords
Returns:

dictionary

virttest.virsh.net_undefine(network, extra='', **dargs)[source]

Undefine a defined network on host.

Parameters:
  • network – name/parameter for network option/argument
  • extra – extra string to pass to command
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.net_update(network, update_cmd, section, xml, extra='', **dargs)[source]

Update parts of an existing network’s configuration

Parameters:
  • network – network name or uuid
  • update_cmd – type of update (add-first, add-last, delete, or modify)
  • section – which section of network configuration to update
  • xml – name of file containing xml
  • extra – extra parameters to pass to command.
  • dargs – standardized virsh function API keywords
Returns:

CmdResult instance

virttest.virsh.net_uuid(network, extra='', **dargs)[source]

Get network UUID on host.

Parameters:
  • network – name/parameter for network option/argument
  • extra – extra parameters to pass to command.
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.node_memtune(shm_pages_to_scan=None, shm_sleep_millisecs=None, shm_merge_across_nodes=None, options=None, **dargs)[source]

Get or set node memory parameters.

Parameters:
  • options – Extra options to virsh.
  • shm-pages-to-scan – Pages to scan.
  • shm-sleep-millisecs – Sleep time (ms).
  • shm-merge-across-nodes – Merge across nodes.
  • dargs – Standardized virsh function API keywords.
Returns:

CmdResult instance

virttest.virsh.nodecpumap(extra='', **dargs)[source]

Displays the node’s total number of CPUs, the number of online CPUs and the list of online CPUs.

Parameters:
  • extra – extra argument string to pass to command
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.nodecpustats(option='', **dargs)[source]

Returns basic information about the node CPU statistics

Parameters:
  • option – additional options (takes none)
  • dargs – standardized virsh function API keywords
virttest.virsh.nodedev_create(xml_file, options=None, **dargs)[source]

Return cmd result of the device to be created by an XML file

Parameters:
  • xml_file – device XML file
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.nodedev_destroy(dev_name, options=None, **dargs)[source]

Return cmd result of the device to be destroyed

Parameters:
  • dev_name – name of the device
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.nodedev_detach(name, options='', **dargs)[source]

Detach node device from host.

Returns:cmdresult object.
virttest.virsh.nodedev_dettach(name, options='', **dargs)[source]

Detach node device from host.

Returns:nodedev_detach(name).
virttest.virsh.nodedev_dumpxml(name, options='', to_file=None, **dargs)[source]

Do dumpxml for node device.

Parameters:
  • name – the name of device.
  • options – extra options to nodedev-dumpxml cmd.
  • to_file – optional file to write XML output to.
Returns:

Cmdobject of virsh nodedev-dumpxml.

virttest.virsh.nodedev_list(tree=False, cap='', options='', **dargs)[source]

List the node devices.

Parameters:
  • tree – list devices in a tree
  • cap – capability names, separated by comma
  • options – extra command options.
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object.

virttest.virsh.nodedev_reattach(name, options='', **dargs)[source]

If node device is detached, this action will reattach it to its device driver.

Returns:cmdresult object.
virttest.virsh.nodedev_reset(name, options='', **dargs)[source]

Trigger a device reset for device node.

Parameters:
  • name – device node name to be reset.
  • options – additional options passed to virsh command
  • dargs – standardized virsh function API keywords
Returns:

cmdresult object.

virttest.virsh.nodeinfo(extra='', **dargs)[source]

Returns basic information about the node,like number and type of CPU, and size of the physical memory.

Parameters:
  • extra – extra argument string to pass to command
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.nodememstats(option='', **dargs)[source]

Returns basic information about the node Memory statistics

Parameters:
  • option – additional options (takes none)
  • dargs – standardized virsh function API keywords
virttest.virsh.nodesuspend(target, duration, extra='', **dargs)[source]

Suspend the host node for a given time duration.

Parameters:
  • target – Suspend target mem/disk/hybrid. mem(Suspend-to-RAM) disk(Suspend-to-Disk) hybrid(Hybrid-Suspend)
  • duration – Suspend duration in seconds, at least 60.
  • extra – extra argument string to pass to command
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.numatune(name, mode=None, nodeset=None, options=None, **dargs)[source]

Set or get a domain’s numa parameters :param name: name of domain :param options: options may be live, config and current :param dargs: standardized virsh function API keywords :return: CmdResult instance

virttest.virsh.nwfilter_define(xml_file, options='', **dargs)[source]

Return cmd result of network filter define.

Parameters:
  • xml_file – network filter XML file
  • options – extra options to nwfilter-define cmd.
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.nwfilter_dumpxml(name, options='', to_file=None, **dargs)[source]

Do dumpxml for network filter.

Parameters:
  • name – the name or uuid of filter.
  • options – extra options to nwfilter-dumpxml cmd.
  • to_file – optional file to write XML output to.
  • dargs – standardized virsh function API keywords
Returns:

Cmdobject of virsh nwfilter-dumpxml.

virttest.virsh.nwfilter_edit(name, options='', **dargs)[source]

Edit the XML configuration for a network filter.

Parameters:
  • name – network filter name or uuid.
  • options – extra options to nwfilter-edit cmd.
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.nwfilter_list(options='', **dargs)[source]

Get list of network filters.

Parameters:
  • options – extra options
  • dargs – standardized virsh function API keywords
Returns:

list of network filters

virttest.virsh.nwfilter_undefine(name, options='', **dargs)[source]

Return cmd result of network filter undefine.

Parameters:
  • name – network filter name or uuid
  • options – extra options to nwfilter-undefine cmd.
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.pool_autostart(name, extra='', **dargs)[source]

Mark for autostart of a pool

Parameters:
  • name – Name of the pool to be mark for autostart
  • extra – Free-form string of options
  • dargs – standardized virsh function API keywords
Returns:

True if pool autostart command was successful

virttest.virsh.pool_build(name, options='', **dargs)[source]

Build pool.

Parameters:
  • name – Name of the pool to be built
  • options – options for pool-build
virttest.virsh.pool_create(xml_file, extra='', **dargs)[source]

Create a pool from an xml file.

Parameters:
  • xml_file – file containing an XML pool description
  • extra – extra parameters to pass to command
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.pool_create_as(name, pool_type, target, extra='', **dargs)[source]

Create a pool from a set of args.

Parameters:
  • name – name of pool
  • pool_type – storage pool type such as ‘dir’
  • target – libvirt uri to send guest to
  • extra – Free-form string of options
  • dargs – standardized virsh function API keywords
Returns:

True if pool creation command was successful

virttest.virsh.pool_define(xml_path, **dargs)[source]

To create the pool from xml file.

Parameters:
  • xml_path – XML file path
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.pool_define_as(name, pool_type, target='', extra='', **dargs)[source]

Define the pool from the arguments

Parameters:
  • name – Name of the pool to be defined
  • pool_type

    Type of the pool to be defined

    dir
    file system directory
    disk
    Physical Disk Device
    fs
    Pre-formatted Block Device
    netfs
    Network Exported Directory
    iscsi
    iSCSI Target
    logical
    LVM Volume Group
    mpath
    Multipath Device Enumerater
    scsi
    SCSI Host Adapter
    rbd
    Rados Block Device
  • target – libvirt uri to send guest to
  • extra – Free-form string of options
  • dargs – standardized virsh function API keywords
Returns:

True if pool define command was successful

virttest.virsh.pool_delete(name, **dargs)[source]

Delete the resources used by a given pool object

Parameters:
  • name – Name of the pool
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.pool_destroy(name, **dargs)[source]

Forcefully stop a given pool.

Parameters:
  • name – name of pool
  • dargs – standardized virsh function API keywords
virttest.virsh.pool_dumpxml(name, extra='', to_file='', **dargs)[source]

Return the pool information as an XML dump.

Parameters:
  • name – pool_name name
  • to_file – optional file to write XML output to
  • dargs – standardized virsh function API keywords
Returns:

standard output from command

virttest.virsh.pool_edit(name, **dargs)[source]

Edit XML configuration for a storage pool.

Parameters:
  • name – pool name or uuid
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.pool_info(name, **dargs)[source]

Returns basic information about the storage pool.

Parameters:
  • name – name of pool
  • dargs – standardized virsh function API keywords
virttest.virsh.pool_list(option='', extra='', **dargs)[source]

Prints the pool information of Host.

Parameters:option – options given to command
all
gives all pool details, including inactive
inactive
gives only inactive pool details
details
Gives the complete details about the pools
Parameters:extra – to provide extra options(to enter invalid options)
virttest.virsh.pool_name(uuid, **dargs)[source]

Convert a pool UUID to pool name

Parameters:
  • name – UUID of the pool
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.pool_refresh(name, **dargs)[source]

Refresh a pool

Parameters:
  • name – Name of the pool
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.pool_start(name, extra='', **dargs)[source]

Start the defined pool

Parameters:
  • name – Name of the pool to be started
  • extra – Free-form string of options
  • dargs – standardized virsh function API keywords
Returns:

True if pool start command was successful

virttest.virsh.pool_state_dict(only_names=False, **dargs)[source]

Return pool name to state/autostart mapping

Parameters:
  • only_names – When true, return pool names as keys and None values
  • dargs – standardized virsh function API keywords
Returns:

dictionary

virttest.virsh.pool_undefine(name, extra='', **dargs)[source]

Undefine the given pool

Parameters:
  • name – Name of the pool to be undefined
  • extra – Free-form string of options
  • dargs – standardized virsh function API keywords
Returns:

True if pool undefine command was successful

virttest.virsh.pool_uuid(name, **dargs)[source]

Convert a pool name to pool UUID

Parameters:
  • name – Name of the pool
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.pwd(options='', **dargs)[source]

Run pwd command in virsh session.

Parameters:
  • options – extra options
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.qemu_agent_command(name, cmd, options='', **dargs)[source]

This helps to execute the qemu agent command through virsh command.

Parameters:
  • name – Name of monitor domain
  • cmd – agent command to execute
  • options – extra options
  • dargs – standardized virsh function API keywords
virttest.virsh.qemu_attach(pid, extra='', **dargs)[source]

This helps to execute the qemu-attach command through virsh command.

Parameters:
  • pid – pid of qemu process
  • extra – extra options
  • dargs – standardized virsh function API keywords
virttest.virsh.qemu_monitor_command(name, cmd, options='', **dargs)[source]

This helps to execute the qemu monitor command through virsh command.

Parameters:
  • name – Name of monitor domain
  • cmd – monitor command to execute
  • options – extra options
  • dargs – standardized virsh function API keywords
virttest.virsh.qemu_monitor_event(domain=None, event=None, event_timeout=None, options='', **dargs)[source]

Listen for QEMU Monitor Events

Parameters:
  • domain – Domain name, id or UUID
  • event – Event type name
  • event_timeout – Timeout seconds
  • options – Extra options
  • dargs – Standardized virsh function API keywords
Returns:

CmdResult instance

virttest.virsh.quit(**dargs)[source]

Run quit command in virsh session.

Parameters:dargs – standardized virsh function API keywords
Returns:CmdResult object
virttest.virsh.reboot(name, options='', **dargs)[source]

Run a reboot command in the target domain.

Parameters:
  • name – Name of domain.
  • options – options: options to pass to reboot command
Returns:

CmdResult object

virttest.virsh.remove_domain(name, options=None, **dargs)[source]

Return True after forcefully removing a domain if it exists.

Parameters:
  • name – VM name
  • dargs – standardized virsh function API keywords
Returns:

True operation was successful

virttest.virsh.reset(name, **dargs)[source]

Reset a domain

Parameters:name – name of domain
Returns:CmdResult object
virttest.virsh.restore(path, options='', **dargs)[source]

Load state of VM from named file and remove file.

Parameters:
  • path – absolute path to state file.
  • options – options for virsh restore.
  • dargs – standardized virsh function API keywords
virttest.virsh.resume(name, **dargs)[source]

True on successful moving domain out of suspend

Parameters:
  • name – VM name
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.save(name, path, options='', **dargs)[source]

Store state of VM into named file.

Parameters:
  • name – VM’name, id or uuid.
  • path – absolute path to state file
  • options – command’s options.
  • dargs – standardized virsh function API keywords
Returns:

CmdResult instance

virttest.virsh.save_image_define(state_file, xmlfile, options='', **dargs)[source]

Redefine the XML for a domain’s saved state file

Parameters:
  • state_file – saved state file to modify
  • xmlfile – filename containing updated XML for the target
  • options – extra options
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.save_image_dumpxml(state_file, options='', to_file='', **dargs)[source]

Dump xml from saved state file

Parameters:
  • state_file – saved state file to read
  • options – extra options
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.schedinfo(domain, options='', **dargs)[source]

Show/Set scheduler parameters.

Parameters:
  • domain – vm’s name id or uuid.
  • options – additional options.
  • dargs – standardized virsh function API keywords
virttest.virsh.screenshot(name, filename, **dargs)[source]

Capture a screenshot of VM’s console and store it in file on host

Parameters:
  • name – VM name
  • filename – name of host file
  • dargs – standardized virsh function API keywords
Returns:

filename

virttest.virsh.screenshot_test(name, filename='', options='', **dargs)[source]

Capture a screenshot of VM’s console and store it in file on host

Parameters:
  • name – VM name or id
  • filename – name of host file
  • options – command options
  • dargs – standardized virsh function API keywords
Returns:

CmdResult instance

virttest.virsh.secret_define(xml_file, options=None, **dargs)[source]

Return cmd result of secret define.

Parameters:
  • xml_file – secret XML file
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.secret_dumpxml(uuid, to_file='', options=None, **dargs)[source]

Return the secret information as an XML dump.

Parameters:
  • uuid – secret UUID
  • to_file – optional file to write XML output to
  • dargs – standardized virsh function API keywords
Returns:

standard output from command

virttest.virsh.secret_get_value(uuid, options=None, **dargs)[source]

Get a secret value

Parameters:uuid – secret UUID
Returns:CmdResult object.
virttest.virsh.secret_list(options='', **dargs)[source]

Get list of secret.

Parameters:
  • options – the option may be ‘–ephemeral’
  • dargs – standardized virsh function API keywords
Returns:

list of secret

virttest.virsh.secret_set_value(uuid, base64, options=None, **dargs)[source]

Set a secret value

Parameters:
  • uuid – secret UUID
  • base64 – base64-encoded secret value
Returns:

CmdResult object.

virttest.virsh.secret_undefine(uuid, options=None, **dargs)[source]

Return cmd result of secret undefine.

Parameters:
  • uuid – secret UUID
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.sendkey(name, options='', **dargs)[source]

Send keycodes to the guest :param name: name of domain :param codeset: the codeset of keycodes :param keycode: the key code :return: CmdResult object

virttest.virsh.setmaxmem(domainarg=None, sizearg=None, domain=None, size=None, use_kilobytes=False, flagstr='', **dargs)[source]

Change the maximum memory allocation for the guest domain.

Parameters:
  • domainarg – Domain name (first pos. parameter)
  • sizearg – Memory size in KiB (second. pos. parameter)
  • domain – Option to –domain parameter
  • size – Option to –size or –kilobytes parameter
  • use_kilobytes – True for –kilobytes, False for –size
  • flagstr – string of “–config, –live, –current, etc.”
Returns:

CmdResult instance

Raise:

error.CmdError: if libvirtd is not running.

virttest.virsh.setmem(domainarg=None, sizearg=None, domain=None, size=None, use_kilobytes=False, flagstr='', **dargs)[source]

Change the current memory allocation in the guest domain.

Parameters:
  • domainarg – Domain name (first pos. parameter)
  • sizearg – Memory size in KiB (second. pos. parameter)
  • domain – Option to –domain parameter
  • size – Option to –size or –kilobytes parameter
  • use_kilobytes – True for –kilobytes, False for –size
  • dargs – standardized virsh function API keywords
  • flagstr – string of “–config, –live, –current, etc.”
Returns:

CmdResult instance

Raise:

error.CmdError: if libvirtd is not running

virttest.virsh.setvcpus(name, count, extra='', **dargs)[source]

Change the number of virtual CPUs in the guest domain.

Parameters:
  • name – name of vm to affect
  • count – value for vcpu parameter
  • options – any extra command options.
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object from command

virttest.virsh.shutdown(name, options='', **dargs)[source]

True on successful domain shutdown.

Parameters:
  • name – VM name
  • options – options for virsh shutdown.
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.snapshot_create(name, options='', **dargs)[source]

Create snapshot of domain.

Parameters:
  • name – name of domain
  • dargs – standardized virsh function API keywords
Returns:

name of snapshot

virttest.virsh.snapshot_create_as(name, options='', **dargs)[source]

Create snapshot of domain with options.

Parameters:
  • name – name of domain
  • options – options of snapshot-create-as
  • dargs – standardized virsh function API keywords
Returns:

name of snapshot

virttest.virsh.snapshot_current(name, options='--name', **dargs)[source]

Get name or xml of current snapshot.

Parameters:
  • name – name of domain
  • options – options of snapshot-current, default is –name
  • dargs – standardized virsh function API keywords
Returns:

CmdResult instance

virttest.virsh.snapshot_delete(name, snapshot, options='', **dargs)[source]

Remove domain snapshot

Parameters:
  • name – name of domain
  • dargs – standardized virsh function API keywords
  • snapshot – snapshot to delete
Returns:

CmdResult instance

virttest.virsh.snapshot_dumpxml(name, snapshot, options=None, to_file=None, **dargs)[source]

Get dumpxml of snapshot

Parameters:
  • name – name of domain
  • snapshot – name of snapshot
  • options – options of snapshot_list
  • to_file – optional file to write XML output to
  • dargs – standardized virsh function API keywords
Returns:

standard output from command

virttest.virsh.snapshot_edit(name, options='', **dargs)[source]

Edit snapshot xml

Parameters:
  • name – name of domain
  • options – options of snapshot-edit command
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.snapshot_info(name, snapshot, **dargs)[source]

Check snapshot information.

Parameters:
  • name – name of domain
  • snapshot – name os snapshot to verify
  • dargs – standardized virsh function API keywords
Returns:

snapshot information dictionary

virttest.virsh.snapshot_list(name, options=None, **dargs)[source]

Get list of snapshots of domain.

Parameters:
  • name – name of domain
  • options – options of snapshot_list
  • dargs – standardized virsh function API keywords
Returns:

list of snapshot names

virttest.virsh.snapshot_parent(name, options, **dargs)[source]

Get name of snapshot parent

Parameters:
  • name – name of domain
  • options – options of snapshot-parent
  • dargs – standardized virsh function API keywords
Returns:

name of snapshot

virttest.virsh.snapshot_revert(name, snapshot, options='', **dargs)[source]

Revert domain state to saved snapshot.

Parameters:
  • name – name of domain
  • dargs – standardized virsh function API keywords
  • snapshot – snapshot to revert to
Returns:

CmdResult instance

virttest.virsh.start(name, options='', **dargs)[source]

True on successful start of (previously defined) inactive domain.

Parameters:
  • name – VM name
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object.

virttest.virsh.suspend(name, **dargs)[source]

True on successful suspend of VM - kept in memory and not scheduled.

Parameters:
  • name – VM name
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.sysinfo(options='', **dargs)[source]

Return the hypervisor sysinfo xml.

Parameters:options – extra options
Returns:CmdResult object
virttest.virsh.ttyconsole(name, **dargs)[source]

Print tty console device.

Parameters:name – name, uuid or id of domain
Returns:CmdResult instance
virttest.virsh.undefine(name, options=None, **dargs)[source]

Return cmd result of domain undefine (after shutdown/destroy).

Parameters:
  • name – VM name
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.update_device(domainarg=None, filearg=None, domain_opt=None, file_opt=None, flagstr='', **dargs)[source]

Update device from an XML <file>.

Parameters:
  • domainarg – Domain name (first pos. parameter)
  • filearg – File name (second pos. parameter)
  • domain_opt – Option to –domain parameter
  • file_opt – Option to –file parameter
  • flagstr – string of “–force, –persistent, etc.”
  • dargs – standardized virsh function API keywords
Returns:

CmdResult instance

virttest.virsh.vcpucount(name, options='', **dargs)[source]

Get the vcpu count of guest.

Parameters:
  • name – name of domain.
  • options – options for vcpucoutn command.
Returns:

CmdResult object.

virttest.virsh.vcpuinfo(name, **dargs)[source]
Parameters:
  • name – name of domain
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.vcpupin(name, vcpu='', cpu_list='', options='', **dargs)[source]

Changes the cpu affinity for respective vcpu.

Parameters:
  • name – name of domain
  • vcpu – virtual CPU to modify
  • cpu_list – physical CPU specification (string)
  • dargs – standardized virsh function API keywords
  • options – –live, –current or –config.
Returns:

CmdResult object.

virttest.virsh.version(option='', **dargs)[source]

Return the major version info about what this built from.

Parameters:
  • option – additional option string to pass
  • dargs – standardized virsh function API keywords
Returns:

CmdResult object

virttest.virsh.vncdisplay(name, **dargs)[source]

Output the IP address and port number for the VNC display.

Parameters:
  • name – VM’s name or id,uuid.
  • dargs – standardized virsh function API keywords.
Returns:

result from command

virttest.virsh.vol_clone(volume_name, new_name, pool_name='', extra='', **dargs)[source]

Clone an existing volume.

Parameters:
  • volume_name – Name of the original volume
  • new_name – Clone name
  • pool_name – Name of the pool
  • extra – Free-form string options
  • dargs – Standardized virsh function API keywords
Returns:

Returns the output of the command

virttest.virsh.vol_create(pool_name, xml_file, extra='', **dargs)[source]

To create the volumes from xml file.

Parameters:
  • pool_name – Name of the pool to be used
  • xml_file – file containing an XML vol description
  • extra – string of extra options
Returns:

CmdResult object

virttest.virsh.vol_create_as(volume_name, pool_name, capacity, allocation, frmt, extra='', **dargs)[source]

To create the volumes on different available pool

Parameters:
  • name – Name of the volume to be created
  • pool_name – Name of the pool to be used
  • capacity – Size of the volume
  • allocaltion – Size of the volume to be pre-allocated
  • frmt – volume formats(e.g. raw, qed, qcow2)
  • extra – Free-form string of options
  • dargs – standardized virsh function API keywords
Returns:

True if pool undefine command was successful

virttest.virsh.vol_create_from(pool_name, vol_file, input_vol, input_pool, extra='', **dargs)[source]

Create a vol, using another volume as input

Param:pool_name: Name of the pool to create the volume in
Param:vol_file: XML <file> with the volume definition
Param:input_vol: Name of the source volume
Param:input_pool: Name of the pool the source volume is in
Param:extra: Free-form string of options
Returns:True if volume create successfully
virttest.virsh.vol_delete(volume_name, pool_name, extra='', **dargs)[source]

Delete a given volume

Parameters:
  • volume_name – Name of the volume
  • pool_name – Name of the pool
  • extra – Free-form string options
  • dargs – standardized virsh function API keywords
Returns:

returns the output of the command

virttest.virsh.vol_download(name, dfile, options='', **dargs)[source]

Download volume contents to a file

Parameters:
  • name – name of volume
  • dfile – file path that will download to
  • options – pool name, offset and length
Returns:

CmdResult object

virttest.virsh.vol_dumpxml(volume_name, pool_name, to_file=None, options='', **dargs)[source]

Dumps volume details in xml

Parameters:
  • volume_name – Name of the volume
  • pool_name – Name of the pool
  • to_file – path of the file to store the output
  • options – Free-form string options
  • dargs – standardized virsh function API keywords
Returns:

returns the output of the command

virttest.virsh.vol_info(volume_name, pool_name, extra='', **drags)[source]

Prints the given volume info

Parameters:
  • volume_name – Name of the volume
  • extra – Free-form string options
  • dargs – standardized virsh function API keywords
Returns:

returns the output of the command

virttest.virsh.vol_key(volume_name, pool_name, extra='', **drags)[source]

Prints the key of the given volume name

Parameters:
  • volume_name – Name of the volume
  • extra – Free-form string options
  • dargs – standardized virsh function API keywords
Returns:

returns the output of the command

virttest.virsh.vol_list(pool_name, extra='', **dargs)[source]

List the volumes for a given pool

Parameters:
  • pool_name – Name of the pool
  • extra – Free-form string options
  • dargs – standardized virsh function API keywords
Returns:

returns the output of the command

virttest.virsh.vol_name(volume_key, extra='', **drags)[source]

Prints the given volume name

Parameters:
  • volume_name – Name of the volume
  • extra – Free-form string options
  • dargs – standardized virsh function API keywords
Returns:

returns the output of the command

virttest.virsh.vol_path(volume_name, pool_name, extra='', **dargs)[source]

Prints the give volume path

Parameters:
  • volume_name – Name of the volume
  • pool_name – Name of the pool
  • extra – Free-form string options
  • dargs – standardized virsh function API keywords
Returns:

returns the output of the command

virttest.virsh.vol_pool(volume_name, extra='', **dargs)[source]

Returns pool name for a given vol-key

Parameters:
  • volume_name – Name of the volume
  • extra – Free-form string options
  • dargs – standardized virsh function API keywords
Returns:

returns the output of the command

virttest.virsh.vol_resize(volume_name, capacity, pool_name='', extra='', **dargs)[source]

Resizes a storage volume.

Parameters:
  • volume_name – Name of the volume
  • capacity – New capacity for the volume (default bytes)
  • pool_name – Name of the pool
  • extra – Free-form string options
  • dargs – Standardized virsh function API keywords
Returns:

Returns the output of the command

virttest.virsh.vol_upload(name, dfile, options='', **dargs)[source]

Upload file contents to a volume

Parameters:
  • name – name of volume
  • dfile – file path that will upload from
  • options – pool name, offset and length
Returns:

CmdResult object

virttest.virsh.vol_wipe(volume_name, pool_name='', alg='', **dargs)[source]

Ensure data previously on a volume is not accessible to future reads.

Parameters:
  • volume_name – Name of the volume
  • pool_name – Name of the pool
  • alg – Perform selected wiping algorithm
  • dargs – Standardized virsh function API keywords
Returns:

Returns the output of the command

virttest.virsh_unittest module

class virttest.virsh_unittest.ConstantsTest(methodName='runTest')[source]

Bases: virttest.virsh_unittest.ModuleLoad

test_ModuleLoad()[source]
class virttest.virsh_unittest.ConstructorsTest(methodName='runTest')[source]

Bases: virttest.virsh_unittest.ModuleLoad

TestVirshClosure()[source]
test_Virsh()[source]
test_VirshBase()[source]
test_VirshPersistent()[source]
virttest.virsh_unittest.FakeVirshFactory(preserve=None)[source]

Return Virsh() instance with methods to raise bogusVirshFailureException.

Users of this class should override methods under test on instance. :param preserve: List of symbol names NOT to modify, None for all

class virttest.virsh_unittest.ModuleLoad(methodName='runTest')[source]

Bases: unittest.case.TestCase

virsh = <module 'virttest.virsh' from '/home/docs/checkouts/readthedocs.org/user_builds/virt-test/checkouts/latest/virttest/virsh.py'>
class virttest.virsh_unittest.ModuleLoadCheckVirsh(methodName='runTest')[source]

Bases: unittest.case.TestCase

run(*args, **dargs)[source]
virsh = <module 'virttest.virsh' from '/home/docs/checkouts/readthedocs.org/user_builds/virt-test/checkouts/latest/virttest/virsh.py'>
class virttest.virsh_unittest.SessionManagerTest(methodName='runTest')[source]

Bases: virttest.virsh_unittest.ModuleLoadCheckVirsh

test_VirshPersistent()[source]

Unittest for session manager of VirshPersistent.

test_VirshSession()[source]

Unittest for VirshSession.

This test use VirshSession over VirshPersistent with auto_close=True.

test_del_VirshPersistent()[source]

Unittest for __del__ of VirshPersistent.

This test makes sure the __del__ method of VirshPersistent works well in del vp_instance.

class virttest.virsh_unittest.TestVirshClosure(methodName='runTest')[source]

Bases: virttest.virsh_unittest.ModuleLoad

class SomeClass[source]

Bases: dict

somemethod()[source]
static TestVirshClosure.somefunc(*args, **dargs)[source]
TestVirshClosure.test_args()[source]
TestVirshClosure.test_args_and_dargs()[source]
TestVirshClosure.test_args_dargs_subclass()[source]
TestVirshClosure.test_dargs()[source]
TestVirshClosure.test_fake_virsh()[source]
TestVirshClosure.test_init()[source]
TestVirshClosure.test_multi_inst()[source]
TestVirshClosure.test_update_args_dargs_subclass()[source]
class virttest.virsh_unittest.VirshClassHasHelpCommandTest(methodName='runTest')[source]

Bases: virttest.virsh_unittest.VirshHasHelpCommandTest

setUp()[source]
class virttest.virsh_unittest.VirshHasHelpCommandTest(methodName='runTest')[source]

Bases: virttest.virsh_unittest.ModuleLoadCheckVirsh

setUp()[source]
test_false_command()[source]
test_groups_in_commands()[source]
test_no_cache()[source]
test_subcommand_help()[source]
test_true_command()[source]
class virttest.virsh_unittest.VirshHelpCommandTest(methodName='runTest')[source]

Bases: virttest.virsh_unittest.ModuleLoadCheckVirsh

test_cache_command()[source]
class virttest.virsh_unittest.VirshPersistentClassHasHelpCommandTest(methodName='runTest')[source]

Bases: virttest.virsh_unittest.VirshHasHelpCommandTest

setUp()[source]
tearDown()[source]
test_recycle_session()[source]
exception virttest.virsh_unittest.bogusVirshFailureException(*args, **dargs)[source]

Bases: exceptions.AssertionError

virttest.virt_vm module

class virttest.virt_vm.BaseVM(name, params)[source]

Bases: object

Base class for all hypervisor specific VM subclasses.

This class should not be used directly, that is, do not attempt to instantiate and use this class. Instead, one should implement a subclass that implements, at the very least, all methods defined right after the the comment blocks that are marked with:

“Public API - must be reimplemented with virt specific code”

and

“Protected API - must be reimplemented with virt specific classes”

The current proposal regarding methods naming convention is:

  • Public API methods: named in the usual way, consumed by tests
  • Protected API methods: name begins with a single underline, to be consumed only by BaseVM and subclasses
  • Private API methods: name begins with double underline, to be consumed only by the VM subclass itself (usually implements virt specific functionality: example: __make_qemu_command())

So called “protected” methods are intended to be used only by VM classes, and not be consumed by tests. Theses should respect a naming convention and always be preceded by a single underline.

Currently most (if not all) methods are public and appears to be consumed by tests. It is a ongoing task to determine whether methods should be “public” or “protected”.

COPY_FILES_TIMEOUT = 600
LOGIN_TIMEOUT = 10
LOGIN_WAIT_TIMEOUT = 240
MIGRATE_TIMEOUT = 3600
MIGRATION_PROTOS = ['tcp']
REBOOT_TIMEOUT = 240
activate_nic(nic_index_or_name)[source]

Activate an inactive network device

Parameters:nic_index_or_name – name or index number for existing NIC
add_nic(**params)[source]

Add new or setup existing NIC with optional model type and mac address

Parameters:params – Dict with additional NIC parameters to set.
Returns:Dict with new NIC’s info.
cleanup_serial_console()[source]

Close serial console and associated log file

clone(name, **params)[source]

Return a clone of the VM object with optionally modified parameters.

This method should be implemented by

commander(*args, **kwargs)

Log into the guest via SSH/Telnet/Netcat. If timeout expires while waiting for output from the guest (e.g. a password prompt or a shell prompt) – fail.

Parameters:
  • nic_index – The index of the NIC to connect to.
  • timeout – Time (seconds) before giving up logging into the guest.
  • commaner_path – Path where will be commader placed.
Returns:

A ShellSession object.

copy_files_from(*args, **kwargs)

Transfer files from the guest.

Parameters:
  • host_path – Guest path
  • guest_path – Host path
  • nic_index – The index of the NIC to connect to.
  • limit – Speed limit of file transfer.
  • verbose – If True, log some stats using logging.debug (RSS only)
  • timeout – Time (seconds) before giving up on doing the remote copy.
copy_files_to(*args, **kwargs)

Transfer files to the remote host(guest).

Parameters:
  • host_path – Host path
  • guest_path – Guest path
  • nic_index – The index of the NIC to connect to.
  • limit – Speed limit of file transfer.
  • verbose – If True, log some stats using logging.debug (RSS only)
  • timeout – Time (seconds) before giving up on doing the remote copy.
create_serial_console()[source]

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()[source]

Establish a session with the virtio console.

deactivate_nic(nic_index_or_name)[source]

Deactivate an active network device

Parameters:nic_index_or_name – name or index number for existing NIC
del_nic(nic_index_or_name)[source]

Remove the nic specified by name, or index number

destroy(gracefully=True, free_mac_addresses=True)[source]

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.
fill_addrs(addrs)[source]

Fill VM’s nic address to the virtnet structure based on VM’s address structure addrs.

Parameters:addrs – Dict of interfaces and address
{"if_name":{"mac":['addrs',],
            "ipv4":['addrs',],
            "ipv6":['addrs',]},
  ...}
free_mac_address(nic_index_or_name=0)[source]

Free a NIC’s MAC address.

Parameters:nic_index – Index of the NIC
get_address(index=0)[source]

Return the IP address of a NIC or guest (in host space).

Parameters:

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

Returns:

‘localhost’: Port redirection is in use

Returns:

IP address of NIC if valid in arp cache.

Raises:
  • VMMACAddressMissingError – If no MAC address is defined for the requested NIC
  • VMIPAddressMissingError – If no IP address is found for the the NIC’s MAC address
  • VMAddressVerificationError – If the MAC-IP address mapping cannot be verified (using arping)
get_cpu_count()[source]

Get the cpu count of the VM.

get_current_memory_size()[source]

Get current memory size of the VM, rather than bootup memory.

get_mac_address(nic_index=0)[source]

Return the MAC address of a NIC.

Parameters:nic_index – Index of the NIC
Raises:VMMACAddressMissingError – If no MAC address is defined for the requested NIC
get_memory_size(cmd=None, timeout=60, re_str=None)[source]

Get bootup memory size of the VM.

Parameters:
  • cmd – Command used to check memory. If not provided, self.params.get(“mem_chk_cmd”) will be used.
  • timeout – timeout for cmd
  • re_str – pattern to get memory size from the command output. If not provided, self.params.get(“mem_chk_re_str”) will be used.
get_params()[source]

Return the VM’s params dict. Most modified params take effect only upon VM.create().

get_port(port, nic_index=0)[source]

Return the port in host space corresponding to port in guest space.

Parameters:
  • port – Port number in host space.
  • nic_index – Index of the NIC.
Returns:

If port redirection is used, return the host port redirected to guest port port. Otherwise return port.

Raises:

VMPortNotRedirectedError – If an unredirected port is requested in user mode

get_testlog_filename()[source]

Return the testlog filename.

get_uuid()[source]

Catch UUID of the VM.

Returns:None,if not specified in config file
get_virtio_port_filename(port_name)[source]

Return the filename corresponding to a givven monitor name.

get_virtio_port_filenames()[source]

Return a list of all virtio port filenames (as specified in the VM’s params).

is_alive()[source]

Return True if the VM is alive and the management interface is responsive.

is_dead()[source]

Return True if the VM is dead.

is_paused()[source]

Return True if the VM is paused

loadvm(tag_name)[source]

Load the virtual machine tagged ‘tag_name’.

Parameters:tag_name – tag of the virtual machine that saved
login(*args, **kwargs)

Log into the guest via SSH/Telnet/Netcat. If timeout expires while waiting for output from the guest (e.g. a password prompt or a shell prompt) – fail.

Parameters:
  • nic_index – The index of the NIC to connect to.
  • timeout – Time (seconds) before giving up logging into the guest.
Returns:

A ShellSession object.

static lookup_vm_class(vm_type, target)[source]
migrate(timeout=3600, protocol='tcp', cancel_delay=None, offline=False, stable_check=False, clean=True, save_path='/tmp', dest_host='localhost', remote_port=None)[source]

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 (‘tcp’, ‘unix’ or ‘exec’).
  • 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.
needs_restart(name, params, basedir)[source]

Verifies whether the current virt_install commandline matches the requested one, based on the test parameters.

pause()[source]

Stop the VM operation.

reboot(session=None, method='shell', nic_index=0, timeout=240, serial=False)[source]

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 port login or not (default is False).
Returns:

A new shell session object.

remote_commander(nic_index=0, timeout=10, username=None, password=None)[source]

Alias for commander() for backward compatibility.

remote_login(nic_index=0, timeout=10, username=None, password=None)[source]

Alias for login() for backward compatibility.

restore_from_file(path)[source]

A shutdown or paused VM is resumed from path, & possibly set running

Throws a VMStatusError if before/after restore state is incorrect

Parameters:path – path to file vm state was saved to
resume()[source]

Resume the VM operation in case it’s stopped.

save_to_file(path)[source]

State of paused VM recorded to path and VM shutdown on success

Throws a VMStatusError if before/after state is incorrect.

Parameters:path – file where VM state recorded
savevm(tag_name)[source]

Save the virtual machine as the tag ‘tag_name’

Parameters:tag_name – tag of the virtual machine that saved
send_key(keystr)[source]

Send a key event to the VM.

Parameters:keystr – A key event string (e.g. “ctrl-alt-delete”)
send_string(sr)[source]

Send a string to the VM.

Parameters:sr – String, that must consist of alphanumeric characters only. Capital letters are allowed.
serial_login(*args, **kwargs)

Log into the guest via the serial console. If timeout expires while waiting for output from the guest (e.g. a password prompt or a shell prompt) – fail.

Parameters:
  • timeout – Time (seconds) before giving up logging into the guest.
  • virtio – is a console virtio console.
Returns:

ShellSession object on success and None on failure.

update_vm_id()[source]

Update vm identifier, we need do that when force reboot vm, since vm virnet params may be changed.

verify_alive()[source]

Make sure the VM is alive and that the main monitor is responsive.

Can be subclassed to provide better information on why the VM is not alive (reason, detail)

Raises:VMDeadError – If the VM is dead
Raise:Various monitor exceptions if the monitor is unresponsive
verify_bsod(scrdump_file)[source]
verify_illegal_instruction()[source]

Find illegal instruction code on VM serial console output.

Raise:VMInvalidInstructionCode, in case a wrong instruction code.
verify_kernel_crash()[source]

Find kernel crash message on the VM serial console.

Raise:VMDeadKernelCrashError, in case a kernel crash message was found.
verify_userspace_crash()[source]

Verify if the userspace component of the virtualization backend crashed.

wait_for_get_address(*args, **kwargs)

Wait for a nic to acquire an IP address, then return it. For ipv6 linklocal address, we can generate it by nic mac, so we can ignore this case

wait_for_login(nic_index=0, timeout=240, internal_timeout=10, serial=False, restart_network=False, username=None, password=None)[source]

Make multiple attempts to log into the guest via SSH/Telnet/Netcat.

Parameters:
  • nic_index – The index of the NIC to connect to.
  • timeout – Time (seconds) to keep trying to log in.
  • internal_timeout – Timeout to pass to login().
  • serial – Whether to use a serial connection when remote login (ssh, rss) failed.
  • restart_network – Whether to try to restart guest’s network when remote login (ssh, rss) failed.
Returns:

A ShellSession object.

wait_for_serial_login(timeout=240, internal_timeout=10, restart_network=False, username=None, password=None, virtio=False)[source]

Make multiple attempts to log into the guest via serial console.

Parameters:
  • timeout – Time (seconds) to keep trying to log in.
  • internal_timeout – Timeout to pass to serial_login().
  • restart_network – Whether try to restart guest’s network.
Params virtio:

is a virtio console.

Returns:

A ShellSession object.

class virttest.virt_vm.CpuInfo(model=None, vendor=None, flags=None, family=None, smp=0, maxcpus=0, sockets=0, cores=0, threads=0)[source]

Bases: object

A class for VM’s cpu information.

exception virttest.virt_vm.VMAddNetDevError(*args)[source]

Bases: virttest.virt_vm.VMError

exception virttest.virt_vm.VMAddNicError(*args)[source]

Bases: virttest.virt_vm.VMError

exception virttest.virt_vm.VMAddressError(*args)[source]

Bases: virttest.virt_vm.VMError

exception virttest.virt_vm.VMAddressVerificationError(mac, ip)[source]

Bases: virttest.virt_vm.VMAddressError

exception virttest.virt_vm.VMBadPATypeError(pa_type)[source]

Bases: virttest.virt_vm.VMError

exception virttest.virt_vm.VMConfigMissingError(name, config)[source]

Bases: virttest.virt_vm.VMError

exception virttest.virt_vm.VMCreateError(cmd, status, output)[source]

Bases: virttest.virt_vm.VMError

exception virttest.virt_vm.VMDeadError(reason='', detail='')[source]

Bases: virttest.virt_vm.VMError

exception virttest.virt_vm.VMDeadKernelCrashError(kernel_crash)[source]

Bases: virttest.virt_vm.VMError

exception virttest.virt_vm.VMDelNetDevError(*args)[source]

Bases: virttest.virt_vm.VMError

exception virttest.virt_vm.VMDelNicError(*args)[source]

Bases: virttest.virt_vm.VMError

exception virttest.virt_vm.VMDeviceError(*args)[source]

Bases: virttest.virt_vm.VMError

exception virttest.virt_vm.VMDeviceNotSupportedError(name, device)[source]

Bases: virttest.virt_vm.VMDeviceError

exception virttest.virt_vm.VMError(*args)[source]

Bases: exceptions.Exception

exception virttest.virt_vm.VMHashMismatchError(actual, expected)[source]

Bases: virttest.virt_vm.VMError

exception virttest.virt_vm.VMHugePageError(cmd, output)[source]

Bases: virttest.virt_vm.VMPostCreateError

exception virttest.virt_vm.VMIPAddressMissingError(mac, ip_version='ipv4')[source]

Bases: virttest.virt_vm.VMAddressError

exception virttest.virt_vm.VMImageCheckError(filename)[source]

Bases: virttest.virt_vm.VMError

exception virttest.virt_vm.VMImageMissingError(filename)[source]

Bases: virttest.virt_vm.VMError

exception virttest.virt_vm.VMInterfaceIndexError(*args)[source]

Bases: virttest.virt_vm.VMError

exception virttest.virt_vm.VMInvalidInstructionCode(invalid_code)[source]

Bases: virttest.virt_vm.VMError

exception virttest.virt_vm.VMKVMInitError(cmd, output)[source]

Bases: virttest.virt_vm.VMPostCreateError

exception virttest.virt_vm.VMMACAddressMissingError(nic_index)[source]

Bases: virttest.virt_vm.VMAddressError

exception virttest.virt_vm.VMMigrateCancelError(*args)[source]

Bases: virttest.virt_vm.VMMigrateError

exception virttest.virt_vm.VMMigrateError(*args)[source]

Bases: virttest.virt_vm.VMError

exception virttest.virt_vm.VMMigrateFailedError(*args)[source]

Bases: virttest.virt_vm.VMMigrateError

exception virttest.virt_vm.VMMigrateProtoUnknownError(protocol)[source]

Bases: autotest.client.shared.error.TestNAError

exception virttest.virt_vm.VMMigrateStateMismatchError[source]

Bases: virttest.virt_vm.VMMigrateError

exception virttest.virt_vm.VMMigrateTimeoutError(*args)[source]

Bases: virttest.virt_vm.VMMigrateError

exception virttest.virt_vm.VMPAError(pa_type)[source]

Bases: virttest.virt_vm.VMError

exception virttest.virt_vm.VMPCIDeviceError(*args)[source]

Bases: virttest.virt_vm.VMDeviceError

exception virttest.virt_vm.VMPCIOutOfRangeError(name, max_dev_num)[source]

Bases: virttest.virt_vm.VMPCIDeviceError

exception virttest.virt_vm.VMPCISlotInUseError(name, slot)[source]

Bases: virttest.virt_vm.VMPCIDeviceError

exception virttest.virt_vm.VMPortNotRedirectedError(port, virtnet_nic=None)[source]

Bases: virttest.virt_vm.VMAddressError

exception virttest.virt_vm.VMPostCreateError(cmd, output)[source]

Bases: virttest.virt_vm.VMError

exception virttest.virt_vm.VMRebootError(*args)[source]

Bases: virttest.virt_vm.VMError

exception virttest.virt_vm.VMRemoveError(*args)[source]

Bases: virttest.virt_vm.VMError

exception virttest.virt_vm.VMScreenInactiveError(vm, inactive_time)[source]

Bases: virttest.virt_vm.VMError

exception virttest.virt_vm.VMStartError(name, reason=None)[source]

Bases: virttest.virt_vm.VMError

exception virttest.virt_vm.VMStatusError(*args)[source]

Bases: virttest.virt_vm.VMError

exception virttest.virt_vm.VMUSBControllerError(*args)[source]

Bases: virttest.virt_vm.VMUSBError

exception virttest.virt_vm.VMUSBControllerMissingError(name, controller_type)[source]

Bases: virttest.virt_vm.VMUSBControllerError

exception virttest.virt_vm.VMUSBControllerPortFullError(name, usb_dev_dict)[source]

Bases: virttest.virt_vm.VMUSBControllerError

exception virttest.virt_vm.VMUSBError(*args)[source]

Bases: virttest.virt_vm.VMError

exception virttest.virt_vm.VMUSBPortInUseError(vm_name, controller, port)[source]

Bases: virttest.virt_vm.VMUSBError

exception virttest.virt_vm.VMUnknownNetTypeError(vmname, nicname, nettype)[source]

Bases: virttest.virt_vm.VMError

virttest.xml_utils module

Utility module standardized on ElementTree 2.6 to minimize dependencies in python 2.4 systems.

Often operations on XML files suggest making a backup copy first is a prudent measure. However, it’s easy to loose track of these temporary files and they can quickly leave a mess behind. The TempXMLFile class helps by trying to clean up the temporary file whenever the instance is deleted, goes out of scope, or an exception is thrown.

The XMLBackup class extends the TempXMLFile class by basing its file- like instances off of an automatically created TempXMLFile instead of pointing at the source. Methods are provided for overwriting the backup copy from the source, or restoring the source from the backup. Similar to TempXMLFile, the temporary backup files are automatically removed. Access to the original source is provided by the sourcefilename attribute.

An interface for querying and manipulating XML data is provided by the XMLTreeFile class. Instances of this class are BOTH file-like and ElementTree-like objects. Whether or not they are constructed from a file or a string, the file-like instance always represents a temporary backup copy. Access to the source (even when itself is temporary) is provided by the sourcefilename attribute, and a (closed) file object attribute sourcebackupfile. See the ElementTree documentation for methods provided by that class.

Finally, the TemplateXML class represents XML templates that support dynamic keyword substitution based on a dictionary. Substitution keys in the XML template (string or file) follow the ‘bash’ variable reference style ($foo or ${bar}). Extension of the parser is possible by subclassing TemplateXML and overriding the ParserClass class attribute. The parser class should be an ElementTree.TreeBuilder class or subclass. Instances of XMLTreeFile are returned by the parse method, which are themselves temporary backups of the parsed content. See the xml_utils_unittest module for examples.

class virttest.xml_utils.Sub(**mapping)[source]

Bases: object

String substituter using string.Template

substitute(text)[source]

Use string.safe_substitute on text and return the result

Parameters:text – string to substitute
class virttest.xml_utils.TempXMLFile(suffix='.xml', prefix='xml_utils_temp_', mode='wb+', buffsz=1)[source]

Bases: file

Temporary XML file auto-removed on instance del / module exit.

Unconditionally delete file, ignoring related exceptions

class virttest.xml_utils.TemplateXML(xml, **mapping)[source]

Bases: virttest.xml_utils.XMLTreeFile

Template-sourced XML ElementTree backed by temporary file.

ParserClass

alias of TemplateXMLTreeBuilder

parse(source, parser=None)[source]

Parse source XML file or filename using TemplateXMLTreeBuilder

Parameters:
  • source – XML file or filename
  • parser – ignored
restore()[source]

Raise an IOError to protect the original template source.

class virttest.xml_utils.TemplateXMLTreeBuilder(**mapping)[source]

Bases: virttest.element_tree.XMLTreeBuilder, virttest.xml_utils.Sub

Resolve XML templates into temporary file-backed ElementTrees

BuilderClass

alias of TreeBuilder

feed(data)[source]
class virttest.xml_utils.XMLBackup(sourcefilename)[source]

Bases: virttest.xml_utils.TempXMLFile

Backup file copy of XML data, automatically removed on instance destruction.

backup()[source]

Overwrite temporary backup with contents of original source.

restore()[source]

Overwrite original source with contents of temporary backup

sourcefilename = None
class virttest.xml_utils.XMLTreeFile(xml)[source]

Bases: virttest.element_tree.ElementTree, virttest.xml_utils.XMLBackup

Combination of ElementTree root and auto-cleaned XML backup file.

backup()[source]

Overwrite original source from current tree

backup_copy()[source]

Return a copy of instance, including copies of files

create_by_xpath(xpath)[source]

Creates all elements in simplistic xpath from root if not exist

get_element_string(xpath)[source]

Returns the string for the element on xpath.

get_parent(element, relative_root=None)[source]

Return the parent node of an element or None

param: element: Element to retrieve parent of param: relative_root: Search only below this element

get_parent_map(element=None)[source]

Return a child to parent mapping dictionary

param: element: Search only below this element

get_xpath(element)[source]

Return the XPath string formed from first-match tag names

read(xml)[source]
remove(element)[source]

Removes a matching subelement.

Parameters:element – element to be removed.
remove_by_xpath(xpath, remove_all=False)[source]

Remove an element found by xpath

Parameters:xpath – element name or path to remove
reroot(xpath)[source]

Return a copy of instance, re-rooted onto xpath

restore()[source]

Overwrite and reparse current tree from original source

sourcebackupfile = None
write(filename=None, encoding='UTF-8')[source]

Write current XML tree to filename, or self.name if None.

virttest.xml_utils_unittest module

class virttest.xml_utils_unittest.test_ElementTree(methodName='runTest')[source]

Bases: virttest.xml_utils_unittest.xml_test_data

test_bundled_elementtree()[source]
class virttest.xml_utils_unittest.test_TempXMLFile(methodName='runTest')[source]

Bases: virttest.xml_utils_unittest.xml_test_data

test_TempXMLFile_explicit()[source]
test_TempXMLFile_implicit()[source]
test_prefix_sufix()[source]
test_test_TempXMLFile_canread()[source]
class virttest.xml_utils_unittest.test_XMLBackup(methodName='runTest')[source]

Bases: virttest.xml_utils_unittest.xml_test_data

class_to_test

alias of XMLBackup

test_TempXMLBackup_exception_exit()[source]
test_TempXMLBackup_implicit()[source]
test_TempXMLBackup_unexception_exit()[source]
test_backup_file()[source]
test_backup_filename()[source]
test_rebackup_file()[source]
test_remove_backup_file()[source]
test_restore_file()[source]
class virttest.xml_utils_unittest.test_XMLTreeFile(methodName='runTest')[source]

Bases: virttest.xml_utils_unittest.xml_test_data

class_to_test

alias of XMLTreeFile

get_xpath_elements(target_path_string)[source]
test_backup_backup_and_remove()[source]
test_create_by_xpath()[source]
test_get_xpath()[source]
test_init_str()[source]
test_init_xml()[source]
test_read_other_changed()[source]
test_restore_from_file()[source]
test_restore_from_string()[source]
test_sourcebackupfile_closed_file()[source]
test_sourcebackupfile_closed_string()[source]
test_stringify()[source]
test_write_default()[source]
test_write_other()[source]
test_write_other_changed()[source]
class virttest.xml_utils_unittest.test_templatized_xml(methodName='runTest')[source]

Bases: virttest.xml_utils_unittest.xml_test_data

setUp()[source]
test_MappingTreeBuilder_standalone()[source]
test_TemplateXML()[source]
test_TemplateXMLTreeBuilder_nosub()[source]
test_restore_fails()[source]
test_sub()[source]
class virttest.xml_utils_unittest.xml_test_data(methodName='runTest')[source]

Bases: unittest.case.TestCase

canonicalize_test_xml()[source]
get_tmp_files(prefix, sufix)[source]
is_same_contents(filename, other=None)[source]

Compare filename contents with XMLSTR, or contents of other

setUp()[source]
tearDown()[source]

virttest.yumrepo module

This module implements classes that allow a user to create, enable and disable YUM repositories on the system.

class virttest.yumrepo.YumRepo(name, baseurl, path=None)[source]

Bases: object

Represents a YUM repository

The goal of this class is not to give access to all features of a YUM Repository, but to provide a simple way to configure a valid one during a test run.

Sample usage:
>>> mainrepo = YumRepo("main", "http://download.project.org/repo",
                       "/etc/yum.repos.d/main.repo")
Or to use a default path:
>>> mainrepo = YumRepo("main", 'http://download.project.org/repo')
And then:
>>> mainrepo.save()

When it comes to the repo URL, currently there’s no support for setting a mirrorlist, only a baseurl.

remove()[source]

Removes the repo file

render()[source]

Renders the repo file

Yes, we could use ConfigParser for this, but it produces files with spaces between keys and values, which look akward by YUM defaults.

save()[source]

Saves the repo file

Module contents