tmt.guest package

Module contents

tmt.guest.BASE_SSH_OPTIONS: list[str | Path] = ['-oForwardX11=no', '-oStrictHostKeyChecking=no', '-oUserKnownHostsFile=/dev/null', '-oConnectionAttempts=5', '-oConnectTimeout=60', '-oServerAliveInterval=5', '-oServerAliveCountMax=60']

Base SSH options. This is the base set of SSH options tmt would use for all SSH connections. It is a combination of the default SSH options and those provided by environment variables. SSH options are processed in order. Options provided via environment variables take precedence over default values. For options that set a specific value (e.g., ServerAliveInterval), the first occurrence takes precedence. For simple on/off flags (e.g., -v/-q), the last one wins. Identity files (-i) are all considered in order.

class tmt.guest.BootMark

Bases: ABC

Fetch and compare “boot mark”

A “boot mark” is a piece of information identifying a particular guest boot, and it changes after a reboot. It is used to detect whether a reboot has already happened or not.

classmethod check(guest: Guest, current: str | None) None

Read the new boot mark, and compare it with the current one.

Intended to be called as tmt.utils.wait.wait() callback.

Raises:

tmt.utils.wait.WaitingIncompleteError – when the guest is not yet ready after a reboot, e.g. because the boot mark is not updated yet.

abstractmethod classmethod fetch(guest: Guest) str

Read and return the current value of the boot mark.

class tmt.guest.BootMarkBootTime

Bases: BootMark

Use boot time as a boot mark.

classmethod fetch(guest: Guest) str

Read and return the current value of the boot mark.

class tmt.guest.BootMarkSystemdSoftRebootCount

Bases: BootMark

Use soft reboot count a boot mark.

classmethod fetch(guest: Guest) str

Read and return the current value of the boot mark.

tmt.guest.CONNECT_TIMEOUT: int = 120

How many seconds to wait for a connection to succeed after guest boot. This is the effective value, combining the default and optional envvar, TMT_CONNECT_TIMEOUT.

class tmt.guest.CommandCollector

Bases: ABC

Mixin for that supports collecting commands for deferred execution.

abstractmethod collect_command(command: Command | ShellScript, *, sourced_files: list[Path] | None = None, cwd: Path | None = None, env: Environment | None = None) None

Collect a command for later batch execution.

Parameters:
  • command – the command to collect.

  • cwd – working directory for the command.

  • env – environment variables for the command.

abstractmethod flush_collected() None

Execute all collected commands.

abstract property has_collected_commands: bool

Return True if there are collected commands pending.

tmt.guest.DEFAULT_CONNECT_TIMEOUT = 120

How many seconds to wait for a connection to succeed after guest boot. This is the default value tmt would use unless told otherwise.

tmt.guest.DEFAULT_REBOOT_TIMEOUT: int = 600

How many seconds to wait for a connection to succeed after guest reboot. This is the default value tmt would use unless told otherwise.

tmt.guest.DEFAULT_SSH_OPTIONS: list[str | Path] = ['-oForwardX11=no', '-oStrictHostKeyChecking=no', '-oUserKnownHostsFile=/dev/null', '-oConnectionAttempts=5', '-oConnectTimeout=60', '-oServerAliveInterval=5', '-oServerAliveCountMax=60']

Default SSH options. This is the default set of SSH options tmt would use for all SSH connections.

tmt.guest.DEFAULT_USER = 'root'

Default username to use in SSH connections.

class tmt.guest.Guest(*, data: GuestData, name: str | None = None, parent: Common | None = None, logger: Logger)

Bases: HasRunWorkdir, HasPlanWorkdir, HasStepWorkdir, HasGuestWorkdir, Common

Guest provisioned for test execution

A base class for guest-like classes. Provides some of the basic methods and functionality, but note some of the methods are left intentionally empty. These do not have valid implementation on this level, and it’s up to Guest subclasses to provide one working in their respective infrastructure.

The following keys are expected in the ‘data’ container:

role ....... guest role in the multihost scenario
guest ...... name, hostname or ip address
become ..... boolean, whether to run shell scripts in tests, prepare, and finish with sudo

These are by default imported into instance attributes.

Initialize guest data

ansible: GuestAnsible | None
property ansible_host_groups: list[str]

Get guest list of groups for Ansible inventory.

property ansible_host_vars: dict[str, Any]

Get host variables for Ansible inventory.

assert_reachable(wait: Waiting | None = None) None

Assert that the guest is reachable and responding.

become: bool
property bootc_builder: PackageManager[PackageManagerEngine]
cli_invocation: 'tmt.cli.CliInvocation' | None = None
collect_log(log: GuestLog, hint: str | None = None) None

Register a guest log for (later) collection.

Parameters:
  • log – guest log to collect and save.

  • hint – if set, it would be included in the logging message emitted by this function.

environment: Environment
classmethod essential_requires() list[DependencySimple | DependencyFmfId | DependencyFile]

Collect all essential requirements of the guest.

Essential requirements of a guest are necessary for the guest to be usable for testing.

Returns:

a list of requirements.

abstractmethod execute(command: Command | ShellScript, cwd: Path | None = None, env: Environment | None = None, friendly_command: str | None = None, test_session: bool = False, immediately: Literal[True] = True, tty: bool = False, silent: bool = False, log: LoggingFunction | None = None, interactive: bool = False, on_process_start: Callable[[Command, Popen[bytes], Logger], None] | None = None, on_process_end: OnProcessEndCallback | None = None, sourced_files: list[Path] | None = None, **kwargs: Any) CommandOutput
abstractmethod execute(command: Command | ShellScript, cwd: Path | None = None, env: Environment | None = None, friendly_command: str | None = None, test_session: bool = False, immediately: Literal[False] = False, tty: bool = False, silent: bool = False, log: LoggingFunction | None = None, interactive: bool = False, on_process_start: Callable[[Command, Popen[bytes], Logger], None] | None = None, on_process_end: OnProcessEndCallback | None = None, sourced_files: list[Path] | None = None, **kwargs: Any) CommandOutput | None

Execute a command on the guest.

Parameters:
  • command – either a command or a shell script to execute.

  • cwd – if set, execute command in this directory on the guest.

  • env – if set, set these environment variables before running the command.

  • friendly_command – nice, human-friendly representation of the command.

  • immediately – if False, the command may be collected for later batch execution on guests that support it (e.g., bootc guests). Commands with immediately=True (default) are always executed right away. Use immediately=False for commands that modify system state and can be batched (e.g., package installation).

property facts: GuestFacts
classmethod get_data_class() type[GuestData]

Return step data class for this plugin.

By default, _data_class is returned, but plugin may override this method to provide different class.

guest_logs: list[GuestLog]

Guest logs active and available for collection.

property guest_workdir: Path

Path to a guest workdir.

Raises:

GeneralError – when there is no guest workdir yet.

hardware: Hardware | None
install_scripts(scripts: Sequence[Script]) None

Install scripts required by tmt.

abstract property is_ready: bool

Detect guest is ready or not

load(data: GuestData) None

Load guest data into object attributes for easy access

Called during guest object initialization. Takes care of storing all supported keys (see class attribute _keys for the list) from provided data to the guest object attributes. Child classes can extend it to make additional guest attributes easily available.

Data dictionary can contain guest information from both command line options / L2 metadata / user configuration and wake up data stored by the save() method below.

localhost = False
property logdir: Path

Path to store logs

Create the directory if it does not exist yet.

mkdtemp(prefix: str | None = None, template: str | None = None, parent: Path | None = None) Iterator[Path]

Create a temporary directory.

Modeled after tempfile.mkdtemp(), but creates the temporary directory on the guest, by invoking mktemp -d. The implementation may slightly differ, but the temporary directory should be created safely, without conflicts, and it should be accessible only to user who created it.

Since the caller is responsible for removing the directory, it is recommended to use it as a context manager, just as one would use tempfile.mkdtemp(); leaving the context will remove the directory:

with guest.mkdtemp() as path:
    ...
Parameters:
  • prefix – if set, the directory name will begin with this string.

  • template – if set, the directory name will follow the given naming scheme: the template must end with 6 consecutive X``s, i.e. ``XXXXXX. All X letters will be replaced with random characters.

  • parent – if set, new directory will be created under this path. Otherwise, the default directory is used.

property multihost_name: str

Return guest’s multihost name, i.e. name and its role

on_step_complete(step: Step) None

Called when a step completes execution.

Does nothing for Guest. Should be overridden in subclass if needed.

Parameters:

step – the step that has completed.

classmethod options(how: str | None = None) list[Callable[[Any], Any]]

Prepare command line options related to guests

property package_manager: PackageManager[PackageManagerEngine]
perform_reboot(mode: RebootMode, action: Callable[[], Any], wait: Waiting) bool

Perform the actual reboot and wait for the guest to recover.

This is the core implementation of the common task of triggering a reboot and waiting for the guest to recover. reboot() is the public API of guest classes, and feeds perform_reboot() with the right action callable.

Note

perform_reboot() should be used by provision plugins only, when they decide what action they need to take to take to perform the desired reboot of the guest. Other code should use Guest.reboot() instead.

Parameters:
  • mode – which boot mode to perform.

  • action – a callable which will trigger the requested reboot.

  • waiting – deadline for the reboot.

Returns:

True if the reboot succeeded, False otherwise.

property plan_workdir: Path

Path to a plan workdir.

Raises:

GeneralError – when there is no plan workdir yet.

primary_address: str | None = None

Primary hostname or IP address for tmt/guest communication.

abstractmethod pull(source: Path | None = None, destination: Path | None = None, options: TransferOptions | None = None) None

Pull files from the guest

abstractmethod push(source: Path | None = None, destination: Path | None = None, options: TransferOptions | None = None, superuser: bool = False) None

Push files to the guest

abstractmethod reboot(mode: Literal[RebootMode.HARD] = RebootMode.HARD, command: None = None, waiting: Waiting | None = None) bool
abstractmethod reboot(mode: Literal[RebootMode.SOFT, RebootMode.SYSTEMD_SOFT] = RebootMode.SOFT, command: Command | ShellScript | None = None, waiting: Waiting | None = None) bool

Reboot the guest, and wait for the guest to recover.

Parameters:
  • mode – which boot mode to perform.

  • command – a command to run on the guest to trigger the reboot. Only usable when mode is not RebootMode.HARD.

  • waiting – deadline for the reboot.

Returns:

True if the reboot succeeded, False otherwise.

reconnect(wait: Waiting | None = None) bool

Ensure the connection to the guest is working

The default timeout is 5 minutes. Custom number of seconds can be provided in the timeout parameter. This may be useful when long operations (such as system upgrade) are performed.

remove() None

Remove the guest

Completely remove all guest instance data so that it does not consume any disk resources.

role: str | None
run_ansible_playbook(playbook: AnsibleCollectionPlaybook | Path, playbook_root: Path | None = None, extra_args: str | None = None, friendly_command: str | None = None, log: LoggingFunction | None = None, silent: bool = False) CommandOutput

Run an Ansible playbook on the guest.

A wrapper for _run_ansible() which is responsible for running the playbook while this method makes sure our logging is consistent.

Parameters:
  • playbook – path to the playbook to run.

  • playbook_root – if set, playbook path must be located under the given root path.

  • extra_args – additional arguments to be passed to ansible-playbook via --extra-args.

  • friendly_command – if set, it would be logged instead of the command itself, to improve visibility of the command in logging output.

  • log – a logging function to use for logging of command output. By default, logger.debug is used.

  • silent – if set, logging of steps taken by this function would be reduced.

property run_workdir: Path

Path to a run workdir.

Raises:

GeneralError – when there is no current run, or the run does not have a workdir yet.

save() GuestData

Save guest data for future wake up

Export all essential guest data into a dictionary which will be stored in the guests.yaml file for possible future wake up of the guest. Everything needed to attach to a running instance should be added into the data dictionary by child classes.

property scripts_path: Path

Absolute path to tmt scripts directory

setup() None

Setup the guest

Setup the guest after it has been started. It is called after Guest.start().

setup_logs(*, logger: Logger) None

Notify all registered logs their collection will begin.

Parameters:

logger – logger to use for logging.

show(show_multihost_name: bool = True) None

Show guest details such as distro and kernel

start() None

Start the guest

Get a new guest instance running. This should include preparing any configuration necessary to get it started. Called after load() is completed so all guest data should be available.

property step_workdir: Path

Path to a step workdir.

Raises:

GeneralError – when there is no step workdir yet.

abstractmethod stop() None

Stop the guest

Shut down a running guest instance so that it does not consume any memory or cpu resources. If needed, perform any actions necessary to store the instance status to disk.

suspend() None

Suspend the guest.

Perform any actions necessary before quitting step and tmt. The guest may be reused by future tmt invocations.

teardown_logs(*, logger: Logger) None

Notify all registered logs their collection will no longer continue.

Parameters:

logger – logger to use for logging.

topology_address: str | None = None

Guest topology hostname or IP address for guest/guest communication.

update_logs(*, logger: Logger) None

Fetch the up-to-date content of guest logs, and update saved files.

Parameters:

logger – logger to use for logging.

wake() None

Wake up the guest

Perform any actions necessary after step wake up to be able to attach to a running guest instance and execute commands. Called after load() is completed so all guest data should be prepared.

class tmt.guest.GuestCapability(*values)

Bases: Enum

Various Linux capabilities

SYSLOG_ACTION_READ_ALL = 'syslog-action-read-all'

Read all messages remaining in the ring buffer.

SYSLOG_ACTION_READ_CLEAR = 'syslog-action-read-clear'

Read and clear all messages remaining in the ring buffer.

class tmt.guest.GuestData(_OPTIONLESS_FIELDS: tuple[str, ...] = ('primary_address', 'topology_address', 'facts'), primary_address: str | None = None, topology_address: str | None = None, role: str | None = None, become: bool = False, facts: ~tmt.guest.GuestFacts = <factory>, environment: ~tmt.utils.Environment = <factory>, hardware: ~tmt.hardware.Hardware | None = None, ansible: ~tmt.ansible.GuestAnsible | None = None)

Bases: SpecBasedContainer[_RawStepData, _RawStepData], SerializableContainer

Keys necessary to describe, create, save and restore a guest.

Very basic set of keys shared across all known guest classes.

ansible: GuestAnsible | None = None
become: bool = False
environment: Environment
facts: GuestFacts
classmethod from_plugin(container: ProvisionPlugin[ProvisionStepDataT]) Self

Create guest data from plugin and its current configuration

classmethod from_spec(raw_data: _RawStepData, logger: Logger) Self

Convert from a specification file or from a CLI option

See https://tmt.readthedocs.io/en/stable/code/classes.html#class-conversions for more details.

See to_spec() for its counterpart.

hardware: Hardware | None = None
classmethod options() Iterator[tuple[str, str]]

Iterate over option names.

Based on keys(), but skips fields that cannot be set by options.

Yields:

two-item tuples, a key and corresponding option name.

primary_address: str | None = None

Primary hostname or IP address for tmt/guest communication.

role: str | None = None
show(*, keys: list[str] | None = None, verbose: int = 0, logger: Logger) None

Display guest data in a nice way.

Parameters:
  • keys – if set, only these keys would be shown.

  • verbose – desired verbosity. Some fields may be omitted in low verbosity modes.

  • logger – logger to use for logging.

to_spec() _RawStepData

Convert to a form suitable for saving in a specification file

See https://tmt.readthedocs.io/en/stable/code/classes.html#class-conversions for more details.

See from_spec() for its counterpart.

topology_address: str | None = None

Guest topology hostname or IP address for guest/guest communication.

class tmt.guest.GuestFacts(in_sync: bool = False, arch: str | None = None, distro: str | None = None, kernel_release: str | None = None, package_manager: tmt.package_managers.GuestPackageManager | None = None, bootc_builder: tmt.package_managers.GuestPackageManager | None = None, has_selinux: bool | None = None, has_systemd: bool | None = None, has_rsync: bool | None = None, is_superuser: bool | None = None, can_sudo: bool | None = None, sudo_prefix: str | None = None, is_ostree: bool | None = None, is_image_mode: bool | None = None, is_toolbox: bool | None = None, toolbox_container_name: str | None = None, is_container: bool | None = None, systemd_soft_reboot: bool | None = None, capabilities: dict[~tmt.guest.GuestCapability, bool] = <factory>, os_release_content: dict[str, str] = <factory>, lsb_release_content: dict[str, str] = <factory>)

Bases: SerializableContainer

Contains interesting facts about the guest.

Inspired by Ansible or Puppet facts, interesting guest facts tmt discovers while managing the guest are stored in this container, plus the code performing the discovery of these facts.

arch: str | None = None
bootc_builder: tmt.package_managers.GuestPackageManager | None = None
can_sudo: bool | None = None
capabilities: dict[GuestCapability, bool]

Various Linux capabilities and whether they are permitted to commands executed on this guest.

distro: str | None = None
format() Iterator[tuple[str, str, str]]

Format facts for pretty printing.

Yields:

three-item tuples: the field name, its pretty label, and formatted representation of its value.

has_capability(cap: GuestCapability) bool
has_rsync: bool | None = None
has_selinux: bool | None = None
has_systemd: bool | None = None
in_sync: bool = False

Set to True by the first call to sync().

is_container: bool | None = None
is_image_mode: bool | None = None
is_ostree: bool | None = None
is_superuser: bool | None = None
is_toolbox: bool | None = None
kernel_release: str | None = None
lsb_release_content: dict[str, str]
os_release_content: dict[str, str]
package_manager: tmt.package_managers.GuestPackageManager | None = None
sudo_prefix: str | None = None
sync(guest: Guest, *facts: str) None

Update stored facts to reflect the given guest.

Parameters:
  • guest – guest whose facts this container should represent.

  • facts – if specified, only the listed facts - names of attributes of this container, like arch or is_container - will be synced.

systemd_soft_reboot: bool | None = None
toolbox_container_name: str | None = None
class tmt.guest.GuestLog(name: str, guest: Guest)

Bases: ABC

Represents a single guest log.

Guest logs are files collected by tmt, containing a wide variety of information about the guest and its behavior. They are not tied to a particular phase or test, instead they document what was happening on the guest while tmt was running its phases.

The actual set of available guest logs, and the way of their acquisition, depends entirely on the plugin providing the guest and its backing infrastructure. Some plugins may simply inspect local files or services, some plugins need to communicate with a hypervisor powering the guest, and so on.

Eventually, guest logs are stored on the runner, as a collection of files, for user to review if needed.

Log life cycle

  • GuestLog instances shall be created by plugin once possible in the context of the guest and its implementation, and added to the Guest.guest_logs list. Generally, it should be possible to fetch content of the log.

  • Once Guest.guest_logs is populated, the plugin shall invoke Guest.setup_logs(). This method is responsible for invoking setup() of all registered logs.

  • After this point, tmt may start collecting logs by invoking their update() methods. It is allowed for the log to not be available yet, the log may be empty, other issues shall raise an exception.

  • The cleanup step will collect logs one more time.

  • The cleanup step will invoke Guest.teardown_logs(), which will invoke teardown() methods of all registered logs.

  • After this point, logs will not be collected anymore.

property filename: str

A filename to use when storing the log.

By default, the name of the log is used.

property filepath: Path

A filepath to use when storing the log.

guest: Guest

Guest whose log this instance represents.

name: str

Name of the guest log.

setup(*, logger: Logger) None

Prepare for collecting the log.

It is left for plugins to setup the needed infrastructure, make API calls, etc.

Parameters:

logger – logger to use for logging.

staging_file(final_filepath: Path, logger: Logger) Iterator[Path]

Provide a temporary file to be swapped with the final filepath.

Instead of writing directly into the final log filepath, log update should write its new content into a temporary file which, should everything go well, would replace the existing content in an atomic move. That way the existing content would not be compromised or broken by a failed update.

Parameters:
  • final_filepath – the desired final filepath, the temporary file would replace this filepath on success.

  • logger – logger to use for logging.

teardown(*, logger: Logger) None

Finalize the collection of the log.

It is left for plugins to tear down and remove what is no longer needed once the log stops being collected.

Parameters:

logger – logger to use for logging.

abstractmethod update(*, logger: Logger) None

Fetch the up-to-date content of the log, and save it into a file.

Parameters:

logger – logger to use for logging.

class tmt.guest.GuestSsh(*, data: GuestData, name: str | None = None, parent: Common | None = None, logger: Logger)

Bases: Guest, CommandCollector

Guest provisioned for test execution, capable of accepting SSH connections

This class implements CommandCollector to support guests in image mode. When running in image mode, commands with immediately=False are collected into a Containerfile rather than executed immediately and applied on step completion.

The following keys are expected in the ‘data’ dictionary:

role ....... guest role in the multihost scenario (inherited)
guest ...... hostname or ip address (inherited)
become ..... run shell scripts in tests, prepare, and finish with sudo (inherited)
port ....... port to connect to
user ....... user name to log in
key ........ path to the private key (str or list)
password ... password

These are by default imported into instance attributes.

Initialize guest data

property ansible_host_vars: dict[str, Any]

Get host variables for Ansible inventory with SSH-specific variables.

cli_invocation: 'tmt.cli.CliInvocation' | None = None
collect_command(command: Command | ShellScript, *, sourced_files: list[Path] | None = None, cwd: Path | None = None, env: Environment | None = None) None

Collect a command for image mode container build.

Adds a RUN directive to the bootc package manager’s Containerfile. Uses the same environment and cwd handling as regular execute().

execute(command: Command | ShellScript, cwd: Path | None = None, env: Environment | None = None, friendly_command: str | None = None, test_session: bool = False, immediately: Literal[True] = True, tty: bool = False, silent: bool = False, log: LoggingFunction | None = None, interactive: bool = False, on_process_start: Callable[[Command, Popen[bytes], Logger], None] | None = None, on_process_end: OnProcessEndCallback | None = None, sourced_files: list[Path] | None = None, **kwargs: Any) CommandOutput
execute(command: Command | ShellScript, cwd: Path | None = None, env: Environment | None = None, friendly_command: str | None = None, test_session: bool = False, immediately: Literal[False] = False, tty: bool = False, silent: bool = False, log: LoggingFunction | None = None, interactive: bool = False, on_process_start: Callable[[Command, Popen[bytes], Logger], None] | None = None, on_process_end: OnProcessEndCallback | None = None, sourced_files: list[Path] | None = None, **kwargs: Any) CommandOutput | None

Execute a command on the guest.

Parameters:
  • command – either a command or a shell script to execute.

  • cwd – execute command in this directory on the guest.

  • env – if set, set these environment variables before running the command.

  • friendly_command – nice, human-friendly representation of the command.

  • test_session – if True, this is the actual test being run.

  • immediately – if False, the command may be collected for later batch execution on guests that support it (e.g., bootc guests). Commands with immediately=True (default) are always executed right away. Use immediately=False for commands that modify system state and can be batched (e.g., package installation). When a command is deferred, None is returned instead of CommandOutput.

Returns:

command output, or None if the command was deferred for batch execution (when immediately=False on supported guests).

flush_collected() None

Build image mode container image from collected commands, switch, and reboot.

Delegates to the bootc package manager’s build_container() method.

property has_collected_commands: bool

Check if there are collected commands to be applied.

property is_ready: bool

Detect guest is ready or not

property is_ssh_multiplexing_enabled: bool

Whether SSH multiplexing should be used

key: list[Path]
on_step_complete(step: Step) None

Called when a step completes execution.

Flush collected commands if there are some.

Parameters:

step – the step that has completed.

password: str | None
port: int | None
pull(source: Path | None = None, destination: Path | None = None, options: TransferOptions | None = None) None

Pull files from the guest.

By default the whole plan workdir is synced from the same location on the guest. Use the source and destination to sync custom locations.

Parameters:
  • source – if set, this path will be downloaded from the guest. If not set, plan workdir is downloaded.

  • destination – if set, content will be downloaded to this path. If not set, root (/) is used.

  • options – custom transfer options to use instead of DEFAULT_PULL_OPTIONS.

push(source: Path | None = None, destination: Path | None = None, options: TransferOptions | None = None, superuser: bool = False) None

Push files to the guest.

By default the whole plan workdir is synced to the same location on the guest. Use the source and destination to sync custom locations.

Parameters:
  • source – if set, this path will be uploaded to the guest. If not set, plan workdir is uploaded.

  • destination – if set, content will be uploaded to this path. If not set, root (/) is used.

  • options – custom transfer options to use instead of DEFAULT_PUSH_OPTIONS.

  • superuser – if set, use sudo if user is not privileged. It is necessary for pushing to locations that only privileged users are allowed to modify.

reboot(mode: Literal[RebootMode.HARD] = RebootMode.HARD, command: None = None, waiting: Waiting | None = None) bool
reboot(mode: Literal[RebootMode.SOFT, RebootMode.SYSTEMD_SOFT] = RebootMode.SOFT, command: Command | ShellScript | None = None, waiting: Waiting | None = None) bool

Reboot the guest, and wait for the guest to recover.

Parameters:
  • mode – which boot mode to perform.

  • command – a command to run on the guest to trigger the reboot. Only usable when mode is not RebootMode.HARD.

  • waiting – deadline for the reboot.

Returns:

True if the reboot succeeded, False otherwise.

remove() None

Remove the guest

Completely remove all guest instance data so that it does not consume any disk resources.

setup() None

Setup the guest

Setup the guest after it has been started. It is called after Guest.start().

ssh_option: list[str]
stop() None

Stop the guest

Shut down a running guest instance so that it does not consume any memory or cpu resources. If needed, perform any actions necessary to store the instance status to disk.

suspend() None

Suspend the guest.

Perform any actions necessary before quitting step and tmt. The guest may be reused by future tmt invocations.

user: str | None
class tmt.guest.GuestSshData(_OPTIONLESS_FIELDS: tuple[str, ...] = ('primary_address', 'topology_address', 'facts'), primary_address: str | None = None, topology_address: str | None = None, role: str | None = None, become: bool = False, facts: ~tmt.guest.GuestFacts = <factory>, environment: ~tmt.utils.Environment = <factory>, hardware: ~tmt.hardware.Hardware | None = None, ansible: ~tmt.ansible.GuestAnsible | None = None, port: int | None = None, user: str = 'root', key: list[~tmt._compat.pathlib.Path] = <factory>, password: str | None = None, ssh_option: list[str] = <factory>)

Bases: GuestData

Keys necessary to describe, create, save and restore a guest with SSH capability.

Derived from GuestData, this class adds keys relevant for guests that can be reached over SSH.

key: list[Path]
password: str | None = None
port: int | None = None
ssh_option: list[str]
user: str = 'root'
tmt.guest.REBOOT_TIMEOUT: int = 600

How many seconds to wait for a connection to succeed after guest reboot. This is the effective value, combining the default and optional envvar, TMT_REBOOT_TIMEOUT.

class tmt.guest.RebootMode(*values)

Bases: Enum

HARD = 'hard'

A hardware-invoked reboot of the guest. Power off/power on kind of reboot.

SOFT = 'soft'

A software-invoked reboot of the guest. reboot or shutdown -r now kind of reboot.

SYSTEMD_SOFT = 'systemd-soft'

A software-invoked reboot of the guest userspace. systemd soft-reboot kind of reboot.

See https://www.freedesktop.org/software/systemd/man/latest/systemd-soft-reboot.service.html for systemd documentation on soft-reboot.

exception tmt.guest.RebootModeNotSupportedError(message: str | None = None, guest: Guest | None = None, mode: RebootMode = RebootMode.SOFT, *args: Any, **kwargs: Any)

Bases: ProvisionError

A requested reboot mode is not supported by the guest

General error.

Parameters:
  • message – error message.

  • causes – optional list of exceptions that caused this one. Since raise ... from ... allows only for a single cause, and some of our workflows may raise exceptions triggered by more than one exception, we need a mechanism for storing them. Our reporting will honor this field, and report causes the same way as __cause__.

tmt.guest.SSH_MASTER_SOCKET_LENGTH_LIMIT = 84

SSH master socket path is limited to this many characters.

  • UNIX socket path is limited to either 108 or 104 characters, depending on the platform. See man 7 unix and/or kernel sources, for example.

  • SSH client processes may create paths with added “connection hash” when connecting to the master, that is a couple of characters we need space for.

tmt.guest.SSH_MASTER_SOCKET_MAX_HASH_LENGTH = 64

A maximal number of characters of guest ID hash used by _socket_path_hash() when looking for a free SSH socket filename.

tmt.guest.SSH_MASTER_SOCKET_MIN_HASH_LENGTH = 4

A minimal number of characters of guest ID hash used by _socket_path_hash() when looking for a free SSH socket filename.

tmt.guest.STAT_BTIME_PATTERN = re.compile('btime\\s+(\\d+)')

A pattern to extract btime from /proc/stat file.

class tmt.guest.TransferOptions(chmod: int | None = None, compress: bool = False, delete: bool = False, exclude: list[str] = <factory>, links: bool = False, preserve_perms: bool = False, protect_args: bool = False, recursive: bool = False, relative: bool = False, safe_links: bool = False, create_destination: bool = False)

Bases: object

Options for transferring files to/from the guest.

chmod: int | None = None

Apply permissions to the destination files

compress: bool = False

Enable compression during transfer

copy() TransferOptions

Create a copy of the options.

create_destination: bool = False

Run a mkdir -p of the destination before doing transfer

delete: bool = False

Delete extraneous files from destination directory

exclude: list[str]

Exclude files matching any of these patterns

Copy symlinks as symlinks

preserve_perms: bool = False

Preserve file permissions

protect_args: bool = False

Protect file and directory names from interpretation

recursive: bool = False

Recurse into directories

relative: bool = False

Use relative paths

Ignore symlinks that point outside the source tree

to_rsync() list[str]

Convert to rsync command line options.

tmt.guest.configure_ssh_options() list[str | Path]

Extract custom SSH options from environment variables

tmt.guest.default_connect_waiting() Waiting

Create default waiting context for connecting to the guest.

tmt.guest.default_reboot_waiting() Waiting

Create default waiting context for guest reboots.

tmt.guest.default_reconnect_waiting() Waiting

Create default waiting context for guest reconnect.

tmt.guest.essential_ansible_requires() list[DependencySimple | DependencyFmfId | DependencyFile]

Return essential requirements for running Ansible modules

tmt.guest.format_guest_full_name(name: str, role: str | None) str

Render guest’s full name, i.e. name and its role

tmt.guest.normalize_hardware(key_address: str, raw_hardware: None | Any | Hardware, logger: Logger) Hardware | None

Normalize a hardware key value.

Parameters:
  • key_address – location of the key being that’s being normalized.

  • logger – logger to use for logging.

  • raw_hardware – input from either command line or fmf node.