sos.policies — Policy Interface

class sos.policies.ContainerRuntime(policy=None)[source]

Bases: object

Encapsulates a container runtime that provides the ability to plugins to check runtime status, check for the presence of specific containers, and to format commands to run in those containers

Parameters:

policy (Policy()) – The loaded policy for the system

Variables:
  • name (str) – The name of the container runtime, e.g. ‘podman’
  • containers (list) – A list of containers known to the runtime
  • images (list) – A list of images known to the runtime
  • binary (str) – The binary command to run for the runtime, must exit within $PATH
check_is_active()[source]

Check to see if the container runtime is both present AND active.

Active in this sense means that the runtime can be used to glean information about the runtime itself and containers that are running.

Returns:True if the runtime is active, else False
Return type:bool
fmt_container_cmd(container, cmd)[source]

Format a command to run inside a container using the runtime

Parameters:
  • container (str) – The name or ID of the container in which to run
  • cmd (str) – The command to run inside container
Returns:

Formatted string to run cmd inside container

Return type:

str

get_container_by_name(name)[source]

Get the container ID for the container matching the provided name

Parameters:name (str) – The name of the container, note this can be a regex
Returns:The id of the first container to match name, else None
Return type:str
get_containers(get_all=False)[source]

Get a list of containers present on the system.

Parameters:get_all (bool) – If set, include stopped containers as well
get_images()[source]

Get a list of images present on the system

Returns:A list of 2-tuples containing (image_name, image_id)
Return type:list
get_logs_command(container)[source]

Get the command string used to dump container logs from the runtime

Parameters:container (str) – The name or ID of the container to get logs for
Returns:Formatted runtime command to get logs from container
Type:str
get_volumes()[source]

Get a list of container volumes present on the system

Returns:A list of volume IDs on the system
Return type:list
load_container_info()[source]

If this runtime is found to be active, attempt to load information on the objects existing in the runtime.

sos.policies.DESC = 'desc'

Constants for on-disk preset fields

class sos.policies.DockerContainerRuntime(policy=None)[source]

Bases: sos.policies.ContainerRuntime

Runtime class to use for systems running Docker

check_is_active()[source]

Check to see if the container runtime is both present AND active.

Active in this sense means that the runtime can be used to glean information about the runtime itself and containers that are running.

Returns:True if the runtime is active, else False
Return type:bool
class sos.policies.GenericPolicy(sysroot=None, probe_runtime=True)[source]

Bases: sos.policies.Policy

This Policy will be returned if no other policy can be loaded. This should allow for IndependentPlugins to be executed on any system

get_msg()[source]

This method is used to prepare the preamble text to display to the user in non-batch mode. If your policy sets self.distro that text will be substituted accordingly. You can also override this method to do something more complicated.

Returns:Formatted banner message string
Return type:str
class sos.policies.InitSystem(init_cmd=None, list_cmd=None, query_cmd=None)[source]

Bases: object

Encapsulates an init system to provide service-oriented functions to sos.

This should be used to query the status of services, such as if they are enabled or disabled on boot, or if the service is currently running.

Parameters:
  • init_cmd (str) – The binary used to interact with the init system
  • list_cmd (str) – The list subcmd given to init_cmd to list services
  • query_cmd (str) – The query subcmd given to query_cmd to query the status of services
get_service_names(regex)[source]

Get a list of all services discovered on the system that match the given regex.

Parameters:regex (str) – The service name regex to match against
get_service_status(name)[source]

Get the status for the given service name along with the output of the query command

Parameters:name (str) – The name of the service
Returns:Service status and query_cmd output from the init system
Return type:dict with keys name, status, and output
is_disabled(name)[source]

Check if a given service name is disabled :param name: The name of the service :type name: str

Returns:True if the service is disabled, else False
Return type:bool
is_enabled(name)[source]

Check if given service name is enabled

Parameters:name (str) – The name of the service
Returns:True if the service is enabled, else False
Return type:bool
is_running(name)[source]

Checks if the given service name is in a running state.

This should be overridden by initsystems that subclass InitSystem

Parameters:name (str) – The name of the service
Returns:True if the service is running, else False
Return type:bool
is_service(name)[source]

Checks if the given service name exists on the system at all, this does not check for the service status

Parameters:name (str) – The name of the service
Returns:True if the service exists, else False
Return type:bool
load_all_services()[source]

This loads all services known to the init system into a dict. The dict should be keyed by the service name, and contain a dict of the name and service status

This must be overridden by anything that subclasses InitSystem in order for service methods to function properly

parse_query(output)[source]

Parses the output returned by the query command to make a determination of what the state of the service is

This should be overriden by anything that subclasses InitSystem

Parameters:output (str) – The raw output from querying the service with the configured query_cmd
Returns:A state for the service, e.g. ‘active’, ‘disabled’, etc…
Return type:str
class sos.policies.LinuxPolicy(sysroot=None, init=None, probe_runtime=True)[source]

Bases: sos.policies.Policy

This policy is meant to be an abc class that provides common implementations used in Linux distros

create_sos_container()[source]

Returns the command that will create the container that will be used for running commands inside a container on hosts that require it.

This will use the container runtime defined for the host type to launch a container. From there, we use the defined runtime to exec into the container’s namespace.

format_container_command(cmd)[source]

Returns the command that allows us to exec into the created container for sos collect.

Parameters:cmd (str) – The command to run in the sos container
Returns:The command to execute to run cmd in the container
Return type:str
get_local_name()[source]

Returns the name usd in the pre_work step

get_preferred_hash_name()[source]

Returns the string name of the hashlib-supported checksum algorithm to use

get_upload_https_auth(user=None, password=None)[source]

Formats the user/password credentials using basic auth

Parameters:
  • user (str) – The username for upload
  • password (str) – Password for user to use for upload
Returns:

The user/password auth suitable for use in reqests calls

Return type:

requests.auth.HTTPBasicAuth()

get_upload_password()[source]

Helper function to determine if we should use the policy default upload password or one provided by the user

Returns:The password to use for upload
Return type:str
get_upload_url()[source]

Helper function to determine if we should use the policy default upload url or one provided by the user

Returns:The URL to use for upload
Return type:str
get_upload_url_string()[source]

Used by distro policies to potentially change the string used to report upload location from the URL to a more human-friendly string

get_upload_user()[source]

Helper function to determine if we should use the policy default upload user or one provided by the user

Returns:The username to use for upload
Return type:str
init_kernel_modules()[source]

Obtain a list of loaded kernel modules to reference later for plugin enablement and SoSPredicate checks

pre_work()[source]

This function is called prior to collection.

prompt_for_upload_password()[source]

Should be overridden by policies to determine if a password needs to be provided for upload or not

prompt_for_upload_user()[source]

Should be overridden by policies to determine if a user needs to be provided or not

restart_sos_container()[source]

Restarts the container created for sos collect if it has stopped.

This is called immediately after create_sos_container() as the command to create the container will exit and the container will stop. For current container runtimes, subsequently starting the container will default to opening a bash shell in the container to keep it running, thus allowing us to exec into it again.

set_cleanup_cmd()[source]

If a host requires additional cleanup, the command should be set and returned here

set_sos_prefix()[source]

If sosreport commands need to always be prefixed with something, for example running in a specific container image, then it should be defined here.

If no prefix should be set, return an empty string instead of None.

upload_archive(archive)[source]

Entry point for sos attempts to upload the generated archive to a policy or user specified location.

Curerntly there is support for HTTPS, SFTP, and FTP. HTTPS uploads are preferred for policy-defined defaults.

Policies that need to override uploading methods should override the respective upload_https(), upload_sftp(), and/or upload_ftp() methods and should NOT override this method.

Parameters:archive (str) – The archive filepath to use for upload

In order to enable this for a policy, that policy needs to implement the following:

Required Class Attrs

_upload_url:The default location to use. Note these MUST include protocol header
_upload_user:Default username, if any else None
_upload_password:
 Default password, if any else None
_use_https_streaming:
 Set to True if the HTTPS endpoint supports streaming data

The following Class Attrs may optionally be overidden by the Policy

_upload_directory:
 Default FTP server directory, if any

The following methods may be overridden by Policy as needed

prompt_for_upload_user()
Determines if sos should prompt for a username or not.
get_upload_user()
Determines if the default or a different username should be used
get_upload_https_auth()
Format authentication data for HTTPS uploads
get_upload_url_string()
Print a more human-friendly string than vendor URLs
upload_ftp(url=None, directory=None, user=None, password=None)[source]

Attempts to upload the archive to either the policy defined or user provided FTP location.

Parameters:
  • url (str) – The URL to upload to
  • directory (str or None) – The directory on the FTP server to write to
  • user (str) – The user to authenticate with
  • password (str) – The password to use for user
Returns:

True if upload is successful

Return type:

bool

Raises:

Exception if upload in unsuccessful

upload_https()[source]

Attempts to upload the archive to an HTTPS location.

Policies may define whether this upload attempt should use streaming or non-streaming data by setting the use_https_streaming class attr to True

Returns:True if upload is successful
Return type:bool
Raises:Exception if upload was unsuccessful
upload_sftp()[source]

Attempts to upload the archive to an SFTP location.

Due to the lack of well maintained, secure, and generally widespread python libraries for SFTP, sos will shell-out to the system’s local ssh installation in order to handle these uploads.

Do not override this method with one that uses python-paramiko, as the upstream sos team will reject any PR that includes that dependency.

class sos.policies.PackageManager(chroot=None, query_command=None, verify_command=None, verify_filter=None, files_command=None, remote_exec=None)[source]

Bases: object

Encapsulates a package manager. If you provide a query_command to the constructor it should print each package on the system in the following format:

package name|package.version

You may also subclass this class and provide a get_pkg_list method to build the list of packages and versions.

Variables:
  • query_command (str or None) – The command to use for querying packages
  • verify_command (str or None) – The command to use for verifying packages
  • verify_filter (str or ``None) – Optional filter to use for controlling package verification
  • files_command (str or None) – The command to use for getting file lists for packages
  • chroot (bool) – Perform a chroot when executing files_command
  • remote_exec (str or None) – If package manager is on a remote system (e.g. for sos collect), prepend this SSH command to run remotely
all_files()[source]

Get a list of files known by the package manager

Returns:All files known by the package manager
Return type:list
all_pkgs()[source]

Get a list of all packages.

Returns:All packages, with name and version, installed on the system
Return type:dict
all_pkgs_by_name(name)[source]

Get a list of packages that match name.

Parameters:name (str) – The name of the package
Returns:List of all packages matching name
Return type:list
all_pkgs_by_name_regex(regex_name, flags=0)[source]

Get a list of packages that match regex_name.

Parameters:
  • regex_name (str) – The regex to use for matching package names against
  • flags – Flags for the re module when matching regex_name
Returns:

All packages matching regex_name

Return type:

list

build_verify_command(self, packages) → str[source]

Generate a command to verify the list of packages given in packages using the native package manager’s verification tool.

The command to be executed is returned as a string that may be passed to a command execution routine (for e.g. sos_get_command_output().

Parameters:packages – a string, or a list of strings giving package names to be verified.
Returns:a string containing an executable command that will perform verification of the given packages.
Return type:str or NoneType
get_pkg_list()[source]

Returns a dictionary of packages in the following format:

{'package_name': {'name': 'package_name',
                  'version': 'major.minor.version'}}
pkg_by_name(name)[source]

Get a single package that matches name.

Parameters:name (str) – The name of the package
Returns:The first package that matches name
Return type:str
pkg_nvra(pkg)[source]

Get the name, version, release, and architecture for a package

Parameters:pkg (str) – The name of the package
Returns:name, version, release, and arch of the package
Return type:tuple
pkg_version(pkg)[source]

Returns the entry in self.packages for pkg if it exists

Parameters:pkg (str) – The name of the package
Returns:Package name and version, if package exists
Return type:dict if found, else None
class sos.policies.PodmanContainerRuntime(policy=None)[source]

Bases: sos.policies.ContainerRuntime

Runtime class to use for systems running Podman

class sos.policies.Policy(sysroot=None, probe_runtime=True)[source]

Bases: object

Policies represent distributions that sos supports, and define the way in which sos behaves on those distributions. A policy should define at minimum a way to identify the distribution, and a package manager to allow for package based plugin enablement.

Policies also control preferred ContainerRuntime()’s, upload support to default locations for distribution vendors, disclaimer text, and default presets supported by that distribution or vendor’s products.

Every Policy will also need at least one “tagging class” for plugins.

Parameters:
  • sysroot (str or None) – Set the sysroot for the system, if not /
  • probe_runtime (bool) – Should the Policy try to load a ContainerRuntime
Variables:
  • distro (str) – The name of the distribution the Policy represents
  • vendor (str) – The name of the vendor producing the distribution
  • vendor_url (str) – URL for the vendor’s website, or support portal
  • vendor_text (str) – Additional text to add to the banner message
  • name_pattern (str) – The naming pattern to be used for naming archives generated by sos. Values of legacy, and friendly are preset patterns. May also be set to an explicit custom pattern, see get_archive_name()
add_preset(name=None, desc=None, note=None, opts=SoSOptions())[source]

Add a new on-disk preset and write it to the configured presets path.

Parameters:preset – the new PresetDefaults to add
check(remote='')[source]

This function is responsible for determining if the underlying system is supported by this policy.

If remote is provided, it should be the contents of os-release from a remote host, or a similar vendor-specific file that can be used in place of a locally available file.

Returns:True if the Policy should be loaded, else False
Return type:bool
display_results(archive, directory, checksum, archivestat=None, map_file=None)[source]

Display final information about a generated archive

Parameters:
  • archive (str) – The name of the archive that was generated
  • directory (str) – The build directory for sos if –build was used
  • checksum (str) – The checksum of the archive
  • archivestat (os.stat_result) – stat() information for the archive
  • map_file (str) – If sos clean was invoked, the location of the mapping file for this run
dist_version()[source]

Return the OS version

find_preset(preset)[source]

Find a preset profile matching the specified preset string.

Parameters:preset – a string containing a preset profile name.
Returns:a matching PresetProfile.
get_archive_name()[source]

This function should return the filename of the archive without the extension.

This uses the policy’s name_pattern attribute to determine the name. There are two pre-defined naming patterns - legacy and friendly that give names like the following:

  • legacy - sosreport-tux.123456-20171224185433
  • friendly - sosreport-tux-mylabel-123456-2017-12-24-ezcfcop.tar.xz

A custom name_pattern can be used by a policy provided that it defines name_pattern using a format() style string substitution.

Usable substitutions are:

  • name - the short hostname of the system
  • label - the label given by –label
  • case - the case id given by –case-id or –ticker-number
  • rand - a random string of 7 alpha characters

Note that if a datestamp is needed, the substring should be set in name_pattern in the format accepted by strftime().

Returns:A name to be used for the archive, as expanded from the Policy name_pattern
Return type:str
get_cmd_for_compress_method(method, threads)[source]

Determine the command to use for compressing the archive

Parameters:
  • method (str) – The compression method/binary to use
  • threads (int) – Number of threads compression should use
Returns:

Full command to use to compress the archive

Return type:

str

get_msg()[source]

This method is used to prepare the preamble text to display to the user in non-batch mode. If your policy sets self.distro that text will be substituted accordingly. You can also override this method to do something more complicated.

Returns:Formatted banner message string
Return type:str
get_preferred_archive()[source]

Return the class object of the prefered archive format for this platform

get_preferred_hash_name()[source]

Returns the string name of the hashlib-supported checksum algorithm to use

host_sysroot()[source]

Get the host’s default sysroot

Returns:Host sysroot
Return type:str or None
in_container()[source]

Are we running inside a container?

Returns:True if in a container, else False
Return type:bool
is_root()[source]

This method should return true if the user calling the script is considered to be a superuser

Returns:True if user is superuser, else False
Return type:bool
load_presets(presets_path=None)[source]

Load presets from disk.

Read JSON formatted preset data from the specified path, or the default location at /var/lib/sos/presets.

Parameters:presets_path – a directory containing JSON presets.
match_plugin(plugin_classes)[source]

Determine what subclass of a Plugin should be used based on the tagging classes assigned to the Plugin

Parameters:plugin_classes (list) – The classes that the Plugin subclasses
Returns:The first subclass that matches one of the Policy’s valid_subclasses
Return type:A tagging class for Plugins
pkg_by_name(pkg)[source]

Wrapper to retrieve a package from the Policy’s package manager

Parameters:pkg (str) – The name of the package
Returns:The first package that matches pkg
Return type:str
post_work()[source]

This function is called after the sosreport has been generated.

pre_work()[source]

This function is called prior to collection.

probe_preset()[source]

Return a PresetDefaults object matching the runing host.

Stub method to be implemented by derived policy classes.

Returns:a PresetDefaults object.
register_presets(presets, replace=False)[source]

Add new presets to this policy object.

Merges the presets dictionary presets into this Policy object, or replaces the current presets if replace is True.

presets should be a dictionary mapping str preset names to <class PresetDefaults> objects specifying the command line defaults.

Parameters:
  • presets – dictionary of presets to add or replace
  • replace – replace presets rather than merge new presets.
set_commons(commons)[source]

Set common host data for the Policy to reference

valid_subclasses

list of subclasses that this policy can process

validate_plugin(plugin_class, experimental=False)[source]

Verifies that the plugin_class should execute under this policy

Parameters:plugin_class (A Plugin() tagging class) – The tagging class being checked
Returns:True if the plugin_class is allowed by the policy
Return type:bool
class sos.policies.PresetDefaults(name='', desc='', note=None, opts=SoSOptions())[source]

Bases: object

Preset command line defaults to allow for quick reference to sets of commonly used options

Parameters:
  • name (str) – The name of the new preset
  • desc (str) – A description for the new preset
  • note (str) – Note for the new preset
  • opts (SoSOptions) – Options set for the new preset
builtin = True

True if this preset if built-in or False otherwise.

delete(presets_path)[source]

Delete a preset from disk

Parameters:presets_path (str) – the directory where the preset is saved
desc = None

Human readable preset description

name = None

Preset name, used for selection

note = None

Notes on preset behaviour

opts = SoSOptions()

Options set for this preset

write(presets_path)[source]

Write this preset to disk in JSON notation.

Parameters:presets_path (str) – the directory where the preset will be written
class sos.policies.SystemdInit[source]

Bases: sos.policies.InitSystem

InitSystem abstraction for SystemD systems

is_running(name)[source]

Checks if the given service name is in a running state.

This should be overridden by initsystems that subclass InitSystem

Parameters:name (str) – The name of the service
Returns:True if the service is running, else False
Return type:bool
load_all_services()[source]

This loads all services known to the init system into a dict. The dict should be keyed by the service name, and contain a dict of the name and service status

This must be overridden by anything that subclasses InitSystem in order for service methods to function properly

parse_query(output)[source]

Parses the output returned by the query command to make a determination of what the state of the service is

This should be overriden by anything that subclasses InitSystem

Parameters:output (str) – The raw output from querying the service with the configured query_cmd
Returns:A state for the service, e.g. ‘active’, ‘disabled’, etc…
Return type:str