The nova.utils Module

Utilities and helper functions.

class ExceptionHelper(target)

Bases: object

Class to wrap another and translate the ClientExceptions raised by its function calls to the actual ones.

class RootwrapDaemonHelper(rootwrap_config)

Bases: nova.utils.RootwrapProcessHelper

execute(*cmd, **kwargs)
trycmd(*args, **kwargs)
class RootwrapProcessHelper

Bases: object

execute(*cmd, **kwargs)
trycmd(*cmd, **kwargs)
class UndoManager

Bases: object

Provides a mechanism to facilitate rolling back a series of actions when an exception is raised.

rollback_and_reraise(msg=None, **kwargs)

Rollback a series of actions then re-raise the exception.

Note

(sirp) This should only be called within an exception handler.

undo_with(undo_func)
check_isinstance(obj, cls)

Checks that obj is of type cls, and lets PyLint infer types.

check_string_length(value, name=None, min_length=0, max_length=None)

Check the length of specified string :param value: the value of the string :param name: the name of the string :param min_length: the min_length of the string :param max_length: the max_length of the string

delete_cached_file(filename)

Delete cached file if present.

Parameters:filename – filename to delete
dict_to_metadata(metadata)
execute(*cmd, **kwargs)

Convenience wrapper around oslo’s execute() method.

expects_func_args(*args)
filter_and_format_resource_metadata(resource_type, resource_list, search_filts, metadata_type=None)

Get all metadata for a list of resources after filtering.

Search_filts is a list of dictionaries, where the values in the dictionary can be string or regex string, or a list of strings/regex strings.

Let’s call a dict a ‘filter block’ and an item in the dict a ‘filter’. A tag is returned if it matches ALL the filters in a filter block. If more than one values are specified for a filter, a tag is returned if it matches ATLEAST ONE value of the filter. If more than one filter blocks are specified, the tag should match ALL the filter blocks.

For example:

search_filts = [{‘key’: [‘key1’, ‘key2’], ‘value’: ‘val1’},
{‘value’: ‘val2’}]
The filter translates to ‘match any tag for which’:
((key=key1 AND value=val1) OR (key=key2 AND value=val1)) AND
(value=val2)

This example filter will never match a tag.

param resource_type:
 The resource type as a string, e.g. ‘instance’
param resource_list:
 List of resource objects
param search_filts:
 Filters to filter metadata to be returned. Can be dict (e.g. {‘key’: ‘env’, ‘value’: ‘prod’}, or a list of dicts (e.g. [{‘key’: ‘env’}, {‘value’: ‘beta’}]. Note that the values of the dict can be regular expressions.
param metadata_type:
 Provided to search for a specific metadata type (e.g. ‘system_metadata’)
returns:List of dicts where each dict is of the form {‘key’: ‘somekey’, ‘value’: ‘somevalue’, ‘instance_id’: ‘some-instance-uuid-aaa’} if resource_type is ‘instance’.
format_remote_path(host, path)

Returns remote path in format acceptable for scp/rsync.

If host is IPv6 address literal, return ‘[host]:path’, otherwise ‘host:path’ is returned.

If host is None, only path is returned.

generate_mac_address()

Generate an Ethernet MAC address.

generate_password(length=None, symbolgroups=('23456789', 'ABCDEFGHJKLMNPQRSTUVWXYZ', 'abcdefghijkmnopqrstuvwxyz'))

Generate a random password from the supplied symbol groups.

At least one symbol from each group will be included. Unpredictable results if length is less than the number of symbol groups.

Believed to be reasonably secure (with a reasonable password length!)

generate_uid(topic, size=8)
get_auto_disk_config_from_image_props(image_properties)
get_auto_disk_config_from_instance(instance=None, sys_meta=None)
get_hash_str(base_str)

Returns string that represents MD5 hash of base_str (in hex format).

If base_str is a Unicode string, encode it to UTF-8.

get_image_from_system_metadata(system_meta)
get_image_metadata_from_volume(volume)
get_ip_version(network)

Returns the IP version of a network (IPv4 or IPv6).

Raises AddrFormatError if invalid network.

get_my_linklocal(interface)
get_root_helper()
get_shortened_ipv6(address)
get_shortened_ipv6_cidr(address)
get_system_metadata_from_image(image_meta, flavor=None)
instance_meta(instance)
instance_sys_meta(instance)
is_auto_disk_config_disabled(auto_disk_config_raw)
is_neutron()
is_none_string(val)

Check if a string represents a None value.

is_valid_cidr(address)

Check if address is valid

The provided address can be a IPv6 or a IPv4 CIDR address.

is_valid_ipv6_cidr(address)
isotime(at=None)

Current time as ISO string, as timeutils.isotime() is deprecated

Returns:Current time in ISO format
last_bytes(file_like_object, num)

Return num bytes from the end of the file, and remaining byte count.

Parameters:
  • file_like_object – The file to read
  • num – The number of bytes to return

:returns (data, remaining)

last_completed_audit_period(unit=None, before=None)

This method gives you the most recently completed audit period.

arguments:
units: string, one of ‘hour’, ‘day’, ‘month’, ‘year’
Periods normally begin at the beginning (UTC) of the period unit (So a ‘day’ period begins at midnight UTC, a ‘month’ unit on the 1st, a ‘year’ on Jan, 1) unit string may be appended with an optional offset like so: 'day@18‘ This will begin the period at 18:00 UTC. 'month@15‘ starts a monthly period on the 15th, and year@3 begins a yearly one on March 1st.
before: Give the audit period most recently completed before
<timestamp>. Defaults to now.
returns: 2 tuple of datetimes (begin, end)
The begin timestamp of this audit period is the same as the end of the previous.
make_dev_path(dev, partition=None, base='/dev')

Return a path to a particular device.

>>> make_dev_path('xvdc')
/dev/xvdc
>>> make_dev_path('xvdc', 1)
/dev/xvdc1
metadata_to_dict(metadata, include_deleted=False)
mkfs(fs, path, label=None, run_as_root=False)

Format a file or block device

Parameters:
  • fs – Filesystem type (examples include ‘swap’, ‘ext3’, ‘ext4’ ‘btrfs’, etc.)
  • path – Path to file or block device to format
  • label – Volume label to use
monkey_patch()

If the CONF.monkey_patch set as True, this function patches a decorator for all functions in specified modules. You can set decorators for each modules using CONF.monkey_patch_modules. The format is “Module path:Decorator function”. Example: ‘nova.api.ec2.cloud:nova.notifications.notify_decorator’

Parameters of the decorator is as follows. (See nova.notifications.notify_decorator)

name - name of the function function - object of the function

parse_server_string(server_str)

Parses the given server_string and returns a tuple of host and port. If it’s not a combination of host part and port, the port element is an empty string. If the input is invalid expression, return a tuple of two empty strings.

read_cached_file(filename, force_reload=False)

Read from a file if it has been modified.

Parameters:force_reload – Whether to reload the file.
Returns:A tuple with a boolean specifying if the data is fresh or not.
read_file_as_root(file_path)

Secure helper to read file as root.

safe_ip_format(ip)

Transform ip string to “safe” format.

Will return ipv4 addresses unchanged, but will nest ipv6 addresses inside square brackets.

safe_truncate(value, length)

Safely truncates unicode strings such that their encoded length is no greater than the length provided.

sanitize_hostname(hostname, default_name=None)

Return a hostname which conforms to RFC-952 and RFC-1123 specs except the length of hostname.

Window, Linux, and Dnsmasq has different limitation:

Windows: 255 (net_bios limits to 15, but window will truncate it) Linux: 64 Dnsmasq: 63

Due to nova-network will leverage dnsmasq to set hostname, so we chose 63.

spawn(func, *args, **kwargs)

Passthrough method for eventlet.spawn.

This utility exists so that it can be stubbed for testing without interfering with the service spawns.

It will also grab the context from the threadlocal store and add it to the store on the new thread. This allows for continuity in logging the context when using this method to spawn a new thread.

spawn_n(func, *args, **kwargs)

Passthrough method for eventlet.spawn_n.

This utility exists so that it can be stubbed for testing without interfering with the service spawns.

It will also grab the context from the threadlocal store and add it to the store on the new thread. This allows for continuity in logging the context when using this method to spawn a new thread.

ssh_execute(dest, *cmd, **kwargs)

Convenience wrapper to execute ssh command.

strtime(at)
tempdir(*args, **kwds)
temporary_chown(*args, **kwds)

Temporarily chown a path.

Parameters:owner_uid – UID of temporary owner (defaults to current user)
temporary_mutation(*args, **kwds)

Temporarily set the attr on a particular object to a given value then revert when finished.

One use of this is to temporarily set the read_deleted flag on a context object:

with temporary_mutation(context, read_deleted=”yes”):
do_something_that_needed_deleted_objects()
trycmd(*args, **kwargs)

Convenience wrapper around oslo’s trycmd() method.

utf8(value)

Try to turn a string into utf-8 if possible.

The original code was copied from the utf8 function in http://github.com/facebook/tornado/blob/master/tornado/escape.py

validate_integer(value, name, min_value=None, max_value=None)

Make sure that value is a valid integer, potentially within range.

vpn_ping(address, port, timeout=0.05, session_id=None)

Sends a vpn negotiation packet and returns the server session.

Returns Boolean indicating whether the vpn_server is listening. Basic packet structure is below.

Client packet (14 bytes):

 0 1      8 9  13
+-+--------+-----+
|x| cli_id |?????|
+-+--------+-----+
x = packet identifier 0x38
cli_id = 64 bit identifier
? = unknown, probably flags/padding

Server packet (26 bytes):

 0 1      8 9  13 14    21 2225
+-+--------+-----+--------+----+
|x| srv_id |?????| cli_id |????|
+-+--------+-----+--------+----+
x = packet identifier 0x40
cli_id = 64 bit identifier
? = unknown, probably flags/padding
bit 9 was 1 and the rest were 0 in testing
walk_class_hierarchy(clazz, encountered=None)

Walk class hierarchy, yielding most derived classes first.

workarounds_opts = [<oslo_config.cfg.BoolOpt object at 0x7f5646e6aa10>, <oslo_config.cfg.BoolOpt object at 0x7f5646e6aa90>, <oslo_config.cfg.BoolOpt object at 0x7f5646e6ab10>, <oslo_config.cfg.BoolOpt object at 0x7f5646e6ab90>]

The workarounds_opts group is for very specific reasons.

If you’re:

  • Working around an issue in a system tool (e.g. libvirt or qemu) where the fix is in flight/discussed in that community.
  • The tool can be/is fixed in some distributions and rather than patch the code those distributions can trivially set a config option to get the “correct” behavior.

Then this is a good place for your workaround.

Warning

Please use with care! Document the BugID that your workaround is paired with.

xhtml_escape(value)

Escapes a string so it is valid within XML or XHTML.

Previous topic

The nova.test Module

Next topic

The nova.version Module

Project Source

This Page